text stringlengths 1 1.05M |
|---|
/**
* @copyright
* Copyright (c) 2012-2017, OpenGeoSys Community (http://www.opengeosys.org)
* Distributed under a Modified BSD License.
* See accompanying file LICENSE.txt or
* http://www.opengeosys.org/LICENSE.txt
*
*/
#include <array>
#include <memory>
#include <string>
#include <tclap/CmdLine.h>
#include "Applications/ApplicationsLib/LogogSetup.h"
#include "BaseLib/BuildInfo.h"
#include "MeshLib/Mesh.h"
#include "MeshLib/Node.h"
#include "MeshLib/IO/readMeshFromFile.h"
#include "MeshLib/IO/writeMeshToFile.h"
static void swapNodeCoordinateAxes(MeshLib::Mesh &mesh, std::array<int, 3> const& new_axes_indices)
{
for (MeshLib::Node* node : mesh.getNodes())
{
for (int i=0; i<3; i++)
(*node)[i] = (*node)[new_axes_indices[i]];
}
}
static bool parseNewOrder(std::string const& str_order, std::array<int, 3> &new_axes_indices)
{
if (str_order.length()!=3)
{
ERR("Invalid argument for the new order. The argument should contain three characters.");
return false;
}
for (std::size_t i=0; i<new_axes_indices.size(); i++)
new_axes_indices[i] = -1;
for (int i=0; i<3; i++)
{
if (str_order[i] == 'x')
new_axes_indices[i] = 0;
else if (str_order[i] == 'y')
new_axes_indices[i] = 1;
else if (str_order[i] == 'z')
new_axes_indices[i] = 2;
else {
ERR("Invalid argument for the new order. The given argument contains a character other than \"x\", \"y\", \"z\".");
return false;
}
}
bool isAxisSet[3] = {false};
for (std::size_t i=0; i<new_axes_indices.size(); i++)
{
if (isAxisSet[new_axes_indices[i]])
{
ERR("Invalid argument for the new order. The argument contains some character used more than once.");
return false;
}
isAxisSet[new_axes_indices[i]] = true;
}
return true;
}
int main(int argc, char *argv[])
{
ApplicationsLib::LogogSetup logog_setup;
TCLAP::CmdLine cmd("Swap node coordinate values", ' ', BaseLib::BuildInfo::git_describe);
TCLAP::ValueArg<std::string> input_arg("i", "input-mesh-file","input mesh file",true,"","string");
cmd.add( input_arg );
TCLAP::ValueArg<std::string> output_arg("o", "output-mesh-file","output mesh file",true,"","string");
cmd.add( output_arg );
TCLAP::ValueArg<std::string> new_order_arg("n", "new-order", "the new order of swapped coordinate values "
"(e.g. \"xzy\" for converting XYZ values to XZY values)",
true, "", "string");
cmd.add( new_order_arg );
cmd.parse( argc, argv );
const std::string str_order = new_order_arg.getValue();
std::array<int, 3> new_order = {};
if (!parseNewOrder(str_order, new_order))
return EXIT_FAILURE;
std::unique_ptr<MeshLib::Mesh> mesh(
MeshLib::IO::readMeshFromFile(input_arg.getValue()));
if (!mesh)
return EXIT_FAILURE;
if (mesh->getDimension() == 3)
{
WARN("Swapping coordinate values of 3D elements can result in incorrect node-ordering.");
}
INFO("Exchange node coordinates from xyz to %s", new_order_arg.getValue().data());
swapNodeCoordinateAxes(*mesh, new_order);
INFO("Save the new mesh into a file");
MeshLib::IO::writeMeshToFile(*mesh, output_arg.getValue());
return EXIT_SUCCESS;
}
|
;
; Z88dk Z88 Maths Library
;
;
; $Id: dleq.asm,v 1.3 2015/01/21 10:56:30 stefano Exp $
PUBLIC dleq
EXTERN fsetup
EXTERN stkequcmp
INCLUDE "fpp.def"
; TOS <= FA?
.dleq
call fsetup
fpp(FP_LEQ)
jp stkequcmp
|
db DEX_VILEPLUME ; pokedex id
db 75 ; base hp
db 80 ; base attack
db 85 ; base defense
db 50 ; base speed
db 100 ; base special
db GRASS ; species type 1
db POISON ; species type 2
db 45 ; catch rate
db 184 ; base exp yield
INCBIN "pic/ymon/vileplume.pic",0,1 ; 77, sprite dimensions
dw VileplumePicFront
dw VileplumePicBack
; attacks known at lvl 0
db STUN_SPORE
db SLEEP_POWDER
db ACID
db PETAL_DANCE
db 3 ; growth rate
; learnset
tmlearn 3,6,8
tmlearn 9,10,15
tmlearn 20,21,22
tmlearn 31,32
tmlearn 33,34
tmlearn 44
tmlearn 50,51
db BANK(VileplumePicFront)
|
lorom
; Door ASM pointer (Door into small corridor before construction zone)
org $838eb4
db $00, $ff
; Door ASM to set Zebes awake
org $8fff00
lda $7ed872
bit #$0400
beq exit
lda $7ed820
ora.w #$0001
sta $7ed820
exit:
rts
|
; A132269: Product{k>=0, 1+floor(n/2^k)}.
; 1,2,6,8,30,36,56,64,270,300,396,432,728,784,960,1024,4590,4860,5700,6000,8316,8712,9936,10368,18200,18928,21168,21952,27840,28800,31744,32768,151470,156060,170100,174960,210900,216600,234000,240000,340956,349272,374616,383328,447120,457056,487296,497664,891800,910000,965328,984256,1121904,1143072,1207360,1229312,1586880,1614720,1699200,1728000,1936384,1968128,2064384,2097152,9845550,9997020,10456020,10612080,11736900,11907000,12422160,12597120,15395700,15606600,16245000,16461600,18018000,18252000,18960000,19200000,27617436,27958392,28989576,29338848,31842360,32216976,33349536,33732864,39793680,40240800,41592096,42049152,45318528,45805824,47278080,47775744,86504600,87396400,90090000,91000000,97498128,98463456,101378368,102362624,117799920,118921824,122308704,123451776,131602240,132809600,136453632,137682944,179317440,180904320,185692800,187307520,198806400,200505600,205632000,207360000,234302464,236238848,242079744,244047872,258048000,260112384,266338304,268435456,1270075950,1279921500,1309609620,1319606640,1390650660,1401106680,1432630800,1443242880,1607955300,1619692200,1655073000,1666980000,1751524560,1763946720,1801388160,1813985280,2232376500,2247772200,2294170200,2309776800,2420505000,2436750000,2485701600,2502163200,2756754000,2774772000,2829060000,2847312000,2976720000,2995680000,3052800000,3072000000,4446407196,4474024632,4557217896,4585176288,4783280040,4812269616,4899587616,4928926464,5381358840,5413201200,5509102896,5541319872,5769469728,5802819264,5903251200,5936984064,7043481360,7083275040,7203103200,7243344000,7528169376,7569761472,7694994816,7737043968,8383927680,8429246208,8565689088,8611494912,8935557120,8982835200,9125167104,9172942848,16695387800,16781892400,17042298000,17129694400,17747730000,17837820000,18109000000,18200000000,19597123728,19694621856,19988081568,20086545024,20782565440,20883943808,21189063168,21291425792,24620183280,24737983200,25092504864,25211426688,26051753952,26174062656,26542131840,26665583616,28557686080,28689288320,29085302400,29218112000,30156252672,30292706304,30703296512,30840979456,40346424000,40525741440,41065280640,41246184960,42523651200,42709344000,43268037120,43455344640,46321891200,46520697600,47118816000,47319321600,48734784000,48940416000,49559040000,49766400000,56466893824,56701196288,57406040064,57642278912,59309537280,59551617024,60279824384,60523872256,64253952000,64512000000
mov $1,5
mov $2,2
lpb $0,1
add $0,1
mul $1,$2
mov $2,$0
sub $0,1
div $0,2
lpe
sub $1,4
div $1,5
add $1,1
|
; ๊ทธ๋ํฝ ์ ์ฉ ๋ผ์ด๋ธ๋ฌ๋ฆฌ ํจ์
; 2015-03-23
; ๋น๋์ค ํ๋ฉด ์ง์ฐ๊ธฐ
; ebx : ColorCode ARGB
_vga_clear_screen:
push esi
push eax
push ecx
mov ax, VGADescriptor
mov es, ax
xor esi, esi
; mov esi, dword [PhysicalBasePointer]
xor eax, eax
xor ecx, ecx
mov ax, word [xResolution]
mov cx, word [yResolution]
mul ecx
; x * y
mov ecx, eax
.clear_loop:
mov dword [es:esi], ebx
add esi, 4
loop .clear_loop
pop ecx
pop eax
pop esi
ret
; push Y์ขํ
; push X์ขํ
; push ์์
; push ์ถ๋ ฅํ ๊ธ์์ ๋ณด
; call _draw_font
; ํ๊ธ์๋ฅผ ํ๋ฉด์ ์ฐ์ด์ฃผ๋ ํจ์
_draw_font:
push ebp
mov ebp, esp
pusha
mov ax, VGADescriptor
mov es, ax
xor esi, esi
mov eax, 4
mul dword [ebp + 16]
add esi, eax
; x position
mov eax, 1024 * 4
mul dword [ebp + 20]
add esi, eax
; y position
mov edi, dword [ebp + 8]
mov eax, 16
.loop_draw:
mov ecx, 8
.loop_px:
mov edx, 1
shl edx, cl
shr edx, 1
test byte [edi], dl
jz .end_px
mov ebx, dword [ebp + 12]
mov dword [es:esi], ebx
.end_px:
add esi, 4
loop .loop_px
add esi, 4 * (1024 - 8)
dec eax
inc edi
cmp eax, 0
jne .loop_draw
popa
mov esp, ebp
pop ebp
ret 16
; ํฐํธ ๊ทธ๋ฆฌ๊ธฐ ํ
์คํธ
_draw_font_test:
mov ecx, 0
.font_test:
mov esi, font
mov eax, 16
mul ecx
add esi, eax
; ๋ค์ ๊ทธ๋ฆด ํฐํธ
mov eax, 8
mul ecx
; x ์ขํ ์์น
push 0
push eax
push 0xFFFFFFFF
push esi
call _draw_font
inc ecx
cmp ecx, 62
jne .font_test
ret
; push Y์ขํ
; push X์ขํ
; push ์์
; push ๊ทธ๋ฆด ์ปค์ ์ข
๋ฅ
; call _draw_font
; ํ๋ฉด์ ๋ง์ฐ์ค ์ปค์๋ฅผ ์ฐ์ด์ฃผ๋ ํจ์
_draw_cursor:
push ebp
mov ebp, esp
pusha
mov ax, VGADescriptor
mov es, ax
xor esi, esi
mov eax, 4
mul dword [ebp + 16]
add esi, eax
; x position
mov eax, 1024 * 4
mul dword [ebp + 20]
add esi, eax
; y position
mov edi, dword [ebp + 8]
mov eax, 16
.loop_draw:
mov ecx, 16
.loop_px:
mov edx, 1
shl edx, cl
shr edx, 1
test word [edi], dx
jz .end_px
mov ebx, dword [ebp + 12]
; Masking
mov edx, 16
sub edx, ecx
add edx, dword [ebp + 16]
cmp word [xResolution], dx
jbe .end_px
mov dword [es:esi], ebx
.end_px:
add esi, 4
loop .loop_px
add esi, 4 * (1024 - 16)
dec eax
add edi, 2
cmp eax, 0
jne .loop_draw
popa
mov esp, ebp
pop ebp
ret 16
; Call Vector Table ์ ๋ฑ๋ก๋ GUI ๋ชจ๋์์์ print ํจ์
; _print32_gui ํจ์์ ํธํ์ฑ์ ๋ง์ถ๊ธฐ ์ํ ๋๋ฒ๊น
์ฉ
_call_print32_gui:
push ebp
mov ebp, esp
pusha
mov eax, dword [ebp+20]
shl eax, 4
push eax
mov eax, dword [ebp+16]
shl eax, 3
push eax
push dword [ebp+12]
push dword [ebp+8]
call _print32_gui
popa
mov esp, ebp
pop ebp
ret 16
; NULL ๋ฌธ์๋ฅผ ๋ง๋ ๋ ๊น์ง ์ถ๋ ฅํฉ๋๋ค.
; ENTER ์ฆ ๊ฐํ ๋ฌธ์๋ฅผ \n ์ผ๋ก ์ ์ ํฉ๋๋ค.
; void print32_gui(const char* str, int colorCode, int x, int y);
_print32_gui:
push ebp
mov ebp, esp
pusha
mov edi, dword [ebp+8]
; ์ถ๋ ฅํ ๋ฉ์์ง
mov esi, dword [ebp+16]
; ์ถ๋ ฅ x ์ขํ
mov ecx, 16
; ํฐํธ ํฌ๊ธฐ
.loop:
xor eax, eax
mov al, byte [edi]
test al, al
jz .end
; NULL ์ฒดํฌํ ์ข
๋ฃ
cmp al, '&'
jae .chk
.chk:
cmp al, 'z'
ja .endloop
sub al, '&'
mul ecx
add eax, font.26h
push dword [ebp+20]
push esi
push dword [ebp+12]
push eax
call _draw_font
.endloop:
add esi, 8
inc edi
; ๊ธ์จ ํฌ๊ธฐ๋งํผ ๋ค์ ์์น๋ก ์ด๋
jmp .loop
.end:
popa
mov esp, ebp
pop ebp
ret 16
|
#include <cppx-core-language/tmp/type-checkers.hpp>
namespace { int satisfy_linker; }
|
-- 7 Billion Humans (2087) --
-- 43: Multiplication Table --
-- Author: landfillbaby
-- Size: 20
-- Speed: 41
step n
step n
step n
step n
step n
step n
step n
step n
step n
step n
mem1 = nearest datacube
if mem1 == 0:
step n
endif
mem2 = nearest datacube
a:
step s
pickup c
write mem2
drop
mem2 = calc mem2 + mem1
jump a |
.include "../qpu/vc4.qinc"
.func gvpm_wr_setup(stride, addr)
# Ignored, Horizontal, Laned (ignored), 32-bit
gvpm_setup(0, stride, 1, 0, 2, addr)
.endf
.func gvpm_rd_setup(num, stride, addr)
# Horizontal, Laned (ignored), 32-bit
gvpm_setup(num, stride, 1, 0, 2, addr)
.endf
.func gvpm_setup(num, stride, horiz, laned, size, addr)
0x00000000 | (num & 0xf) << 20 |(stride & 0x3f) << 12 | (horiz & 0x1) << 11 | (laned & 0x1) << 10 | (size & 0x3) << 8 | (addr & 0xff)
# Table 32: VPM Generic Block Write Setup Format
.endf
.func dma_wr_setup(units, depth, laned, horiz, vpmbase, modew)
0x80000000 | (units & 0x7f) << 23 | (depth & 0x7f) << 16 | (laned & 0x1) << 15 | (horiz & 0x1) << 14 | (vpmbase & 0x7ff) << 3 | (modew & 0x7)
# Table 34: VCD DMA Store (VDW) Basic Setup Format
.endf
.func dma_rd_setup(modew, mpitch, rowlen, nrows, vpitch, vert, addrxy)
0x80000000 | (modew & 0x7) << 28 | (mpitch & 0xf) << 24 | (rowlen & 0xf) << 20 | (nrows & 0xf) << 16 | (vpitch & 0xf) << 12 | (vert & 0x1) << 11 | (addrxy & 0x7ff)
# Table 36: VCD DMA Load (VDR) Basic Setup Format
.endf
# Create vector 0-15
.macro store_vector_seq_in, reg
mov r0, [0x0, 0x0, 0x0, 0x0, 0x1, 0x1, 0x1, 0x1, 0x2, 0x2, 0x2, 0x2, 0x3, 0x3, 0x3, 0x3]
shl r0, r0, 2
mov r1, [0x0, 0x1, 0x2, 0x3, 0x0, 0x1, 0x2, 0x3, 0x0, 0x1, 0x2, 0x3, 0x0, 0x1, 0x2, 0x3]
add reg, r1, r0
.endm
# Init width and height steps
.macro store_vector_seq_in, reg
mov r0, [0x0, 0x0, 0x0, 0x0, 0x1, 0x1, 0x1, 0x1, 0x2, 0x2, 0x2, 0x2, 0x3, 0x3, 0x3, 0x3]
shl r0, r0, 2
mov r1, [0x0, 0x1, 0x2, 0x3, 0x0, 0x1, 0x2, 0x3, 0x0, 0x1, 0x2, 0x3, 0x0, 0x1, 0x2, 0x3]
add reg, r1, r0
.endm
.set frame_width, ra2
.set frame_height, ra8
.set frame_ptr, ra3
.set obuf_ptr, ra4
.set obuf_off, rb5
.set vec_seq, rb6
.set fstep_w, ra7
.set fstep_w16, rb8
.set fstep_h, ra9
# Store uniforms
mov frame_width, unif # Frame width
mov frame_height, unif # Frame height
mov fstep_w, unif # 1.0f / frame_width
mov fstep_h, unif # 1.0f / frame_height
mov frame_ptr, unif # Frame buffer ptr
mov obuf_ptr, unif # Output buffer ptr
# Init variables
store_vector_seq_in vec_seq
mov obuf_off, 0x0
fmul fstep_w16, fstep_w, 16.0
.set j, ra20 # column counter
.set i, ra21 # row counter
.set column_off, rb11
.set row_off, rb12
mov row_off, 1.0
mov i, frame_height
:1
# Setup the VPM for writing
ldi vw_setup, gvpm_setup(0, 1, 1, 0, 0, 0) # Increase addr by 1 byte, start from 0
mov column_off, 0.0
shr j, frame_width, 4
:2
itof r0, vec_seq # load [0-16]
fmul r0, fstep_w, r0 # step * [0-16]
fadd r1, column_off, r0 # add element offset
#mov r1, row_off
#mov r0, 255.0
#fmul r1, r1, r0
#ftoi r1, r1
#mov vpm, r1
mov t0t, r1
mov t0s, row_off
mov unif_addr_rel, -2
ldtmu0
nop
nop
nop
mov vpm, r4
mov r0, fstep_w16
fadd column_off, column_off, r0 # add vector column offset
sub.setf j, j, 1
brr.anynz -, :2
nop # Branch delay
nop
nop
fsub row_off, row_off, fstep_h # sub row offset
ldi vw_setup, dma_wr_setup(20, 16, 0, 1, 0, 0)
add vw_addr, obuf_ptr, obuf_off
ldi r0, (16*4*20)
add obuf_off, obuf_off, r0
read vw_wait
sub.setf i, i, 1
brr.anynz -, :1
nop
nop
nop
# trigger a host interrupt (writing rb38) to stop the program
mov.setf irq, nop; read rb0
nop; thrend
nop
nop
|
#include <DataTypes/EnumValues.h>
#include <boost/algorithm/string.hpp>
#include <base/sort.h>
namespace DB
{
namespace ErrorCodes
{
extern const int SYNTAX_ERROR;
extern const int EMPTY_DATA_PASSED;
extern const int BAD_ARGUMENTS;
}
template <typename T>
EnumValues<T>::EnumValues(const Values & values_)
: values(values_)
{
if (values.empty())
throw Exception{"DataTypeEnum enumeration cannot be empty", ErrorCodes::EMPTY_DATA_PASSED};
::sort(std::begin(values), std::end(values), [] (auto & left, auto & right)
{
return left.second < right.second;
});
fillMaps();
}
template <typename T>
void EnumValues<T>::fillMaps()
{
for (const auto & name_and_value : values)
{
const auto inserted_value = name_to_value_map.insert(
{ StringRef{name_and_value.first}, name_and_value.second });
if (!inserted_value.second)
throw Exception{"Duplicate names in enum: '" + name_and_value.first + "' = " + toString(name_and_value.second)
+ " and " + toString(inserted_value.first->getMapped()),
ErrorCodes::SYNTAX_ERROR};
const auto inserted_name = value_to_name_map.insert(
{ name_and_value.second, StringRef{name_and_value.first} });
if (!inserted_name.second)
throw Exception{"Duplicate values in enum: '" + name_and_value.first + "' = " + toString(name_and_value.second)
+ " and '" + toString((*inserted_name.first).first) + "'",
ErrorCodes::SYNTAX_ERROR};
}
}
template <typename T>
T EnumValues<T>::getValue(StringRef field_name, bool try_treat_as_id) const
{
const auto it = name_to_value_map.find(field_name);
if (!it)
{
/// It is used in CSV and TSV input formats. If we fail to find given string in
/// enum names, we will try to treat it as enum id.
if (try_treat_as_id)
{
T x;
ReadBufferFromMemory tmp_buf(field_name.data, field_name.size);
readText(x, tmp_buf);
/// Check if we reached end of the tmp_buf (otherwise field_name is not a number)
/// and try to find it in enum ids
if (tmp_buf.eof() && value_to_name_map.find(x) != value_to_name_map.end())
return x;
}
auto hints = this->getHints(field_name.toString());
auto hints_string = !hints.empty() ? ", maybe you meant: " + toString(hints) : "";
throw Exception{"Unknown element '" + field_name.toString() + "' for enum" + hints_string, ErrorCodes::BAD_ARGUMENTS};
}
return it->getMapped();
}
template <typename T>
Names EnumValues<T>::getAllRegisteredNames() const
{
Names result;
for (const auto & value : values)
result.emplace_back(value.first);
return result;
}
template <typename T>
std::unordered_set<String> EnumValues<T>::getSetOfAllNames(bool to_lower) const
{
std::unordered_set<String> result;
for (const auto & value : values)
result.insert(to_lower ? boost::algorithm::to_lower_copy(value.first) : value.first);
return result;
}
template <typename T>
std::unordered_set<T> EnumValues<T>::getSetOfAllValues() const
{
std::unordered_set<T> result;
for (const auto & value : values)
result.insert(value.second);
return result;
}
template class EnumValues<Int8>;
template class EnumValues<Int16>;
}
|
.data # Program at 4.1
|
; A187539: Alternated binomial partial sums of central Lah numbers (A187535).
; Submitted by Christian Krause
; 1,1,33,1097,54209,3527889,285356449,27608615257,3110179582593,399896866564001,57791843384031521,9273757516482276201,1636151050649025202753,314786007405793614831217,65590496972310741712688289,14714600180590751334321307769,3536193493145216936469915298049,906324877026568027795119504047937,246776509267192382428534285646717473,71137642609727725584136759116036406921,21643904123345486014145154483336491138241,6931278606192692756913452413433211790454801,2330506994967966747969357289400925479840800673
mov $1,1
mov $2,2
mov $3,$0
mov $4,1
lpb $3
mul $1,$4
mul $1,$3
mul $1,4
mul $2,-2
add $5,$4
div $1,$5
mul $1,$4
div $2,2
add $2,$1
sub $3,1
add $4,2
lpe
mov $0,$2
div $0,2
|
.global s_prepare_buffers
s_prepare_buffers:
push %r12
push %r14
push %r9
push %rbp
push %rcx
push %rdi
push %rdx
push %rsi
lea addresses_WT_ht+0x12d67, %rbp
nop
nop
nop
sub %r12, %r12
mov $0x6162636465666768, %rdx
movq %rdx, (%rbp)
nop
nop
nop
nop
nop
inc %r14
lea addresses_UC_ht+0x170e7, %rsi
lea addresses_UC_ht+0xf067, %rdi
clflush (%rsi)
nop
and $63476, %r9
mov $55, %rcx
rep movsq
nop
nop
nop
nop
nop
and $3379, %rdx
lea addresses_D_ht+0x11e7, %r12
clflush (%r12)
nop
nop
nop
nop
sub %rcx, %rcx
vmovups (%r12), %ymm2
vextracti128 $0, %ymm2, %xmm2
vpextrq $0, %xmm2, %rbp
nop
nop
xor $32242, %r14
lea addresses_WC_ht+0x12487, %rbp
nop
nop
nop
nop
nop
xor %r9, %r9
movl $0x61626364, (%rbp)
nop
inc %r12
lea addresses_A_ht+0x10567, %rsi
lea addresses_UC_ht+0x1beb7, %rdi
dec %r9
mov $107, %rcx
rep movsb
nop
nop
lfence
lea addresses_normal_ht+0x7ae7, %r9
nop
nop
nop
xor $40462, %rdx
movups (%r9), %xmm7
vpextrq $1, %xmm7, %rsi
xor %r12, %r12
lea addresses_D_ht+0xc06d, %rcx
nop
nop
nop
nop
nop
xor %r12, %r12
vmovups (%rcx), %ymm5
vextracti128 $1, %ymm5, %xmm5
vpextrq $0, %xmm5, %rdi
nop
xor %rdx, %rdx
lea addresses_A_ht+0x1da7, %r9
nop
nop
nop
nop
nop
add %r14, %r14
movb $0x61, (%r9)
nop
nop
nop
sub %rdx, %rdx
lea addresses_A_ht+0x971f, %rsi
lea addresses_A_ht+0x94e7, %rdi
clflush (%rdi)
add $34303, %rbp
mov $28, %rcx
rep movsw
nop
nop
and $62159, %rsi
lea addresses_UC_ht+0x6967, %rsi
lea addresses_UC_ht+0x4b67, %rdi
nop
nop
nop
dec %rbp
mov $73, %rcx
rep movsq
nop
nop
nop
nop
dec %r9
lea addresses_D_ht+0x1ede7, %rbp
and %r14, %r14
mov (%rbp), %cx
nop
nop
and $42091, %rcx
lea addresses_D_ht+0xb5a7, %rsi
nop
nop
nop
nop
xor $177, %rdx
mov $0x6162636465666768, %r14
movq %r14, %xmm4
and $0xffffffffffffffc0, %rsi
vmovntdq %ymm4, (%rsi)
nop
nop
and %rcx, %rcx
lea addresses_WC_ht+0x2aa3, %r9
nop
cmp $48043, %r12
movw $0x6162, (%r9)
xor %rsi, %rsi
lea addresses_D_ht+0xa897, %r14
clflush (%r14)
nop
nop
nop
nop
and $52214, %rdx
movb (%r14), %r12b
nop
nop
nop
xor %r12, %r12
lea addresses_A_ht+0x14c6d, %r14
nop
nop
nop
nop
nop
and $46797, %r9
mov (%r14), %di
and $63471, %rcx
pop %rsi
pop %rdx
pop %rdi
pop %rcx
pop %rbp
pop %r9
pop %r14
pop %r12
ret
.global s_faulty_load
s_faulty_load:
push %r10
push %r11
push %r8
push %rbp
push %rbx
push %rdx
// Store
lea addresses_A+0x15d67, %r8
nop
add $44813, %rbx
movw $0x5152, (%r8)
and $40727, %rbp
// Faulty Load
lea addresses_A+0x15d67, %rdx
nop
nop
nop
nop
inc %r10
vmovups (%rdx), %ymm5
vextracti128 $0, %ymm5, %xmm5
vpextrq $1, %xmm5, %rbx
lea oracles, %rdx
and $0xff, %rbx
shlq $12, %rbx
mov (%rdx,%rbx,1), %rbx
pop %rdx
pop %rbx
pop %rbp
pop %r8
pop %r11
pop %r10
ret
/*
<gen_faulty_load>
[REF]
{'src': {'same': False, 'congruent': 0, 'NT': False, 'type': 'addresses_A', 'size': 16, 'AVXalign': False}, 'OP': 'LOAD'}
{'OP': 'STOR', 'dst': {'same': True, 'congruent': 0, 'NT': False, 'type': 'addresses_A', 'size': 2, 'AVXalign': True}}
[Faulty Load]
{'src': {'same': True, 'congruent': 0, 'NT': False, 'type': 'addresses_A', 'size': 32, 'AVXalign': False}, 'OP': 'LOAD'}
<gen_prepare_buffer>
{'OP': 'STOR', 'dst': {'same': False, 'congruent': 9, 'NT': False, 'type': 'addresses_WT_ht', 'size': 8, 'AVXalign': False}}
{'src': {'type': 'addresses_UC_ht', 'congruent': 7, 'same': False}, 'OP': 'REPM', 'dst': {'type': 'addresses_UC_ht', 'congruent': 7, 'same': False}}
{'src': {'same': False, 'congruent': 7, 'NT': False, 'type': 'addresses_D_ht', 'size': 32, 'AVXalign': False}, 'OP': 'LOAD'}
{'OP': 'STOR', 'dst': {'same': False, 'congruent': 5, 'NT': False, 'type': 'addresses_WC_ht', 'size': 4, 'AVXalign': False}}
{'src': {'type': 'addresses_A_ht', 'congruent': 10, 'same': False}, 'OP': 'REPM', 'dst': {'type': 'addresses_UC_ht', 'congruent': 2, 'same': False}}
{'src': {'same': False, 'congruent': 7, 'NT': False, 'type': 'addresses_normal_ht', 'size': 16, 'AVXalign': False}, 'OP': 'LOAD'}
{'src': {'same': False, 'congruent': 1, 'NT': False, 'type': 'addresses_D_ht', 'size': 32, 'AVXalign': False}, 'OP': 'LOAD'}
{'OP': 'STOR', 'dst': {'same': False, 'congruent': 6, 'NT': False, 'type': 'addresses_A_ht', 'size': 1, 'AVXalign': False}}
{'src': {'type': 'addresses_A_ht', 'congruent': 2, 'same': False}, 'OP': 'REPM', 'dst': {'type': 'addresses_A_ht', 'congruent': 6, 'same': False}}
{'src': {'type': 'addresses_UC_ht', 'congruent': 10, 'same': False}, 'OP': 'REPM', 'dst': {'type': 'addresses_UC_ht', 'congruent': 6, 'same': False}}
{'src': {'same': False, 'congruent': 5, 'NT': False, 'type': 'addresses_D_ht', 'size': 2, 'AVXalign': False}, 'OP': 'LOAD'}
{'OP': 'STOR', 'dst': {'same': False, 'congruent': 3, 'NT': True, 'type': 'addresses_D_ht', 'size': 32, 'AVXalign': False}}
{'OP': 'STOR', 'dst': {'same': False, 'congruent': 1, 'NT': False, 'type': 'addresses_WC_ht', 'size': 2, 'AVXalign': False}}
{'src': {'same': False, 'congruent': 2, 'NT': False, 'type': 'addresses_D_ht', 'size': 1, 'AVXalign': False}, 'OP': 'LOAD'}
{'src': {'same': False, 'congruent': 1, 'NT': False, 'type': 'addresses_A_ht', 'size': 2, 'AVXalign': False}, 'OP': 'LOAD'}
{'35': 21829}
35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35
*/
|
copyright zengfr site:http://github.com/zengfr/romhack
00042A move.l D1, (A0)+
00042C dbra D0, $42a
01487A move.w (A1)+, D2
01487C movem.w D0-D3, (A4) [base+6588, base+6590, base+6598, base+65A0, base+65A8]
014936 move.w (A1)+, D2
014938 movem.w D0-D3, (A4) [base+6008, base+6020, base+6030, base+6110, base+6118, base+6188, base+6190, base+6198, base+61A0, base+61A8, base+61B0, base+6220, base+6230, base+62B8, base+6310, base+6318, base+6388, base+6390, base+6398, base+63A0, base+63A8, base+63B0, base+6420, base+6428, base+6430, base+64B8, base+6508, base+6510, base+6518, base+6590, base+6598, base+65A0, base+65A8]
081090 move.l (A1)+, (A0)+
081092 dbra D0, $81090 [base+6574, base+6576, base+6578, base+657A, base+657C, base+657E, base+6580, base+6582, base+6584, base+6586, base+658E, base+6590, base+6592, base+6594, base+6596, base+6598, base+659A, base+659C, base+659E, base+65A2, base+65A4, base+65A6, base+65A8, base+65AA, base+65AC, base+65AE, base+65B0, base+65B2, base+65B4, base+65B6, base+65B8, base+65BA]
081180 move.w (A1,D0.w), ($24,A0)
081186 rts [base+6598]
0AAACA move.l (A0), D2
0AAACC move.w D0, (A0) [123p+11A, 123p+11C, 123p+11E, 123p+120, 123p+122, 123p+124, 123p+126, 123p+128, 123p+12A, base+6FFE, enemy+BC, enemy+C0, enemy+C2, enemy+C4, enemy+CC, enemy+CE, enemy+D0, enemy+D2, enemy+D4, enemy+D6, enemy+D8, enemy+DA, item+86, item+88, item+8A, item+98, item+9A, item+9C, item+9E, item+A0, item+A2, item+A4, item+A6, scr1]
0AAACE move.w D0, ($2,A0)
0AAAD2 cmp.l (A0), D0
0AAAD4 bne $aaafc
0AAAD8 move.l D2, (A0)+
0AAADA cmpa.l A0, A1 [123p+11A, 123p+11C, 123p+11E, 123p+120, 123p+122, 123p+124, 123p+126, 123p+128, 123p+12A, base+6FFE, enemy+BC, enemy+C0, enemy+C2, enemy+C4, enemy+CC, enemy+CE, enemy+D0, enemy+D2, enemy+D4, enemy+D6, enemy+D8, enemy+DA, item+86, item+88, item+8A, item+98, item+9A, item+9C, item+9E, item+A0, item+A2, item+A4, item+A6, scr1]
0AAAE6 move.l (A0), D2
0AAAE8 move.w D0, (A0) [123p+11A, 123p+11C, 123p+11E, 123p+120, 123p+122, 123p+124, 123p+126, 123p+128, 123p+12A, base+6FFE, enemy+BC, enemy+C0, enemy+C2, enemy+C4, enemy+CC, enemy+CE, enemy+D0, enemy+D2, enemy+D4, enemy+D6, enemy+D8, enemy+DA, item+86, item+88, item+8A, item+98, item+9A, item+9C, item+9E, item+A0, item+A2, item+A4, item+A6, scr1]
0AAAF4 move.l D2, (A0)+
0AAAF6 cmpa.l A0, A1 [123p+11A, 123p+11C, 123p+11E, 123p+120, 123p+122, 123p+124, 123p+126, 123p+128, 123p+12A, base+6FFE, enemy+BC, enemy+C0, enemy+C2, enemy+C4, enemy+CC, enemy+CE, enemy+D0, enemy+D2, enemy+D4, enemy+D6, enemy+D8, enemy+DA, item+86, item+88, item+8A, item+98, item+9A, item+9C, item+9E, item+A0, item+A2, item+A4, item+A6, scr1]
copyright zengfr site:http://github.com/zengfr/romhack
|
/*
* Copyright (c) 2020, The OpenThread Authors.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. Neither the name of the copyright holder nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
#include "posix/platform/multicast_routing.hpp"
#if OPENTHREAD_CONFIG_BACKBONE_ROUTER_MULTICAST_ROUTING_ENABLE
#include <assert.h>
#include <net/if.h>
#include <netinet/icmp6.h>
#include <netinet/in.h>
#include <sys/ioctl.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <unistd.h>
#if __linux__
#include <linux/mroute6.h>
#else
#error "Multicast Routing feature is not ported to non-Linux platforms yet."
#endif
#include <openthread/backbone_router_ftd.h>
#include "core/common/logging.hpp"
namespace ot {
namespace Posix {
void MulticastRoutingManager::Init(otInstance *aInstance)
{
mInstance = aInstance;
otBackboneRouterSetMulticastListenerCallback(aInstance,
&MulticastRoutingManager::HandleBackboneMulticastListenerEvent, this);
}
void MulticastRoutingManager::HandleBackboneMulticastListenerEvent(void * aContext,
otBackboneRouterMulticastListenerEvent aEvent,
const otIp6Address * aAddress)
{
static_cast<MulticastRoutingManager *>(aContext)->HandleBackboneMulticastListenerEvent(
aEvent, static_cast<const Ip6::Address &>(*aAddress));
}
void MulticastRoutingManager::HandleBackboneMulticastListenerEvent(otBackboneRouterMulticastListenerEvent aEvent,
const Ip6::Address & aAddress)
{
switch (aEvent)
{
case OT_BACKBONE_ROUTER_MULTICAST_LISTENER_ADDED:
Add(aAddress);
break;
case OT_BACKBONE_ROUTER_MULTICAST_LISTENER_REMOVED:
Remove(aAddress);
break;
}
}
void MulticastRoutingManager::Enable(void)
{
VerifyOrExit(!IsEnabled());
InitMulticastRouterSock();
otLogResultPlat(OT_ERROR_NONE, "MulticastRoutingManager: %s", __FUNCTION__);
exit:
return;
}
void MulticastRoutingManager::Disable(void)
{
FinalizeMulticastRouterSock();
otLogResultPlat(OT_ERROR_NONE, "MulticastRoutingManager: %s", __FUNCTION__);
}
void MulticastRoutingManager::Add(const Ip6::Address &aAddress)
{
VerifyOrExit(IsEnabled());
UnblockInboundMulticastForwardingCache(aAddress);
otLogResultPlat(OT_ERROR_NONE, "MulticastRoutingManager: %s: %s", __FUNCTION__, aAddress.ToString().AsCString());
exit:
return;
}
void MulticastRoutingManager::Remove(const Ip6::Address &aAddress)
{
otError error = OT_ERROR_NONE;
VerifyOrExit(IsEnabled());
RemoveInboundMulticastForwardingCache(aAddress);
otLogResultPlat(error, "MulticastRoutingManager: %s: %s", __FUNCTION__, aAddress.ToString().AsCString());
exit:
return;
}
bool MulticastRoutingManager::HasMulticastListener(const Ip6::Address &aAddress) const
{
bool found = false;
otBackboneRouterMulticastListenerIterator iter = OT_BACKBONE_ROUTER_MULTICAST_LISTENER_ITERATOR_INIT;
otBackboneRouterMulticastListenerInfo listenerInfo;
while (otBackboneRouterMulticastListenerGetNext(mInstance, &iter, &listenerInfo) == OT_ERROR_NONE)
{
VerifyOrExit(static_cast<const Ip6::Address &>(listenerInfo.mAddress) != aAddress, found = true);
}
exit:
return found;
}
void MulticastRoutingManager::UpdateFdSet(fd_set &aReadFdSet, int &aMaxFd) const
{
VerifyOrExit(IsEnabled());
FD_SET(mMulticastRouterSock, &aReadFdSet);
aMaxFd = OT_MAX(aMaxFd, mMulticastRouterSock);
exit:
return;
}
void MulticastRoutingManager::Process(const fd_set &aReadFdSet)
{
VerifyOrExit(IsEnabled());
ExpireMulticastForwardingCache();
if (FD_ISSET(mMulticastRouterSock, &aReadFdSet))
{
ProcessMulticastRouterMessages();
}
exit:
return;
}
void MulticastRoutingManager::InitMulticastRouterSock(void)
{
int one = 1;
struct icmp6_filter filter;
struct mif6ctl mif6ctl;
// Create a Multicast Routing socket
mMulticastRouterSock = SocketWithCloseExec(AF_INET6, SOCK_RAW, IPPROTO_ICMPV6, kSocketBlock);
VerifyOrDie(mMulticastRouterSock != -1, OT_EXIT_ERROR_ERRNO);
// Enable Multicast Forwarding in Kernel
VerifyOrDie(0 == setsockopt(mMulticastRouterSock, IPPROTO_IPV6, MRT6_INIT, &one, sizeof(one)), OT_EXIT_ERROR_ERRNO);
// Filter all ICMPv6 messages
ICMP6_FILTER_SETBLOCKALL(&filter);
VerifyOrDie(0 == setsockopt(mMulticastRouterSock, IPPROTO_ICMPV6, ICMP6_FILTER, (void *)&filter, sizeof(filter)),
OT_EXIT_ERROR_ERRNO);
memset(&mif6ctl, 0, sizeof(mif6ctl));
mif6ctl.mif6c_flags = 0;
mif6ctl.vifc_threshold = 1;
mif6ctl.vifc_rate_limit = 0;
// Add Thread network interface to MIF
mif6ctl.mif6c_mifi = kMifIndexThread;
mif6ctl.mif6c_pifi = if_nametoindex(gNetifName);
VerifyOrDie(mif6ctl.mif6c_pifi > 0, OT_EXIT_ERROR_ERRNO);
VerifyOrDie(0 == setsockopt(mMulticastRouterSock, IPPROTO_IPV6, MRT6_ADD_MIF, &mif6ctl, sizeof(mif6ctl)),
OT_EXIT_ERROR_ERRNO);
// Add Backbone network interface to MIF
mif6ctl.mif6c_mifi = kMifIndexBackbone;
mif6ctl.mif6c_pifi = if_nametoindex(gBackboneNetifName);
VerifyOrDie(mif6ctl.mif6c_pifi > 0, OT_EXIT_ERROR_ERRNO);
VerifyOrDie(0 == setsockopt(mMulticastRouterSock, IPPROTO_IPV6, MRT6_ADD_MIF, &mif6ctl, sizeof(mif6ctl)),
OT_EXIT_ERROR_ERRNO);
}
void MulticastRoutingManager::FinalizeMulticastRouterSock(void)
{
VerifyOrExit(IsEnabled());
close(mMulticastRouterSock);
mMulticastRouterSock = -1;
exit:
return;
}
void MulticastRoutingManager::ProcessMulticastRouterMessages(void)
{
otError error = OT_ERROR_NONE;
char buf[sizeof(struct mrt6msg)];
int nr;
struct mrt6msg *mrt6msg;
Ip6::Address src, dst;
nr = read(mMulticastRouterSock, buf, sizeof(buf));
VerifyOrExit(nr >= static_cast<int>(sizeof(struct mrt6msg)), error = OT_ERROR_FAILED);
mrt6msg = reinterpret_cast<struct mrt6msg *>(buf);
VerifyOrExit(mrt6msg->im6_mbz == 0);
VerifyOrExit(mrt6msg->im6_msgtype == MRT6MSG_NOCACHE);
src.SetBytes(mrt6msg->im6_src.s6_addr);
dst.SetBytes(mrt6msg->im6_dst.s6_addr);
error = AddMulticastForwardingCache(src, dst, static_cast<MifIndex>(mrt6msg->im6_mif));
exit:
otLogResultPlat(error, "MulticastRoutingManager: %s", __FUNCTION__);
}
otError MulticastRoutingManager::AddMulticastForwardingCache(const Ip6::Address &aSrcAddr,
const Ip6::Address &aGroupAddr,
MifIndex aIif)
{
otError error = OT_ERROR_NONE;
struct mf6cctl mf6cctl;
MifIndex forwardMif = kMifIndexNone;
VerifyOrExit(aIif == kMifIndexThread || aIif == kMifIndexBackbone, error = OT_ERROR_INVALID_ARGS);
ExpireMulticastForwardingCache();
if (aIif == kMifIndexBackbone)
{
// Forward multicast traffic from Backbone to Thread if the group address is subscribed by any Thread device via
// MLR.
if (HasMulticastListener(aGroupAddr))
{
forwardMif = kMifIndexThread;
}
}
else
{
// Forward multicast traffic from Thread to Backbone if multicast scope > kRealmLocalScope
// TODO: (MLR) allow scope configuration of outbound multicast routing
if (aGroupAddr.GetScope() > Ip6::Address::kRealmLocalScope)
{
forwardMif = kMifIndexBackbone;
}
}
memset(&mf6cctl, 0, sizeof(mf6cctl));
memcpy(mf6cctl.mf6cc_origin.sin6_addr.s6_addr, aSrcAddr.GetBytes(), sizeof(mf6cctl.mf6cc_origin.sin6_addr.s6_addr));
memcpy(mf6cctl.mf6cc_mcastgrp.sin6_addr.s6_addr, aGroupAddr.GetBytes(),
sizeof(mf6cctl.mf6cc_mcastgrp.sin6_addr.s6_addr));
mf6cctl.mf6cc_parent = aIif;
if (forwardMif != kMifIndexNone)
{
IF_SET(forwardMif, &mf6cctl.mf6cc_ifset);
}
// Note that kernel reports repetitive `MRT6MSG_NOCACHE` upcalls with a rate limit (e.g. once per 10s for Linux).
// Because of it, we need to add a "blocking" MFC even if there is no forwarding for this group address.
// When a Multicast Listener is later added, the "blocking" MFC will be altered to be a "forwarding" MFC so that
// corresponding multicast traffic can be forwarded instantly.
VerifyOrExit(0 == setsockopt(mMulticastRouterSock, IPPROTO_IPV6, MRT6_ADD_MFC, &mf6cctl, sizeof(mf6cctl)),
error = OT_ERROR_FAILED);
SaveMulticastForwardingCache(aSrcAddr, aGroupAddr, aIif, forwardMif);
exit:
otLogResultPlat(error, "MulticastRoutingManager: %s: add dynamic route: %s %s => %s %s", __FUNCTION__,
MifIndexToString(aIif), aSrcAddr.ToString().AsCString(), aGroupAddr.ToString().AsCString(),
MifIndexToString(forwardMif));
return error;
}
void MulticastRoutingManager::UnblockInboundMulticastForwardingCache(const Ip6::Address &aGroupAddr)
{
struct mf6cctl mf6cctl;
memset(&mf6cctl, 0, sizeof(mf6cctl));
memcpy(mf6cctl.mf6cc_mcastgrp.sin6_addr.s6_addr, aGroupAddr.GetBytes(),
sizeof(mf6cctl.mf6cc_mcastgrp.sin6_addr.s6_addr));
mf6cctl.mf6cc_parent = kMifIndexBackbone;
IF_SET(kMifIndexThread, &mf6cctl.mf6cc_ifset);
for (MulticastForwardingCache &mfc : mMulticastForwardingCacheTable)
{
otError error;
if (!mfc.IsValid() || mfc.mIif != kMifIndexBackbone || mfc.mOif == kMifIndexThread ||
mfc.mGroupAddr != aGroupAddr)
{
continue;
}
// Unblock this inbound route
memcpy(mf6cctl.mf6cc_origin.sin6_addr.s6_addr, mfc.mSrcAddr.GetBytes(),
sizeof(mf6cctl.mf6cc_origin.sin6_addr.s6_addr));
error = (0 == setsockopt(mMulticastRouterSock, IPPROTO_IPV6, MRT6_ADD_MFC, &mf6cctl, sizeof(mf6cctl)))
? OT_ERROR_NONE
: OT_ERROR_FAILED;
mfc.Set(kMifIndexBackbone, kMifIndexThread);
otLogResultPlat(error, "MulticastRoutingManager: %s: %s %s => %s %s", __FUNCTION__, MifIndexToString(mfc.mIif),
mfc.mSrcAddr.ToString().AsCString(), mfc.mGroupAddr.ToString().AsCString(),
MifIndexToString(kMifIndexThread));
}
}
void MulticastRoutingManager::RemoveInboundMulticastForwardingCache(const Ip6::Address &aGroupAddr)
{
for (MulticastForwardingCache &mfc : mMulticastForwardingCacheTable)
{
if (mfc.IsValid() && mfc.mIif == kMifIndexBackbone && mfc.mGroupAddr == aGroupAddr)
{
RemoveMulticastForwardingCache(mfc);
}
}
}
void MulticastRoutingManager::ExpireMulticastForwardingCache(void)
{
struct sioc_sg_req6 sioc_sg_req6;
uint64_t now = otPlatTimeGet();
struct mf6cctl mf6cctl;
VerifyOrExit(now >= mLastExpireTime + kMulticastForwardingCacheExpiringInterval * US_PER_S);
mLastExpireTime = now;
memset(&mf6cctl, 0, sizeof(mf6cctl));
memset(&sioc_sg_req6, 0, sizeof(sioc_sg_req6));
for (MulticastForwardingCache &mfc : mMulticastForwardingCacheTable)
{
if (mfc.IsValid() && mfc.mLastUseTime + kMulticastForwardingCacheExpireTimeout * US_PER_S < now)
{
if (!UpdateMulticastRouteInfo(mfc))
{
// The multicast route is expired
RemoveMulticastForwardingCache(mfc);
}
}
}
DumpMulticastForwardingCache();
exit:
return;
}
bool MulticastRoutingManager::UpdateMulticastRouteInfo(MulticastForwardingCache &aMfc) const
{
bool updated = false;
struct sioc_sg_req6 sioc_sg_req6;
memset(&sioc_sg_req6, 0, sizeof(sioc_sg_req6));
memcpy(sioc_sg_req6.src.sin6_addr.s6_addr, aMfc.mSrcAddr.GetBytes(), sizeof(sioc_sg_req6.src.sin6_addr.s6_addr));
memcpy(sioc_sg_req6.grp.sin6_addr.s6_addr, aMfc.mGroupAddr.GetBytes(), sizeof(sioc_sg_req6.grp.sin6_addr.s6_addr));
if (ioctl(mMulticastRouterSock, SIOCGETSGCNT_IN6, &sioc_sg_req6) != -1)
{
unsigned long validPktCnt;
otLogDebgPlat("MulticastRoutingManager: %s: SIOCGETSGCNT_IN6 %s => %s: bytecnt=%lu, pktcnt=%lu, wrong_if=%lu",
__FUNCTION__, aMfc.mSrcAddr.ToString().AsCString(), aMfc.mGroupAddr.ToString().AsCString(),
sioc_sg_req6.bytecnt, sioc_sg_req6.pktcnt, sioc_sg_req6.wrong_if);
validPktCnt = sioc_sg_req6.pktcnt - sioc_sg_req6.wrong_if;
if (validPktCnt != aMfc.mValidPktCnt)
{
aMfc.SetValidPktCnt(validPktCnt);
updated = true;
}
}
else
{
otLogWarnPlat("MulticastRoutingManager: %s: SIOCGETSGCNT_IN6 %s => %s failed: %s", __FUNCTION__,
aMfc.mSrcAddr.ToString().AsCString(), aMfc.mGroupAddr.ToString().AsCString(), strerror(errno));
}
return updated;
}
const char *MulticastRoutingManager::MifIndexToString(MifIndex aMif)
{
const char *string = "Unknown";
switch (aMif)
{
case kMifIndexNone:
string = "None";
break;
case kMifIndexThread:
string = "Thread";
break;
case kMifIndexBackbone:
string = "Backbone";
break;
}
return string;
}
void MulticastRoutingManager::DumpMulticastForwardingCache(void) const
{
#if OPENTHREAD_CONFIG_LOG_LEVEL >= OT_LOG_LEVEL_DEBG
otLogDebgPlat("MulticastRoutingManager: ==================== MFC ENTRIES ====================");
for (const MulticastForwardingCache &mfc : mMulticastForwardingCacheTable)
{
if (mfc.IsValid())
{
otLogDebgPlat("MulticastRoutingManager: %s %s => %s %s", MifIndexToString(mfc.mIif),
mfc.mSrcAddr.ToString().AsCString(), mfc.mGroupAddr.ToString().AsCString(),
MifIndexToString(mfc.mOif));
}
}
otLogDebgPlat("MulticastRoutingManager: =====================================================");
#endif
}
void MulticastRoutingManager::HandleStateChange(otInstance *aInstance, otChangedFlags aFlags)
{
if (aFlags & OT_CHANGED_THREAD_BACKBONE_ROUTER_STATE)
{
otBackboneRouterState state = otBackboneRouterGetState(aInstance);
switch (state)
{
case OT_BACKBONE_ROUTER_STATE_DISABLED:
case OT_BACKBONE_ROUTER_STATE_SECONDARY:
Disable();
break;
case OT_BACKBONE_ROUTER_STATE_PRIMARY:
Enable();
break;
}
}
}
void MulticastRoutingManager::MulticastForwardingCache::Set(MulticastRoutingManager::MifIndex aIif,
MulticastRoutingManager::MifIndex aOif)
{
mIif = aIif;
mOif = aOif;
mValidPktCnt = 0;
mLastUseTime = otPlatTimeGet();
}
void MulticastRoutingManager::MulticastForwardingCache::Set(const Ip6::Address &aSrcAddr,
const Ip6::Address &aGroupAddr,
MifIndex aIif,
MifIndex aOif)
{
mSrcAddr = aSrcAddr;
mGroupAddr = aGroupAddr;
Set(aIif, aOif);
}
void MulticastRoutingManager::MulticastForwardingCache::SetValidPktCnt(unsigned long aValidPktCnt)
{
mValidPktCnt = aValidPktCnt;
mLastUseTime = otPlatTimeGet();
}
void MulticastRoutingManager::SaveMulticastForwardingCache(const Ip6::Address & aSrcAddr,
const Ip6::Address & aGroupAddr,
MulticastRoutingManager::MifIndex aIif,
MulticastRoutingManager::MifIndex aOif)
{
MulticastForwardingCache *invalid = nullptr;
MulticastForwardingCache *oldest = nullptr;
for (MulticastForwardingCache &mfc : mMulticastForwardingCacheTable)
{
if (mfc.IsValid())
{
if (mfc.mSrcAddr == aSrcAddr && mfc.mGroupAddr == aGroupAddr)
{
mfc.Set(aIif, aOif);
ExitNow();
}
if (oldest == nullptr || mfc.mLastUseTime < oldest->mLastUseTime)
{
oldest = &mfc;
}
}
else if (invalid == nullptr)
{
invalid = &mfc;
}
}
if (invalid != nullptr)
{
invalid->Set(aSrcAddr, aGroupAddr, aIif, aOif);
}
else
{
RemoveMulticastForwardingCache(*oldest);
oldest->Set(aSrcAddr, aGroupAddr, aIif, aOif);
}
exit:
return;
}
void MulticastRoutingManager::RemoveMulticastForwardingCache(
MulticastRoutingManager::MulticastForwardingCache &aMfc) const
{
otError error;
struct mf6cctl mf6cctl;
memset(&mf6cctl, 0, sizeof(mf6cctl));
memcpy(mf6cctl.mf6cc_origin.sin6_addr.s6_addr, aMfc.mSrcAddr.GetBytes(),
sizeof(mf6cctl.mf6cc_origin.sin6_addr.s6_addr));
memcpy(mf6cctl.mf6cc_mcastgrp.sin6_addr.s6_addr, aMfc.mGroupAddr.GetBytes(),
sizeof(mf6cctl.mf6cc_mcastgrp.sin6_addr.s6_addr));
mf6cctl.mf6cc_parent = aMfc.mIif;
error = (0 == setsockopt(mMulticastRouterSock, IPPROTO_IPV6, MRT6_DEL_MFC, &mf6cctl, sizeof(mf6cctl)))
? OT_ERROR_NONE
: OT_ERROR_FAILED;
otLogResultPlat(error, "MulticastRoutingManager: %s: %s %s => %s %s", __FUNCTION__, MifIndexToString(aMfc.mIif),
aMfc.mSrcAddr.ToString().AsCString(), aMfc.mGroupAddr.ToString().AsCString(),
MifIndexToString(aMfc.mOif));
aMfc.Erase();
}
} // namespace Posix
} // namespace ot
#endif // OPENTHREAD_CONFIG_BACKBONE_ROUTER_MULTICAST_ROUTING_ENABLE
|
// Example program for the Commander X16.
// Demonstrates the usage of the VERA layer 0 and 1.
.cpu _65c02
// Commodore 64 PRG executable file
.file [name="cx16-veralayers.prg", type="prg", segments="Program"]
.segmentdef Program [segments="Basic, Code, Data"]
.segmentdef Basic [start=$0801]
.segmentdef Code [start=$80d]
.segmentdef Data [startAfter="Code"]
.segment Basic
:BasicUpstart(__start)
/// The colors of the CX16
.const BLACK = 0
.const WHITE = 1
.const RED = 2
.const GREEN = 5
.const BLUE = 6
.const YELLOW = 7
.const VERA_INC_1 = $10
.const VERA_ADDRSEL = 1
.const VERA_LAYER1_ENABLE = $20
.const VERA_LAYER0_ENABLE = $10
.const VERA_LAYER_WIDTH_128 = $20
.const VERA_LAYER_WIDTH_MASK = $30
.const VERA_LAYER_HEIGHT_64 = $40
.const VERA_LAYER_HEIGHT_MASK = $c0
.const VERA_LAYER_CONFIG_256C = 8
.const VERA_LAYER_TILEBASE_MASK = $fc
.const BINARY = 2
.const OCTAL = 8
.const DECIMAL = $a
.const HEXADECIMAL = $10
.const SIZEOF_UNSIGNED_INT = 2
.const SIZEOF_POINTER = 2
.const SIZEOF_UNSIGNED_LONG = 4
.const OFFSET_STRUCT_PRINTF_BUFFER_NUMBER_DIGITS = 1
.const STACK_BASE = $103
.const SIZEOF_STRUCT_PRINTF_BUFFER_NUMBER = $c
/// $9F20 VRAM Address (7:0)
.label VERA_ADDRX_L = $9f20
/// $9F21 VRAM Address (15:8)
.label VERA_ADDRX_M = $9f21
/// $9F22 VRAM Address (7:0)
/// Bit 4-7: Address Increment The following is the amount incremented per value value:increment
/// 0:0, 1:1, 2:2, 3:4, 4:8, 5:16, 6:32, 7:64, 8:128, 9:256, 10:512, 11:40, 12:80, 13:160, 14:320, 15:640
/// Bit 3: DECR Setting the DECR bit, will decrement instead of increment by the value set by the 'Address Increment' field.
/// Bit 0: VRAM Address (16)
.label VERA_ADDRX_H = $9f22
/// $9F23 DATA0 VRAM Data port 0
.label VERA_DATA0 = $9f23
/// $9F24 DATA1 VRAM Data port 1
.label VERA_DATA1 = $9f24
/// $9F25 CTRL Control
/// Bit 7: Reset
/// Bit 1: DCSEL
/// Bit 2: ADDRSEL
.label VERA_CTRL = $9f25
/// $9F29 DC_VIDEO (DCSEL=0)
/// Bit 7: Current Field Read-only bit which reflects the active interlaced field in composite and RGB modes. (0: even, 1: odd)
/// Bit 6: Sprites Enable Enable output from the Sprites renderer
/// Bit 5: Layer1 Enable Enable output from the Layer1 renderer
/// Bit 4: Layer0 Enable Enable output from the Layer0 renderer
/// Bit 2: Chroma Disable Setting 'Chroma Disable' disables output of chroma in NTSC composite mode and will give a better picture on a monochrome display. (Setting this bit will also disable the chroma output on the S-video output.)
/// Bit 0-1: Output Mode 0: Video disabled, 1: VGA output, 2: NTSC composite, 3: RGB interlaced, composite sync (via VGA connector)
.label VERA_DC_VIDEO = $9f29
/// $9F2A DC_HSCALE (DCSEL=0) Active Display H-Scale
.label VERA_DC_HSCALE = $9f2a
/// $9F2B DC_VSCALE (DCSEL=0) Active Display V-Scale
.label VERA_DC_VSCALE = $9f2b
/// $9F2D L0_CONFIG Layer 0 Configuration
.label VERA_L0_CONFIG = $9f2d
/// $9F2E L0_MAPBASE Layer 0 Map Base Address (16:9)
.label VERA_L0_MAPBASE = $9f2e
/// Bit 0: Tile Width (0:8 pixels, 1:16 pixels)
.label VERA_L0_TILEBASE = $9f2f
/// $9F34 L1_CONFIG Layer 1 Configuration
.label VERA_L1_CONFIG = $9f34
/// $9F35 L1_MAPBASE Layer 1 Map Base Address (16:9)
.label VERA_L1_MAPBASE = $9f35
/// $9F36 L1_TILEBASE Layer 1 Tile Base
/// Bit 2-7: Tile Base Address (16:11)
/// Bit 1: Tile Height (0:8 pixels, 1:16 pixels)
/// Bit 0: Tile Width (0:8 pixels, 1:16 pixels)
.label VERA_L1_TILEBASE = $9f36
// Variable holding the screen width;
.label conio_screen_width = $13
// Variable holding the screen height;
.label conio_screen_height = $1c
// Variable holding the screen layer on the VERA card with which conio interacts;
.label conio_screen_layer = $14
// Variables holding the current map width and map height of the layer.
.label conio_width = $32
.label conio_height = $27
.label conio_rowshift = $15
.label conio_rowskip = $16
.label CONIO_SCREEN_BANK = $30
// The screen width
// The screen height
// The text screen base address, which is a 16:0 bit value in VERA VRAM.
// That is 128KB addressable space, thus 17 bits in total.
// CONIO_SCREEN_TEXT contains bits 15:0 of the address.
// CONIO_SCREEN_BANK contains bit 16, the the 64K memory bank in VERA VRAM (the upper 17th bit).
// !!! note that these values are not const for the cx16!
// This conio implements the two layers of VERA, which can be layer 0 or layer 1.
// Configuring conio to output to a different layer, will change these fields to the address base
// configured using VERA_L0_MAPBASE = 0x9f2e or VERA_L1_MAPBASE = 0x9f35.
// Using the function setscreenlayer(layer) will re-calculate using CONIO_SCREEN_TEXT and CONIO_SCREEN_BASE
// based on the values of VERA_L0_MAPBASE or VERA_L1_MAPBASE, mapping the base address of the selected layer.
// The function setscreenlayermapbase(layer,mapbase) allows to configure bit 16:9 of the
// mapbase address of the time map in VRAM of the selected layer VERA_L0_MAPBASE or VERA_L1_MAPBASE.
.label CONIO_SCREEN_TEXT = $a
.label CONIO_SCREEN_BANK_1 = $35
// The screen width
// The screen height
// The text screen base address, which is a 16:0 bit value in VERA VRAM.
// That is 128KB addressable space, thus 17 bits in total.
// CONIO_SCREEN_TEXT contains bits 15:0 of the address.
// CONIO_SCREEN_BANK contains bit 16, the the 64K memory bank in VERA VRAM (the upper 17th bit).
// !!! note that these values are not const for the cx16!
// This conio implements the two layers of VERA, which can be layer 0 or layer 1.
// Configuring conio to output to a different layer, will change these fields to the address base
// configured using VERA_L0_MAPBASE = 0x9f2e or VERA_L1_MAPBASE = 0x9f35.
// Using the function setscreenlayer(layer) will re-calculate using CONIO_SCREEN_TEXT and CONIO_SCREEN_BASE
// based on the values of VERA_L0_MAPBASE or VERA_L1_MAPBASE, mapping the base address of the selected layer.
// The function setscreenlayermapbase(layer,mapbase) allows to configure bit 16:9 of the
// mapbase address of the time map in VRAM of the selected layer VERA_L0_MAPBASE or VERA_L1_MAPBASE.
.label CONIO_SCREEN_TEXT_1 = $39
.segment Code
__start: {
// __ma unsigned byte conio_screen_width = 0
lda #0
sta.z conio_screen_width
// __ma unsigned byte conio_screen_height = 0
sta.z conio_screen_height
// __ma unsigned byte conio_screen_layer = 1
lda #1
sta.z conio_screen_layer
// __ma word conio_width = 0
lda #<0
sta.z conio_width
sta.z conio_width+1
// __ma word conio_height = 0
sta.z conio_height
sta.z conio_height+1
// __ma byte conio_rowshift = 0
sta.z conio_rowshift
// __ma word conio_rowskip = 0
sta.z conio_rowskip
sta.z conio_rowskip+1
// #pragma constructor_for(conio_x16_init, cputc, clrscr, cscroll)
jsr conio_x16_init
jsr main
rts
}
// Set initial cursor position
conio_x16_init: {
// Position cursor at current line
.label BASIC_CURSOR_LINE = $d6
.label line = $34
// char line = *BASIC_CURSOR_LINE
lda.z BASIC_CURSOR_LINE
sta.z line
// vera_layer_mode_text(1,(dword)0x00000,(dword)0x0F800,128,64,8,8,16)
jsr vera_layer_mode_text
// screensize(&conio_screen_width, &conio_screen_height)
jsr screensize
// screenlayer(1)
lda #1
jsr screenlayer
// vera_layer_set_textcolor(1, WHITE)
lda #WHITE
ldx #1
jsr vera_layer_set_textcolor
// vera_layer_set_backcolor(1, BLUE)
lda #BLUE
ldx #1
jsr vera_layer_set_backcolor
// vera_layer_set_mapbase(0,0x20)
ldx #$20
lda #0
jsr vera_layer_set_mapbase
// vera_layer_set_mapbase(1,0x00)
ldx #0
lda #1
jsr vera_layer_set_mapbase
// if(line>=CONIO_HEIGHT)
lda.z line
cmp.z conio_screen_height
bcc __b1
// line=CONIO_HEIGHT-1
ldx.z conio_screen_height
dex
stx.z line
__b1:
// gotoxy(0, line)
ldx.z line
ldy #0
jsr gotoxy
// }
rts
}
// Output one character at the current cursor position
// Moves the cursor forward. Scrolls the entire screen if needed
// void cputc(__zp($2b) char c)
cputc: {
.const OFFSET_STACK_C = 0
.label __16 = $24
.label c = $2b
.label conio_addr = 2
tsx
lda STACK_BASE+OFFSET_STACK_C,x
sta.z c
// char color = vera_layer_get_color( conio_screen_layer)
ldx.z conio_screen_layer
jsr vera_layer_get_color
// char color = vera_layer_get_color( conio_screen_layer)
tax
// char* conio_addr = CONIO_SCREEN_TEXT + conio_line_text[conio_screen_layer]
lda.z conio_screen_layer
asl
tay
clc
lda.z CONIO_SCREEN_TEXT
adc conio_line_text,y
sta.z conio_addr
lda.z CONIO_SCREEN_TEXT+1
adc conio_line_text+1,y
sta.z conio_addr+1
// conio_cursor_x[conio_screen_layer] << 1
ldy.z conio_screen_layer
lda conio_cursor_x,y
asl
// conio_addr += conio_cursor_x[conio_screen_layer] << 1
clc
adc.z conio_addr
sta.z conio_addr
bcc !+
inc.z conio_addr+1
!:
// if(c=='\n')
lda #'\n'
cmp.z c
beq __b1
// *VERA_CTRL &= ~VERA_ADDRSEL
// Select DATA0
lda #VERA_ADDRSEL^$ff
and VERA_CTRL
sta VERA_CTRL
// BYTE0(conio_addr)
lda.z conio_addr
// *VERA_ADDRX_L = BYTE0(conio_addr)
// Set address
sta VERA_ADDRX_L
// BYTE1(conio_addr)
lda.z conio_addr+1
// *VERA_ADDRX_M = BYTE1(conio_addr)
sta VERA_ADDRX_M
// CONIO_SCREEN_BANK | VERA_INC_1
lda #VERA_INC_1
ora.z CONIO_SCREEN_BANK
// *VERA_ADDRX_H = CONIO_SCREEN_BANK | VERA_INC_1
sta VERA_ADDRX_H
// *VERA_DATA0 = c
lda.z c
sta VERA_DATA0
// *VERA_DATA0 = color
stx VERA_DATA0
// conio_cursor_x[conio_screen_layer]++;
ldx.z conio_screen_layer
inc conio_cursor_x,x
// byte scroll_enable = conio_scroll_enable[conio_screen_layer]
ldy.z conio_screen_layer
lda conio_scroll_enable,y
// if(scroll_enable)
cmp #0
bne __b5
// (unsigned int)conio_cursor_x[conio_screen_layer] == conio_width
lda conio_cursor_x,y
sta.z __16
lda #0
sta.z __16+1
// if((unsigned int)conio_cursor_x[conio_screen_layer] == conio_width)
cmp.z conio_width+1
bne __breturn
lda.z __16
cmp.z conio_width
bne __breturn
// cputln()
jsr cputln
__breturn:
// }
rts
__b5:
// if(conio_cursor_x[conio_screen_layer] == CONIO_WIDTH)
lda.z conio_screen_width
ldy.z conio_screen_layer
cmp conio_cursor_x,y
bne __breturn
// cputln()
jsr cputln
rts
__b1:
// cputln()
jsr cputln
rts
}
main: {
.const vera_layer_is_visible1_layer = 1
.label screensizex1_return = $31
.label screensizey1_return = $38
.label dcvideo = $31
.label config = $31
.label vera_layer_is_visible1_return = $2f
.label mapbase = $31
.label tilebase = $36
.label vera_layer_is_visible2_return = $31
.label tilebase_1 = $37
.label vera_layer_is_visible3_return = $31
.label vera_layer_is_visible4_return = $31
// vera_layer_set_textcolor(conio_screen_layer, color)
ldx.z conio_screen_layer
lda #WHITE
jsr vera_layer_set_textcolor
// vera_layer_set_backcolor(conio_screen_layer, color)
ldx.z conio_screen_layer
lda #BLACK
jsr vera_layer_set_backcolor
// clrscr()
jsr clrscr
// vera_layer_set_textcolor(conio_screen_layer, color)
ldx.z conio_screen_layer
lda #YELLOW
jsr vera_layer_set_textcolor
// printf("press a key")
lda #<cputc
sta.z printf_str.putc
lda #>cputc
sta.z printf_str.putc+1
lda #<s
sta.z printf_str.s
lda #>s
sta.z printf_str.s+1
jsr printf_str
__b1:
// kbhit()
jsr kbhit
// while(!kbhit())
cmp #0
beq __b1
lda.z CONIO_SCREEN_TEXT_1
sta.z CONIO_SCREEN_TEXT
lda.z CONIO_SCREEN_TEXT_1+1
sta.z CONIO_SCREEN_TEXT+1
// clearline()
jsr clearline
// screenlayer(1)
lda #1
jsr screenlayer
// gotoxy(0,16)
ldy #0
ldx #$10
jsr gotoxy
// vera_layer_set_textcolor(conio_screen_layer, color)
ldx.z conio_screen_layer
lda #GREEN
jsr vera_layer_set_textcolor
// printf("this program demonstrates the layer functionality in text mode.\n")
lda #<cputc
sta.z printf_str.putc
lda #>cputc
sta.z printf_str.putc+1
lda #<s1
sta.z printf_str.s
lda #>s1
sta.z printf_str.s+1
jsr printf_str
// return conio_screen_width;
lda.z conio_screen_width
sta.z screensizex1_return
// return conio_screen_height;
lda.z conio_screen_height
sta.z screensizey1_return
// printf("\nvera card width = %u; height = %u\n", screensizex(), screensizey())
lda #<cputc
sta.z printf_str.putc
lda #>cputc
sta.z printf_str.putc+1
lda #<s2
sta.z printf_str.s
lda #>s2
sta.z printf_str.s+1
jsr printf_str
// printf("\nvera card width = %u; height = %u\n", screensizex(), screensizey())
ldy #DECIMAL
jsr printf_uchar
// printf("\nvera card width = %u; height = %u\n", screensizex(), screensizey())
lda #<cputc
sta.z printf_str.putc
lda #>cputc
sta.z printf_str.putc+1
lda #<s3
sta.z printf_str.s
lda #>s3
sta.z printf_str.s+1
jsr printf_str
lda.z screensizey1_return
sta.z printf_uchar.uvalue
// printf("\nvera card width = %u; height = %u\n", screensizex(), screensizey())
ldy #DECIMAL
jsr printf_uchar
// printf("\nvera card width = %u; height = %u\n", screensizex(), screensizey())
lda #<cputc
sta.z printf_str.putc
lda #>cputc
sta.z printf_str.putc+1
lda #<s4
sta.z printf_str.s
lda #>s4
sta.z printf_str.s+1
jsr printf_str
// unsigned byte dcvideo = *VERA_DC_VIDEO
// This is the content of the main controller registers of the VERA of layer 1.
// Layer 1 is the default layer that is activated in the CX16 at startup.
// It displays the characters in 1BPP 16x16 color mode!
lda VERA_DC_VIDEO
sta.z dcvideo
// printf("\nvera dc video = %x\n", dcvideo)
lda #<cputc
sta.z printf_str.putc
lda #>cputc
sta.z printf_str.putc+1
lda #<s5
sta.z printf_str.s
lda #>s5
sta.z printf_str.s+1
jsr printf_str
// printf("\nvera dc video = %x\n", dcvideo)
ldy #HEXADECIMAL
jsr printf_uchar
// printf("\nvera dc video = %x\n", dcvideo)
lda #<cputc
sta.z printf_str.putc
lda #>cputc
sta.z printf_str.putc+1
lda #<s4
sta.z printf_str.s
lda #>s4
sta.z printf_str.s+1
jsr printf_str
// unsigned byte config = vera_layer_get_config(1)
lda #1
jsr vera_layer_get_config
// unsigned byte config = vera_layer_get_config(1)
sta.z config
// printf("\nvera layer 1 config = %x\n", config)
lda #<cputc
sta.z printf_str.putc
lda #>cputc
sta.z printf_str.putc+1
lda #<s7
sta.z printf_str.s
lda #>s7
sta.z printf_str.s+1
jsr printf_str
// printf("\nvera layer 1 config = %x\n", config)
ldy #HEXADECIMAL
jsr printf_uchar
// printf("\nvera layer 1 config = %x\n", config)
lda #<cputc
sta.z printf_str.putc
lda #>cputc
sta.z printf_str.putc+1
lda #<s4
sta.z printf_str.s
lda #>s4
sta.z printf_str.s+1
jsr printf_str
// *VERA_DC_VIDEO & vera_layer_enable[layer]
lda VERA_DC_VIDEO
and vera_layer_enable+vera_layer_is_visible1_layer
sta.z vera_layer_is_visible1_return
// printf("vera layer 1 shown = %c\n", layershown)
lda #<cputc
sta.z printf_str.putc
lda #>cputc
sta.z printf_str.putc+1
lda #<s9
sta.z printf_str.s
lda #>s9
sta.z printf_str.s+1
jsr printf_str
// printf("vera layer 1 shown = %c\n", layershown)
lda.z vera_layer_is_visible1_return
pha
jsr cputc
pla
lda #<cputc
sta.z printf_str.putc
lda #>cputc
sta.z printf_str.putc+1
lda #<s4
sta.z printf_str.s
lda #>s4
sta.z printf_str.s+1
jsr printf_str
// unsigned byte mapbase = vera_layer_get_mapbase(1)
lda #1
jsr vera_layer_get_mapbase
// unsigned byte mapbase = vera_layer_get_mapbase(1)
sta.z mapbase
// unsigned byte tilebase = vera_layer_get_tilebase(1)
lda #1
jsr vera_layer_get_tilebase
// unsigned byte tilebase = vera_layer_get_tilebase(1)
sta.z tilebase
// printf("vera layer 1 mapbase = %hhx, tilebase = %hhx\n", mapbase, tilebase)
lda #<cputc
sta.z printf_str.putc
lda #>cputc
sta.z printf_str.putc+1
lda #<s11
sta.z printf_str.s
lda #>s11
sta.z printf_str.s+1
jsr printf_str
// printf("vera layer 1 mapbase = %hhx, tilebase = %hhx\n", mapbase, tilebase)
ldy #HEXADECIMAL
jsr printf_uchar
// printf("vera layer 1 mapbase = %hhx, tilebase = %hhx\n", mapbase, tilebase)
lda #<cputc
sta.z printf_str.putc
lda #>cputc
sta.z printf_str.putc+1
lda #<s12
sta.z printf_str.s
lda #>s12
sta.z printf_str.s+1
jsr printf_str
// printf("vera layer 1 mapbase = %hhx, tilebase = %hhx\n", mapbase, tilebase)
lda.z tilebase
sta.z printf_uchar.uvalue
ldy #HEXADECIMAL
jsr printf_uchar
// printf("vera layer 1 mapbase = %hhx, tilebase = %hhx\n", mapbase, tilebase)
lda #<cputc
sta.z printf_str.putc
lda #>cputc
sta.z printf_str.putc+1
lda #<s4
sta.z printf_str.s
lda #>s4
sta.z printf_str.s+1
jsr printf_str
// vera_layer_set_textcolor(conio_screen_layer, color)
ldx.z conio_screen_layer
lda #YELLOW
jsr vera_layer_set_textcolor
// printf("press a key")
lda #<cputc
sta.z printf_str.putc
lda #>cputc
sta.z printf_str.putc+1
lda #<s
sta.z printf_str.s
lda #>s
sta.z printf_str.s+1
jsr printf_str
__b3:
// kbhit()
jsr kbhit
// while(!kbhit())
cmp #0
beq __b3
lda.z CONIO_SCREEN_TEXT_1
sta.z CONIO_SCREEN_TEXT
lda.z CONIO_SCREEN_TEXT_1+1
sta.z CONIO_SCREEN_TEXT+1
// clearline()
jsr clearline
// vera_layer_set_mapbase(0,0x80)
// Now we continue with demonstrating the layering!
// We set the mapbase of layer 0 to an address in VRAM.
// We copy the tilebase address from layer 1, so that we reference to the same tilebase.
// We print a text on layer 0, which of course, won't yet be displayed,
// because we haven't activated layer 0 on the VERA.
// But the text will be printed and awaiting to be displayer later, once we activate layer 0!
// But first, we also print the layer 0 VERA configuration.
// This statement sets the base of the display layer 1 at VRAM address 0x0200
ldx #$80
lda #0
jsr vera_layer_set_mapbase
// vera_layer_get_config(1)
lda #1
jsr vera_layer_get_config
// vera_layer_get_config(1)
// vera_layer_set_config(0, vera_layer_get_config(1))
tax
// Set the map base to address 0x10000 in VERA VRAM!
lda #0
jsr vera_layer_set_config
// vera_layer_get_tilebase(1)
lda #1
jsr vera_layer_get_tilebase
// vera_layer_get_tilebase(1)
// vera_layer_set_tilebase(0, vera_layer_get_tilebase(1))
tax
lda #0
jsr vera_layer_set_tilebase
// vera_layer_set_textcolor(conio_screen_layer, color)
ldx.z conio_screen_layer
lda #WHITE
jsr vera_layer_set_textcolor
// vera_layer_get_config(0)
lda #0
jsr vera_layer_get_config
// vera_layer_get_config(0)
lda #0
jsr vera_layer_get_config
// vera_layer_get_config(0)
// printf("\nvera layer 0 config = %x\n", vera_layer_get_config(0))
sta.z printf_uchar.uvalue
lda #<cputc
sta.z printf_str.putc
lda #>cputc
sta.z printf_str.putc+1
lda #<s15
sta.z printf_str.s
lda #>s15
sta.z printf_str.s+1
jsr printf_str
// printf("\nvera layer 0 config = %x\n", vera_layer_get_config(0))
ldy #HEXADECIMAL
jsr printf_uchar
// printf("\nvera layer 0 config = %x\n", vera_layer_get_config(0))
lda #<cputc
sta.z printf_str.putc
lda #>cputc
sta.z printf_str.putc+1
lda #<s4
sta.z printf_str.s
lda #>s4
sta.z printf_str.s+1
jsr printf_str
// *VERA_DC_VIDEO & vera_layer_enable[layer]
lda VERA_DC_VIDEO
and vera_layer_enable
sta.z vera_layer_is_visible2_return
// printf("vera layer 0 shown = %x\n", layershown)
lda #<cputc
sta.z printf_str.putc
lda #>cputc
sta.z printf_str.putc+1
lda #<s17
sta.z printf_str.s
lda #>s17
sta.z printf_str.s+1
jsr printf_str
// printf("vera layer 0 shown = %x\n", layershown)
ldy #HEXADECIMAL
jsr printf_uchar
// printf("vera layer 0 shown = %x\n", layershown)
lda #<cputc
sta.z printf_str.putc
lda #>cputc
sta.z printf_str.putc+1
lda #<s4
sta.z printf_str.s
lda #>s4
sta.z printf_str.s+1
jsr printf_str
// vera_layer_get_mapbase(0)
lda #0
jsr vera_layer_get_mapbase
// vera_layer_get_mapbase(0)
// mapbase = vera_layer_get_mapbase(0)
sta.z mapbase
// vera_layer_get_tilebase(0)
lda #0
jsr vera_layer_get_tilebase
// vera_layer_get_tilebase(0)
// tilebase = vera_layer_get_tilebase(0)
sta.z tilebase_1
// printf("vera layer 0 mapbase = %x, tilebase = %x\n", mapbase, tilebase)
lda #<cputc
sta.z printf_str.putc
lda #>cputc
sta.z printf_str.putc+1
lda #<s19
sta.z printf_str.s
lda #>s19
sta.z printf_str.s+1
jsr printf_str
// printf("vera layer 0 mapbase = %x, tilebase = %x\n", mapbase, tilebase)
ldy #HEXADECIMAL
jsr printf_uchar
// printf("vera layer 0 mapbase = %x, tilebase = %x\n", mapbase, tilebase)
lda #<cputc
sta.z printf_str.putc
lda #>cputc
sta.z printf_str.putc+1
lda #<s12
sta.z printf_str.s
lda #>s12
sta.z printf_str.s+1
jsr printf_str
// printf("vera layer 0 mapbase = %x, tilebase = %x\n", mapbase, tilebase)
lda.z tilebase_1
sta.z printf_uchar.uvalue
ldy #HEXADECIMAL
jsr printf_uchar
// printf("vera layer 0 mapbase = %x, tilebase = %x\n", mapbase, tilebase)
lda #<cputc
sta.z printf_str.putc
lda #>cputc
sta.z printf_str.putc+1
lda #<s4
sta.z printf_str.s
lda #>s4
sta.z printf_str.s+1
jsr printf_str
// screenlayer(0)
// Now we print the layer 0 text on the layer 0!
lda #0
jsr screenlayer
// vera_layer_set_textcolor(conio_screen_layer, color)
ldx.z conio_screen_layer
lda #BLUE
jsr vera_layer_set_textcolor
// vera_layer_set_backcolor(conio_screen_layer, color)
ldx.z conio_screen_layer
lda #BLACK
jsr vera_layer_set_backcolor
// clrscr()
jsr clrscr
// vera_layer_set_backcolor(conio_screen_layer, color)
ldx.z conio_screen_layer
lda #WHITE
jsr vera_layer_set_backcolor
// gotoxy(19,4)
ldy #$13
ldx #4
jsr gotoxy
// printf(" ")
lda #<cputc
sta.z printf_str.putc
lda #>cputc
sta.z printf_str.putc+1
lda #<s22
sta.z printf_str.s
lda #>s22
sta.z printf_str.s+1
jsr printf_str
// gotoxy(19,5)
ldy #$13
ldx #5
jsr gotoxy
// printf(" this is printed on layer 0 !!! ")
lda #<cputc
sta.z printf_str.putc
lda #>cputc
sta.z printf_str.putc+1
lda #<s23
sta.z printf_str.s
lda #>s23
sta.z printf_str.s+1
jsr printf_str
// gotoxy(19,6)
ldy #$13
ldx #6
jsr gotoxy
// printf(" ")
lda #<cputc
sta.z printf_str.putc
lda #>cputc
sta.z printf_str.putc+1
lda #<s22
sta.z printf_str.s
lda #>s22
sta.z printf_str.s+1
jsr printf_str
// screenlayer(1)
lda #1
jsr screenlayer
// vera_layer_set_textcolor(conio_screen_layer, color)
ldx.z conio_screen_layer
lda #YELLOW
jsr vera_layer_set_textcolor
// vera_layer_set_backcolor(conio_screen_layer, color)
ldx.z conio_screen_layer
lda #BLACK
jsr vera_layer_set_backcolor
// printf("press a key to show layer 0 and show the text!")
lda #<cputc
sta.z printf_str.putc
lda #>cputc
sta.z printf_str.putc+1
lda #<s25
sta.z printf_str.s
lda #>s25
sta.z printf_str.s+1
jsr printf_str
__b5:
// kbhit()
jsr kbhit
// while(!kbhit())
cmp #0
beq __b5
lda.z CONIO_SCREEN_TEXT_1
sta.z CONIO_SCREEN_TEXT
lda.z CONIO_SCREEN_TEXT_1+1
sta.z CONIO_SCREEN_TEXT+1
// clearline()
jsr clearline
// *VERA_DC_VIDEO |= vera_layer_enable[layer]
lda VERA_DC_VIDEO
ora vera_layer_enable
sta VERA_DC_VIDEO
// vera_layer_set_textcolor(conio_screen_layer, color)
ldx.z conio_screen_layer
lda #WHITE
jsr vera_layer_set_textcolor
// vera_layer_set_backcolor(conio_screen_layer, color)
ldx.z conio_screen_layer
lda #BLACK
jsr vera_layer_set_backcolor
// *VERA_DC_VIDEO & vera_layer_enable[layer]
lda VERA_DC_VIDEO
and vera_layer_enable
sta.z vera_layer_is_visible3_return
// printf("vera layer 0 shown = %x. ", vera_layer_is_visible(0))
lda #<cputc
sta.z printf_str.putc
lda #>cputc
sta.z printf_str.putc+1
lda #<s17
sta.z printf_str.s
lda #>s17
sta.z printf_str.s+1
jsr printf_str
// printf("vera layer 0 shown = %x. ", vera_layer_is_visible(0))
ldy #HEXADECIMAL
jsr printf_uchar
// printf("vera layer 0 shown = %x. ", vera_layer_is_visible(0))
lda #<cputc
sta.z printf_str.putc
lda #>cputc
sta.z printf_str.putc+1
lda #<s27
sta.z printf_str.s
lda #>s27
sta.z printf_str.s+1
jsr printf_str
// vera_layer_set_textcolor(conio_screen_layer, color)
ldx.z conio_screen_layer
lda #YELLOW
jsr vera_layer_set_textcolor
// vera_layer_set_backcolor(conio_screen_layer, color)
ldx.z conio_screen_layer
lda #BLACK
jsr vera_layer_set_backcolor
// printf("press a key to hide layer 0 and hide the text again")
lda #<cputc
sta.z printf_str.putc
lda #>cputc
sta.z printf_str.putc+1
lda #<s28
sta.z printf_str.s
lda #>s28
sta.z printf_str.s+1
jsr printf_str
__b7:
// kbhit()
jsr kbhit
// while(!kbhit())
cmp #0
beq __b7
lda.z CONIO_SCREEN_TEXT_1
sta.z CONIO_SCREEN_TEXT
lda.z CONIO_SCREEN_TEXT_1+1
sta.z CONIO_SCREEN_TEXT+1
// clearline()
jsr clearline
// ~vera_layer_enable[layer]
lda vera_layer_enable
eor #$ff
// *VERA_DC_VIDEO &= ~vera_layer_enable[layer]
and VERA_DC_VIDEO
sta VERA_DC_VIDEO
// vera_layer_set_textcolor(conio_screen_layer, color)
ldx.z conio_screen_layer
lda #WHITE
jsr vera_layer_set_textcolor
// vera_layer_set_backcolor(conio_screen_layer, color)
ldx.z conio_screen_layer
lda #BLACK
jsr vera_layer_set_backcolor
// *VERA_DC_VIDEO & vera_layer_enable[layer]
lda VERA_DC_VIDEO
and vera_layer_enable
sta.z vera_layer_is_visible4_return
// printf("vera layer 0 shown = %x. ", vera_layer_is_visible(0))
lda #<cputc
sta.z printf_str.putc
lda #>cputc
sta.z printf_str.putc+1
lda #<s17
sta.z printf_str.s
lda #>s17
sta.z printf_str.s+1
jsr printf_str
// printf("vera layer 0 shown = %x. ", vera_layer_is_visible(0))
ldy #HEXADECIMAL
jsr printf_uchar
// printf("vera layer 0 shown = %x. ", vera_layer_is_visible(0))
lda #<cputc
sta.z printf_str.putc
lda #>cputc
sta.z printf_str.putc+1
lda #<s27
sta.z printf_str.s
lda #>s27
sta.z printf_str.s+1
jsr printf_str
// vera_layer_set_textcolor(conio_screen_layer, color)
ldx.z conio_screen_layer
lda #YELLOW
jsr vera_layer_set_textcolor
// vera_layer_set_backcolor(conio_screen_layer, color)
ldx.z conio_screen_layer
lda #BLACK
jsr vera_layer_set_backcolor
// printf("press a key to finish")
lda #<cputc
sta.z printf_str.putc
lda #>cputc
sta.z printf_str.putc+1
lda #<s31
sta.z printf_str.s
lda #>s31
sta.z printf_str.s+1
jsr printf_str
__b9:
// kbhit()
jsr kbhit
// while(!kbhit())
cmp #0
beq __b9
lda.z CONIO_SCREEN_TEXT_1
sta.z CONIO_SCREEN_TEXT
lda.z CONIO_SCREEN_TEXT_1+1
sta.z CONIO_SCREEN_TEXT+1
// clearline()
jsr clearline
// clrscr()
jsr clrscr
// vera_layer_set_textcolor(conio_screen_layer, color)
ldx.z conio_screen_layer
lda #RED
jsr vera_layer_set_textcolor
// vera_layer_set_backcolor(conio_screen_layer, color)
ldx.z conio_screen_layer
lda #WHITE
jsr vera_layer_set_backcolor
// gotoxy(19,10)
ldy #$13
ldx #$a
jsr gotoxy
// printf(" ")
lda #<cputc
sta.z printf_str.putc
lda #>cputc
sta.z printf_str.putc+1
lda #<s32
sta.z printf_str.s
lda #>s32
sta.z printf_str.s+1
jsr printf_str
// gotoxy(19,11)
ldy #$13
ldx #$b
jsr gotoxy
// printf(" analyze the code and learn! ")
lda #<cputc
sta.z printf_str.putc
lda #>cputc
sta.z printf_str.putc+1
lda #<s33
sta.z printf_str.s
lda #>s33
sta.z printf_str.s+1
jsr printf_str
// gotoxy(19,12)
ldy #$13
ldx #$c
jsr gotoxy
// printf(" ")
lda #<cputc
sta.z printf_str.putc
lda #>cputc
sta.z printf_str.putc+1
lda #<s32
sta.z printf_str.s
lda #>s32
sta.z printf_str.s+1
jsr printf_str
// }
rts
.segment Data
s: .text "press a key"
.byte 0
s1: .text @"this program demonstrates the layer functionality in text mode.\n"
.byte 0
s2: .text @"\nvera card width = "
.byte 0
s3: .text "; height = "
.byte 0
s4: .text @"\n"
.byte 0
s5: .text @"\nvera dc video = "
.byte 0
s7: .text @"\nvera layer 1 config = "
.byte 0
s9: .text "vera layer 1 shown = "
.byte 0
s11: .text "vera layer 1 mapbase = "
.byte 0
s12: .text ", tilebase = "
.byte 0
s15: .text @"\nvera layer 0 config = "
.byte 0
s17: .text "vera layer 0 shown = "
.byte 0
s19: .text "vera layer 0 mapbase = "
.byte 0
s22: .text " "
.byte 0
s23: .text " this is printed on layer 0 !!! "
.byte 0
s25: .text "press a key to show layer 0 and show the text!"
.byte 0
s27: .text ". "
.byte 0
s28: .text "press a key to hide layer 0 and hide the text again"
.byte 0
s31: .text "press a key to finish"
.byte 0
s32: .text " "
.byte 0
s33: .text " analyze the code and learn! "
.byte 0
}
.segment Code
// Set a vera layer in text mode and configure the:
// - layer: Value of 0 or 1.
// - mapbase_address: A dword typed address (4 bytes), that specifies the full address of the map base.
// The function does the translation from the dword that contains the 17 bit address,
// to the respective mapbase vera register.
// Note that the register only specifies bits 16:9 of the address,
// so the resulting address in the VERA VRAM is always aligned to a multiple of 512 bytes.
// - tilebase_address: A dword typed address (4 bytes), that specifies the base address of the tile map.
// The function does the translation from the dword that contains the 17 bit address,
// to the respective tilebase vera register.
// Note that the resulting vera register holds only specifies bits 16:11 of the address,
// so the resulting address in the VERA VRAM is always aligned to a multiple of 2048 bytes!
// - mapwidth: The width of the map in number of tiles.
// - mapheight: The height of the map in number of tiles.
// - tilewidth: The width of a tile, which can be 8 or 16 pixels.
// - tileheight: The height of a tile, which can be 8 or 16 pixels.
// - color_mode: The color mode, which can be 16 or 256.
// void vera_layer_mode_text(char layer, unsigned long mapbase_address, unsigned long tilebase_address, unsigned int mapwidth, unsigned int mapheight, char tilewidth, char tileheight, unsigned int color_mode)
vera_layer_mode_text: {
.label layer = 1
.label mapbase_address = 0
.label tilebase_address = $f800
// vera_layer_mode_tile( layer, mapbase_address, tilebase_address, mapwidth, mapheight, tilewidth, tileheight, 1 )
jsr vera_layer_mode_tile
// vera_layer_set_text_color_mode( layer, VERA_LAYER_CONFIG_16C )
jsr vera_layer_set_text_color_mode
// }
rts
}
// Return the current screen size.
// void screensize(char *x, char *y)
screensize: {
.label x = conio_screen_width
.label y = conio_screen_height
// char hscale = (*VERA_DC_HSCALE) >> 7
// VERA returns in VERA_DC_HSCALE the value of 128 when 80 columns is used in text mode,
// and the value of 64 when 40 columns is used in text mode.
// Basically, 40 columns mode in the VERA is a double scan mode.
// Same for the VERA_DC_VSCALE mode, but then the subdivision is 60 or 30 rows.
// I still need to test the other modes, but this will suffice for now for the pure text modes.
lda VERA_DC_HSCALE
rol
rol
and #1
// 40 << hscale
tay
lda #$28
cpy #0
beq !e+
!:
asl
dey
bne !-
!e:
// *x = 40 << hscale
sta.z x
// char vscale = (*VERA_DC_VSCALE) >> 7
lda VERA_DC_VSCALE
rol
rol
and #1
// 30 << vscale
tay
lda #$1e
cpy #0
beq !e+
!:
asl
dey
bne !-
!e:
// *y = 30 << vscale
sta.z y
// }
rts
}
// Set the layer with which the conio will interact.
// - layer: value of 0 or 1.
// void screenlayer(__register(A) char layer)
screenlayer: {
.label __2 = $20
.label __4 = $1e
.label __5 = $29
.label vera_layer_get_width1_config = $2d
.label vera_layer_get_width1_return = $20
.label vera_layer_get_height1_config = $22
.label vera_layer_get_height1_return = $29
// conio_screen_layer = layer
sta.z conio_screen_layer
// vera_layer_get_mapbase_bank(conio_screen_layer)
tax
jsr vera_layer_get_mapbase_bank
sta.z CONIO_SCREEN_BANK_1
// vera_layer_get_mapbase_offset(conio_screen_layer)
lda.z conio_screen_layer
jsr vera_layer_get_mapbase_offset
lda.z vera_layer_get_mapbase_offset.return
sta.z CONIO_SCREEN_TEXT_1
lda.z vera_layer_get_mapbase_offset.return+1
sta.z CONIO_SCREEN_TEXT_1+1
// vera_layer_get_width(conio_screen_layer)
lda.z conio_screen_layer
// byte* config = vera_layer_config[layer]
asl
tay
lda vera_layer_config,y
sta.z vera_layer_get_width1_config
lda vera_layer_config+1,y
sta.z vera_layer_get_width1_config+1
// *config & VERA_LAYER_WIDTH_MASK
lda #VERA_LAYER_WIDTH_MASK
ldy #0
and (vera_layer_get_width1_config),y
// (*config & VERA_LAYER_WIDTH_MASK) >> 4
lsr
lsr
lsr
lsr
// return VERA_LAYER_WIDTH[ (*config & VERA_LAYER_WIDTH_MASK) >> 4];
asl
tay
lda VERA_LAYER_WIDTH,y
sta.z vera_layer_get_width1_return
lda VERA_LAYER_WIDTH+1,y
sta.z vera_layer_get_width1_return+1
// }
// vera_layer_get_width(conio_screen_layer)
// conio_width = vera_layer_get_width(conio_screen_layer)
lda.z __2
sta.z conio_width
lda.z __2+1
sta.z conio_width+1
// vera_layer_get_rowshift(conio_screen_layer)
ldx.z conio_screen_layer
jsr vera_layer_get_rowshift
// conio_rowshift = vera_layer_get_rowshift(conio_screen_layer)
sta.z conio_rowshift
// vera_layer_get_rowskip(conio_screen_layer)
lda.z conio_screen_layer
jsr vera_layer_get_rowskip
// conio_rowskip = vera_layer_get_rowskip(conio_screen_layer)
lda.z __4
sta.z conio_rowskip
lda.z __4+1
sta.z conio_rowskip+1
// vera_layer_get_height(conio_screen_layer)
lda.z conio_screen_layer
// byte* config = vera_layer_config[layer]
asl
tay
lda vera_layer_config,y
sta.z vera_layer_get_height1_config
lda vera_layer_config+1,y
sta.z vera_layer_get_height1_config+1
// *config & VERA_LAYER_HEIGHT_MASK
lda #VERA_LAYER_HEIGHT_MASK
ldy #0
and (vera_layer_get_height1_config),y
// (*config & VERA_LAYER_HEIGHT_MASK) >> 6
rol
rol
rol
and #3
// return VERA_LAYER_HEIGHT[ (*config & VERA_LAYER_HEIGHT_MASK) >> 6];
asl
tay
lda VERA_LAYER_HEIGHT,y
sta.z vera_layer_get_height1_return
lda VERA_LAYER_HEIGHT+1,y
sta.z vera_layer_get_height1_return+1
// }
// vera_layer_get_height(conio_screen_layer)
// conio_height = vera_layer_get_height(conio_screen_layer)
lda.z __5
sta.z conio_height
lda.z __5+1
sta.z conio_height+1
// }
rts
}
// Set the front color for text output. The old front text color setting is returned.
// - layer: Value of 0 or 1.
// - color: a 4 bit value ( decimal between 0 and 15) when the VERA works in 16x16 color text mode.
// An 8 bit value (decimal between 0 and 255) when the VERA works in 256 text mode.
// Note that on the VERA, the transparent color has value 0.
// char vera_layer_set_textcolor(__register(X) char layer, __register(A) char color)
vera_layer_set_textcolor: {
// vera_layer_textcolor[layer] = color
sta vera_layer_textcolor,x
// }
rts
}
// Set the back color for text output. The old back text color setting is returned.
// - layer: Value of 0 or 1.
// - color: a 4 bit value ( decimal between 0 and 15).
// This will only work when the VERA is in 16 color mode!
// Note that on the VERA, the transparent color has value 0.
// char vera_layer_set_backcolor(__register(X) char layer, __register(A) char color)
vera_layer_set_backcolor: {
// vera_layer_backcolor[layer] = color
sta vera_layer_backcolor,x
// }
rts
}
// Set the base of the map layer with which the conio will interact.
// - layer: Value of 0 or 1.
// - mapbase: Specifies the base address of the tile map.
// Note that the register only specifies bits 16:9 of the address,
// so the resulting address in the VERA VRAM is always aligned to a multiple of 512 bytes.
// void vera_layer_set_mapbase(__register(A) char layer, __register(X) char mapbase)
vera_layer_set_mapbase: {
.label addr = $20
// byte* addr = vera_layer_mapbase[layer]
asl
tay
lda vera_layer_mapbase,y
sta.z addr
lda vera_layer_mapbase+1,y
sta.z addr+1
// *addr = mapbase
txa
ldy #0
sta (addr),y
// }
rts
}
// Set the cursor to the specified position
// void gotoxy(__register(Y) char x, __register(X) char y)
gotoxy: {
.label __6 = $c
.label line_offset = $c
// if(y>CONIO_HEIGHT)
lda.z conio_screen_height
stx.z $ff
cmp.z $ff
bcs __b1
ldx #0
__b1:
// if(x>=CONIO_WIDTH)
cpy.z conio_screen_width
bcc __b2
ldy #0
__b2:
// conio_cursor_x[conio_screen_layer] = x
tya
ldy.z conio_screen_layer
sta conio_cursor_x,y
// conio_cursor_y[conio_screen_layer] = y
txa
sta conio_cursor_y,y
// unsigned int line_offset = (unsigned int)y << conio_rowshift
txa
sta.z __6
lda #0
sta.z __6+1
ldy.z conio_rowshift
beq !e+
!:
asl.z line_offset
rol.z line_offset+1
dey
bne !-
!e:
// conio_line_text[conio_screen_layer] = line_offset
lda.z conio_screen_layer
asl
tay
lda.z line_offset
sta conio_line_text,y
lda.z line_offset+1
sta conio_line_text+1,y
// }
rts
}
// Get the text and back color for text output in 16 color mode.
// - layer: Value of 0 or 1.
// - return: an 8 bit value with bit 7:4 containing the back color and bit 3:0 containing the front color.
// This will only work when the VERA is in 16 color mode!
// Note that on the VERA, the transparent color has value 0.
// __register(A) char vera_layer_get_color(__register(X) char layer)
vera_layer_get_color: {
.label addr = 6
// byte* addr = vera_layer_config[layer]
txa
asl
tay
lda vera_layer_config,y
sta.z addr
lda vera_layer_config+1,y
sta.z addr+1
// *addr & VERA_LAYER_CONFIG_256C
lda #VERA_LAYER_CONFIG_256C
ldy #0
and (addr),y
// if( *addr & VERA_LAYER_CONFIG_256C )
cmp #0
bne __b1
// vera_layer_backcolor[layer] << 4
lda vera_layer_backcolor,x
asl
asl
asl
asl
// return ((vera_layer_backcolor[layer] << 4) | vera_layer_textcolor[layer]);
ora vera_layer_textcolor,x
// }
rts
__b1:
// return (vera_layer_textcolor[layer]);
lda vera_layer_textcolor,x
rts
}
// Print a newline
cputln: {
.label temp = 6
// word temp = conio_line_text[conio_screen_layer]
lda.z conio_screen_layer
asl
// TODO: This needs to be optimized! other variations don't compile because of sections not available!
tay
lda conio_line_text,y
sta.z temp
lda conio_line_text+1,y
sta.z temp+1
// temp += conio_rowskip
clc
lda.z temp
adc.z conio_rowskip
sta.z temp
lda.z temp+1
adc.z conio_rowskip+1
sta.z temp+1
// conio_line_text[conio_screen_layer] = temp
lda.z conio_screen_layer
asl
tay
lda.z temp
sta conio_line_text,y
lda.z temp+1
sta conio_line_text+1,y
// conio_cursor_x[conio_screen_layer] = 0
lda #0
ldy.z conio_screen_layer
sta conio_cursor_x,y
// conio_cursor_y[conio_screen_layer]++;
ldx.z conio_screen_layer
inc conio_cursor_y,x
// cscroll()
jsr cscroll
// }
rts
}
// clears the screen and moves the cursor to the upper left-hand corner of the screen.
clrscr: {
.label __1 = $1d
.label line_text = $1a
.label color = $1d
// char* line_text = CONIO_SCREEN_TEXT
lda.z CONIO_SCREEN_TEXT_1
sta.z line_text
lda.z CONIO_SCREEN_TEXT_1+1
sta.z line_text+1
// vera_layer_get_backcolor(conio_screen_layer)
ldx.z conio_screen_layer
jsr vera_layer_get_backcolor
// vera_layer_get_backcolor(conio_screen_layer) << 4
asl
asl
asl
asl
sta.z __1
// vera_layer_get_textcolor(conio_screen_layer)
ldx.z conio_screen_layer
jsr vera_layer_get_textcolor
// char color = ( vera_layer_get_backcolor(conio_screen_layer) << 4 ) | vera_layer_get_textcolor(conio_screen_layer)
ora.z color
sta.z color
ldx #0
__b1:
// for( char l=0;l<conio_height; l++ )
lda.z conio_height+1
bne __b2
cpx.z conio_height
bcc __b2
// conio_cursor_x[conio_screen_layer] = 0
lda #0
ldy.z conio_screen_layer
sta conio_cursor_x,y
// conio_cursor_y[conio_screen_layer] = 0
sta conio_cursor_y,y
// conio_line_text[conio_screen_layer] = 0
tya
asl
tay
lda #0
sta conio_line_text,y
sta conio_line_text+1,y
// }
rts
__b2:
// *VERA_CTRL &= ~VERA_ADDRSEL
// Select DATA0
lda #VERA_ADDRSEL^$ff
and VERA_CTRL
sta VERA_CTRL
// BYTE0(ch)
lda.z line_text
// *VERA_ADDRX_L = BYTE0(ch)
// Set address
sta VERA_ADDRX_L
// BYTE1(ch)
lda.z line_text+1
// *VERA_ADDRX_M = BYTE1(ch)
sta VERA_ADDRX_M
// CONIO_SCREEN_BANK | VERA_INC_1
lda #VERA_INC_1
ora.z CONIO_SCREEN_BANK_1
// *VERA_ADDRX_H = CONIO_SCREEN_BANK | VERA_INC_1
sta VERA_ADDRX_H
ldy #0
__b4:
// for( char c=0;c<conio_width; c++ )
lda.z conio_width+1
bne __b5
cpy.z conio_width
bcc __b5
// line_text += conio_rowskip
clc
lda.z line_text
adc.z conio_rowskip
sta.z line_text
lda.z line_text+1
adc.z conio_rowskip+1
sta.z line_text+1
// for( char l=0;l<conio_height; l++ )
inx
jmp __b1
__b5:
// *VERA_DATA0 = ' '
lda #' '
sta VERA_DATA0
// *VERA_DATA0 = color
lda.z color
sta VERA_DATA0
// for( char c=0;c<conio_width; c++ )
iny
jmp __b4
}
/// Print a NUL-terminated string
// void printf_str(__zp($1a) void (*putc)(char), __zp($18) const char *s)
printf_str: {
.label s = $18
.label putc = $1a
__b1:
// while(c=*s++)
ldy #0
lda (s),y
inc.z s
bne !+
inc.z s+1
!:
cmp #0
bne __b2
// }
rts
__b2:
// putc(c)
pha
jsr icall2
pla
jmp __b1
icall2:
jmp (putc)
}
// Return true if there's a key waiting, return false if not
kbhit: {
.label chptr = ch
.label IN_DEV = $28a
// Current input device number
.label GETIN = $ffe4
.label ch = $2c
// char ch = 0
lda #0
sta.z ch
// kickasm
// CBM GETIN API
jsr _kbhit
bne L3
jmp continue1
.var via1 = $9f60 //VIA#1
.var d1pra = via1+1
_kbhit:
ldy d1pra // The count of keys pressed is stored in RAM bank 0.
stz d1pra // Set d1pra to zero to access RAM bank 0.
lda $A00A // Get number of characters from this address in the ROM of the CX16 (ROM 38).
sty d1pra // Set d1pra to previous value.
rts
L3:
ldy IN_DEV // Save current input device
stz IN_DEV // Keyboard
phy
jsr GETIN // Read char, and return in .A
ply
sta chptr // Store the character read in ch
sty IN_DEV // Restore input device
ldx #>$0000
rts
continue1:
nop
// return ch;
lda.z ch
// }
rts
}
clearline: {
.label addr = 8
.label c = 2
// *VERA_CTRL &= ~VERA_ADDRSEL
// Select DATA0
lda #VERA_ADDRSEL^$ff
and VERA_CTRL
sta VERA_CTRL
// byte* addr = CONIO_SCREEN_TEXT + conio_line_text[conio_screen_layer]
lda.z conio_screen_layer
asl
// Set address
tay
clc
lda.z CONIO_SCREEN_TEXT
adc conio_line_text,y
sta.z addr
lda.z CONIO_SCREEN_TEXT+1
adc conio_line_text+1,y
sta.z addr+1
// BYTE0(addr)
lda.z addr
// *VERA_ADDRX_L = BYTE0(addr)
sta VERA_ADDRX_L
// BYTE1(addr)
lda.z addr+1
// *VERA_ADDRX_M = BYTE1(addr)
sta VERA_ADDRX_M
// *VERA_ADDRX_H = VERA_INC_1
lda #VERA_INC_1
sta VERA_ADDRX_H
// char color = vera_layer_get_color( conio_screen_layer)
ldx.z conio_screen_layer
jsr vera_layer_get_color
// char color = vera_layer_get_color( conio_screen_layer)
tax
lda #<0
sta.z c
sta.z c+1
__b1:
// for( unsigned int c=0;c<CONIO_WIDTH; c++ )
lda.z c+1
bne !+
lda.z c
cmp.z conio_screen_width
bcc __b2
!:
// conio_cursor_x[conio_screen_layer] = 0
lda #0
ldy.z conio_screen_layer
sta conio_cursor_x,y
// }
rts
__b2:
// *VERA_DATA0 = ' '
// Set data
lda #' '
sta VERA_DATA0
// *VERA_DATA0 = color
stx VERA_DATA0
// for( unsigned int c=0;c<CONIO_WIDTH; c++ )
inc.z c
bne !+
inc.z c+1
!:
jmp __b1
}
// Print an unsigned char using a specific format
// void printf_uchar(void (*putc)(char), __zp($31) char uvalue, char format_min_length, char format_justify_left, char format_sign_always, char format_zero_padding, char format_upper_case, __register(Y) char format_radix)
printf_uchar: {
.label uvalue = $31
// printf_buffer.sign = format.sign_always?'+':0
// Handle any sign
lda #0
sta printf_buffer
// uctoa(uvalue, printf_buffer.digits, format.radix)
ldx.z uvalue
// Format number into buffer
jsr uctoa
// printf_number_buffer(putc, printf_buffer, format)
lda printf_buffer
// Print using format
jsr printf_number_buffer
// }
rts
}
// Get the configuration of the layer.
// - layer: Value of 0 or 1.
// - return: Specifies the modes which are specified using T256C / 'Bitmap Mode' / 'Color Depth'.
// __register(A) char vera_layer_get_config(__register(A) char layer)
vera_layer_get_config: {
.label config = $1a
// byte* config = vera_layer_config[layer]
asl
tay
lda vera_layer_config,y
sta.z config
lda vera_layer_config+1,y
sta.z config+1
// return *config;
ldy #0
lda (config),y
// }
rts
}
// Get the base of the map layer with which the conio will interact.
// - layer: Value of 0 or 1.
// - return: Returns the base address of the tile map.
// Note that the register is a byte, specifying only bits 16:9 of the address,
// so the resulting address in the VERA VRAM is always aligned to a multiple of 512 bytes.
// __register(A) char vera_layer_get_mapbase(__register(A) char layer)
vera_layer_get_mapbase: {
.label mapbase = $18
// byte* mapbase = vera_layer_mapbase[layer]
asl
tay
lda vera_layer_mapbase,y
sta.z mapbase
lda vera_layer_mapbase+1,y
sta.z mapbase+1
// return *mapbase;
ldy #0
lda (mapbase),y
// }
rts
}
// Get the base of the tiles for the layer with which the conio will interact.
// - layer: Value of 0 or 1.
// - return: Specifies the base address of the tile map.
// Note that the register only specifies bits 16:11 of the address,
// so the resulting address in the VERA VRAM is always aligned to a multiple of 2048 bytes!
// __register(A) char vera_layer_get_tilebase(__register(A) char layer)
vera_layer_get_tilebase: {
.label tilebase = $18
// byte* tilebase = vera_layer_tilebase[layer]
asl
tay
lda vera_layer_tilebase,y
sta.z tilebase
lda vera_layer_tilebase+1,y
sta.z tilebase+1
// return *tilebase;
ldy #0
lda (tilebase),y
// }
rts
}
// Set the configuration of the layer.
// - layer: Value of 0 or 1.
// - config: Specifies the modes which are specified using T256C / 'Bitmap Mode' / 'Color Depth'.
// void vera_layer_set_config(__register(A) char layer, __register(X) char config)
vera_layer_set_config: {
.label addr = $1e
// byte* addr = vera_layer_config[layer]
asl
tay
lda vera_layer_config,y
sta.z addr
lda vera_layer_config+1,y
sta.z addr+1
// *addr = config
txa
ldy #0
sta (addr),y
// }
rts
}
// Set the base of the tiles for the layer with which the conio will interact.
// - layer: Value of 0 or 1.
// - tilebase: Specifies the base address of the tile map.
// Note that the register only specifies bits 16:11 of the address,
// so the resulting address in the VERA VRAM is always aligned to a multiple of 2048 bytes!
// void vera_layer_set_tilebase(__register(A) char layer, __register(X) char tilebase)
vera_layer_set_tilebase: {
.label addr = $22
// byte* addr = vera_layer_tilebase[layer]
asl
tay
lda vera_layer_tilebase,y
sta.z addr
lda vera_layer_tilebase+1,y
sta.z addr+1
// *addr = tilebase
txa
ldy #0
sta (addr),y
// }
rts
}
// Set a vera layer in tile mode and configure the:
// - layer: Value of 0 or 1.
// - mapbase_address: A dword typed address (4 bytes), that specifies the full address of the map base.
// The function does the translation from the dword that contains the 17 bit address,
// to the respective mapbase vera register.
// Note that the register only specifies bits 16:9 of the address,
// so the resulting address in the VERA VRAM is always aligned to a multiple of 512 bytes.
// - tilebase_address: A dword typed address (4 bytes), that specifies the base address of the tile map.
// The function does the translation from the dword that contains the 17 bit address,
// to the respective tilebase vera register.
// Note that the resulting vera register holds only specifies bits 16:11 of the address,
// so the resulting address in the VERA VRAM is always aligned to a multiple of 2048 bytes!
// - mapwidth: The width of the map in number of tiles.
// - mapheight: The height of the map in number of tiles.
// - tilewidth: The width of a tile, which can be 8 or 16 pixels.
// - tileheight: The height of a tile, which can be 8 or 16 pixels.
// - color_depth: The color depth in bits per pixel (BPP), which can be 1, 2, 4 or 8.
// void vera_layer_mode_tile(char layer, unsigned long mapbase_address, unsigned long tilebase_address, unsigned int mapwidth, unsigned int mapheight, char tilewidth, char tileheight, char color_depth)
vera_layer_mode_tile: {
.const tilebase_address = vera_layer_mode_text.tilebase_address>>1
.const mapbase = 0
// config
.const config = VERA_LAYER_WIDTH_128|VERA_LAYER_HEIGHT_64
// vera_layer_rowshift[layer] = 8
lda #8
sta vera_layer_rowshift+vera_layer_mode_text.layer
// vera_layer_rowskip[layer] = 256
lda #<$100
sta vera_layer_rowskip+vera_layer_mode_text.layer*SIZEOF_UNSIGNED_INT
lda #>$100
sta vera_layer_rowskip+vera_layer_mode_text.layer*SIZEOF_UNSIGNED_INT+1
// vera_layer_set_config(layer, config)
ldx #config
lda #vera_layer_mode_text.layer
jsr vera_layer_set_config
// vera_mapbase_offset[layer] = WORD0(mapbase_address)
// mapbase
lda #<0
sta vera_mapbase_offset+vera_layer_mode_text.layer*SIZEOF_UNSIGNED_INT
sta vera_mapbase_offset+vera_layer_mode_text.layer*SIZEOF_UNSIGNED_INT+1
// vera_mapbase_bank[layer] = BYTE2(mapbase_address)
sta vera_mapbase_bank+vera_layer_mode_text.layer
// vera_mapbase_address[layer] = mapbase_address
lda #<vera_layer_mode_text.mapbase_address
sta vera_mapbase_address+vera_layer_mode_text.layer*SIZEOF_UNSIGNED_LONG
lda #>vera_layer_mode_text.mapbase_address
sta vera_mapbase_address+vera_layer_mode_text.layer*SIZEOF_UNSIGNED_LONG+1
lda #<vera_layer_mode_text.mapbase_address>>$10
sta vera_mapbase_address+vera_layer_mode_text.layer*SIZEOF_UNSIGNED_LONG+2
lda #>vera_layer_mode_text.mapbase_address>>$10
sta vera_mapbase_address+vera_layer_mode_text.layer*SIZEOF_UNSIGNED_LONG+3
// vera_layer_set_mapbase(layer,mapbase)
ldx #mapbase
lda #vera_layer_mode_text.layer
jsr vera_layer_set_mapbase
// vera_tilebase_offset[layer] = WORD0(tilebase_address)
// tilebase
lda #<vera_layer_mode_text.tilebase_address&$ffff
sta vera_tilebase_offset+vera_layer_mode_text.layer*SIZEOF_UNSIGNED_INT
lda #>vera_layer_mode_text.tilebase_address&$ffff
sta vera_tilebase_offset+vera_layer_mode_text.layer*SIZEOF_UNSIGNED_INT+1
// vera_tilebase_bank[layer] = BYTE2(tilebase_address)
lda #0
sta vera_tilebase_bank+vera_layer_mode_text.layer
// vera_tilebase_address[layer] = tilebase_address
lda #<vera_layer_mode_text.tilebase_address
sta vera_tilebase_address+vera_layer_mode_text.layer*SIZEOF_UNSIGNED_LONG
lda #>vera_layer_mode_text.tilebase_address
sta vera_tilebase_address+vera_layer_mode_text.layer*SIZEOF_UNSIGNED_LONG+1
lda #<vera_layer_mode_text.tilebase_address>>$10
sta vera_tilebase_address+vera_layer_mode_text.layer*SIZEOF_UNSIGNED_LONG+2
lda #>vera_layer_mode_text.tilebase_address>>$10
sta vera_tilebase_address+vera_layer_mode_text.layer*SIZEOF_UNSIGNED_LONG+3
// vera_layer_set_tilebase(layer,tilebase)
ldx #(>tilebase_address)&VERA_LAYER_TILEBASE_MASK
lda #vera_layer_mode_text.layer
jsr vera_layer_set_tilebase
// }
rts
}
// Set the configuration of the layer text color mode.
// - layer: Value of 0 or 1.
// - color_mode: Specifies the color mode to be VERA_LAYER_CONFIG_16 or VERA_LAYER_CONFIG_256 for text mode.
// void vera_layer_set_text_color_mode(char layer, char color_mode)
vera_layer_set_text_color_mode: {
.label addr = $29
// byte* addr = vera_layer_config[layer]
lda vera_layer_config+vera_layer_mode_text.layer*SIZEOF_POINTER
sta.z addr
lda vera_layer_config+vera_layer_mode_text.layer*SIZEOF_POINTER+1
sta.z addr+1
// *addr &= ~VERA_LAYER_CONFIG_256C
lda #VERA_LAYER_CONFIG_256C^$ff
ldy #0
and (addr),y
sta (addr),y
// *addr |= color_mode
lda (addr),y
sta (addr),y
// }
rts
}
// Get the map base bank of the tiles for the layer.
// - layer: Value of 0 or 1.
// - return: Bank in vera vram.
// __register(A) char vera_layer_get_mapbase_bank(__register(X) char layer)
vera_layer_get_mapbase_bank: {
// return vera_mapbase_bank[layer];
lda vera_mapbase_bank,x
// }
rts
}
// Get the map base lower 16-bit address (offset) of the tiles for the layer.
// - layer: Value of 0 or 1.
// - return: Offset in vera vram of the specified bank.
// __zp($2d) unsigned int vera_layer_get_mapbase_offset(__register(A) char layer)
vera_layer_get_mapbase_offset: {
.label return = $2d
// return vera_mapbase_offset[layer];
asl
tay
lda vera_mapbase_offset,y
sta.z return
lda vera_mapbase_offset+1,y
sta.z return+1
// }
rts
}
// Get the bit shift value required to skip a whole line fast.
// - layer: Value of 0 or 1.
// - return: Rowshift value to calculate fast from a y value to line offset in tile mode.
// __register(A) char vera_layer_get_rowshift(__register(X) char layer)
vera_layer_get_rowshift: {
// return vera_layer_rowshift[layer];
lda vera_layer_rowshift,x
// }
rts
}
// Get the value required to skip a whole line fast.
// - layer: Value of 0 or 1.
// - return: Skip value to calculate fast from a y value to line offset in tile mode.
// __zp($1e) unsigned int vera_layer_get_rowskip(__register(A) char layer)
vera_layer_get_rowskip: {
.label return = $1e
// return vera_layer_rowskip[layer];
asl
tay
lda vera_layer_rowskip,y
sta.z return
lda vera_layer_rowskip+1,y
sta.z return+1
// }
rts
}
// Scroll the entire screen if the cursor is beyond the last line
cscroll: {
// if(conio_cursor_y[conio_screen_layer]>=CONIO_HEIGHT)
ldy.z conio_screen_layer
lda conio_cursor_y,y
cmp.z conio_screen_height
bcc __b3
// if(conio_scroll_enable[conio_screen_layer])
lda conio_scroll_enable,y
cmp #0
bne __b4
// if(conio_cursor_y[conio_screen_layer]>=conio_height)
lda conio_cursor_y,y
ldy.z conio_height+1
bne __b3
cmp.z conio_height
__b3:
// }
rts
__b4:
// insertup()
jsr insertup
// gotoxy( 0, CONIO_HEIGHT-1)
ldx.z conio_screen_height
dex
ldy #0
jsr gotoxy
rts
}
// Get the back color for text output. The old back text color setting is returned.
// - layer: Value of 0 or 1.
// - return: a 4 bit value ( decimal between 0 and 15).
// This will only work when the VERA is in 16 color mode!
// Note that on the VERA, the transparent color has value 0.
// __register(A) char vera_layer_get_backcolor(__register(X) char layer)
vera_layer_get_backcolor: {
// return vera_layer_backcolor[layer];
lda vera_layer_backcolor,x
// }
rts
}
// Get the front color for text output. The old front text color setting is returned.
// - layer: Value of 0 or 1.
// - return: a 4 bit value ( decimal between 0 and 15).
// This will only work when the VERA is in 16 color mode!
// Note that on the VERA, the transparent color has value 0.
// __register(A) char vera_layer_get_textcolor(__register(X) char layer)
vera_layer_get_textcolor: {
// return vera_layer_textcolor[layer];
lda vera_layer_textcolor,x
// }
rts
}
// Converts unsigned number value to a string representing it in RADIX format.
// If the leading digits are zero they are not included in the string.
// - value : The number to be converted to RADIX
// - buffer : receives the string representing the number and zero-termination.
// - radix : The radix to convert the number to (from the enum RADIX)
// void uctoa(__register(X) char value, __zp($1a) char *buffer, __register(Y) char radix)
uctoa: {
.label buffer = $1a
.label digit = $1d
.label started = $26
.label max_digits = $2f
.label digit_values = $18
// if(radix==DECIMAL)
cpy #DECIMAL
beq __b2
// if(radix==HEXADECIMAL)
cpy #HEXADECIMAL
beq __b3
// if(radix==OCTAL)
cpy #OCTAL
beq __b4
// if(radix==BINARY)
cpy #BINARY
beq __b5
// *buffer++ = 'e'
// Unknown radix
lda #'e'
sta printf_buffer+OFFSET_STRUCT_PRINTF_BUFFER_NUMBER_DIGITS
// *buffer++ = 'r'
lda #'r'
sta printf_buffer+OFFSET_STRUCT_PRINTF_BUFFER_NUMBER_DIGITS+1
sta printf_buffer+OFFSET_STRUCT_PRINTF_BUFFER_NUMBER_DIGITS+2
// *buffer = 0
lda #0
sta printf_buffer+OFFSET_STRUCT_PRINTF_BUFFER_NUMBER_DIGITS+3
// }
rts
__b2:
lda #<RADIX_DECIMAL_VALUES_CHAR
sta.z digit_values
lda #>RADIX_DECIMAL_VALUES_CHAR
sta.z digit_values+1
lda #3
sta.z max_digits
jmp __b1
__b3:
lda #<RADIX_HEXADECIMAL_VALUES_CHAR
sta.z digit_values
lda #>RADIX_HEXADECIMAL_VALUES_CHAR
sta.z digit_values+1
lda #2
sta.z max_digits
jmp __b1
__b4:
lda #<RADIX_OCTAL_VALUES_CHAR
sta.z digit_values
lda #>RADIX_OCTAL_VALUES_CHAR
sta.z digit_values+1
lda #3
sta.z max_digits
jmp __b1
__b5:
lda #<RADIX_BINARY_VALUES_CHAR
sta.z digit_values
lda #>RADIX_BINARY_VALUES_CHAR
sta.z digit_values+1
lda #8
sta.z max_digits
__b1:
lda #<printf_buffer+OFFSET_STRUCT_PRINTF_BUFFER_NUMBER_DIGITS
sta.z buffer
lda #>printf_buffer+OFFSET_STRUCT_PRINTF_BUFFER_NUMBER_DIGITS
sta.z buffer+1
lda #0
sta.z started
sta.z digit
__b6:
// max_digits-1
lda.z max_digits
sec
sbc #1
// for( char digit=0; digit<max_digits-1; digit++ )
cmp.z digit
beq !+
bcs __b7
!:
// *buffer++ = DIGITS[(char)value]
lda DIGITS,x
ldy #0
sta (buffer),y
// *buffer++ = DIGITS[(char)value];
inc.z buffer
bne !+
inc.z buffer+1
!:
// *buffer = 0
lda #0
tay
sta (buffer),y
rts
__b7:
// unsigned char digit_value = digit_values[digit]
ldy.z digit
lda (digit_values),y
tay
// if (started || value >= digit_value)
lda.z started
bne __b10
sty.z $ff
cpx.z $ff
bcs __b10
__b9:
// for( char digit=0; digit<max_digits-1; digit++ )
inc.z digit
jmp __b6
__b10:
// uctoa_append(buffer++, value, digit_value)
sty.z uctoa_append.sub
jsr uctoa_append
// uctoa_append(buffer++, value, digit_value)
// value = uctoa_append(buffer++, value, digit_value)
// value = uctoa_append(buffer++, value, digit_value);
inc.z buffer
bne !+
inc.z buffer+1
!:
lda #1
sta.z started
jmp __b9
}
// Print the contents of the number buffer using a specific format.
// This handles minimum length, zero-filling, and left/right justification from the format
// void printf_number_buffer(void (*putc)(char), __register(A) char buffer_sign, char *buffer_digits, char format_min_length, char format_justify_left, char format_sign_always, char format_zero_padding, char format_upper_case, char format_radix)
printf_number_buffer: {
.label buffer_digits = printf_buffer+OFFSET_STRUCT_PRINTF_BUFFER_NUMBER_DIGITS
.label putc = cputc
// if(buffer.sign)
cmp #0
beq __b2
// putc(buffer.sign)
pha
jsr cputc
pla
__b2:
// printf_str(putc, buffer.digits)
lda #<putc
sta.z printf_str.putc
lda #>putc
sta.z printf_str.putc+1
lda #<buffer_digits
sta.z printf_str.s
lda #>buffer_digits
sta.z printf_str.s+1
jsr printf_str
// }
rts
}
// Insert a new line, and scroll the upper part of the screen up.
insertup: {
.label cy = $11
.label width = $10
.label line = 8
.label start = 8
// unsigned byte cy = conio_cursor_y[conio_screen_layer]
ldy.z conio_screen_layer
lda conio_cursor_y,y
sta.z cy
// unsigned byte width = CONIO_WIDTH * 2
lda.z conio_screen_width
asl
sta.z width
ldx #1
__b1:
// for(unsigned byte i=1; i<=cy; i++)
lda.z cy
stx.z $ff
cmp.z $ff
bcs __b2
// clearline()
jsr clearline
// }
rts
__b2:
// i-1
txa
sec
sbc #1
// unsigned int line = (i-1) << conio_rowshift
ldy.z conio_rowshift
sta.z line
lda #0
sta.z line+1
cpy #0
beq !e+
!:
asl.z line
rol.z line+1
dey
bne !-
!e:
// unsigned char* start = CONIO_SCREEN_TEXT + line
clc
lda.z start
adc.z CONIO_SCREEN_TEXT
sta.z start
lda.z start+1
adc.z CONIO_SCREEN_TEXT+1
sta.z start+1
// start+conio_rowskip
lda.z start
clc
adc.z conio_rowskip
sta.z memcpy_in_vram.src
lda.z start+1
adc.z conio_rowskip+1
sta.z memcpy_in_vram.src+1
// memcpy_in_vram(0, start, VERA_INC_1, 0, start+conio_rowskip, VERA_INC_1, width)
lda.z width
sta.z memcpy_in_vram.num
lda #0
sta.z memcpy_in_vram.num+1
jsr memcpy_in_vram
// for(unsigned byte i=1; i<=cy; i++)
inx
jmp __b1
}
// Used to convert a single digit of an unsigned number value to a string representation
// Counts a single digit up from '0' as long as the value is larger than sub.
// Each time the digit is increased sub is subtracted from value.
// - buffer : pointer to the char that receives the digit
// - value : The value where the digit will be derived from
// - sub : the value of a '1' in the digit. Subtracted continually while the digit is increased.
// (For decimal the subs used are 10000, 1000, 100, 10, 1)
// returns : the value reduced by sub * digit so that it is less than sub.
// __register(X) char uctoa_append(__zp($1a) char *buffer, __register(X) char value, __zp($12) char sub)
uctoa_append: {
.label buffer = $1a
.label sub = $12
ldy #0
__b1:
// while (value >= sub)
cpx.z sub
bcs __b2
// *buffer = DIGITS[digit]
lda DIGITS,y
ldy #0
sta (buffer),y
// }
rts
__b2:
// digit++;
iny
// value -= sub
txa
sec
sbc.z sub
tax
jmp __b1
}
// Copy block of memory (from VRAM to VRAM)
// Copies the values from the location pointed by src to the location pointed by dest.
// The method uses the VERA access ports 0 and 1 to copy data from and to in VRAM.
// - src_bank: 64K VRAM bank number to copy from (0/1).
// - src: pointer to the location to copy from. Note that the address is a 16 bit value!
// - src_increment: the increment indicator, VERA needs this because addressing increment is automated by VERA at each access.
// - dest_bank: 64K VRAM bank number to copy to (0/1).
// - dest: pointer to the location to copy to. Note that the address is a 16 bit value!
// - dest_increment: the increment indicator, VERA needs this because addressing increment is automated by VERA at each access.
// - num: The number of bytes to copy
// void memcpy_in_vram(char dest_bank, __zp(8) void *dest, char dest_increment, char src_bank, __zp($e) char *src, char src_increment, __zp(4) unsigned int num)
memcpy_in_vram: {
.label i = 2
.label dest = 8
.label src = $e
.label num = 4
// *VERA_CTRL &= ~VERA_ADDRSEL
// Select DATA0
lda #VERA_ADDRSEL^$ff
and VERA_CTRL
sta VERA_CTRL
// BYTE0(src)
lda.z src
// *VERA_ADDRX_L = BYTE0(src)
// Set address
sta VERA_ADDRX_L
// BYTE1(src)
lda.z src+1
// *VERA_ADDRX_M = BYTE1(src)
sta VERA_ADDRX_M
// *VERA_ADDRX_H = src_increment | src_bank
lda #VERA_INC_1
sta VERA_ADDRX_H
// *VERA_CTRL |= VERA_ADDRSEL
// Select DATA1
lda #VERA_ADDRSEL
ora VERA_CTRL
sta VERA_CTRL
// BYTE0(dest)
lda.z dest
// *VERA_ADDRX_L = BYTE0(dest)
// Set address
sta VERA_ADDRX_L
// BYTE1(dest)
lda.z dest+1
// *VERA_ADDRX_M = BYTE1(dest)
sta VERA_ADDRX_M
// *VERA_ADDRX_H = dest_increment | dest_bank
lda #VERA_INC_1
sta VERA_ADDRX_H
lda #<0
sta.z i
sta.z i+1
// Transfer the data
__b1:
// for(unsigned int i=0; i<num; i++)
lda.z i+1
cmp.z num+1
bcc __b2
bne !+
lda.z i
cmp.z num
bcc __b2
!:
// }
rts
__b2:
// *VERA_DATA1 = *VERA_DATA0
lda VERA_DATA0
sta VERA_DATA1
// for(unsigned int i=0; i<num; i++)
inc.z i
bne !+
inc.z i+1
!:
jmp __b1
}
.segment Data
VERA_LAYER_WIDTH: .word $20, $40, $80, $100
VERA_LAYER_HEIGHT: .word $20, $40, $80, $100
/// --- VERA function encapsulation ---
vera_mapbase_offset: .word 0, 0
vera_mapbase_bank: .byte 0, 0
vera_mapbase_address: .dword 0, 0
vera_tilebase_offset: .word 0, 0
vera_tilebase_bank: .byte 0, 0
vera_tilebase_address: .dword 0, 0
vera_layer_rowshift: .byte 0, 0
vera_layer_rowskip: .word 0, 0
vera_layer_config: .word VERA_L0_CONFIG, VERA_L1_CONFIG
vera_layer_enable: .byte VERA_LAYER0_ENABLE, VERA_LAYER1_ENABLE
vera_layer_mapbase: .word VERA_L0_MAPBASE, VERA_L1_MAPBASE
vera_layer_tilebase: .word VERA_L0_TILEBASE, VERA_L1_TILEBASE
vera_layer_textcolor: .byte WHITE, WHITE
vera_layer_backcolor: .byte BLUE, BLUE
// The number of bytes on the screen
// The current cursor x-position
conio_cursor_x: .byte 0, 0
// The current cursor y-position
conio_cursor_y: .byte 0, 0
// The current text cursor line start
conio_line_text: .word 0, 0
// Is scrolling enabled when outputting beyond the end of the screen (1: yes, 0: no).
// If disabled the cursor just moves back to (0,0) instead
conio_scroll_enable: .byte 1, 1
// The digits used for numbers
DIGITS: .text "0123456789abcdef"
// Values of binary digits
RADIX_BINARY_VALUES_CHAR: .byte $80, $40, $20, $10, 8, 4, 2
// Values of octal digits
RADIX_OCTAL_VALUES_CHAR: .byte $40, 8
// Values of decimal digits
RADIX_DECIMAL_VALUES_CHAR: .byte $64, $a
// Values of hexadecimal digits
RADIX_HEXADECIMAL_VALUES_CHAR: .byte $10
// Buffer used for stringified number being printed
printf_buffer: .fill SIZEOF_STRUCT_PRINTF_BUFFER_NUMBER, 0
|
// Copyright (c) FIRST and other WPILib contributors.
// Open Source Software; you can modify and/or share it under the terms of
// the WPILib BSD license file in the root directory of this project.
#include "../PortsInternal.h"
#include "RelayDataInternal.h"
using namespace hal;
namespace hal::init {
void InitializeRelayData() {
static RelayData srd[kNumRelayHeaders];
::hal::SimRelayData = srd;
}
} // namespace hal::init
RelayData* hal::SimRelayData;
void RelayData::ResetData() {
initializedForward.Reset(false);
initializedReverse.Reset(false);
forward.Reset(false);
reverse.Reset(false);
}
extern "C" {
void HALSIM_ResetRelayData(int32_t index) {
SimRelayData[index].ResetData();
}
#define DEFINE_CAPI(TYPE, CAPINAME, LOWERNAME) \
HAL_SIMDATAVALUE_DEFINE_CAPI(TYPE, HALSIM, Relay##CAPINAME, SimRelayData, \
LOWERNAME)
DEFINE_CAPI(HAL_Bool, InitializedForward, initializedForward)
DEFINE_CAPI(HAL_Bool, InitializedReverse, initializedReverse)
DEFINE_CAPI(HAL_Bool, Forward, forward)
DEFINE_CAPI(HAL_Bool, Reverse, reverse)
#define REGISTER(NAME) \
SimRelayData[index].NAME.RegisterCallback(callback, param, initialNotify)
void HALSIM_RegisterRelayAllCallbacks(int32_t index,
HAL_NotifyCallback callback, void* param,
HAL_Bool initialNotify) {
REGISTER(initializedForward);
REGISTER(initializedReverse);
REGISTER(forward);
REGISTER(reverse);
}
} // extern "C"
|
#define BASE_ADDR_0 0x00000000 // (core 0)
#define BASE_ADDR_1 0x02000000 // (core 1)
#define BASE_ADDR_2 0x04000000 // (core 2)
#define BASE_ADDR_3 0x06000000 // (core 3)
#int main0() {
# int *arr0 = (int *) BASE_ADDR_0; // data mapped on core 0
# int *arr1 = (int *) BASE_ADDR_1; // data mapped on core 1
#
# *(arr0+0) = 0; // local access
# *(arr1+0) = 0;
#
# for (int i = 0; i < 20; i++) {
# *(arr0+0) += 1;
# *(arr1+0) += 1;
# }
#
# return 0;
#}
#(RA)
#@ENTRY:
PUSH 0;
PUSH 0;
ST_EM 2 0;
PUSH 0;
PUSH 0;
SETHI 0x0200;
ST_EM 2 0;
PUSH 0;
#(i, RA)
#@CONDITION:
PULL_CP 0;
PUSH 20;
COMP_ULE;
B_Z 2; #branch to @BODY
#(i, RA)
#@RETURN:
DROP 0;
HALT;
#(i, RA)
#@BODY:
PUSH 0;
LD_EM 1 0;
PUSH 1;
ADD;
PUSH 0;
ST_EM 2 0;
PUSH 0;
SETHI 0x0200;
PULL_CP 0;
LD_EM 1 0;
PUSH 1;
ADD;
PULL 1;
ST_EM 2 0;
#(i, RA)
#@FOR.END:
PUSH 1;
ADD;
J_REL -23; #jump to @CONDITION |
; A141939: Primes congruent to 16 mod 25.
; Submitted by Christian Krause
; 41,191,241,491,541,641,691,941,991,1091,1291,1741,2141,2341,2441,2591,2741,2791,3041,3191,3391,3491,3541,3691,4091,4241,4391,4441,4591,4691,5441,5591,5641,5741,5791,6091,6491,6691,6791,6841,6991,7541,7591,7691,7741,7841,8191,8291,8641,8741,8941,9041,9091,9241,9341,9391,9491,9791,9941,10091,10141,10391,10691,10891,11491,11941,12041,12241,12391,12491,12541,12641,12791,12841,12941,13241,13291,13441,13591,13691,13841,14341,14591,14741,14891,15091,15241,15391,15541,15641,15791,15991,16091,16141
mov $1,7
mov $2,$0
add $2,2
pow $2,2
lpb $2
add $1,33
mov $3,$1
seq $3,10051 ; Characteristic function of primes: 1 if n is prime, else 0.
sub $0,$3
add $1,17
mov $4,$0
max $4,0
cmp $4,$0
mul $2,$4
sub $2,1
lpe
mov $0,$1
add $0,34
|
; A273743: Number of active (ON,black) cells in n-th stage of growth of two-dimensional cellular automaton defined by "Rule 901", based on the 5-celled von Neumann neighborhood.
; 1,8,25,49,81,121,169,225,289,361,441,529,625,729,841,961,1089,1225,1369,1521,1681,1849,2025,2209,2401,2601,2809,3025,3249,3481,3721,3969,4225,4489,4761,5041,5329,5625,5929,6241,6561,6889,7225,7569,7921,8281,8649,9025,9409,9801,10201,10609,11025,11449,11881,12321,12769,13225,13689,14161,14641,15129,15625,16129,16641,17161,17689,18225,18769,19321,19881,20449,21025,21609,22201,22801,23409,24025,24649,25281,25921,26569,27225,27889,28561,29241,29929,30625,31329,32041,32761,33489,34225,34969,35721
mul $0,2
mov $1,$0
cmp $0,2
add $1,1
pow $1,2
sub $1,$0
mov $0,$1
|
// Copyright 2016 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "base/task/thread_pool/thread_group_impl.h"
#include <stddef.h>
#include <algorithm>
#include <atomic>
#include <memory>
#include <unordered_set>
#include <utility>
#include <vector>
#include "base/atomicops.h"
#include "base/barrier_closure.h"
#include "base/bind.h"
#include "base/callback.h"
#include "base/callback_helpers.h"
#include "base/memory/ptr_util.h"
#include "base/memory/raw_ptr.h"
#include "base/memory/ref_counted.h"
#include "base/metrics/histogram.h"
#include "base/metrics/histogram_samples.h"
#include "base/metrics/statistics_recorder.h"
#include "base/synchronization/atomic_flag.h"
#include "base/synchronization/condition_variable.h"
#include "base/synchronization/lock.h"
#include "base/task/task_features.h"
#include "base/task/task_runner.h"
#include "base/task/thread_pool/delayed_task_manager.h"
#include "base/task/thread_pool/environment_config.h"
#include "base/task/thread_pool/pooled_task_runner_delegate.h"
#include "base/task/thread_pool/sequence.h"
#include "base/task/thread_pool/task_source_sort_key.h"
#include "base/task/thread_pool/task_tracker.h"
#include "base/task/thread_pool/test_task_factory.h"
#include "base/task/thread_pool/test_utils.h"
#include "base/task/thread_pool/worker_thread_observer.h"
#include "base/test/bind.h"
#include "base/test/gtest_util.h"
#include "base/test/metrics/histogram_tester.h"
#include "base/test/test_simple_task_runner.h"
#include "base/test/test_timeouts.h"
#include "base/test/test_waitable_event.h"
#include "base/threading/platform_thread.h"
#include "base/threading/scoped_blocking_call.h"
#include "base/threading/simple_thread.h"
#include "base/threading/thread.h"
#include "base/threading/thread_checker_impl.h"
#include "base/threading/thread_local_storage.h"
#include "base/time/time.h"
#include "base/timer/timer.h"
#include "build/build_config.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "third_party/abseil-cpp/absl/types/optional.h"
namespace base {
namespace internal {
namespace {
constexpr size_t kMaxTasks = 4;
constexpr size_t kNumThreadsPostingTasks = 4;
constexpr size_t kNumTasksPostedPerThread = 150;
// This can't be lower because Windows' TestWaitableEvent wakes up too early
// when a small timeout is used. This results in many spurious wake ups before a
// worker is allowed to cleanup.
constexpr TimeDelta kReclaimTimeForCleanupTests = Milliseconds(500);
constexpr size_t kLargeNumber = 512;
class ThreadGroupImplImplTestBase : public ThreadGroup::Delegate {
public:
ThreadGroupImplImplTestBase(const ThreadGroupImplImplTestBase&) = delete;
ThreadGroupImplImplTestBase& operator=(const ThreadGroupImplImplTestBase&) =
delete;
protected:
ThreadGroupImplImplTestBase()
: service_thread_("ThreadPoolServiceThread"),
tracked_ref_factory_(this) {}
void CommonTearDown() {
service_thread_.Stop();
task_tracker_.FlushForTesting();
if (thread_group_)
thread_group_->JoinForTesting();
thread_group_.reset();
}
void CreateThreadGroup(ThreadPriority priority = ThreadPriority::NORMAL) {
ASSERT_FALSE(thread_group_);
service_thread_.Start();
delayed_task_manager_.Start(service_thread_.task_runner());
thread_group_ = std::make_unique<ThreadGroupImpl>(
"TestThreadGroup", "A", priority, task_tracker_.GetTrackedRef(),
tracked_ref_factory_.GetTrackedRef());
ASSERT_TRUE(thread_group_);
mock_pooled_task_runner_delegate_.SetThreadGroup(thread_group_.get());
}
void StartThreadGroup(
TimeDelta suggested_reclaim_time,
size_t max_tasks,
absl::optional<int> max_best_effort_tasks = absl::nullopt,
WorkerThreadObserver* worker_observer = nullptr,
absl::optional<TimeDelta> may_block_threshold = absl::nullopt) {
ASSERT_TRUE(thread_group_);
thread_group_->Start(
max_tasks,
max_best_effort_tasks ? max_best_effort_tasks.value() : max_tasks,
suggested_reclaim_time, service_thread_.task_runner(), worker_observer,
ThreadGroup::WorkerEnvironment::NONE,
/* synchronous_thread_start_for_testing=*/false, may_block_threshold);
}
void CreateAndStartThreadGroup(
TimeDelta suggested_reclaim_time = TimeDelta::Max(),
size_t max_tasks = kMaxTasks,
absl::optional<int> max_best_effort_tasks = absl::nullopt,
WorkerThreadObserver* worker_observer = nullptr,
absl::optional<TimeDelta> may_block_threshold = absl::nullopt) {
CreateThreadGroup();
StartThreadGroup(suggested_reclaim_time, max_tasks, max_best_effort_tasks,
worker_observer, may_block_threshold);
}
Thread service_thread_;
TaskTracker task_tracker_;
std::unique_ptr<ThreadGroupImpl> thread_group_;
DelayedTaskManager delayed_task_manager_;
TrackedRefFactory<ThreadGroup::Delegate> tracked_ref_factory_;
test::MockPooledTaskRunnerDelegate mock_pooled_task_runner_delegate_ = {
task_tracker_.GetTrackedRef(), &delayed_task_manager_};
private:
// ThreadGroup::Delegate:
ThreadGroup* GetThreadGroupForTraits(const TaskTraits& traits) override {
return thread_group_.get();
}
};
class ThreadGroupImplImplTest : public ThreadGroupImplImplTestBase,
public testing::Test {
public:
ThreadGroupImplImplTest(const ThreadGroupImplImplTest&) = delete;
ThreadGroupImplImplTest& operator=(const ThreadGroupImplImplTest&) = delete;
protected:
ThreadGroupImplImplTest() = default;
void SetUp() override { CreateAndStartThreadGroup(); }
void TearDown() override { ThreadGroupImplImplTestBase::CommonTearDown(); }
};
class ThreadGroupImplImplTestParam
: public ThreadGroupImplImplTestBase,
public testing::TestWithParam<TaskSourceExecutionMode> {
public:
ThreadGroupImplImplTestParam(const ThreadGroupImplImplTestParam&) = delete;
ThreadGroupImplImplTestParam& operator=(const ThreadGroupImplImplTestParam&) =
delete;
protected:
ThreadGroupImplImplTestParam() = default;
void SetUp() override { CreateAndStartThreadGroup(); }
void TearDown() override { ThreadGroupImplImplTestBase::CommonTearDown(); }
};
using PostNestedTask = test::TestTaskFactory::PostNestedTask;
class ThreadPostingTasksWaitIdle : public SimpleThread {
public:
// Constructs a thread that posts tasks to |thread_group| through an
// |execution_mode| task runner. The thread waits until all workers in
// |thread_group| are idle before posting a new task.
ThreadPostingTasksWaitIdle(
ThreadGroupImpl* thread_group,
test::MockPooledTaskRunnerDelegate* mock_pooled_task_runner_delegate_,
TaskSourceExecutionMode execution_mode)
: SimpleThread("ThreadPostingTasksWaitIdle"),
thread_group_(thread_group),
factory_(CreatePooledTaskRunnerWithExecutionMode(
execution_mode,
mock_pooled_task_runner_delegate_),
execution_mode) {
DCHECK(thread_group_);
}
ThreadPostingTasksWaitIdle(const ThreadPostingTasksWaitIdle&) = delete;
ThreadPostingTasksWaitIdle& operator=(const ThreadPostingTasksWaitIdle&) =
delete;
const test::TestTaskFactory* factory() const { return &factory_; }
private:
void Run() override {
for (size_t i = 0; i < kNumTasksPostedPerThread; ++i) {
thread_group_->WaitForAllWorkersIdleForTesting();
EXPECT_TRUE(factory_.PostTask(PostNestedTask::NO, OnceClosure()));
}
}
const raw_ptr<ThreadGroupImpl> thread_group_;
const scoped_refptr<TaskRunner> task_runner_;
test::TestTaskFactory factory_;
};
} // namespace
TEST_P(ThreadGroupImplImplTestParam, PostTasksWaitAllWorkersIdle) {
// Create threads to post tasks. To verify that workers can sleep and be woken
// up when new tasks are posted, wait for all workers to become idle before
// posting a new task.
std::vector<std::unique_ptr<ThreadPostingTasksWaitIdle>>
threads_posting_tasks;
for (size_t i = 0; i < kNumThreadsPostingTasks; ++i) {
threads_posting_tasks.push_back(
std::make_unique<ThreadPostingTasksWaitIdle>(
thread_group_.get(), &mock_pooled_task_runner_delegate_,
GetParam()));
threads_posting_tasks.back()->Start();
}
// Wait for all tasks to run.
for (const auto& thread_posting_tasks : threads_posting_tasks) {
thread_posting_tasks->Join();
thread_posting_tasks->factory()->WaitForAllTasksToRun();
}
// Wait until all workers are idle to be sure that no task accesses its
// TestTaskFactory after |thread_posting_tasks| is destroyed.
thread_group_->WaitForAllWorkersIdleForTesting();
}
TEST_P(ThreadGroupImplImplTestParam, PostTasksWithOneAvailableWorker) {
// Post blocking tasks to keep all workers busy except one until |event| is
// signaled. Use different factories so that tasks are added to different
// sequences and can run simultaneously when the execution mode is SEQUENCED.
TestWaitableEvent event;
std::vector<std::unique_ptr<test::TestTaskFactory>> blocked_task_factories;
for (size_t i = 0; i < (kMaxTasks - 1); ++i) {
blocked_task_factories.push_back(std::make_unique<test::TestTaskFactory>(
CreatePooledTaskRunnerWithExecutionMode(
GetParam(), &mock_pooled_task_runner_delegate_),
GetParam()));
EXPECT_TRUE(blocked_task_factories.back()->PostTask(
PostNestedTask::NO,
BindOnce(&TestWaitableEvent::Wait, Unretained(&event))));
blocked_task_factories.back()->WaitForAllTasksToRun();
}
// Post |kNumTasksPostedPerThread| tasks that should all run despite the fact
// that only one worker in |thread_group_| isn't busy.
test::TestTaskFactory short_task_factory(
CreatePooledTaskRunnerWithExecutionMode(
GetParam(), &mock_pooled_task_runner_delegate_),
GetParam());
for (size_t i = 0; i < kNumTasksPostedPerThread; ++i)
EXPECT_TRUE(short_task_factory.PostTask(PostNestedTask::NO, OnceClosure()));
short_task_factory.WaitForAllTasksToRun();
// Release tasks waiting on |event|.
event.Signal();
// Wait until all workers are idle to be sure that no task accesses
// its TestTaskFactory after it is destroyed.
thread_group_->WaitForAllWorkersIdleForTesting();
}
TEST_P(ThreadGroupImplImplTestParam, Saturate) {
// Verify that it is possible to have |kMaxTasks| tasks/sequences running
// simultaneously. Use different factories so that the blocking tasks are
// added to different sequences and can run simultaneously when the execution
// mode is SEQUENCED.
TestWaitableEvent event;
std::vector<std::unique_ptr<test::TestTaskFactory>> factories;
for (size_t i = 0; i < kMaxTasks; ++i) {
factories.push_back(std::make_unique<test::TestTaskFactory>(
CreatePooledTaskRunnerWithExecutionMode(
GetParam(), &mock_pooled_task_runner_delegate_),
GetParam()));
EXPECT_TRUE(factories.back()->PostTask(
PostNestedTask::NO,
BindOnce(&TestWaitableEvent::Wait, Unretained(&event))));
factories.back()->WaitForAllTasksToRun();
}
// Release tasks waiting on |event|.
event.Signal();
// Wait until all workers are idle to be sure that no task accesses
// its TestTaskFactory after it is destroyed.
thread_group_->WaitForAllWorkersIdleForTesting();
}
// Verifies that ShouldYield() returns true for priorities lower than the
// highest priority pending while the thread group is flooded with USER_VISIBLE
// tasks.
TEST_F(ThreadGroupImplImplTest, ShouldYieldFloodedUserVisible) {
TestWaitableEvent threads_running;
TestWaitableEvent threads_continue;
// Saturate workers with USER_VISIBLE tasks to ensure ShouldYield() returns
// true when a tasks of higher priority is posted.
RepeatingClosure threads_running_barrier = BarrierClosure(
kMaxTasks,
BindOnce(&TestWaitableEvent::Signal, Unretained(&threads_running)));
auto job_task = base::MakeRefCounted<test::MockJobTask>(
BindLambdaForTesting(
[&threads_running_barrier, &threads_continue](JobDelegate* delegate) {
threads_running_barrier.Run();
threads_continue.Wait();
}),
/* num_tasks_to_run */ kMaxTasks);
scoped_refptr<JobTaskSource> task_source =
job_task->GetJobTaskSource(FROM_HERE, {TaskPriority::USER_VISIBLE},
&mock_pooled_task_runner_delegate_);
auto registered_task_source = task_tracker_.RegisterTaskSource(task_source);
ASSERT_TRUE(registered_task_source);
static_cast<ThreadGroup*>(thread_group_.get())
->PushTaskSourceAndWakeUpWorkers(
TransactionWithRegisteredTaskSource::FromTaskSource(
std::move(registered_task_source)));
threads_running.Wait();
// Posting a BEST_EFFORT task should not cause any other tasks to yield.
// Once this task gets to run, no other task needs to yield.
// Note: This is only true because this test is using a single ThreadGroup.
// Under the ThreadPool this wouldn't be racy because BEST_EFFORT tasks
// run in an independent ThreadGroup.
test::CreatePooledTaskRunner({TaskPriority::BEST_EFFORT},
&mock_pooled_task_runner_delegate_)
->PostTask(
FROM_HERE, BindLambdaForTesting([&]() {
EXPECT_FALSE(thread_group_->ShouldYield(
{TaskPriority::BEST_EFFORT, TimeTicks(), /* worker_count=*/1}));
}));
// A BEST_EFFORT task with more workers shouldn't have to yield.
EXPECT_FALSE(thread_group_->ShouldYield(
{TaskPriority::BEST_EFFORT, TimeTicks(), /* worker_count=*/2}));
EXPECT_FALSE(thread_group_->ShouldYield(
{TaskPriority::BEST_EFFORT, TimeTicks(), /* worker_count=*/0}));
EXPECT_FALSE(thread_group_->ShouldYield(
{TaskPriority::USER_VISIBLE, TimeTicks(), /* worker_count=*/0}));
EXPECT_FALSE(thread_group_->ShouldYield(
{TaskPriority::USER_BLOCKING, TimeTicks(), /* worker_count=*/0}));
// Posting a USER_VISIBLE task should cause BEST_EFFORT and USER_VISIBLE with
// higher worker_count tasks to yield.
auto post_user_visible = [&]() {
test::CreatePooledTaskRunner({TaskPriority::USER_VISIBLE},
&mock_pooled_task_runner_delegate_)
->PostTask(FROM_HERE, BindLambdaForTesting([&]() {
EXPECT_FALSE(thread_group_->ShouldYield(
{TaskPriority::USER_VISIBLE, TimeTicks(),
/* worker_count=*/1}));
}));
};
// A USER_VISIBLE task with too many workers should yield.
post_user_visible();
EXPECT_TRUE(thread_group_->ShouldYield(
{TaskPriority::USER_VISIBLE, TimeTicks(), /* worker_count=*/2}));
post_user_visible();
EXPECT_TRUE(thread_group_->ShouldYield(
{TaskPriority::BEST_EFFORT, TimeTicks(), /* worker_count=*/0}));
post_user_visible();
EXPECT_FALSE(thread_group_->ShouldYield(
{TaskPriority::USER_VISIBLE, TimeTicks(), /* worker_count=*/1}));
EXPECT_FALSE(thread_group_->ShouldYield(
{TaskPriority::USER_BLOCKING, TimeTicks(), /* worker_count=*/0}));
// Posting a USER_BLOCKING task should cause BEST_EFFORT, USER_VISIBLE and
// USER_BLOCKING with higher worker_count tasks to yield.
auto post_user_blocking = [&]() {
test::CreatePooledTaskRunner({TaskPriority::USER_BLOCKING},
&mock_pooled_task_runner_delegate_)
->PostTask(FROM_HERE, BindLambdaForTesting([&]() {
// Once this task got to start, no other task needs to
// yield.
EXPECT_FALSE(thread_group_->ShouldYield(
{TaskPriority::USER_BLOCKING, TimeTicks(),
/* worker_count=*/1}));
}));
};
// A USER_BLOCKING task with too many workers should have to yield.
post_user_blocking();
EXPECT_TRUE(thread_group_->ShouldYield(
{TaskPriority::USER_BLOCKING, TimeTicks(), /* worker_count=*/2}));
post_user_blocking();
EXPECT_TRUE(thread_group_->ShouldYield(
{TaskPriority::BEST_EFFORT, TimeTicks(), /* worker_count=*/0}));
post_user_blocking();
EXPECT_TRUE(thread_group_->ShouldYield(
{TaskPriority::USER_VISIBLE, TimeTicks(), /* worker_count=*/0}));
post_user_blocking();
EXPECT_FALSE(thread_group_->ShouldYield(
{TaskPriority::USER_BLOCKING, TimeTicks(), /* worker_count=*/1}));
threads_continue.Signal();
task_tracker_.FlushForTesting();
}
INSTANTIATE_TEST_SUITE_P(Parallel,
ThreadGroupImplImplTestParam,
::testing::Values(TaskSourceExecutionMode::kParallel));
INSTANTIATE_TEST_SUITE_P(
Sequenced,
ThreadGroupImplImplTestParam,
::testing::Values(TaskSourceExecutionMode::kSequenced));
INSTANTIATE_TEST_SUITE_P(Job,
ThreadGroupImplImplTestParam,
::testing::Values(TaskSourceExecutionMode::kJob));
namespace {
class ThreadGroupImplImplStartInBodyTest : public ThreadGroupImplImplTest {
public:
void SetUp() override {
CreateThreadGroup();
// Let the test start the thread group.
}
};
void TaskPostedBeforeStart(PlatformThreadRef* platform_thread_ref,
TestWaitableEvent* task_running,
TestWaitableEvent* barrier) {
*platform_thread_ref = PlatformThread::CurrentRef();
task_running->Signal();
barrier->Wait();
}
} // namespace
// Verify that 2 tasks posted before Start() to a ThreadGroupImpl with
// more than 2 workers run on different workers when Start() is called.
TEST_F(ThreadGroupImplImplStartInBodyTest, PostTasksBeforeStart) {
PlatformThreadRef task_1_thread_ref;
PlatformThreadRef task_2_thread_ref;
TestWaitableEvent task_1_running;
TestWaitableEvent task_2_running;
// This event is used to prevent a task from completing before the other task
// starts running. If that happened, both tasks could run on the same worker
// and this test couldn't verify that the correct number of workers were woken
// up.
TestWaitableEvent barrier;
test::CreatePooledTaskRunner({WithBaseSyncPrimitives()},
&mock_pooled_task_runner_delegate_)
->PostTask(
FROM_HERE,
BindOnce(&TaskPostedBeforeStart, Unretained(&task_1_thread_ref),
Unretained(&task_1_running), Unretained(&barrier)));
test::CreatePooledTaskRunner({WithBaseSyncPrimitives()},
&mock_pooled_task_runner_delegate_)
->PostTask(
FROM_HERE,
BindOnce(&TaskPostedBeforeStart, Unretained(&task_2_thread_ref),
Unretained(&task_2_running), Unretained(&barrier)));
// Workers should not be created and tasks should not run before the thread
// group is started.
EXPECT_EQ(0U, thread_group_->NumberOfWorkersForTesting());
EXPECT_FALSE(task_1_running.IsSignaled());
EXPECT_FALSE(task_2_running.IsSignaled());
StartThreadGroup(TimeDelta::Max(), kMaxTasks);
// Tasks should run shortly after the thread group is started.
task_1_running.Wait();
task_2_running.Wait();
// Tasks should run on different threads.
EXPECT_NE(task_1_thread_ref, task_2_thread_ref);
barrier.Signal();
task_tracker_.FlushForTesting();
}
// Verify that posting many tasks before Start will cause the number of workers
// to grow to |max_tasks_| after Start.
TEST_F(ThreadGroupImplImplStartInBodyTest, PostManyTasks) {
scoped_refptr<TaskRunner> task_runner = test::CreatePooledTaskRunner(
{WithBaseSyncPrimitives()}, &mock_pooled_task_runner_delegate_);
constexpr size_t kNumTasksPosted = 2 * kMaxTasks;
TestWaitableEvent threads_running;
TestWaitableEvent threads_continue;
RepeatingClosure threads_running_barrier = BarrierClosure(
kMaxTasks,
BindOnce(&TestWaitableEvent::Signal, Unretained(&threads_running)));
// Posting these tasks should cause new workers to be created.
for (size_t i = 0; i < kMaxTasks; ++i) {
task_runner->PostTask(
FROM_HERE, BindLambdaForTesting([&]() {
threads_running_barrier.Run();
threads_continue.Wait();
}));
}
// Post the remaining |kNumTasksPosted - kMaxTasks| tasks, don't wait for them
// as they'll be blocked behind the above kMaxtasks.
for (size_t i = kMaxTasks; i < kNumTasksPosted; ++i)
task_runner->PostTask(FROM_HERE, DoNothing());
EXPECT_EQ(0U, thread_group_->NumberOfWorkersForTesting());
StartThreadGroup(TimeDelta::Max(), kMaxTasks);
EXPECT_GT(thread_group_->NumberOfWorkersForTesting(), 0U);
EXPECT_EQ(kMaxTasks, thread_group_->GetMaxTasksForTesting());
threads_running.Wait();
EXPECT_EQ(thread_group_->NumberOfWorkersForTesting(),
thread_group_->GetMaxTasksForTesting());
threads_continue.Signal();
task_tracker_.FlushForTesting();
}
namespace {
class BackgroundThreadGroupImplTest : public ThreadGroupImplImplTest {
public:
void CreateAndStartThreadGroup(
TimeDelta suggested_reclaim_time = TimeDelta::Max(),
size_t max_tasks = kMaxTasks,
absl::optional<int> max_best_effort_tasks = absl::nullopt,
WorkerThreadObserver* worker_observer = nullptr,
absl::optional<TimeDelta> may_block_threshold = absl::nullopt) {
if (!CanUseBackgroundPriorityForWorkerThread())
return;
CreateThreadGroup(ThreadPriority::BACKGROUND);
StartThreadGroup(suggested_reclaim_time, max_tasks, max_best_effort_tasks,
worker_observer, may_block_threshold);
}
void SetUp() override { CreateAndStartThreadGroup(); }
};
} // namespace
// Verify that ScopedBlockingCall updates thread priority when necessary per
// shutdown state.
TEST_F(BackgroundThreadGroupImplTest, UpdatePriorityBlockingStarted) {
if (!CanUseBackgroundPriorityForWorkerThread())
return;
const scoped_refptr<TaskRunner> task_runner = test::CreatePooledTaskRunner(
{MayBlock(), WithBaseSyncPrimitives(), TaskPriority::BEST_EFFORT},
&mock_pooled_task_runner_delegate_);
TestWaitableEvent threads_running;
RepeatingClosure threads_running_barrier = BarrierClosure(
kMaxTasks,
BindOnce(&TestWaitableEvent::Signal, Unretained(&threads_running)));
TestWaitableEvent blocking_threads_continue;
for (size_t i = 0; i < kMaxTasks; ++i) {
task_runner->PostTask(
FROM_HERE, BindLambdaForTesting([&]() {
EXPECT_EQ(ThreadPriority::BACKGROUND,
PlatformThread::GetCurrentThreadPriority());
{
// ScopedBlockingCall before shutdown doesn't affect priority.
ScopedBlockingCall scoped_blocking_call(FROM_HERE,
BlockingType::MAY_BLOCK);
EXPECT_EQ(ThreadPriority::BACKGROUND,
PlatformThread::GetCurrentThreadPriority());
}
threads_running_barrier.Run();
blocking_threads_continue.Wait();
// This is reached after StartShutdown(), at which point we expect
// ScopedBlockingCall to update thread priority.
ScopedBlockingCall scoped_blocking_call(FROM_HERE,
BlockingType::MAY_BLOCK);
EXPECT_EQ(ThreadPriority::NORMAL,
PlatformThread::GetCurrentThreadPriority());
}));
}
threads_running.Wait();
task_tracker_.StartShutdown();
blocking_threads_continue.Signal();
task_tracker_.FlushForTesting();
}
namespace {
constexpr size_t kMagicTlsValue = 42;
class ThreadGroupImplCheckTlsReuse : public ThreadGroupImplImplTest {
public:
ThreadGroupImplCheckTlsReuse(const ThreadGroupImplCheckTlsReuse&) = delete;
ThreadGroupImplCheckTlsReuse& operator=(const ThreadGroupImplCheckTlsReuse&) =
delete;
void SetTlsValueAndWait() {
slot_.Set(reinterpret_cast<void*>(kMagicTlsValue));
waiter_.Wait();
}
void CountZeroTlsValuesAndWait(TestWaitableEvent* count_waiter) {
if (!slot_.Get())
subtle::NoBarrier_AtomicIncrement(&zero_tls_values_, 1);
count_waiter->Signal();
waiter_.Wait();
}
protected:
ThreadGroupImplCheckTlsReuse() = default;
void SetUp() override {
CreateAndStartThreadGroup(kReclaimTimeForCleanupTests, kMaxTasks);
}
subtle::Atomic32 zero_tls_values_ = 0;
TestWaitableEvent waiter_;
private:
ThreadLocalStorage::Slot slot_;
};
} // namespace
// Checks that at least one worker has been cleaned up by checking the TLS.
TEST_F(ThreadGroupImplCheckTlsReuse, CheckCleanupWorkers) {
// Saturate the workers and mark each worker's thread with a magic TLS value.
std::vector<std::unique_ptr<test::TestTaskFactory>> factories;
for (size_t i = 0; i < kMaxTasks; ++i) {
factories.push_back(std::make_unique<test::TestTaskFactory>(
test::CreatePooledTaskRunner({WithBaseSyncPrimitives()},
&mock_pooled_task_runner_delegate_),
TaskSourceExecutionMode::kParallel));
ASSERT_TRUE(factories.back()->PostTask(
PostNestedTask::NO,
BindOnce(&ThreadGroupImplCheckTlsReuse::SetTlsValueAndWait,
Unretained(this))));
factories.back()->WaitForAllTasksToRun();
}
// Release tasks waiting on |waiter_|.
waiter_.Signal();
thread_group_->WaitForAllWorkersIdleForTesting();
// All workers should be done running by now, so reset for the next phase.
waiter_.Reset();
// Wait for the thread group to clean up at least one worker.
thread_group_->WaitForWorkersCleanedUpForTesting(1U);
// Saturate and count the worker threads that do not have the magic TLS value.
// If the value is not there, that means we're at a new worker.
std::vector<std::unique_ptr<TestWaitableEvent>> count_waiters;
for (auto& factory : factories) {
count_waiters.push_back(std::make_unique<TestWaitableEvent>());
ASSERT_TRUE(factory->PostTask(
PostNestedTask::NO,
BindOnce(&ThreadGroupImplCheckTlsReuse::CountZeroTlsValuesAndWait,
Unretained(this), count_waiters.back().get())));
factory->WaitForAllTasksToRun();
}
// Wait for all counters to complete.
for (auto& count_waiter : count_waiters)
count_waiter->Wait();
EXPECT_GT(subtle::NoBarrier_Load(&zero_tls_values_), 0);
// Release tasks waiting on |waiter_|.
waiter_.Signal();
}
namespace {
class ThreadGroupImplHistogramTest : public ThreadGroupImplImplTest {
public:
ThreadGroupImplHistogramTest() = default;
ThreadGroupImplHistogramTest(const ThreadGroupImplHistogramTest&) = delete;
ThreadGroupImplHistogramTest& operator=(const ThreadGroupImplHistogramTest&) =
delete;
protected:
// Override SetUp() to allow every test case to initialize a thread group with
// its own arguments.
void SetUp() override {}
private:
std::unique_ptr<StatisticsRecorder> statistics_recorder_ =
StatisticsRecorder::CreateTemporaryForTesting();
};
} // namespace
TEST_F(ThreadGroupImplHistogramTest, NumTasksBeforeCleanup) {
CreateThreadGroup();
auto histogrammed_thread_task_runner = test::CreatePooledSequencedTaskRunner(
{WithBaseSyncPrimitives()}, &mock_pooled_task_runner_delegate_);
// Post 3 tasks and hold the thread for idle thread stack ordering.
// This test assumes |histogrammed_thread_task_runner| gets assigned the same
// thread for each of its tasks.
PlatformThreadRef thread_ref;
histogrammed_thread_task_runner->PostTask(
FROM_HERE, BindOnce(
[](PlatformThreadRef* thread_ref) {
ASSERT_TRUE(thread_ref);
*thread_ref = PlatformThread::CurrentRef();
},
Unretained(&thread_ref)));
histogrammed_thread_task_runner->PostTask(
FROM_HERE, BindOnce(
[](PlatformThreadRef* thread_ref) {
ASSERT_FALSE(thread_ref->is_null());
EXPECT_EQ(*thread_ref, PlatformThread::CurrentRef());
},
Unretained(&thread_ref)));
TestWaitableEvent cleanup_thread_running;
TestWaitableEvent cleanup_thread_continue;
histogrammed_thread_task_runner->PostTask(
FROM_HERE,
BindOnce(
[](PlatformThreadRef* thread_ref,
TestWaitableEvent* cleanup_thread_running,
TestWaitableEvent* cleanup_thread_continue) {
ASSERT_FALSE(thread_ref->is_null());
EXPECT_EQ(*thread_ref, PlatformThread::CurrentRef());
cleanup_thread_running->Signal();
cleanup_thread_continue->Wait();
},
Unretained(&thread_ref), Unretained(&cleanup_thread_running),
Unretained(&cleanup_thread_continue)));
// Start the thread group with 2 workers, to avoid depending on the internal
// logic to always keep one extra idle worker.
//
// The thread group is started after the 3 initial tasks have been posted to
// ensure that they are scheduled on the same worker. If the tasks could run
// as they are posted, there would be a chance that:
// 1. Worker #1: Runs a tasks and empties the sequence, without adding
// itself to the idle stack yet.
// 2. Posting thread: Posts another task to the now empty sequence.
// Wakes up a new worker, since worker #1 isn't on the
// idle stack yet.
// 3: Worker #2: Runs the tasks, violating the expectation that the 3
// initial tasks run on the same worker.
constexpr size_t kTwoWorkers = 2;
StartThreadGroup(kReclaimTimeForCleanupTests, kTwoWorkers);
// Wait until the 3rd task is scheduled.
cleanup_thread_running.Wait();
// To allow the WorkerThread associated with
// |histogrammed_thread_task_runner| to cleanup, make sure it isn't on top of
// the idle stack by waking up another WorkerThread via
// |task_runner_for_top_idle|. |histogrammed_thread_task_runner| should
// release and go idle first and then |task_runner_for_top_idle| should
// release and go idle. This allows the WorkerThread associated with
// |histogrammed_thread_task_runner| to cleanup.
TestWaitableEvent top_idle_thread_running;
TestWaitableEvent top_idle_thread_continue;
auto task_runner_for_top_idle = test::CreatePooledSequencedTaskRunner(
{WithBaseSyncPrimitives()}, &mock_pooled_task_runner_delegate_);
task_runner_for_top_idle->PostTask(
FROM_HERE,
BindOnce(
[](PlatformThreadRef thread_ref,
TestWaitableEvent* top_idle_thread_running,
TestWaitableEvent* top_idle_thread_continue) {
ASSERT_FALSE(thread_ref.is_null());
EXPECT_NE(thread_ref, PlatformThread::CurrentRef())
<< "Worker reused. Worker will not cleanup and the "
"histogram value will be wrong.";
top_idle_thread_running->Signal();
top_idle_thread_continue->Wait();
},
thread_ref, Unretained(&top_idle_thread_running),
Unretained(&top_idle_thread_continue)));
top_idle_thread_running.Wait();
EXPECT_EQ(0U, thread_group_->NumberOfIdleWorkersForTesting());
cleanup_thread_continue.Signal();
// Wait for the cleanup thread to also become idle.
thread_group_->WaitForWorkersIdleForTesting(1U);
top_idle_thread_continue.Signal();
// Allow the thread processing the |histogrammed_thread_task_runner| work to
// cleanup.
thread_group_->WaitForWorkersCleanedUpForTesting(1U);
// Verify that counts were recorded to the histogram as expected.
const auto* histogram = thread_group_->num_tasks_before_detach_histogram();
EXPECT_EQ(0, histogram->SnapshotSamples()->GetCount(0));
EXPECT_EQ(0, histogram->SnapshotSamples()->GetCount(1));
EXPECT_EQ(0, histogram->SnapshotSamples()->GetCount(2));
EXPECT_EQ(1, histogram->SnapshotSamples()->GetCount(3));
EXPECT_EQ(0, histogram->SnapshotSamples()->GetCount(4));
EXPECT_EQ(0, histogram->SnapshotSamples()->GetCount(5));
EXPECT_EQ(0, histogram->SnapshotSamples()->GetCount(6));
EXPECT_EQ(0, histogram->SnapshotSamples()->GetCount(10));
}
namespace {
class ThreadGroupImplStandbyPolicyTest : public ThreadGroupImplImplTestBase,
public testing::Test {
public:
ThreadGroupImplStandbyPolicyTest() = default;
ThreadGroupImplStandbyPolicyTest(const ThreadGroupImplStandbyPolicyTest&) =
delete;
ThreadGroupImplStandbyPolicyTest& operator=(
const ThreadGroupImplStandbyPolicyTest&) = delete;
void SetUp() override {
CreateAndStartThreadGroup(kReclaimTimeForCleanupTests);
}
void TearDown() override { ThreadGroupImplImplTestBase::CommonTearDown(); }
};
} // namespace
TEST_F(ThreadGroupImplStandbyPolicyTest, InitOne) {
EXPECT_EQ(1U, thread_group_->NumberOfWorkersForTesting());
}
// Verify that the ThreadGroupImpl keeps at least one idle standby
// thread, capacity permitting.
TEST_F(ThreadGroupImplStandbyPolicyTest, VerifyStandbyThread) {
auto task_runner = test::CreatePooledTaskRunner(
{WithBaseSyncPrimitives()}, &mock_pooled_task_runner_delegate_);
TestWaitableEvent thread_running(WaitableEvent::ResetPolicy::AUTOMATIC);
TestWaitableEvent threads_continue;
RepeatingClosure thread_blocker = BindLambdaForTesting([&]() {
thread_running.Signal();
threads_continue.Wait();
});
// There should be one idle thread until we reach capacity
for (size_t i = 0; i < kMaxTasks; ++i) {
EXPECT_EQ(i + 1, thread_group_->NumberOfWorkersForTesting());
task_runner->PostTask(FROM_HERE, thread_blocker);
thread_running.Wait();
}
// There should not be an extra idle thread if it means going above capacity
EXPECT_EQ(kMaxTasks, thread_group_->NumberOfWorkersForTesting());
threads_continue.Signal();
// Wait long enough for all but one worker to clean up.
thread_group_->WaitForWorkersCleanedUpForTesting(kMaxTasks - 1);
EXPECT_EQ(1U, thread_group_->NumberOfWorkersForTesting());
// Give extra time for a worker to cleanup : none should as the thread group
// is expected to keep a worker ready regardless of how long it was idle for.
PlatformThread::Sleep(kReclaimTimeForCleanupTests);
EXPECT_EQ(1U, thread_group_->NumberOfWorkersForTesting());
}
// Verify that being "the" idle thread counts as being active (i.e. won't be
// reclaimed even if not on top of the idle stack when reclaim timeout expires).
// Regression test for https://crbug.com/847501.
TEST_F(ThreadGroupImplStandbyPolicyTest, InAndOutStandbyThreadIsActive) {
auto sequenced_task_runner = test::CreatePooledSequencedTaskRunner(
{}, &mock_pooled_task_runner_delegate_);
TestWaitableEvent timer_started;
RepeatingTimer recurring_task;
sequenced_task_runner->PostTask(
FROM_HERE, BindLambdaForTesting([&]() {
recurring_task.Start(FROM_HERE, kReclaimTimeForCleanupTests / 2,
DoNothing());
timer_started.Signal();
}));
timer_started.Wait();
// Running a task should have brought up a new standby thread.
EXPECT_EQ(2U, thread_group_->NumberOfWorkersForTesting());
// Give extra time for a worker to cleanup : none should as the two workers
// are both considered "active" per the timer ticking faster than the reclaim
// timeout.
PlatformThread::Sleep(kReclaimTimeForCleanupTests * 2);
EXPECT_EQ(2U, thread_group_->NumberOfWorkersForTesting());
sequenced_task_runner->PostTask(FROM_HERE, BindLambdaForTesting([&]() {
recurring_task.AbandonAndStop();
}));
// Stopping the recurring task should let the second worker be reclaimed per
// not being "the" standby thread for a full reclaim timeout.
thread_group_->WaitForWorkersCleanedUpForTesting(1);
EXPECT_EQ(1U, thread_group_->NumberOfWorkersForTesting());
}
// Verify that being "the" idle thread counts as being active but isn't sticky.
// Regression test for https://crbug.com/847501.
TEST_F(ThreadGroupImplStandbyPolicyTest, OnlyKeepActiveStandbyThreads) {
auto sequenced_task_runner = test::CreatePooledSequencedTaskRunner(
{}, &mock_pooled_task_runner_delegate_);
// Start this test like
// ThreadGroupImplStandbyPolicyTest.InAndOutStandbyThreadIsActive and
// give it some time to stabilize.
RepeatingTimer recurring_task;
sequenced_task_runner->PostTask(
FROM_HERE, BindLambdaForTesting([&]() {
recurring_task.Start(FROM_HERE, kReclaimTimeForCleanupTests / 2,
DoNothing());
}));
PlatformThread::Sleep(kReclaimTimeForCleanupTests * 2);
EXPECT_EQ(2U, thread_group_->NumberOfWorkersForTesting());
// Then also flood the thread group (cycling the top of the idle stack).
{
auto task_runner = test::CreatePooledTaskRunner(
{WithBaseSyncPrimitives()}, &mock_pooled_task_runner_delegate_);
TestWaitableEvent thread_running(WaitableEvent::ResetPolicy::AUTOMATIC);
TestWaitableEvent threads_continue;
RepeatingClosure thread_blocker = BindLambdaForTesting([&]() {
thread_running.Signal();
threads_continue.Wait();
});
for (size_t i = 0; i < kMaxTasks; ++i) {
task_runner->PostTask(FROM_HERE, thread_blocker);
thread_running.Wait();
}
EXPECT_EQ(kMaxTasks, thread_group_->NumberOfWorkersForTesting());
threads_continue.Signal();
// Flush to ensure all references to |threads_continue| are gone before it
// goes out of scope.
task_tracker_.FlushForTesting();
}
// All workers should clean up but two (since the timer is still running).
thread_group_->WaitForWorkersCleanedUpForTesting(kMaxTasks - 2);
EXPECT_EQ(2U, thread_group_->NumberOfWorkersForTesting());
// Extra time shouldn't change this.
PlatformThread::Sleep(kReclaimTimeForCleanupTests * 2);
EXPECT_EQ(2U, thread_group_->NumberOfWorkersForTesting());
// Stopping the timer should let the number of active threads go down to one.
sequenced_task_runner->PostTask(FROM_HERE, BindLambdaForTesting([&]() {
recurring_task.AbandonAndStop();
}));
thread_group_->WaitForWorkersCleanedUpForTesting(1);
EXPECT_EQ(1U, thread_group_->NumberOfWorkersForTesting());
}
namespace {
enum class OptionalBlockingType {
NO_BLOCK,
MAY_BLOCK,
WILL_BLOCK,
};
struct NestedBlockingType {
NestedBlockingType(BlockingType first_in,
OptionalBlockingType second_in,
BlockingType behaves_as_in)
: first(first_in), second(second_in), behaves_as(behaves_as_in) {}
BlockingType first;
OptionalBlockingType second;
BlockingType behaves_as;
};
class NestedScopedBlockingCall {
public:
explicit NestedScopedBlockingCall(
const NestedBlockingType& nested_blocking_type)
: first_scoped_blocking_call_(FROM_HERE, nested_blocking_type.first),
second_scoped_blocking_call_(
nested_blocking_type.second == OptionalBlockingType::WILL_BLOCK
? std::make_unique<ScopedBlockingCall>(FROM_HERE,
BlockingType::WILL_BLOCK)
: (nested_blocking_type.second ==
OptionalBlockingType::MAY_BLOCK
? std::make_unique<ScopedBlockingCall>(
FROM_HERE,
BlockingType::MAY_BLOCK)
: nullptr)) {}
NestedScopedBlockingCall(const NestedScopedBlockingCall&) = delete;
NestedScopedBlockingCall& operator=(const NestedScopedBlockingCall&) = delete;
private:
ScopedBlockingCall first_scoped_blocking_call_;
std::unique_ptr<ScopedBlockingCall> second_scoped_blocking_call_;
};
} // namespace
class ThreadGroupImplBlockingTest
: public ThreadGroupImplImplTestBase,
public testing::TestWithParam<NestedBlockingType> {
public:
ThreadGroupImplBlockingTest() = default;
ThreadGroupImplBlockingTest(const ThreadGroupImplBlockingTest&) = delete;
ThreadGroupImplBlockingTest& operator=(const ThreadGroupImplBlockingTest&) =
delete;
static std::string ParamInfoToString(
::testing::TestParamInfo<NestedBlockingType> param_info) {
std::string str = param_info.param.first == BlockingType::MAY_BLOCK
? "MAY_BLOCK"
: "WILL_BLOCK";
if (param_info.param.second == OptionalBlockingType::MAY_BLOCK)
str += "_MAY_BLOCK";
else if (param_info.param.second == OptionalBlockingType::WILL_BLOCK)
str += "_WILL_BLOCK";
return str;
}
void TearDown() override { ThreadGroupImplImplTestBase::CommonTearDown(); }
protected:
// Saturates the thread group with a task that first blocks, waits to be
// unblocked, then exits.
void SaturateWithBlockingTasks(
const NestedBlockingType& nested_blocking_type,
TaskPriority priority = TaskPriority::USER_BLOCKING) {
TestWaitableEvent threads_running;
const scoped_refptr<TaskRunner> task_runner = test::CreatePooledTaskRunner(
{MayBlock(), WithBaseSyncPrimitives(), priority},
&mock_pooled_task_runner_delegate_);
RepeatingClosure threads_running_barrier = BarrierClosure(
kMaxTasks,
BindOnce(&TestWaitableEvent::Signal, Unretained(&threads_running)));
for (size_t i = 0; i < kMaxTasks; ++i) {
task_runner->PostTask(
FROM_HERE, BindLambdaForTesting([this, &threads_running_barrier,
nested_blocking_type]() {
NestedScopedBlockingCall nested_scoped_blocking_call(
nested_blocking_type);
threads_running_barrier.Run();
blocking_threads_continue_.Wait();
}));
}
threads_running.Wait();
}
// Saturates the thread group with a task that waits for other tasks without
// entering a ScopedBlockingCall, then exits.
void SaturateWithBusyTasks(
TaskPriority priority = TaskPriority::USER_BLOCKING,
TaskShutdownBehavior shutdown_behavior =
TaskShutdownBehavior::SKIP_ON_SHUTDOWN) {
TestWaitableEvent threads_running;
const scoped_refptr<TaskRunner> task_runner = test::CreatePooledTaskRunner(
{MayBlock(), WithBaseSyncPrimitives(), priority, shutdown_behavior},
&mock_pooled_task_runner_delegate_);
RepeatingClosure threads_running_barrier = BarrierClosure(
kMaxTasks,
BindOnce(&TestWaitableEvent::Signal, Unretained(&threads_running)));
// Posting these tasks should cause new workers to be created.
for (size_t i = 0; i < kMaxTasks; ++i) {
task_runner->PostTask(
FROM_HERE, BindLambdaForTesting([this, &threads_running_barrier]() {
threads_running_barrier.Run();
busy_threads_continue_.Wait();
}));
}
threads_running.Wait();
}
// Returns how long we can expect a change to |max_tasks_| to occur
// after a task has become blocked.
TimeDelta GetMaxTasksChangeSleepTime() {
return std::max(thread_group_->blocked_workers_poll_period_for_testing(),
thread_group_->may_block_threshold_for_testing()) +
TestTimeouts::tiny_timeout();
}
// Waits indefinitely, until |thread_group_|'s max tasks increases to
// |expected_max_tasks|.
void ExpectMaxTasksIncreasesTo(size_t expected_max_tasks) {
size_t max_tasks = thread_group_->GetMaxTasksForTesting();
while (max_tasks != expected_max_tasks) {
PlatformThread::Sleep(GetMaxTasksChangeSleepTime());
size_t new_max_tasks = thread_group_->GetMaxTasksForTesting();
ASSERT_GE(new_max_tasks, max_tasks);
max_tasks = new_max_tasks;
}
}
// Unblocks tasks posted by SaturateWithBlockingTasks().
void UnblockBlockingTasks() { blocking_threads_continue_.Signal(); }
// Unblocks tasks posted by SaturateWithBusyTasks().
void UnblockBusyTasks() { busy_threads_continue_.Signal(); }
const scoped_refptr<TaskRunner> task_runner_ =
test::CreatePooledTaskRunner({MayBlock(), WithBaseSyncPrimitives()},
&mock_pooled_task_runner_delegate_);
private:
TestWaitableEvent blocking_threads_continue_;
TestWaitableEvent busy_threads_continue_;
};
// Verify that SaturateWithBlockingTasks() causes max tasks to increase and
// creates a worker if needed. Also verify that UnblockBlockingTasks() decreases
// max tasks after an increase.
TEST_P(ThreadGroupImplBlockingTest, ThreadBlockedUnblocked) {
CreateAndStartThreadGroup();
ASSERT_EQ(thread_group_->GetMaxTasksForTesting(), kMaxTasks);
SaturateWithBlockingTasks(GetParam());
// Forces |kMaxTasks| extra workers to be instantiated by posting tasks. This
// should not block forever.
SaturateWithBusyTasks();
EXPECT_EQ(thread_group_->NumberOfWorkersForTesting(), 2 * kMaxTasks);
UnblockBusyTasks();
UnblockBlockingTasks();
task_tracker_.FlushForTesting();
EXPECT_EQ(thread_group_->GetMaxTasksForTesting(), kMaxTasks);
}
// Verify that SaturateWithBlockingTasks() of BEST_EFFORT tasks causes max best
// effort tasks to increase and creates a worker if needed. Also verify that
// UnblockBlockingTasks() decreases max best effort tasks after an increase.
TEST_P(ThreadGroupImplBlockingTest, ThreadBlockedUnblockedBestEffort) {
CreateAndStartThreadGroup();
ASSERT_EQ(thread_group_->GetMaxTasksForTesting(), kMaxTasks);
ASSERT_EQ(thread_group_->GetMaxBestEffortTasksForTesting(), kMaxTasks);
SaturateWithBlockingTasks(GetParam(), TaskPriority::BEST_EFFORT);
// Forces |kMaxTasks| extra workers to be instantiated by posting tasks. This
// should not block forever.
SaturateWithBusyTasks(TaskPriority::BEST_EFFORT);
EXPECT_EQ(thread_group_->NumberOfWorkersForTesting(), 2 * kMaxTasks);
UnblockBusyTasks();
UnblockBlockingTasks();
task_tracker_.FlushForTesting();
EXPECT_EQ(thread_group_->GetMaxTasksForTesting(), kMaxTasks);
EXPECT_EQ(thread_group_->GetMaxBestEffortTasksForTesting(), kMaxTasks);
}
// Verify that flooding the thread group with more BEST_EFFORT tasks than
// kMaxBestEffortTasks doesn't prevent USER_VISIBLE tasks from running.
TEST_P(ThreadGroupImplBlockingTest, TooManyBestEffortTasks) {
constexpr size_t kMaxBestEffortTasks = kMaxTasks / 2;
CreateAndStartThreadGroup(TimeDelta::Max(), kMaxTasks, kMaxBestEffortTasks);
TestWaitableEvent threads_continue;
{
TestWaitableEvent entered_blocking_scope;
RepeatingClosure entered_blocking_scope_barrier = BarrierClosure(
kMaxBestEffortTasks + 1, BindOnce(&TestWaitableEvent::Signal,
Unretained(&entered_blocking_scope)));
TestWaitableEvent exit_blocking_scope;
TestWaitableEvent threads_running;
RepeatingClosure threads_running_barrier = BarrierClosure(
kMaxBestEffortTasks + 1,
BindOnce(&TestWaitableEvent::Signal, Unretained(&threads_running)));
const auto best_effort_task_runner =
test::CreatePooledTaskRunner({TaskPriority::BEST_EFFORT, MayBlock()},
&mock_pooled_task_runner_delegate_);
for (size_t i = 0; i < kMaxBestEffortTasks + 1; ++i) {
best_effort_task_runner->PostTask(
FROM_HERE, BindLambdaForTesting([&]() {
{
NestedScopedBlockingCall scoped_blocking_call(GetParam());
entered_blocking_scope_barrier.Run();
exit_blocking_scope.Wait();
}
threads_running_barrier.Run();
threads_continue.Wait();
}));
}
entered_blocking_scope.Wait();
exit_blocking_scope.Signal();
threads_running.Wait();
}
// At this point, kMaxBestEffortTasks + 1 threads are running (plus
// potentially the idle thread), but max_task and max_best_effort_task are
// back to normal.
EXPECT_GE(thread_group_->NumberOfWorkersForTesting(),
kMaxBestEffortTasks + 1);
EXPECT_LE(thread_group_->NumberOfWorkersForTesting(),
kMaxBestEffortTasks + 2);
EXPECT_EQ(thread_group_->GetMaxTasksForTesting(), kMaxTasks);
TestWaitableEvent threads_running;
task_runner_->PostTask(FROM_HERE, BindLambdaForTesting([&]() {
threads_running.Signal();
threads_continue.Wait();
}));
// This should not block forever.
threads_running.Wait();
EXPECT_GE(thread_group_->NumberOfWorkersForTesting(),
kMaxBestEffortTasks + 2);
EXPECT_LE(thread_group_->NumberOfWorkersForTesting(),
kMaxBestEffortTasks + 3);
threads_continue.Signal();
task_tracker_.FlushForTesting();
}
// Verify that tasks posted in a saturated thread group before a
// ScopedBlockingCall will execute after ScopedBlockingCall is instantiated.
TEST_P(ThreadGroupImplBlockingTest, PostBeforeBlocking) {
CreateAndStartThreadGroup();
TestWaitableEvent thread_running(WaitableEvent::ResetPolicy::AUTOMATIC);
TestWaitableEvent thread_can_block;
TestWaitableEvent threads_continue;
for (size_t i = 0; i < kMaxTasks; ++i) {
task_runner_->PostTask(
FROM_HERE,
BindOnce(
[](const NestedBlockingType& nested_blocking_type,
TestWaitableEvent* thread_running,
TestWaitableEvent* thread_can_block,
TestWaitableEvent* threads_continue) {
thread_running->Signal();
thread_can_block->Wait();
NestedScopedBlockingCall nested_scoped_blocking_call(
nested_blocking_type);
threads_continue->Wait();
},
GetParam(), Unretained(&thread_running),
Unretained(&thread_can_block), Unretained(&threads_continue)));
thread_running.Wait();
}
// All workers should be occupied and the thread group should be saturated.
// Workers have not entered ScopedBlockingCall yet.
EXPECT_EQ(thread_group_->NumberOfWorkersForTesting(), kMaxTasks);
EXPECT_EQ(thread_group_->GetMaxTasksForTesting(), kMaxTasks);
TestWaitableEvent extra_threads_running;
TestWaitableEvent extra_threads_continue;
RepeatingClosure extra_threads_running_barrier = BarrierClosure(
kMaxTasks,
BindOnce(&TestWaitableEvent::Signal, Unretained(&extra_threads_running)));
for (size_t i = 0; i < kMaxTasks; ++i) {
task_runner_->PostTask(
FROM_HERE, BindOnce(
[](RepeatingClosure* extra_threads_running_barrier,
TestWaitableEvent* extra_threads_continue) {
extra_threads_running_barrier->Run();
extra_threads_continue->Wait();
},
Unretained(&extra_threads_running_barrier),
Unretained(&extra_threads_continue)));
}
// Allow tasks to enter ScopedBlockingCall. Workers should be created for the
// tasks we just posted.
thread_can_block.Signal();
// Should not block forever.
extra_threads_running.Wait();
EXPECT_EQ(thread_group_->NumberOfWorkersForTesting(), 2 * kMaxTasks);
extra_threads_continue.Signal();
threads_continue.Signal();
task_tracker_.FlushForTesting();
}
// Verify that workers become idle when the thread group is over-capacity and
// that those workers do no work.
TEST_P(ThreadGroupImplBlockingTest, WorkersIdleWhenOverCapacity) {
CreateAndStartThreadGroup();
ASSERT_EQ(thread_group_->GetMaxTasksForTesting(), kMaxTasks);
SaturateWithBlockingTasks(GetParam());
// Forces |kMaxTasks| extra workers to be instantiated by posting tasks.
SaturateWithBusyTasks();
ASSERT_EQ(thread_group_->NumberOfIdleWorkersForTesting(), 0U);
EXPECT_EQ(thread_group_->NumberOfWorkersForTesting(), 2 * kMaxTasks);
AtomicFlag is_exiting;
// These tasks should not get executed until after other tasks become
// unblocked.
for (size_t i = 0; i < kMaxTasks; ++i) {
task_runner_->PostTask(FROM_HERE, BindOnce(
[](AtomicFlag* is_exiting) {
EXPECT_TRUE(is_exiting->IsSet());
},
Unretained(&is_exiting)));
}
// The original |kMaxTasks| will finish their tasks after being unblocked.
// There will be work in the work queue, but the thread group should now be
// over-capacity and workers will become idle.
UnblockBlockingTasks();
thread_group_->WaitForWorkersIdleForTesting(kMaxTasks);
EXPECT_EQ(thread_group_->NumberOfIdleWorkersForTesting(), kMaxTasks);
// Posting more tasks should not cause workers idle from the thread group
// being over capacity to begin doing work.
for (size_t i = 0; i < kMaxTasks; ++i) {
task_runner_->PostTask(FROM_HERE, BindOnce(
[](AtomicFlag* is_exiting) {
EXPECT_TRUE(is_exiting->IsSet());
},
Unretained(&is_exiting)));
}
// Give time for those idle workers to possibly do work (which should not
// happen).
PlatformThread::Sleep(TestTimeouts::tiny_timeout());
is_exiting.Set();
// Unblocks the new workers.
UnblockBusyTasks();
task_tracker_.FlushForTesting();
}
// Verify that an increase of max tasks with SaturateWithBlockingTasks()
// increases the number of tasks that can run before ShouldYield returns true.
TEST_P(ThreadGroupImplBlockingTest, ThreadBlockedUnblockedShouldYield) {
CreateAndStartThreadGroup();
ASSERT_EQ(thread_group_->GetMaxTasksForTesting(), kMaxTasks);
EXPECT_FALSE(
thread_group_->ShouldYield({TaskPriority::BEST_EFFORT, TimeTicks()}));
SaturateWithBlockingTasks(GetParam());
EXPECT_FALSE(
thread_group_->ShouldYield({TaskPriority::BEST_EFFORT, TimeTicks()}));
// Forces |kMaxTasks| extra workers to be instantiated by posting tasks. This
// should not block forever.
SaturateWithBusyTasks();
// All tasks can run, hence ShouldYield returns false.
EXPECT_FALSE(
thread_group_->ShouldYield({TaskPriority::BEST_EFFORT, TimeTicks()}));
// Post a USER_VISIBLE task that can't run since workers are saturated. This
// should cause BEST_EFFORT tasks to yield.
test::CreatePooledTaskRunner({TaskPriority::USER_VISIBLE},
&mock_pooled_task_runner_delegate_)
->PostTask(FROM_HERE, BindLambdaForTesting([&]() {
EXPECT_FALSE(thread_group_->ShouldYield(
{TaskPriority::BEST_EFFORT, TimeTicks()}));
}));
EXPECT_TRUE(
thread_group_->ShouldYield({TaskPriority::BEST_EFFORT, TimeTicks()}));
// Post a USER_BLOCKING task that can't run since workers are saturated. This
// should cause USER_VISIBLE tasks to yield.
test::CreatePooledTaskRunner({TaskPriority::USER_BLOCKING},
&mock_pooled_task_runner_delegate_)
->PostTask(FROM_HERE, BindLambdaForTesting([&]() {
EXPECT_FALSE(thread_group_->ShouldYield(
{TaskPriority::USER_VISIBLE, TimeTicks()}));
}));
EXPECT_TRUE(
thread_group_->ShouldYield({TaskPriority::USER_VISIBLE, TimeTicks()}));
UnblockBusyTasks();
UnblockBlockingTasks();
task_tracker_.FlushForTesting();
EXPECT_EQ(thread_group_->GetMaxTasksForTesting(), kMaxTasks);
}
INSTANTIATE_TEST_SUITE_P(
All,
ThreadGroupImplBlockingTest,
::testing::Values(NestedBlockingType(BlockingType::MAY_BLOCK,
OptionalBlockingType::NO_BLOCK,
BlockingType::MAY_BLOCK),
NestedBlockingType(BlockingType::WILL_BLOCK,
OptionalBlockingType::NO_BLOCK,
BlockingType::WILL_BLOCK),
NestedBlockingType(BlockingType::MAY_BLOCK,
OptionalBlockingType::WILL_BLOCK,
BlockingType::WILL_BLOCK),
NestedBlockingType(BlockingType::WILL_BLOCK,
OptionalBlockingType::MAY_BLOCK,
BlockingType::WILL_BLOCK)),
ThreadGroupImplBlockingTest::ParamInfoToString);
// Verify that if a thread enters the scope of a MAY_BLOCK ScopedBlockingCall,
// but exits the scope before the MayBlock threshold is reached, that the max
// tasks does not increase.
TEST_F(ThreadGroupImplBlockingTest, ThreadBlockUnblockPremature) {
// Create a thread group with an infinite MayBlock threshold so that a
// MAY_BLOCK ScopedBlockingCall never increases the max tasks.
CreateAndStartThreadGroup(TimeDelta::Max(), // |suggested_reclaim_time|
kMaxTasks, // |max_tasks|
absl::nullopt, // |max_best_effort_tasks|
nullptr, // |worker_observer|
TimeDelta::Max()); // |may_block_threshold|
ASSERT_EQ(thread_group_->GetMaxTasksForTesting(), kMaxTasks);
SaturateWithBlockingTasks(NestedBlockingType(BlockingType::MAY_BLOCK,
OptionalBlockingType::NO_BLOCK,
BlockingType::MAY_BLOCK));
PlatformThread::Sleep(
2 * thread_group_->blocked_workers_poll_period_for_testing());
EXPECT_EQ(thread_group_->NumberOfWorkersForTesting(), kMaxTasks);
EXPECT_EQ(thread_group_->GetMaxTasksForTesting(), kMaxTasks);
UnblockBlockingTasks();
task_tracker_.FlushForTesting();
EXPECT_EQ(thread_group_->GetMaxTasksForTesting(), kMaxTasks);
}
// Verify that if a BEST_EFFORT task enters the scope of a WILL_BLOCK
// ScopedBlockingCall, but exits the scope before the MayBlock threshold is
// reached, that the max best effort tasks does not increase.
TEST_F(ThreadGroupImplBlockingTest, ThreadBlockUnblockPrematureBestEffort) {
// Create a thread group with an infinite MayBlock threshold so that a
// MAY_BLOCK ScopedBlockingCall never increases the max tasks.
CreateAndStartThreadGroup(TimeDelta::Max(), // |suggested_reclaim_time|
kMaxTasks, // |max_tasks|
kMaxTasks, // |max_best_effort_tasks|
nullptr, // |worker_observer|
TimeDelta::Max()); // |may_block_threshold|
ASSERT_EQ(thread_group_->GetMaxTasksForTesting(), kMaxTasks);
ASSERT_EQ(thread_group_->GetMaxBestEffortTasksForTesting(), kMaxTasks);
SaturateWithBlockingTasks(NestedBlockingType(BlockingType::WILL_BLOCK,
OptionalBlockingType::NO_BLOCK,
BlockingType::WILL_BLOCK),
TaskPriority::BEST_EFFORT);
PlatformThread::Sleep(
2 * thread_group_->blocked_workers_poll_period_for_testing());
EXPECT_GE(thread_group_->NumberOfWorkersForTesting(), kMaxTasks);
EXPECT_EQ(thread_group_->GetMaxTasksForTesting(), 2 * kMaxTasks);
EXPECT_EQ(thread_group_->GetMaxBestEffortTasksForTesting(), kMaxTasks);
UnblockBlockingTasks();
task_tracker_.FlushForTesting();
EXPECT_EQ(thread_group_->GetMaxTasksForTesting(), kMaxTasks);
EXPECT_EQ(thread_group_->GetMaxBestEffortTasksForTesting(), kMaxTasks);
}
// Verify that if max tasks is incremented because of a MAY_BLOCK
// ScopedBlockingCall, it isn't incremented again when there is a nested
// WILL_BLOCK ScopedBlockingCall.
TEST_F(ThreadGroupImplBlockingTest, MayBlockIncreaseCapacityNestedWillBlock) {
CreateAndStartThreadGroup();
ASSERT_EQ(thread_group_->GetMaxTasksForTesting(), kMaxTasks);
auto task_runner =
test::CreatePooledTaskRunner({MayBlock(), WithBaseSyncPrimitives()},
&mock_pooled_task_runner_delegate_);
TestWaitableEvent can_return;
// Saturate the thread group so that a MAY_BLOCK ScopedBlockingCall would
// increment the max tasks.
for (size_t i = 0; i < kMaxTasks - 1; ++i) {
task_runner->PostTask(
FROM_HERE, BindOnce(&TestWaitableEvent::Wait, Unretained(&can_return)));
}
TestWaitableEvent can_instantiate_will_block;
TestWaitableEvent did_instantiate_will_block;
// Post a task that instantiates a MAY_BLOCK ScopedBlockingCall.
task_runner->PostTask(
FROM_HERE,
BindOnce(
[](TestWaitableEvent* can_instantiate_will_block,
TestWaitableEvent* did_instantiate_will_block,
TestWaitableEvent* can_return) {
ScopedBlockingCall may_block(FROM_HERE, BlockingType::MAY_BLOCK);
can_instantiate_will_block->Wait();
ScopedBlockingCall will_block(FROM_HERE, BlockingType::WILL_BLOCK);
did_instantiate_will_block->Signal();
can_return->Wait();
},
Unretained(&can_instantiate_will_block),
Unretained(&did_instantiate_will_block), Unretained(&can_return)));
// After a short delay, max tasks should be incremented.
ExpectMaxTasksIncreasesTo(kMaxTasks + 1);
// Wait until the task instantiates a WILL_BLOCK ScopedBlockingCall.
can_instantiate_will_block.Signal();
did_instantiate_will_block.Wait();
// Max tasks shouldn't be incremented again.
EXPECT_EQ(kMaxTasks + 1, thread_group_->GetMaxTasksForTesting());
// Tear down.
can_return.Signal();
task_tracker_.FlushForTesting();
EXPECT_EQ(thread_group_->GetMaxTasksForTesting(), kMaxTasks);
}
// Verify that OnShutdownStarted() causes max tasks to increase and creates a
// worker if needed. Also verify that UnblockBusyTasks() decreases max tasks
// after an increase.
TEST_F(ThreadGroupImplBlockingTest, ThreadBusyShutdown) {
CreateAndStartThreadGroup();
ASSERT_EQ(thread_group_->GetMaxTasksForTesting(), kMaxTasks);
SaturateWithBusyTasks(TaskPriority::BEST_EFFORT,
TaskShutdownBehavior::CONTINUE_ON_SHUTDOWN);
thread_group_->OnShutdownStarted();
// Forces |kMaxTasks| extra workers to be instantiated by posting tasks. This
// should not block forever.
SaturateWithBusyTasks(TaskPriority::BEST_EFFORT,
TaskShutdownBehavior::BLOCK_SHUTDOWN);
EXPECT_EQ(thread_group_->NumberOfWorkersForTesting(), 2 * kMaxTasks);
UnblockBusyTasks();
task_tracker_.FlushForTesting();
thread_group_->JoinForTesting();
EXPECT_EQ(thread_group_->GetMaxTasksForTesting(), kMaxTasks);
thread_group_.reset();
}
class ThreadGroupImplOverCapacityTest : public ThreadGroupImplImplTestBase,
public testing::Test {
public:
ThreadGroupImplOverCapacityTest() = default;
ThreadGroupImplOverCapacityTest(const ThreadGroupImplOverCapacityTest&) =
delete;
ThreadGroupImplOverCapacityTest& operator=(
const ThreadGroupImplOverCapacityTest&) = delete;
void SetUp() override {
CreateAndStartThreadGroup(kReclaimTimeForCleanupTests, kLocalMaxTasks);
task_runner_ =
test::CreatePooledTaskRunner({MayBlock(), WithBaseSyncPrimitives()},
&mock_pooled_task_runner_delegate_);
}
void TearDown() override { ThreadGroupImplImplTestBase::CommonTearDown(); }
protected:
scoped_refptr<TaskRunner> task_runner_;
static constexpr size_t kLocalMaxTasks = 3;
void CreateThreadGroup() {
ASSERT_FALSE(thread_group_);
service_thread_.Start();
delayed_task_manager_.Start(service_thread_.task_runner());
thread_group_ = std::make_unique<ThreadGroupImpl>(
"OverCapacityTestThreadGroup", "A", ThreadPriority::NORMAL,
task_tracker_.GetTrackedRef(), tracked_ref_factory_.GetTrackedRef());
ASSERT_TRUE(thread_group_);
}
};
// Verify that workers that become idle due to the thread group being over
// capacity will eventually cleanup.
TEST_F(ThreadGroupImplOverCapacityTest, VerifyCleanup) {
TestWaitableEvent threads_running;
TestWaitableEvent threads_continue;
RepeatingClosure threads_running_barrier = BarrierClosure(
kLocalMaxTasks,
BindOnce(&TestWaitableEvent::Signal, Unretained(&threads_running)));
TestWaitableEvent blocked_call_continue;
RepeatingClosure closure = BindRepeating(
[](RepeatingClosure* threads_running_barrier,
TestWaitableEvent* threads_continue,
TestWaitableEvent* blocked_call_continue) {
threads_running_barrier->Run();
{
ScopedBlockingCall scoped_blocking_call(FROM_HERE,
BlockingType::WILL_BLOCK);
blocked_call_continue->Wait();
}
threads_continue->Wait();
},
Unretained(&threads_running_barrier), Unretained(&threads_continue),
Unretained(&blocked_call_continue));
for (size_t i = 0; i < kLocalMaxTasks; ++i)
task_runner_->PostTask(FROM_HERE, closure);
threads_running.Wait();
TestWaitableEvent extra_threads_running;
TestWaitableEvent extra_threads_continue;
RepeatingClosure extra_threads_running_barrier = BarrierClosure(
kLocalMaxTasks,
BindOnce(&TestWaitableEvent::Signal, Unretained(&extra_threads_running)));
// These tasks should run on the new threads from increasing max tasks.
for (size_t i = 0; i < kLocalMaxTasks; ++i) {
task_runner_->PostTask(
FROM_HERE, BindOnce(
[](RepeatingClosure* extra_threads_running_barrier,
TestWaitableEvent* extra_threads_continue) {
extra_threads_running_barrier->Run();
extra_threads_continue->Wait();
},
Unretained(&extra_threads_running_barrier),
Unretained(&extra_threads_continue)));
}
extra_threads_running.Wait();
ASSERT_EQ(kLocalMaxTasks * 2, thread_group_->NumberOfWorkersForTesting());
EXPECT_EQ(kLocalMaxTasks * 2, thread_group_->GetMaxTasksForTesting());
blocked_call_continue.Signal();
extra_threads_continue.Signal();
// Periodically post tasks to ensure that posting tasks does not prevent
// workers that are idle due to the thread group being over capacity from
// cleaning up.
for (int i = 0; i < 16; ++i) {
task_runner_->PostDelayedTask(FROM_HERE, DoNothing(),
kReclaimTimeForCleanupTests * i * 0.5);
}
// Note: one worker above capacity will not get cleaned up since it's on the
// top of the idle stack.
thread_group_->WaitForWorkersCleanedUpForTesting(kLocalMaxTasks - 1);
EXPECT_EQ(kLocalMaxTasks + 1, thread_group_->NumberOfWorkersForTesting());
threads_continue.Signal();
task_tracker_.FlushForTesting();
}
// Verify that the maximum number of workers is 256 and that hitting the max
// leaves the thread group in a valid state with regards to max tasks.
TEST_F(ThreadGroupImplBlockingTest, MaximumWorkersTest) {
CreateAndStartThreadGroup();
constexpr size_t kMaxNumberOfWorkers = 256;
constexpr size_t kNumExtraTasks = 10;
TestWaitableEvent early_blocking_threads_running;
RepeatingClosure early_threads_barrier_closure =
BarrierClosure(kMaxNumberOfWorkers,
BindOnce(&TestWaitableEvent::Signal,
Unretained(&early_blocking_threads_running)));
TestWaitableEvent early_threads_finished;
RepeatingClosure early_threads_finished_barrier = BarrierClosure(
kMaxNumberOfWorkers, BindOnce(&TestWaitableEvent::Signal,
Unretained(&early_threads_finished)));
TestWaitableEvent early_release_threads_continue;
// Post ScopedBlockingCall tasks to hit the worker cap.
for (size_t i = 0; i < kMaxNumberOfWorkers; ++i) {
task_runner_->PostTask(
FROM_HERE, BindOnce(
[](RepeatingClosure* early_threads_barrier_closure,
TestWaitableEvent* early_release_threads_continue,
RepeatingClosure* early_threads_finished) {
{
ScopedBlockingCall scoped_blocking_call(
FROM_HERE, BlockingType::WILL_BLOCK);
early_threads_barrier_closure->Run();
early_release_threads_continue->Wait();
}
early_threads_finished->Run();
},
Unretained(&early_threads_barrier_closure),
Unretained(&early_release_threads_continue),
Unretained(&early_threads_finished_barrier)));
}
early_blocking_threads_running.Wait();
EXPECT_EQ(thread_group_->GetMaxTasksForTesting(),
kMaxTasks + kMaxNumberOfWorkers);
TestWaitableEvent late_release_thread_contine;
TestWaitableEvent late_blocking_threads_running;
RepeatingClosure late_threads_barrier_closure = BarrierClosure(
kNumExtraTasks, BindOnce(&TestWaitableEvent::Signal,
Unretained(&late_blocking_threads_running)));
// Posts additional tasks. Note: we should already have |kMaxNumberOfWorkers|
// tasks running. These tasks should not be able to get executed yet as the
// thread group is already at its max worker cap.
for (size_t i = 0; i < kNumExtraTasks; ++i) {
task_runner_->PostTask(
FROM_HERE, BindOnce(
[](RepeatingClosure* late_threads_barrier_closure,
TestWaitableEvent* late_release_thread_contine) {
ScopedBlockingCall scoped_blocking_call(
FROM_HERE, BlockingType::WILL_BLOCK);
late_threads_barrier_closure->Run();
late_release_thread_contine->Wait();
},
Unretained(&late_threads_barrier_closure),
Unretained(&late_release_thread_contine)));
}
// Give time to see if we exceed the max number of workers.
PlatformThread::Sleep(TestTimeouts::tiny_timeout());
EXPECT_LE(thread_group_->NumberOfWorkersForTesting(), kMaxNumberOfWorkers);
early_release_threads_continue.Signal();
early_threads_finished.Wait();
late_blocking_threads_running.Wait();
TestWaitableEvent final_tasks_running;
TestWaitableEvent final_tasks_continue;
RepeatingClosure final_tasks_running_barrier = BarrierClosure(
kMaxTasks,
BindOnce(&TestWaitableEvent::Signal, Unretained(&final_tasks_running)));
// Verify that we are still able to saturate the thread group.
for (size_t i = 0; i < kMaxTasks; ++i) {
task_runner_->PostTask(FROM_HERE,
BindOnce(
[](RepeatingClosure* closure,
TestWaitableEvent* final_tasks_continue) {
closure->Run();
final_tasks_continue->Wait();
},
Unretained(&final_tasks_running_barrier),
Unretained(&final_tasks_continue)));
}
final_tasks_running.Wait();
EXPECT_EQ(thread_group_->GetMaxTasksForTesting(), kMaxTasks + kNumExtraTasks);
late_release_thread_contine.Signal();
final_tasks_continue.Signal();
task_tracker_.FlushForTesting();
}
// Verify that the maximum number of best-effort tasks that can run concurrently
// is honored.
TEST_F(ThreadGroupImplImplStartInBodyTest, MaxBestEffortTasks) {
constexpr int kMaxBestEffortTasks = kMaxTasks / 2;
StartThreadGroup(TimeDelta::Max(), // |suggested_reclaim_time|
kMaxTasks, // |max_tasks|
kMaxBestEffortTasks); // |max_best_effort_tasks|
const scoped_refptr<TaskRunner> foreground_runner =
test::CreatePooledTaskRunner({MayBlock()},
&mock_pooled_task_runner_delegate_);
const scoped_refptr<TaskRunner> background_runner =
test::CreatePooledTaskRunner({TaskPriority::BEST_EFFORT, MayBlock()},
&mock_pooled_task_runner_delegate_);
// It should be possible to have |kMaxBestEffortTasks|
// TaskPriority::BEST_EFFORT tasks running concurrently.
TestWaitableEvent best_effort_tasks_running;
TestWaitableEvent unblock_best_effort_tasks;
RepeatingClosure best_effort_tasks_running_barrier = BarrierClosure(
kMaxBestEffortTasks, BindOnce(&TestWaitableEvent::Signal,
Unretained(&best_effort_tasks_running)));
for (int i = 0; i < kMaxBestEffortTasks; ++i) {
background_runner->PostTask(
FROM_HERE, base::BindLambdaForTesting([&]() {
best_effort_tasks_running_barrier.Run();
unblock_best_effort_tasks.Wait();
}));
}
best_effort_tasks_running.Wait();
// No more TaskPriority::BEST_EFFORT task should run.
AtomicFlag extra_best_effort_task_can_run;
TestWaitableEvent extra_best_effort_task_running;
background_runner->PostTask(
FROM_HERE, base::BindLambdaForTesting([&]() {
EXPECT_TRUE(extra_best_effort_task_can_run.IsSet());
extra_best_effort_task_running.Signal();
}));
// An extra foreground task should be able to run.
TestWaitableEvent foreground_task_running;
foreground_runner->PostTask(
FROM_HERE, base::BindOnce(&TestWaitableEvent::Signal,
Unretained(&foreground_task_running)));
foreground_task_running.Wait();
// Completion of the TaskPriority::BEST_EFFORT tasks should allow the extra
// TaskPriority::BEST_EFFORT task to run.
extra_best_effort_task_can_run.Set();
unblock_best_effort_tasks.Signal();
extra_best_effort_task_running.Wait();
// Wait for all tasks to complete before exiting to avoid invalid accesses.
task_tracker_.FlushForTesting();
}
// Verify that flooding the thread group with BEST_EFFORT tasks doesn't cause
// the creation of more than |max_best_effort_tasks| + 1 workers.
TEST_F(ThreadGroupImplImplStartInBodyTest,
FloodBestEffortTasksDoesNotCreateTooManyWorkers) {
constexpr size_t kMaxBestEffortTasks = kMaxTasks / 2;
StartThreadGroup(TimeDelta::Max(), // |suggested_reclaim_time|
kMaxTasks, // |max_tasks|
kMaxBestEffortTasks); // |max_best_effort_tasks|
const scoped_refptr<TaskRunner> runner =
test::CreatePooledTaskRunner({TaskPriority::BEST_EFFORT, MayBlock()},
&mock_pooled_task_runner_delegate_);
for (size_t i = 0; i < kLargeNumber; ++i) {
runner->PostTask(FROM_HERE, BindLambdaForTesting([&]() {
EXPECT_LE(thread_group_->NumberOfWorkersForTesting(),
kMaxBestEffortTasks + 1);
}));
}
// Wait for all tasks to complete before exiting to avoid invalid accesses.
task_tracker_.FlushForTesting();
}
// Previously, a WILL_BLOCK ScopedBlockingCall unconditionally woke up a worker
// if the priority queue was non-empty. Sometimes, that caused multiple workers
// to be woken up for the same sequence. This test verifies that it is no longer
// the case:
// 1. Post and run task A.
// 2. Post task B from task A.
// 3. Task A enters a WILL_BLOCK ScopedBlockingCall. Once the idle thread is
// created, this should no-op because there are already enough workers
// (previously, a worker would be woken up because the priority queue isn't
// empty).
// 5. Wait for all tasks to complete.
TEST_F(ThreadGroupImplImplStartInBodyTest,
RepeatedWillBlockDoesNotCreateTooManyWorkers) {
constexpr size_t kNumWorkers = 2U;
StartThreadGroup(TimeDelta::Max(), // |suggested_reclaim_time|
kNumWorkers, // |max_tasks|
absl::nullopt); // |max_best_effort_tasks|
const scoped_refptr<TaskRunner> runner = test::CreatePooledTaskRunner(
{MayBlock()}, &mock_pooled_task_runner_delegate_);
for (size_t i = 0; i < kLargeNumber; ++i) {
runner->PostTask(FROM_HERE, BindLambdaForTesting([&]() {
runner->PostTask(
FROM_HERE, BindLambdaForTesting([&]() {
EXPECT_LE(
thread_group_->NumberOfWorkersForTesting(),
kNumWorkers + 1);
}));
// Number of workers should not increase when there is
// enough capacity to accommodate queued and running
// sequences.
ScopedBlockingCall scoped_blocking_call(
FROM_HERE, BlockingType::WILL_BLOCK);
EXPECT_EQ(kNumWorkers + 1,
thread_group_->NumberOfWorkersForTesting());
}));
// Wait for all tasks to complete.
task_tracker_.FlushForTesting();
}
}
namespace {
class ThreadGroupImplBlockingCallAndMaxBestEffortTasksTest
: public ThreadGroupImplImplTestBase,
public testing::TestWithParam<BlockingType> {
public:
static constexpr int kMaxBestEffortTasks = kMaxTasks / 2;
ThreadGroupImplBlockingCallAndMaxBestEffortTasksTest() = default;
ThreadGroupImplBlockingCallAndMaxBestEffortTasksTest(
const ThreadGroupImplBlockingCallAndMaxBestEffortTasksTest&) = delete;
ThreadGroupImplBlockingCallAndMaxBestEffortTasksTest& operator=(
const ThreadGroupImplBlockingCallAndMaxBestEffortTasksTest&) = delete;
void SetUp() override {
CreateThreadGroup();
thread_group_->Start(kMaxTasks, kMaxBestEffortTasks, base::TimeDelta::Max(),
service_thread_.task_runner(), nullptr,
ThreadGroup::WorkerEnvironment::NONE);
}
void TearDown() override { ThreadGroupImplImplTestBase::CommonTearDown(); }
private:
};
} // namespace
TEST_P(ThreadGroupImplBlockingCallAndMaxBestEffortTasksTest,
BlockingCallAndMaxBestEffortTasksTest) {
const scoped_refptr<TaskRunner> background_runner =
test::CreatePooledTaskRunner({TaskPriority::BEST_EFFORT, MayBlock()},
&mock_pooled_task_runner_delegate_);
// Post |kMaxBestEffortTasks| TaskPriority::BEST_EFFORT tasks that block in a
// ScopedBlockingCall.
TestWaitableEvent blocking_best_effort_tasks_running;
TestWaitableEvent unblock_blocking_best_effort_tasks;
RepeatingClosure blocking_best_effort_tasks_running_barrier =
BarrierClosure(kMaxBestEffortTasks,
BindOnce(&TestWaitableEvent::Signal,
Unretained(&blocking_best_effort_tasks_running)));
for (int i = 0; i < kMaxBestEffortTasks; ++i) {
background_runner->PostTask(
FROM_HERE, base::BindLambdaForTesting([&]() {
blocking_best_effort_tasks_running_barrier.Run();
ScopedBlockingCall scoped_blocking_call(FROM_HERE, GetParam());
unblock_blocking_best_effort_tasks.Wait();
}));
}
blocking_best_effort_tasks_running.Wait();
// Post an extra |kMaxBestEffortTasks| TaskPriority::BEST_EFFORT tasks. They
// should be able to run, because the existing TaskPriority::BEST_EFFORT tasks
// are blocked within a ScopedBlockingCall.
//
// Note: We block the tasks until they have all started running to make sure
// that it is possible to run an extra |kMaxBestEffortTasks| concurrently.
TestWaitableEvent best_effort_tasks_running;
TestWaitableEvent unblock_best_effort_tasks;
RepeatingClosure best_effort_tasks_running_barrier = BarrierClosure(
kMaxBestEffortTasks, BindOnce(&TestWaitableEvent::Signal,
Unretained(&best_effort_tasks_running)));
for (int i = 0; i < kMaxBestEffortTasks; ++i) {
background_runner->PostTask(
FROM_HERE, base::BindLambdaForTesting([&]() {
best_effort_tasks_running_barrier.Run();
unblock_best_effort_tasks.Wait();
}));
}
best_effort_tasks_running.Wait();
// Unblock all tasks and tear down.
unblock_blocking_best_effort_tasks.Signal();
unblock_best_effort_tasks.Signal();
task_tracker_.FlushForTesting();
}
INSTANTIATE_TEST_SUITE_P(MayBlock,
ThreadGroupImplBlockingCallAndMaxBestEffortTasksTest,
::testing::Values(BlockingType::MAY_BLOCK));
INSTANTIATE_TEST_SUITE_P(WillBlock,
ThreadGroupImplBlockingCallAndMaxBestEffortTasksTest,
::testing::Values(BlockingType::WILL_BLOCK));
// Verify that worker detachment doesn't race with worker cleanup, regression
// test for https://crbug.com/810464.
TEST_F(ThreadGroupImplImplStartInBodyTest, RacyCleanup) {
constexpr size_t kLocalMaxTasks = 256;
constexpr TimeDelta kReclaimTimeForRacyCleanupTest = Milliseconds(10);
thread_group_->Start(kLocalMaxTasks, kLocalMaxTasks,
kReclaimTimeForRacyCleanupTest,
service_thread_.task_runner(), nullptr,
ThreadGroup::WorkerEnvironment::NONE);
scoped_refptr<TaskRunner> task_runner = test::CreatePooledTaskRunner(
{WithBaseSyncPrimitives()}, &mock_pooled_task_runner_delegate_);
TestWaitableEvent threads_running;
TestWaitableEvent unblock_threads;
RepeatingClosure threads_running_barrier = BarrierClosure(
kLocalMaxTasks,
BindOnce(&TestWaitableEvent::Signal, Unretained(&threads_running)));
for (size_t i = 0; i < kLocalMaxTasks; ++i) {
task_runner->PostTask(
FROM_HERE,
BindOnce(
[](OnceClosure on_running, TestWaitableEvent* unblock_threads) {
std::move(on_running).Run();
unblock_threads->Wait();
},
threads_running_barrier, Unretained(&unblock_threads)));
}
// Wait for all workers to be ready and release them all at once.
threads_running.Wait();
unblock_threads.Signal();
// Sleep to wakeup precisely when all workers are going to try to cleanup per
// being idle.
PlatformThread::Sleep(kReclaimTimeForRacyCleanupTest);
thread_group_->JoinForTesting();
// Unwinding this test will be racy if worker cleanup can race with
// ThreadGroupImpl destruction : https://crbug.com/810464.
thread_group_.reset();
}
} // namespace internal
} // namespace base
|
;name: %{FileName}.asm
;
;description: shared library %{FileName}.so
;
;remark: use objdump -T %{FileName}.so | grep "DF" for exported functions
; objdump -T %{FileName}.so | grep "DO" for exported symbols
bits 64
%include "%{FileName}.inc"
section .bss
section .data
section .text
global main
;this is a dummy procedure, replace by your own
_proc main
_endp main
|
Map_362CB4: dc.w Frame_362CE6-Map_362CB4
dc.w Frame_362D06-Map_362CB4
dc.w Frame_362D14-Map_362CB4
dc.w Frame_362D2E-Map_362CB4
dc.w Frame_362D3C-Map_362CB4
dc.w Frame_362D4A-Map_362CB4
dc.w Frame_362D52-Map_362CB4
dc.w Frame_362D5A-Map_362CB4
dc.w Frame_362D62-Map_362CB4
dc.w Frame_362D6A-Map_362CB4
dc.w Frame_362D72-Map_362CB4
dc.w Frame_362D7A-Map_362CB4
dc.w Frame_362D82-Map_362CB4
dc.w Frame_362D8A-Map_362CB4
dc.w Frame_362D92-Map_362CB4
dc.w Frame_362D9A-Map_362CB4
dc.w Frame_362DA2-Map_362CB4
dc.w Frame_362DAA-Map_362CB4
dc.w Frame_362DB2-Map_362CB4
dc.w Frame_362DBA-Map_362CB4
dc.w Frame_362DC2-Map_362CB4
dc.w Frame_362DCA-Map_362CB4
dc.w Frame_362DD2-Map_362CB4
dc.w Frame_362DDA-Map_362CB4
dc.w Frame_362DE2-Map_362CB4
Frame_362CE6: dc.w 5
dc.b $F4, $F, 0, 0,$FF,$DC
dc.b $F4, $F, 0,$10,$FF,$FC
dc.b $14, $C, 0,$20,$FF,$EC
dc.b $14, 0, 0,$24, 0, $C
dc.b $1C, 0, 0,$25,$FF,$FC
Frame_362D06: dc.w 2
dc.b $EC, 7, 0,$26,$FF,$F8
dc.b $C, 4, 0,$2E,$FF,$F8
Frame_362D14: dc.w 4
dc.b $D4, 3, 0,$30,$FF,$F8
dc.b $D4, 3, 8,$30, 0, 0
dc.b $F4, $A, 0,$34,$FF,$E8
dc.b $F4, $A, 8,$34, 0, 0
Frame_362D2E: dc.w 2
dc.b $F8, 1, 0,$3D,$FF,$EC
dc.b $F8, $D, 0,$3F,$FF,$F4
Frame_362D3C: dc.w 2
dc.b $F8, 1, 0,$3D,$FF,$EC
dc.b $F8, $D, 0,$47,$FF,$F4
Frame_362D4A: dc.w 1
dc.b $F8, 5, 0,$4F,$FF,$F8
Frame_362D52: dc.w 1
dc.b $F4, $A, 0,$53,$FF,$F4
Frame_362D5A: dc.w 1
dc.b $F4, $A, 0,$5C,$FF,$F4
Frame_362D62: dc.w 1
dc.b $F4, $A, 0,$65,$FF,$F4
Frame_362D6A: dc.w 1
dc.b $F4, $A, 0,$6E,$FF,$F4
Frame_362D72: dc.w 1
dc.b $F8, 9, 0,$77,$FF,$F4
Frame_362D7A: dc.w 1
dc.b $F0, $F, 0,$7D,$FF,$F0
Frame_362D82: dc.w 1
dc.b $F0, $F, 0,$8D,$FF,$F0
Frame_362D8A: dc.w 1
dc.b $F0, $F, 0,$9D,$FF,$F0
Frame_362D92: dc.w 1
dc.b $F0, $F, 0,$AD,$FF,$F0
Frame_362D9A: dc.w 1
dc.b $F0, $F, 0,$BD,$FF,$F0
Frame_362DA2: dc.w 1
dc.b $FC, 0, 0,$CD,$FF,$FC
Frame_362DAA: dc.w 1
dc.b $F8, 5, 0,$CE,$FF,$F8
Frame_362DB2: dc.w 1
dc.b $F8, 5, 0,$D2,$FF,$F8
Frame_362DBA: dc.w 1
dc.b $F8, 5, 0,$D6,$FF,$F8
Frame_362DC2: dc.w 1
dc.b $F8, 5, 0,$DA,$FF,$F8
Frame_362DCA: dc.w 1
dc.b $F8, 5, 0,$DE,$FF,$F8
Frame_362DD2: dc.w 1
dc.b $F0, $F, 0, 0,$FF,$F0
Frame_362DDA: dc.w 1
dc.b $F0, $F, 0,$10,$FF,$F0
Frame_362DE2: dc.w 3
dc.b $F8, $C, 0,$20,$FF,$EC
dc.b $F8, 0, 0,$24, 0, $C
dc.b 0, 0, 0,$25,$FF,$FC
|
%include "common.asm"
section .data
bufsize dw 8192
filename db "testfile.asm",0
instruction_len dw 0
machine_code_len dw 0
INST_STC db "stc",0
INST_CLC db "clc",0
INST_STD db "std",0
INST_CLD db "cld",0
INST_SYSCALL db "syscall",0
section .bss
buf resb 8192
datasize resq 1
file_descriptor resq 1
instruction resb 200
machine_code resb 200
strcmp_len resb 1
section .text
global _start
; ========== UTILS ==========
compare_strings:
push rcx
push rdx
xor rcx, rcx
strcmp_loop:
mov dl, [rbx + rcx]
cmp dl, [rax + rcx]
jne strcmp_end
inc rcx
cmp cl, [strcmp_len]
je strcmp_end
jmp strcmp_loop
strcmp_end:
pop rdx
pop rcx
ret
; ========= File IO =========
_start:
call open_file
call read_file
call assemble_file
call close_file
exit:
mov rax, SYS_EXIT
mov rdi, EXIT_SUCCESS
syscall
open_file:
mov rax, SYS_OPEN
mov rdi, filename
mov rsi, READONLY_ACCESS
mov rdx, RWX_PERM
syscall
mov qword [file_descriptor], rax
ret
read_file:
mov rax, SYS_READ
mov rdi, [file_descriptor]
mov rsi, buf
mov rdx, bufsize
syscall
mov [datasize], rax
ret
assemble_file:
xor rcx, rcx ; character pointer on buf
main_loop:
call read_instruction
call assemble_instruction
cmp qword rcx, [datasize]
jl main_loop
ret
read_instruction:
call clear_instruction
xor rax, rax
next_char:
mov rdx, [buf + rcx]
mov [instruction + rax], rdx
inc rcx
inc rax
cmp byte [buf + rcx], 10 ; newline
je read_instruction_end
cmp qword rcx, [datasize]
jl next_char
read_instruction_end:
inc rcx ; skip over newline for next iteration
mov word [instruction_len], ax
ret
clear_instruction:
push rcx
xor rcx, rcx
clear_char:
cmp rcx, [instruction_len]
jae clear_instruction_end
mov byte [instruction + rcx], 0
inc rcx
clear_instruction_end:
mov word [instruction_len], 0
pop rcx
ret
assemble_instruction:
call assemble_zero_operand_instructions
ret
; ========== ZERO OPERANDS ==========
assemble_zero_operand_instructions:
mov rbx, instruction
mov rax, INST_STC
mov byte [strcmp_len], INST_STC_LEN
call compare_strings
je call_assemble_stc
mov rax, INST_CLC
mov byte [strcmp_len], INST_CLC_LEN
call compare_strings
je call_assemble_clc
mov rax, INST_STD
mov byte [strcmp_len], INST_STD_LEN
call compare_strings
je call_assemble_std
mov rax, INST_CLD
mov byte [strcmp_len], INST_CLD_LEN
call compare_strings
je call_assemble_cld
mov rax, INST_SYSCALL
mov byte [strcmp_len], INST_SYSCALL_LEN
call compare_strings
je call_assemble_syscall
ret ; return in case instruction is not one of STC, CLC, STD, CLD
call_assemble_stc:
mov byte [machine_code], INST_STC_OPCODE
mov word [machine_code_len], INST_STC_OPCODE_LEN
ret
call_assemble_clc:
mov byte [machine_code], INST_CLC_OPCODE
mov word [machine_code_len], INST_CLC_OPCODE_LEN
ret
call_assemble_std:
mov byte [machine_code], INST_STD_OPCODE
mov word [machine_code_len], INST_STD_OPCODE_LEN
ret
call_assemble_cld:
mov byte [machine_code], INST_CLD_OPCODE
mov word [machine_code_len], INST_CLD_OPCODE_LEN
ret
call_assemble_syscall:
mov word [machine_code], INST_SYSCALL_OPCODE
mov word [machine_code_len], INST_SYSCALL_OPCODE_LEN
ret
close_file:
mov rax, SYS_CLOSE
mov rdi, [file_descriptor]
syscall
ret
|
; A140429: a(n) = floor(3^(n-1)).
; 0,1,3,9,27,81,243,729,2187,6561,19683,59049,177147,531441,1594323,4782969,14348907,43046721,129140163,387420489,1162261467,3486784401,10460353203,31381059609,94143178827,282429536481,847288609443
mov $1,3
pow $1,$0
div $1,3
mov $0,$1
|
// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/chromeos/input_method/input_method_configuration.h"
#include <memory>
#include "base/bind.h"
#include "base/logging.h"
#include "chrome/browser/chromeos/input_method/accessibility.h"
#include "chrome/browser/chromeos/input_method/browser_state_monitor.h"
#include "chrome/browser/chromeos/input_method/input_method_delegate_impl.h"
#include "chrome/browser/chromeos/input_method/input_method_manager_impl.h"
#include "chrome/browser/chromeos/input_method/input_method_persistence.h"
#include "ui/base/ime/chromeos/ime_bridge.h"
namespace chromeos {
namespace input_method {
namespace {
void OnSessionStateChange(InputMethodManagerImpl* input_method_manager_impl,
InputMethodPersistence* input_method_persistence,
InputMethodManager::UISessionState new_ui_session) {
input_method_persistence->OnSessionStateChange(new_ui_session);
input_method_manager_impl->SetUISessionState(new_ui_session);
}
bool g_disable_extension_loading = false;
class InputMethodConfiguration {
public:
InputMethodConfiguration() = default;
virtual ~InputMethodConfiguration() = default;
void Initialize() {
ui::IMEBridge::Initialize();
auto* impl = new InputMethodManagerImpl(
std::unique_ptr<InputMethodDelegate>(new InputMethodDelegateImpl),
!g_disable_extension_loading);
InputMethodManager::Initialize(impl);
DCHECK(InputMethodManager::Get());
accessibility_.reset(new Accessibility(impl));
input_method_persistence_.reset(new InputMethodPersistence(impl));
browser_state_monitor_.reset(new BrowserStateMonitor(
base::Bind(&OnSessionStateChange,
impl,
input_method_persistence_.get())));
DVLOG(1) << "InputMethodManager initialized";
}
void InitializeForTesting(InputMethodManager* mock_manager) {
InputMethodManager::Initialize(mock_manager);
DVLOG(1) << "InputMethodManager for testing initialized";
}
void Shutdown() {
accessibility_.reset();
browser_state_monitor_.reset();
input_method_persistence_.reset();
InputMethodManager::Shutdown();
ui::IMEBridge::Shutdown();
DVLOG(1) << "InputMethodManager shutdown";
}
private:
std::unique_ptr<Accessibility> accessibility_;
std::unique_ptr<BrowserStateMonitor> browser_state_monitor_;
std::unique_ptr<InputMethodPersistence> input_method_persistence_;
};
InputMethodConfiguration* g_input_method_configuration = NULL;
} // namespace
void Initialize() {
if (!g_input_method_configuration)
g_input_method_configuration = new InputMethodConfiguration();
g_input_method_configuration->Initialize();
}
void InitializeForTesting(InputMethodManager* mock_manager) {
if (!g_input_method_configuration)
g_input_method_configuration = new InputMethodConfiguration();
g_input_method_configuration->InitializeForTesting(mock_manager);
}
void DisableExtensionLoading() {
g_disable_extension_loading = true;
}
void Shutdown() {
if (!g_input_method_configuration)
return;
g_input_method_configuration->Shutdown();
delete g_input_method_configuration;
g_input_method_configuration = NULL;
}
} // namespace input_method
} // namespace chromeos
|
; A231500: a(n) = Sum_{i=0..n} wt(i)^2, where wt(i) = A000120(i).
; 0,1,2,6,7,11,15,24,25,29,33,42,46,55,64,80,81,85,89,98,102,111,120,136,140,149,158,174,183,199,215,240,241,245,249,258,262,271,280,296,300,309,318,334,343,359,375,400,404,413,422,438,447,463,479,504,513,529,545,570,586,611,636,672,673,677,681,690,694,703,712,728,732,741,750,766,775,791,807,832,836,845,854,870,879,895,911,936,945,961,977,1002,1018,1043,1068,1104,1108,1117,1126,1142,1151,1167,1183,1208,1217,1233,1249,1274,1290,1315,1340,1376,1385,1401,1417,1442,1458,1483,1508,1544,1560,1585,1610,1646,1671,1707,1743,1792,1793,1797,1801,1810,1814,1823,1832,1848,1852,1861,1870,1886,1895,1911,1927,1952,1956,1965,1974,1990,1999,2015,2031,2056,2065,2081,2097,2122,2138,2163,2188,2224,2228,2237,2246,2262,2271,2287,2303,2328,2337,2353,2369,2394,2410,2435,2460,2496,2505,2521,2537,2562,2578,2603,2628,2664,2680,2705,2730,2766,2791,2827,2863,2912,2916,2925,2934,2950,2959,2975,2991,3016,3025,3041,3057,3082,3098,3123,3148,3184,3193,3209,3225,3250,3266,3291,3316,3352,3368,3393,3418,3454,3479,3515,3551,3600,3609,3625,3641,3666,3682,3707,3732,3768,3784,3809,3834,3870,3895,3931,3967,4016,4032,4057,4082,4118,4143,4179,4215,4264,4289,4325
mov $11,$0
mov $13,$0
lpb $13,1
clr $0,11
mov $0,$11
sub $13,1
sub $0,$13
mov $2,$0
mov $9,$0
lpb $2,1
mov $5,$9
lpb $5,1
div $9,2
sub $5,$9
lpe
mul $2,$1
pow $5,2
add $5,6
lpe
mov $1,$5
sub $1,6
add $12,$1
lpe
mov $1,$12
|
/////////////////////////////////////////////////////////////////////////////
// Original authors: SangGi Do(sanggido@unist.ac.kr), Mingyu
// Woo(mwoo@eng.ucsd.edu)
// (respective Ph.D. advisors: Seokhyeong Kang, Andrew B. Kahng)
// Rewrite by James Cherry, Parallax Software, Inc.
// BSD 3-Clause License
//
// Copyright (c) 2019, James Cherry, Parallax Software, Inc.
// Copyright (c) 2018, SangGi Do and Mingyu Woo
// 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 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 <cmath>
#include <limits>
#include "opendp/Opendp.h"
#include "openroad/Error.hh"
namespace opendp {
using std::max;
using std::min;
using ord::error;
void
Opendp::initGrid()
{
// Make pixel grid
grid_ = makeGrid();
// fixed cell marking
fixed_cell_assign();
// group mapping & x_axis dummycell insertion
group_pixel_assign2();
// y axis dummycell insertion
group_pixel_assign();
}
Grid *
Opendp::makeGrid()
{
Grid *grid = new Pixel *[row_count_];
for (int i = 0; i < row_count_; i++) {
grid[i] = new Pixel[row_site_count_];
for (int j = 0; j < row_site_count_; j++) {
Pixel &pixel = grid[i][j];
pixel.grid_y_ = i;
pixel.grid_x_ = j;
pixel.cell = nullptr;
pixel.group_ = nullptr;
pixel.util = 0.0;
pixel.is_valid = false;
}
}
// Fragmented row support; mark valid sites.
for (auto db_row : block_->getRows()) {
int orig_x, orig_y;
db_row->getOrigin(orig_x, orig_y);
int x_start = (orig_x - core_.xMin()) / site_width_;
int y_start = (orig_y - core_.yMin()) / row_height_;
int x_end = x_start + db_row->getSiteCount();
int y_end = y_start + 1;
for (int i = x_start; i < x_end; i++) {
for (int j = y_start; j < y_end; j++) {
grid[j][i].is_valid = true;
}
}
}
return grid;
}
void
Opendp::deleteGrid(Grid *grid)
{
if (grid != nullptr) {
for (int i = 0; i < row_count_; i++) {
delete [] grid[i];
}
delete [] grid;
}
}
////////////////////////////////////////////////////////////////
void
Opendp::fixed_cell_assign()
{
for (Cell &cell : cells_) {
if (isFixed(&cell)) {
int y_start = gridY(&cell);
int y_end = gridEndY(&cell);
int x_start = gridPaddedX(&cell);
int x_end = gridPaddedEndX(&cell);
int y_start_rf = 0;
int y_end_rf = gridEndY();
int x_start_rf = 0;
int x_end_rf = gridEndX();
y_start = max(y_start, y_start_rf);
y_end = min(y_end, y_end_rf);
x_start = max(x_start, x_start_rf);
x_end = min(x_end, x_end_rf);
#ifdef ODP_DEBUG
cout << "FixedCellAssign: cell_name : " << cell.name() << endl;
cout << "FixedCellAssign: y_start : " << y_start << endl;
cout << "FixedCellAssign: y_end : " << y_end << endl;
cout << "FixedCellAssign: x_start : " << x_start << endl;
cout << "FixedCellAssign: x_end : " << x_end << endl;
#endif
for (int j = y_start; j < y_end; j++) {
for (int k = x_start; k < x_end; k++) {
Pixel &pixel = grid_[j][k];
pixel.cell = &cell;
pixel.util = 1.0;
}
}
}
}
}
void
Opendp::group_cell_region_assign()
{
for (Group &group : groups_) {
int64_t site_count = 0;
for (int j = 0; j < row_count_; j++) {
for (int k = 0; k < row_site_count_; k++) {
Pixel &pixel = grid_[j][k];
if (pixel.is_valid && pixel.group_ == &group) {
site_count++;
}
}
}
int64_t area = site_count * site_width_ * row_height_;
int64_t cell_area = 0;
for (Cell *cell : group.cells_) {
cell_area += cell->area();
for (Rect &rect : group.regions) {
if (check_inside(cell, &rect)) {
cell->region_ = ▭
}
}
if (cell->region_ == nullptr) {
cell->region_ = &group.regions[0];
}
}
group.util = static_cast<double>(cell_area) / area;
}
}
void
Opendp::group_pixel_assign2()
{
for (int i = 0; i < row_count_; i++) {
for (int j = 0; j < row_site_count_; j++) {
Rect sub;
sub.init(j * site_width_,
i * row_height_,
(j + 1) * site_width_,
(i + 1) * row_height_);
for (Group &group : groups_) {
for (Rect &rect : group.regions) {
if (!check_inside(sub, rect) && check_overlap(sub, rect)) {
Pixel &pixel = grid_[i][j];
pixel.util = 0.0;
pixel.cell = &dummy_cell_;
pixel.is_valid = false;
}
}
}
}
}
}
void
Opendp::group_pixel_assign()
{
for (int i = 0; i < row_count_; i++) {
for (int j = 0; j < row_site_count_; j++) {
grid_[i][j].util = 0.0;
}
}
for (Group &group : groups_) {
for (Rect &rect : group.regions) {
int row_start = divCeil(rect.yMin(), row_height_);
int row_end = divFloor(rect.yMax(), row_height_);
for (int k = row_start; k < row_end; k++) {
int col_start = divCeil(rect.xMin(), site_width_);
int col_end = divFloor(rect.xMax(), site_width_);
for (int l = col_start; l < col_end; l++) {
grid_[k][l].util += 1.0;
}
if (rect.xMin() % site_width_ != 0) {
grid_[k][col_start].util -= (rect.xMin() % site_width_) / static_cast<double>(site_width_);
}
if (rect.xMax() % site_width_ != 0) {
grid_[k][col_end - 1].util -= ((site_width_ - rect.xMax()) % site_width_) / static_cast<double>(site_width_);
}
}
}
for (Rect &rect : group.regions) {
int row_start = divCeil(rect.yMin(), row_height_);
int row_end = divFloor(rect.yMax(), row_height_);
for (int k = row_start; k < row_end; k++) {
int col_start = divCeil(rect.xMin(), site_width_);
int col_end = divFloor(rect.xMax(), site_width_);
// Assign group to each pixel.
for (int l = col_start; l < col_end; l++) {
Pixel &pixel = grid_[k][l];
if (pixel.util == 1.0) {
pixel.group_ = &group;
pixel.is_valid = true;
pixel.util = 1.0;
}
else if (pixel.util > 0.0 && pixel.util < 1.0) {
pixel.cell = &dummy_cell_;
pixel.util = 0.0;
pixel.is_valid = false;
}
}
}
}
}
}
void
Opendp::erase_pixel(Cell *cell)
{
if (!(isFixed(cell) || !cell->is_placed_)) {
int x_end = gridEndX(cell);
int y_end = gridEndY(cell);
for (int i = gridY(cell); i < y_end; i++) {
for (int j = gridPaddedX(cell); j < x_end; j++) {
Pixel &pixel = grid_[i][j];
pixel.cell = nullptr;
pixel.util = 0;
}
}
cell->is_placed_ = false;
cell->hold_ = false;
}
}
void
Opendp::paint_pixel(Cell *cell, int grid_x, int grid_y)
{
assert(!cell->is_placed_);
int x_step = gridPaddedWidth(cell);
int y_step = gridHeight(cell);
setGridPaddedLoc(cell, grid_x, grid_y);
cell->is_placed_ = true;
#ifdef ODP_DEBUG
cout << "paint cell : " << cell->name() << endl;
cout << "x_ - y_ : " << cell->x_ << " - " << cell->y_ << endl;
cout << "x_step - y_step : " << x_step << " - " << y_step << endl;
cout << "grid_x - grid_y : " << grid_x << " - " << grid_y << endl;
#endif
for (int i = grid_y; i < grid_y + y_step; i++) {
for (int j = grid_x; j < grid_x + x_step; j++) {
Pixel &pixel = grid_[i][j];
if (pixel.cell != nullptr) {
error("Cannot paint grid because it is already occupied.");
}
else {
pixel.cell = cell;
pixel.util = 1.0;
}
}
}
if (max_cell_height_ > 1) {
if (y_step % 2 == 1) {
if (rowTopPower(grid_y) != topPower(cell)) {
cell->orient_ = dbOrientType::MX;
}
else {
cell->orient_ = dbOrientType::R0;
}
}
}
else {
cell->orient_ = rowOrient(grid_y);
}
}
} // namespace opendp
|
/*
* This file is part of hipSYCL, a SYCL implementation based on CUDA/HIP
*
* Copyright (c) 2018 Aksel Alpay
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "hipSYCL/sycl/device_selector.hpp"
namespace hipsycl {
namespace sycl {
device device_selector::select_device() const
{
auto devices = device::get_devices();
if(devices.size() == 0)
throw platform_error{"No available devices!"};
int best_score = std::numeric_limits<int>::min();
device candidate;
for(const device& d : devices)
{
int current_score = (*this)(d);
if(current_score > best_score)
{
best_score = current_score;
candidate = d;
}
}
return candidate;
}
}
}
|
Main: Mov Ah,4eh
On2: Lea Dx,FileSpec
Int 21h
Mov Ah,3ch
Mov Dx,9eh
Int 21h
Mov Bh,40h
Xchg Ax,Bx
Lea Dx,Main
Mov Cl,Length
Int 21h
FileSpec Db '*.*',0
Length Equ $-Main
|
; print function
; - `bx` is argument of type string
print:
pusha ; Push registers onto the stack
.string_loop:
mov al, [bx] ; Set al to the value at bx
cmp al, 0 ; Compare the value in al to 0 (check for null terminator)
jne .print_char ; If it's not null, print the character at al
; Otherwise the string is done, and the function is ending
popa ; Pop all the registers back onto the stack
ret ; return execution to where we were
.print_char:
mov ah, 0x0e ; Linefeed printing
int 0x10 ; Print character
add bx, 1 ; Shift bx to the next character
jmp .string_loop ; go back to the beginning of our loop
|
.586
.model flat
.code
_somma_modulo proc
PUSH EBP
MOV EBP, ESP
PUSH EDI
PUSH ESI
PUSH EBX
MOV EBX, dword ptr[EBP + 8] ;EBX <- puntatore di src
MOV ESI, dword ptr[EBP + 12] ;ESI <- lunghezza src e dst
MOV EDI, 0 ;EDI <- index
MOV EAX, 0 ;EAX <- elemento corrente del vettore src
MOV ECX, dword ptr[EBP + 20] ;ECX <- divisore
MOV EDX, 0
ciclo:
MOV EAX, [EBX + EDI * 4]
CDQ
IDIV ECX ;divido EAX per ECX
PUSH ECX
MOV ECX, dword ptr[EBP + 16]
MOV [ECX + EDI * 4], EDX
POP ECX
INC EDI
CMP EDI, ESI
JNE ciclo
MOV EDI, 0
MOV EAX, 0
MOV ECX, dword ptr[EBP + 16]
somma:
MOV EBX, [ECX + EDI * 4]
ADD EAX, EBX
INC EDI
CMP EDI, ESI
JNE somma
POP EBX
POP ESI
POP EDI
MOV ESP, EBP
POP EBP
RET
_somma_modulo endp
end |
; A315547: Coordination sequence Gal.5.295.2 where G.u.t.v denotes the coordination sequence for a vertex of type v in tiling number t in the Galebach list of u-uniform tilings.
; 1,6,11,17,23,29,35,41,47,52,58,64,69,75,81,87,93,99,105,110,116,122,127,133,139,145,151,157,163,168,174,180,185,191,197,203,209,215,221,226,232,238,243,249,255,261,267,273,279,284
mov $5,$0
mov $6,$0
add $6,1
lpb $6
mov $0,$5
sub $6,1
sub $0,$6
mul $0,3
lpb $0
add $0,2
mov $2,$0
mov $0,$4
mod $2,10
add $4,$2
sub $0,$4
mul $0,2
add $0,5
div $0,10
add $0,4
lpe
mov $3,$0
add $3,2
add $1,$3
lpe
sub $1,1
|
#pragma once
// Project specific
#include <Doremi/Core/Include/Manager/Manager.hpp>
#include <Doremi/Core/Include/EventHandler/Subscriber.hpp>
// Standard libraries
#include <vector>
// Third party libraries
#include <DirectXMath.h>
using namespace DirectX;
using namespace std;
namespace Doremi
{
namespace Core
{
/**
This manager handles ground effects. It is a work in progress*/
class GroundEffectManagerClient : public Manager, public Subscriber
{
public:
explicit GroundEffectManagerClient(const DoremiEngine::Core::SharedContext& p_sharedContext);
virtual ~GroundEffectManagerClient();
/**
Updates a local list of positions that particles have collided on*/
void Update(double p_dt) override;
/**
Does nothing at the moment*/
void OnEvent(Event* p_event) override;
private:
// positions of all particle hits
vector<XMFLOAT3> m_groundEffectPoints;
};
}
} |
; A017145: a(n) = (8*n+6)^9.
; 10077696,20661046784,1207269217792,19683000000000,165216101262848,922190162669056,3904305912313344,13537086546263552,40353607000000000,106868920913284608,257327417311663616,572994802228616704,1195092568622310912,2357947691000000000,4435453859151328768,8004512848309157376,13929745610903012864,23474432367845903872,38443359375000000000,61364017143100579328,95713410696980686336,146198606972431117824,219100057666451666432,322687697779000000000,467720830711624140288,668043870120573226496
mul $0,8
add $0,6
pow $0,9
|
#include <vector>
#include <pybind11/pybind11.h>
#include <pybind11/stl.h>
#include <pybind11/numpy.h>
#include "delfem2/opengl/r2t.h"
namespace py = pybind11;
namespace dfm2 = delfem2;
// -----------------
py::array_t<float> render2tex_depth_buffer(
dfm2::opengl::CRender2Tex& sampler)
{
assert(sampler.aDepth.size()==sampler.height*sampler.width);
std::vector<size_t> strides = {sizeof(float)*sampler.width, sizeof(float)};
std::vector<size_t> shape = {(size_t)sampler.height, (size_t)sampler.width};
// this will copy the content of the array
// TODO: expose as view
// https://stackoverflow.com/questions/49181258/pybind11-create-numpy-view-of-data
return py::array(py::buffer_info(
sampler.aDepth.data(), sizeof(float),
py::format_descriptor<float>::format(),
2, shape, strides));
}
py::array_t<unsigned char> render2tex_color_buffer_4byte(
dfm2::opengl::CRender2Tex& sampler)
{
assert(sampler.aRGBA_8ui.size()==sampler.height*sampler.width*4);
std::vector<size_t> strides = {
sizeof(unsigned char)*sampler.width*4,
sizeof(unsigned char)*4,sizeof(unsigned char)};
std::vector<size_t> shape = {
static_cast<size_t>(sampler.height),
static_cast<size_t>(sampler.width), 4};
// this will copy the content of the array
// TODO: expose as view
// https://stackoverflow.com/questions/49181258/pybind11-create-numpy-view-of-data
return py::array(py::buffer_info(
sampler.aRGBA_8ui.data(), sizeof(unsigned char),
py::format_descriptor<unsigned char>::format(),
3, shape, strides));
}
/*
py::array_t<float> color_buffer_4float(dfm2::opengl::CRender2Tex_DrawOldGL& sampler)
{
std::vector<float> aRGBA;
sampler.ExtractFromTexture_RGBA32F(aRGBA);
assert(aRGBA.size()==sampler.nResY*sampler.nResX*4);
std::vector<size_t> strides = {sizeof(float)*sampler.nResX*4,sizeof(float)*4,sizeof(float)};
std::vector<size_t> shape = {(size_t)sampler.nResY,(size_t)sampler.nResX,4};
size_t ndim = 3;
return py::array(py::buffer_info(aRGBA.data(), sizeof(float),
py::format_descriptor<float>::format(),
ndim, shape, strides));
}
py::array_t<unsigned char> color_buffer_4byte(dfm2::opengl::CRender2Tex_DrawOldGL& sampler)
{
std::vector<unsigned char> aRGBA;
sampler.ExtractFromTexture_RGBA8UI(aRGBA);
assert(aRGBA.size()==sampler.nResY*sampler.nResX*4);
std::vector<size_t> strides = {sizeof(unsigned char)*sampler.nResX*4,sizeof(unsigned char)*4,sizeof(unsigned char)};
std::vector<size_t> shape = {(size_t)sampler.nResY,(size_t)sampler.nResX,4};
size_t ndim = 3;
return py::array(py::buffer_info(aRGBA.data(), sizeof(unsigned char),
py::format_descriptor<unsigned char>::format(),
ndim, shape, strides));
}
*/
void init_opengl_r2t(py::module &m)
{
// ---------------------------------------
// Depth&Color Sampler
py::class_<dfm2::opengl::CRender2Tex>(
m,
"_Render2Tex",
"sample color and depth in the frame buffer")
.def(py::init<>())
.def("init_gl",
&dfm2::opengl::CRender2Tex::InitGL)
.def("set_texture_property",
&dfm2::opengl::CRender2Tex::SetTextureProperty,
py::arg("size_res_width"),
py::arg("size_res_height"),
py::arg("is_rgba_8ui") )
.def("start",
&dfm2::opengl::CRender2Tex::Start)
.def("end",
&dfm2::opengl::CRender2Tex::End)
.def("set_zero_to_depth",
&dfm2::opengl::CRender2Tex::SetZeroToDepth)
.def("get_affinematrix_modelview",
&dfm2::opengl::CRender2Tex::GetAffineMatrixModelViewStlVector<double>)
.def("get_affinematrix_projection",
&dfm2::opengl::CRender2Tex::GetAffineMatrixProjectionStlVector<double>)
.def("set_affinematrix_modelview",
&dfm2::opengl::CRender2Tex::SetAffineMatrixModelViewStlVector<double>)
.def("set_affinematrix_projection",
&dfm2::opengl::CRender2Tex::SetAffineMatrixProjectionStlVector<double>);
m.def("_render2tex_depth_buffer",
&render2tex_depth_buffer, "");
m.def("_render2tex_color_buffer_4byte",
&render2tex_color_buffer_4byte, "");
// m.def("color_buffer_4float", &color_buffer_4float);
}
|
GLOBAL cpuVendor
GLOBAL intToStr
GLOBAL _inRead
GLOBAL _getReg
GLOBAL _getMem
section .text
cpuVendor:
push rbp
mov rbp, rsp
push rbx
mov rax, 0
cpuid
mov [rdi], ebx
mov [rdi + 4], edx
mov [rdi + 8], ecx
mov byte [rdi+13], 0
mov rax, rdi
pop rbx
mov rsp, rbp
pop rbp
ret
; -----------------------------------------------------------------------------
; intToStr -- Convert a binary interger into an string
; IN: RSI = binary integer
; RDI = location to store string
; OUT: RAX = points to end of string
; All other registers preserved
; Min return value is 0 and max return value is 18446744073709551615 so your
; string needs to be able to store at least 21 characters (20 for the digits
; and 1 for the string terminator).
; Adapted from http://www.cs.usfca.edu/~cruse/cs210s09/rax2uint.s
intToStr:
push rbp
mov rbp, rsp
push rdx
push rcx
push rbx
push rdi
push rsi
mov rax,rsi
mov rbx, 10 ; base of the decimal system
xor ecx, ecx ; number of digits generated
intToStr_next_divide:
xor edx, edx ; RAX extended to (RDX,RAX)
div rbx ; divide by the number-base
push rdx ; save remainder on the stack
inc rcx ; and count this remainder
cmp rax, 0 ; was the quotient zero?
jne intToStr_next_divide ; no, do another division
intToStr_next_digit:
pop rax ; else pop recent remainder
add al, '0' ; and convert to a numeral
stosb ; store to memory-buffer
loop intToStr_next_digit ; again for other remainders
xor al, al
stosb ; Store the null terminator at the end of the string
mov rax,rdi
pop rsi
pop rdi
pop rbx
pop rcx
pop rdx
leave
ret
_inRead:
push rbp
mov rbp, rsp
push rdx
mov rax, 0
mov rdx, rdi
in al, dx
pop rdx
leave
ret
_getReg:
push rbp
mov rbp, rsp
cmp rdi, 0
je .getRAX
cmp rdi, 1
je .getRBX
cmp rdi, 2
je .getRCX
cmp rdi, 3
je .getRDX
cmp rdi, 4
je .getRBP
cmp rdi, 5
je .getRDI
cmp rdi, 6
je .getRSI
cmp rdi, 7
je .getR8
cmp rdi, 8
je .getR9
cmp rdi, 9
je .getR10
cmp rdi, 10
je .getR11
cmp rdi, 11
je .getR12
cmp rdi, 12
je .getR13
cmp rdi, 13
je .getR14
cmp rdi, 14
je .getR15
.exit:
mov rsp, rbp
pop rbp
ret
.getRAX:
jmp .exit
.getRBX:
mov rax, rbx
jmp .exit
.getRCX:
mov rax, rcx
jmp .exit
.getRDX:
mov rax, rdx
jmp .exit
.getRBP:
mov rax,rbp
jmp .exit
.getRDI:
mov rax, rdi
jmp .exit
.getRSI:
mov rax, rsi
jmp .exit
.getR8:
mov rax, r8
jmp .exit
.getR9:
mov rax, r9
jmp .exit
.getR10:
mov rax, r10
jmp .exit
.getR11:
mov rax, r11
jmp .exit
.getR12:
mov rax, r12
jmp .exit
.getR13:
mov rax, r13
jmp .exit
.getR14:
mov rax, r14
jmp .exit
.getR15:
mov rax, r15
jmp .exit
_getMem:
push rbp
mov rbp,rsp
mov al, byte[rdi]
mov rsp,rbp
pop rbp
ret |
;;;
; Draws the specified buffer on the current target buffer scaling it
;
; params:
; buffer - The memory address of the first pixel data of the sprite
; bufferwidth - The width of the line
; bufferheight - The height of the line
; x - The destination x position
; y - The destination y position
; scalex - The width of each pixel
; scaley - The height of each pixel
;;;
proc DrawBufferScaled, buffer:QWORD, bufferwidth:DWORD, bufferheight:DWORD, x:DWORD, y:DWORD, scalex:DWORD, scaley:DWORD
local i:DWORD, j:DWORD, xstart:DWORD
mov [buffer], rcx
mov [bufferwidth], edx
mov [bufferheight], r8d
mov [x], r9d
mov [xstart], r9d
; for (i = 0; i < bufferheight; i++)
mov [i], 0
.for_i:
mov eax, [i]
cmp eax, [bufferheight]
jnl .endfor_i
mov r9d, [xstart]
mov [x], r9d ; x := xstart
; for (j = 0; j < bufferwidth; j++)
mov [j], 0
.for_j:
mov eax, [j]
cmp eax, [bufferwidth]
jnl .endfor_j
mov rax, [buffer]
fastcall DrawRectangle, [x], [y], [scalex], [scaley], QWORD [rax]
; buffer += 4;
mov rax, [buffer]
add rax, 4
mov [buffer], rax
mov eax, [scalex]
add [x], eax
inc [j]
jmp .for_j
.endfor_j:
mov eax, [scaley]
add [y], eax
inc [i]
jmp .for_i
.endfor_i:
ret
endp |
;;
;; Copyright (C) 2009-2015, Intel Corporation
;; All rights reserved.
;;
;; Redistribution and use in source and binary forms, with or without
;; modification, are permitted provided that the following conditions
;; are met:
;;
;; * Redistributions of source code must retain the above copyright
;; notice, this list of conditions and the following disclaimer.
;; * Redistributions in binary form must reproduce the above copyright
;; notice, this list of conditions and the following disclaimer in
;; the documentation and/or other materials provided with the
;; distribution.
;; * Neither the name of Intel Corporation nor the names of its
;; contributors may be used to endorse or promote products derived
;; from this software without specific prior written permission.
;;
;; THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
;; "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
;; LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
;; A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
;; 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.
;;
;; *********************************************************************
;;
;; PLEASE NOTE: This file is a downstream copy of a file mainitained in
;; a repository at cilkplus.org. Changes made to this file that are not
;; submitted through the contribution process detailed at
;; http://www.cilkplus.org/submit-cilk-contribution will be lost the next
;; time that a new version is released. Changes only submitted to the
;; GNU compiler collection or posted to the git repository at
;; https://bitbucket.org/intelcilkplusruntime/itnel-cilk-runtime.git are
;; not tracked.
;;
;; We welcome your contributions to this open source project. Thank you
;; for your assistance in helping us improve Cilk Plus.
;;
;;*****************************************************************************
;;
;; safe_seh.asm
;;
;; This module declares our exception handlers "safe". That is, they are in
;; the generated code and the exception dispatcher is sure that they weren't
;; injected by some virus which is trying to get control. Chris Brumme's blog
;; discusses this briefly:
;; http://blogs.msdn.com/b/cbrumme/archive/2003/10/01/51524.aspx
;;
;; Failure to mark our exception handlers as safe will result in the exception
;; dispatcher skipping them.
;;
;; This only applies to the Win32 build
.386
.model flat
IF _MSC_VER LT 1600
__cilkrts_detach_handler proto
__cilkrts_stub_handler proto
.safeseh __cilkrts_detach_handler
.safeseh __cilkrts_stub_handler
ELSE
___cilkrts_detach_handler proto
___cilkrts_stub_handler proto
.safeseh ___cilkrts_detach_handler
.safeseh ___cilkrts_stub_handler
ENDIF
end
|
.text
j main
collatz_map:
addi $sp, $sp, -4
sw $ra, 0($sp)
bne
main:
jal collatz_map |
// Copyright 2018 the V8 project authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "include/v8.h"
#include "src/api/api-inl.h"
#include "src/builtins/builtins.h"
#include "src/execution/isolate.h"
#include "src/heap/spaces.h"
#include "src/objects/code-inl.h"
#include "test/cctest/cctest.h"
namespace v8 {
namespace internal {
namespace test_unwinder {
static const void* fake_stack_base = nullptr;
// Ignore deprecation warnings so that we can keep the tests for now.
// TODO(petermarshall): Delete all the tests here when the old API is removed to
// reduce the duplication.
#if __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wdeprecated"
#endif
TEST(Unwind_BadState_Fail) {
UnwindState unwind_state; // Fields are intialized to nullptr.
RegisterState register_state;
bool unwound = v8::Unwinder::TryUnwindV8Frames(unwind_state, ®ister_state,
fake_stack_base);
CHECK(!unwound);
// The register state should not change when unwinding fails.
CHECK_NULL(register_state.fp);
CHECK_NULL(register_state.sp);
CHECK_NULL(register_state.pc);
}
TEST(Unwind_BuiltinPCInMiddle_Success) {
LocalContext env;
v8::Isolate* isolate = env->GetIsolate();
Isolate* i_isolate = reinterpret_cast<Isolate*>(isolate);
UnwindState unwind_state = isolate->GetUnwindState();
RegisterState register_state;
uintptr_t stack[3];
void* stack_base = stack + arraysize(stack);
stack[0] = reinterpret_cast<uintptr_t>(stack + 2); // saved FP (rbp).
stack[1] = 202; // Return address into C++ code.
stack[2] = 303; // The SP points here in the caller's frame.
register_state.sp = stack;
register_state.fp = stack;
// Put the current PC inside of a valid builtin.
Code builtin = i_isolate->builtins()->builtin(Builtins::kStringEqual);
const uintptr_t offset = 40;
CHECK_LT(offset, builtin.InstructionSize());
register_state.pc =
reinterpret_cast<void*>(builtin.InstructionStart() + offset);
bool unwound = v8::Unwinder::TryUnwindV8Frames(unwind_state, ®ister_state,
stack_base);
CHECK(unwound);
CHECK_EQ(reinterpret_cast<void*>(stack + 2), register_state.fp);
CHECK_EQ(reinterpret_cast<void*>(stack + 2), register_state.sp);
CHECK_EQ(reinterpret_cast<void*>(202), register_state.pc);
}
// The unwinder should be able to unwind even if we haven't properly set up the
// current frame, as long as there is another JS frame underneath us (i.e. as
// long as the PC isn't in JSEntry). This test puts the PC at the start
// of a JS builtin and creates a fake JSEntry frame before it on the stack. The
// unwinder should be able to unwind to the C++ frame before the JSEntry frame.
TEST(Unwind_BuiltinPCAtStart_Success) {
LocalContext env;
v8::Isolate* isolate = env->GetIsolate();
Isolate* i_isolate = reinterpret_cast<Isolate*>(isolate);
UnwindState unwind_state = isolate->GetUnwindState();
RegisterState register_state;
const size_t code_length = 40;
uintptr_t code[code_length] = {0};
unwind_state.code_range.start = code;
unwind_state.code_range.length_in_bytes = code_length * sizeof(uintptr_t);
uintptr_t stack[6];
void* stack_base = stack + arraysize(stack);
stack[0] = 101;
// Return address into JS code. It doesn't matter that this is not actually in
// JSEntry, because we only check that for the top frame.
stack[1] = reinterpret_cast<uintptr_t>(code + 10);
stack[2] = reinterpret_cast<uintptr_t>(stack + 5); // saved FP (rbp).
stack[3] = 303; // Return address into C++ code.
stack[4] = 404;
stack[5] = 505;
register_state.sp = stack;
register_state.fp = stack + 2; // FP to the JSEntry frame.
// Put the current PC at the start of a valid builtin, so that we are setting
// up the frame.
Code builtin = i_isolate->builtins()->builtin(Builtins::kStringEqual);
register_state.pc = reinterpret_cast<void*>(builtin.InstructionStart());
bool unwound = v8::Unwinder::TryUnwindV8Frames(unwind_state, ®ister_state,
stack_base);
CHECK(unwound);
CHECK_EQ(reinterpret_cast<void*>(stack + 5), register_state.fp);
CHECK_EQ(reinterpret_cast<void*>(stack + 4), register_state.sp);
CHECK_EQ(reinterpret_cast<void*>(303), register_state.pc);
}
const char* foo_source = R"(
function foo(a, b) {
let x = a * b;
let y = x ^ b;
let z = y / a;
return x + y - z;
};
%PrepareFunctionForOptimization(foo);
foo(1, 2);
foo(1, 2);
%OptimizeFunctionOnNextCall(foo);
foo(1, 2);
)";
// Check that we can unwind when the pc is within an optimized code object on
// the V8 heap.
TEST(Unwind_CodeObjectPCInMiddle_Success) {
FLAG_allow_natives_syntax = true;
LocalContext env;
v8::Isolate* isolate = env->GetIsolate();
Isolate* i_isolate = reinterpret_cast<Isolate*>(isolate);
HandleScope scope(i_isolate);
UnwindState unwind_state = isolate->GetUnwindState();
RegisterState register_state;
uintptr_t stack[3];
void* stack_base = stack + arraysize(stack);
stack[0] = reinterpret_cast<uintptr_t>(stack + 2); // saved FP (rbp).
stack[1] = 202; // Return address into C++ code.
stack[2] = 303; // The SP points here in the caller's frame.
register_state.sp = stack;
register_state.fp = stack;
// Create an on-heap code object. Make sure we run the function so that it is
// compiled and not just marked for lazy compilation.
CompileRun(foo_source);
v8::Local<v8::Function> local_foo = v8::Local<v8::Function>::Cast(
env.local()->Global()->Get(env.local(), v8_str("foo")).ToLocalChecked());
Handle<JSFunction> foo =
Handle<JSFunction>::cast(v8::Utils::OpenHandle(*local_foo));
// Put the current PC inside of the created code object.
AbstractCode abstract_code = foo->abstract_code();
// We don't produce optimized code when run with --no-opt.
if (!abstract_code.IsCode() && FLAG_opt == false) return;
CHECK(abstract_code.IsCode());
Code code = abstract_code.GetCode();
// We don't want the offset too early or it could be the `push rbp`
// instruction (which is not at the start of generated code, because the lazy
// deopt check happens before frame setup).
const uintptr_t offset = code.InstructionSize() - 20;
CHECK_LT(offset, code.InstructionSize());
Address pc = code.InstructionStart() + offset;
register_state.pc = reinterpret_cast<void*>(pc);
// Check that the created code is within the code range that we get from the
// API.
Address start = reinterpret_cast<Address>(unwind_state.code_range.start);
CHECK(pc >= start && pc < start + unwind_state.code_range.length_in_bytes);
bool unwound = v8::Unwinder::TryUnwindV8Frames(unwind_state, ®ister_state,
stack_base);
CHECK(unwound);
CHECK_EQ(reinterpret_cast<void*>(stack + 2), register_state.fp);
CHECK_EQ(reinterpret_cast<void*>(stack + 2), register_state.sp);
CHECK_EQ(reinterpret_cast<void*>(202), register_state.pc);
}
// If the PC is within JSEntry but we haven't set up the frame yet, then we
// cannot unwind.
TEST(Unwind_JSEntryBeforeFrame_Fail) {
LocalContext env;
v8::Isolate* isolate = env->GetIsolate();
UnwindState unwind_state = isolate->GetUnwindState();
RegisterState register_state;
const size_t code_length = 40;
uintptr_t code[code_length] = {0};
unwind_state.code_range.start = code;
unwind_state.code_range.length_in_bytes = code_length * sizeof(uintptr_t);
// Pretend that it takes 5 instructions to set up the frame in JSEntry.
unwind_state.js_entry_stub.code.start = code + 10;
unwind_state.js_entry_stub.code.length_in_bytes = 10 * sizeof(uintptr_t);
uintptr_t stack[10];
void* stack_base = stack + arraysize(stack);
stack[0] = 101;
stack[1] = 111;
stack[2] = 121;
stack[3] = 131;
stack[4] = 141;
stack[5] = 151;
stack[6] = 100; // Return address into C++ code.
stack[7] = 303; // The SP points here in the caller's frame.
stack[8] = 404;
stack[9] = 505;
register_state.sp = stack + 5;
register_state.fp = stack + 9;
// Put the current PC inside of JSEntry, before the frame is set up.
register_state.pc = code + 12;
bool unwound = v8::Unwinder::TryUnwindV8Frames(unwind_state, ®ister_state,
stack_base);
CHECK(!unwound);
// The register state should not change when unwinding fails.
CHECK_EQ(reinterpret_cast<void*>(stack + 9), register_state.fp);
CHECK_EQ(reinterpret_cast<void*>(stack + 5), register_state.sp);
CHECK_EQ(code + 12, register_state.pc);
// Change the PC to a few instructions later, after the frame is set up.
register_state.pc = code + 16;
unwound = v8::Unwinder::TryUnwindV8Frames(unwind_state, ®ister_state,
stack_base);
// TODO(petermarshall): More precisely check position within JSEntry rather
// than just assuming the frame is unreadable.
CHECK(!unwound);
// The register state should not change when unwinding fails.
CHECK_EQ(reinterpret_cast<void*>(stack + 9), register_state.fp);
CHECK_EQ(reinterpret_cast<void*>(stack + 5), register_state.sp);
CHECK_EQ(code + 16, register_state.pc);
}
TEST(Unwind_OneJSFrame_Success) {
LocalContext env;
v8::Isolate* isolate = env->GetIsolate();
UnwindState unwind_state = isolate->GetUnwindState();
RegisterState register_state;
// Use a fake code range so that we can initialize it to 0s.
const size_t code_length = 40;
uintptr_t code[code_length] = {0};
unwind_state.code_range.start = code;
unwind_state.code_range.length_in_bytes = code_length * sizeof(uintptr_t);
// Our fake stack has two frames - one C++ frame and one JS frame (on top).
// The stack grows from high addresses to low addresses.
uintptr_t stack[10];
void* stack_base = stack + arraysize(stack);
stack[0] = 101;
stack[1] = 111;
stack[2] = 121;
stack[3] = 131;
stack[4] = 141;
stack[5] = reinterpret_cast<uintptr_t>(stack + 9); // saved FP (rbp).
stack[6] = 100; // Return address into C++ code.
stack[7] = 303; // The SP points here in the caller's frame.
stack[8] = 404;
stack[9] = 505;
register_state.sp = stack;
register_state.fp = stack + 5;
// Put the current PC inside of the code range so it looks valid.
register_state.pc = code + 30;
bool unwound = v8::Unwinder::TryUnwindV8Frames(unwind_state, ®ister_state,
stack_base);
CHECK(unwound);
CHECK_EQ(reinterpret_cast<void*>(stack + 9), register_state.fp);
CHECK_EQ(reinterpret_cast<void*>(stack + 7), register_state.sp);
CHECK_EQ(reinterpret_cast<void*>(100), register_state.pc);
}
// Creates a fake stack with two JS frames on top of a C++ frame and checks that
// the unwinder correctly unwinds past the JS frames and returns the C++ frame's
// details.
TEST(Unwind_TwoJSFrames_Success) {
LocalContext env;
v8::Isolate* isolate = env->GetIsolate();
UnwindState unwind_state = isolate->GetUnwindState();
RegisterState register_state;
// Use a fake code range so that we can initialize it to 0s.
const size_t code_length = 40;
uintptr_t code[code_length] = {0};
unwind_state.code_range.start = code;
unwind_state.code_range.length_in_bytes = code_length * sizeof(uintptr_t);
// Our fake stack has three frames - one C++ frame and two JS frames (on top).
// The stack grows from high addresses to low addresses.
uintptr_t stack[10];
void* stack_base = stack + arraysize(stack);
stack[0] = 101;
stack[1] = 111;
stack[2] = reinterpret_cast<uintptr_t>(stack + 5); // saved FP (rbp).
// The fake return address is in the JS code range.
stack[3] = reinterpret_cast<uintptr_t>(code + 10);
stack[4] = 141;
stack[5] = reinterpret_cast<uintptr_t>(stack + 9); // saved FP (rbp).
stack[6] = 100; // Return address into C++ code.
stack[7] = 303; // The SP points here in the caller's frame.
stack[8] = 404;
stack[9] = 505;
register_state.sp = stack;
register_state.fp = stack + 2;
// Put the current PC inside of the code range so it looks valid.
register_state.pc = code + 30;
bool unwound = v8::Unwinder::TryUnwindV8Frames(unwind_state, ®ister_state,
stack_base);
CHECK(unwound);
CHECK_EQ(reinterpret_cast<void*>(stack + 9), register_state.fp);
CHECK_EQ(reinterpret_cast<void*>(stack + 7), register_state.sp);
CHECK_EQ(reinterpret_cast<void*>(100), register_state.pc);
}
// If the PC is in JSEntry then the frame might not be set up correctly, meaning
// we can't unwind the stack properly.
TEST(Unwind_JSEntry_Fail) {
LocalContext env;
v8::Isolate* isolate = env->GetIsolate();
Isolate* i_isolate = reinterpret_cast<Isolate*>(isolate);
UnwindState unwind_state = isolate->GetUnwindState();
RegisterState register_state;
Code js_entry = i_isolate->heap()->builtin(Builtins::kJSEntry);
byte* start = reinterpret_cast<byte*>(js_entry.InstructionStart());
register_state.pc = start + 10;
bool unwound = v8::Unwinder::TryUnwindV8Frames(unwind_state, ®ister_state,
fake_stack_base);
CHECK(!unwound);
// The register state should not change when unwinding fails.
CHECK_NULL(register_state.fp);
CHECK_NULL(register_state.sp);
CHECK_EQ(start + 10, register_state.pc);
}
TEST(Unwind_StackBounds_Basic) {
LocalContext env;
v8::Isolate* isolate = env->GetIsolate();
UnwindState unwind_state = isolate->GetUnwindState();
RegisterState register_state;
const size_t code_length = 10;
uintptr_t code[code_length] = {0};
unwind_state.code_range.start = code;
unwind_state.code_range.length_in_bytes = code_length * sizeof(uintptr_t);
uintptr_t stack[3];
stack[0] = reinterpret_cast<uintptr_t>(stack + 2); // saved FP (rbp).
stack[1] = 202; // Return address into C++ code.
stack[2] = 303; // The SP points here in the caller's frame.
register_state.sp = stack;
register_state.fp = stack;
register_state.pc = code;
void* wrong_stack_base = reinterpret_cast<void*>(
reinterpret_cast<uintptr_t>(stack) - sizeof(uintptr_t));
bool unwound = v8::Unwinder::TryUnwindV8Frames(unwind_state, ®ister_state,
wrong_stack_base);
CHECK(!unwound);
// Correct the stack base and unwinding should succeed.
void* correct_stack_base = stack + arraysize(stack);
unwound = v8::Unwinder::TryUnwindV8Frames(unwind_state, ®ister_state,
correct_stack_base);
CHECK(unwound);
}
TEST(Unwind_StackBounds_WithUnwinding) {
LocalContext env;
v8::Isolate* isolate = env->GetIsolate();
UnwindState unwind_state = isolate->GetUnwindState();
RegisterState register_state;
// Use a fake code range so that we can initialize it to 0s.
const size_t code_length = 40;
uintptr_t code[code_length] = {0};
unwind_state.code_range.start = code;
unwind_state.code_range.length_in_bytes = code_length * sizeof(uintptr_t);
// Our fake stack has two frames - one C++ frame and one JS frame (on top).
// The stack grows from high addresses to low addresses.
uintptr_t stack[11];
void* stack_base = stack + arraysize(stack);
stack[0] = 101;
stack[1] = 111;
stack[2] = 121;
stack[3] = 131;
stack[4] = 141;
stack[5] = reinterpret_cast<uintptr_t>(stack + 9); // saved FP (rbp).
stack[6] = reinterpret_cast<uintptr_t>(code + 20); // JS code.
stack[7] = 303; // The SP points here in the caller's frame.
stack[8] = 404;
stack[9] = reinterpret_cast<uintptr_t>(stack) +
(12 * sizeof(uintptr_t)); // saved FP (OOB).
stack[10] = reinterpret_cast<uintptr_t>(code + 20); // JS code.
register_state.sp = stack;
register_state.fp = stack + 5;
// Put the current PC inside of the code range so it looks valid.
register_state.pc = code + 30;
// Unwind will fail because stack[9] FP points outside of the stack.
bool unwound = v8::Unwinder::TryUnwindV8Frames(unwind_state, ®ister_state,
stack_base);
CHECK(!unwound);
// Change the return address so that it is not in range. We will not range
// check the stack[9] FP value because we have finished unwinding and the
// contents of rbp does not necessarily have to be the FP in this case.
stack[10] = 202;
unwound = v8::Unwinder::TryUnwindV8Frames(unwind_state, ®ister_state,
stack_base);
CHECK(unwound);
}
TEST(PCIsInV8_BadState_Fail) {
UnwindState unwind_state;
void* pc = nullptr;
CHECK(!v8::Unwinder::PCIsInV8(unwind_state, pc));
}
TEST(PCIsInV8_ValidStateNullPC_Fail) {
LocalContext env;
v8::Isolate* isolate = env->GetIsolate();
UnwindState unwind_state = isolate->GetUnwindState();
void* pc = nullptr;
CHECK(!v8::Unwinder::PCIsInV8(unwind_state, pc));
}
void TestRangeBoundaries(const UnwindState& unwind_state, byte* range_start,
size_t range_length) {
void* pc = range_start - 1;
CHECK(!v8::Unwinder::PCIsInV8(unwind_state, pc));
pc = range_start;
CHECK(v8::Unwinder::PCIsInV8(unwind_state, pc));
pc = range_start + 1;
CHECK(v8::Unwinder::PCIsInV8(unwind_state, pc));
pc = range_start + range_length - 1;
CHECK(v8::Unwinder::PCIsInV8(unwind_state, pc));
pc = range_start + range_length;
CHECK(!v8::Unwinder::PCIsInV8(unwind_state, pc));
pc = range_start + range_length + 1;
CHECK(!v8::Unwinder::PCIsInV8(unwind_state, pc));
}
TEST(PCIsInV8_InCodeOrEmbeddedRange) {
LocalContext env;
v8::Isolate* isolate = env->GetIsolate();
UnwindState unwind_state = isolate->GetUnwindState();
byte* code_range_start = const_cast<byte*>(
reinterpret_cast<const byte*>(unwind_state.code_range.start));
size_t code_range_length = unwind_state.code_range.length_in_bytes;
TestRangeBoundaries(unwind_state, code_range_start, code_range_length);
byte* embedded_range_start = const_cast<byte*>(
reinterpret_cast<const byte*>(unwind_state.embedded_code_range.start));
size_t embedded_range_length =
unwind_state.embedded_code_range.length_in_bytes;
TestRangeBoundaries(unwind_state, embedded_range_start,
embedded_range_length);
}
// PCIsInV8 doesn't check if the PC is in JSEntry directly. It's assumed that
// the CodeRange or EmbeddedCodeRange contain JSEntry.
TEST(PCIsInV8_InJSEntryRange) {
LocalContext env;
v8::Isolate* isolate = env->GetIsolate();
Isolate* i_isolate = reinterpret_cast<Isolate*>(isolate);
UnwindState unwind_state = isolate->GetUnwindState();
Code js_entry = i_isolate->heap()->builtin(Builtins::kJSEntry);
byte* start = reinterpret_cast<byte*>(js_entry.InstructionStart());
size_t length = js_entry.InstructionSize();
void* pc = start;
CHECK(v8::Unwinder::PCIsInV8(unwind_state, pc));
pc = start + 1;
CHECK(v8::Unwinder::PCIsInV8(unwind_state, pc));
pc = start + length - 1;
CHECK(v8::Unwinder::PCIsInV8(unwind_state, pc));
}
// Large code objects can be allocated in large object space. Check that this is
// inside the CodeRange.
TEST(PCIsInV8_LargeCodeObject) {
FLAG_allow_natives_syntax = true;
LocalContext env;
v8::Isolate* isolate = env->GetIsolate();
Isolate* i_isolate = reinterpret_cast<Isolate*>(isolate);
HandleScope scope(i_isolate);
UnwindState unwind_state = isolate->GetUnwindState();
// Create a big function that ends up in CODE_LO_SPACE.
const int instruction_size = Page::kPageSize + 1;
STATIC_ASSERT(instruction_size > kMaxRegularHeapObjectSize);
std::unique_ptr<byte[]> instructions(new byte[instruction_size]);
CodeDesc desc;
desc.buffer = instructions.get();
desc.buffer_size = instruction_size;
desc.instr_size = instruction_size;
desc.reloc_size = 0;
desc.constant_pool_size = 0;
desc.unwinding_info = nullptr;
desc.unwinding_info_size = 0;
desc.origin = nullptr;
Handle<Code> foo_code =
Factory::CodeBuilder(i_isolate, desc, Code::WASM_FUNCTION).Build();
CHECK(i_isolate->heap()->InSpace(*foo_code, CODE_LO_SPACE));
byte* start = reinterpret_cast<byte*>(foo_code->InstructionStart());
void* pc = start;
CHECK(v8::Unwinder::PCIsInV8(unwind_state, pc));
}
#if __clang__
#pragma clang diagnostic pop
#endif
} // namespace test_unwinder
} // namespace internal
} // namespace v8
|
#include <vga.h>
#include <nvboard.h>
#include <macro.h>
#include <assert.h>
VGA_MODE vga_mod_accepted[NR_VGA_MODE] = {
[VGA_MODE_640_480] = {
.h_frontporch = 96,
.h_active = 144,
.h_backporch = 784,
.h_total = 800,
.v_frontporch = 2,
.v_active = 35,
.v_backporch = 515,
.v_total = 525,
},
};
VGA::VGA(SDL_Renderer *rend, int cnt, int init_val, int it, int ct):
Component(rend, cnt, init_val, it, ct),
vga_screen_width(VGA_DEFAULT_WIDTH), vga_screen_height(VGA_DEFAULT_HEIGHT),
vga_pre_clk(0), vga_pre_hsync(0), vga_pre_vsync(0),
vga_pos(0), vga_vaddr(0), vga_haddr(0) {
SDL_Texture *temp_texture = SDL_CreateTexture(rend, SDL_PIXELFORMAT_ARGB8888,
SDL_TEXTUREACCESS_STATIC, vga_screen_width, vga_screen_height);
set_texture(temp_texture, 0);
pixels = new uint32_t[vga_screen_width * vga_screen_height];
memset(pixels, 0, vga_screen_width * vga_screen_height * sizeof(uint32_t));
}
VGA::~VGA() {
SDL_DestroyTexture(get_texture(0));
delete []pixels;
}
void VGA::update_gui() {
static int frames = 0;
frames ++;
printf("%d frames\n", frames);
SDL_Texture *temp_texture = get_texture(0);
SDL_Renderer *temp_renderer = get_renderer();
SDL_Rect *temp_rect = get_rect(0);
SDL_UpdateTexture(temp_texture, NULL, pixels, vga_screen_width * sizeof(uint32_t));
//SDL_RenderClear(temp_renderer);
SDL_RenderCopy(temp_renderer, temp_texture, NULL, temp_rect);
}
void VGA::update_state() {
int vga_clk = output_map[output_pin::VGA_CLK];
int vga_vsync = output_map[output_pin::VGA_VSYNC];
int vga_hsync = output_map[output_pin::VGA_HSYNC];
int vga_blank_n = output_map[output_pin::VGA_BLANK_N];
if(!VGA_NEG_EDGE(clk)){
vga_pre_clk = vga_clk;
return;
}
if(vga_blank_n) {
int vga_r = (output_map[output_pin::VGA_R7] << 7) |
(output_map[output_pin::VGA_R6] << 6) |
(output_map[output_pin::VGA_R5] << 5) |
(output_map[output_pin::VGA_R4] << 4) |
(output_map[output_pin::VGA_R3] << 3) |
(output_map[output_pin::VGA_R2] << 2) |
(output_map[output_pin::VGA_R1] << 1) |
output_map[output_pin::VGA_R0];
int vga_g = (output_map[output_pin::VGA_G7] << 7) |
(output_map[output_pin::VGA_G6] << 6) |
(output_map[output_pin::VGA_G5] << 5) |
(output_map[output_pin::VGA_G4] << 4) |
(output_map[output_pin::VGA_G3] << 3) |
(output_map[output_pin::VGA_G2] << 2) |
(output_map[output_pin::VGA_G1] << 1) |
output_map[output_pin::VGA_G0];
int vga_b = (output_map[output_pin::VGA_B7] << 7) |
(output_map[output_pin::VGA_B6] << 6) |
(output_map[output_pin::VGA_B5] << 5) |
(output_map[output_pin::VGA_B4] << 4) |
(output_map[output_pin::VGA_B3] << 3) |
(output_map[output_pin::VGA_B2] << 2) |
(output_map[output_pin::VGA_B1] << 1) |
output_map[output_pin::VGA_B0];
uint32_t vga_rgb = (vga_r << 16) | (vga_g << 8) | (vga_b);
assert(vga_pos < vga_screen_width * vga_screen_height);
pixels[vga_pos] = vga_rgb;
vga_pos ++;
}
if(VGA_NEG_EDGE(vsync)) {
vga_pos = 0;
update_gui();
}
vga_pre_vsync = vga_vsync;
vga_pre_clk = vga_clk;
}
|
Name: bged_dt0.asm
Type: file
Size: 174050
Last-Modified: '2016-05-13T04:25:37Z'
SHA-1: 6A6156C3E2B4DE6882B90BEB98501DF04CDC1764
Description: null
|
.global s_prepare_buffers
s_prepare_buffers:
push %r10
push %r11
push %rax
push %rbp
push %rcx
push %rdi
push %rsi
lea addresses_normal_ht+0x9944, %rsi
lea addresses_A_ht+0x91d4, %rdi
add %rax, %rax
mov $107, %rcx
rep movsq
nop
nop
nop
nop
sub $61125, %r11
lea addresses_A_ht+0x6adb, %rbp
nop
nop
nop
nop
xor $20940, %r10
movb $0x61, (%rbp)
nop
nop
xor $18814, %rax
lea addresses_UC_ht+0x9294, %rax
nop
sub $36856, %rsi
movb (%rax), %cl
nop
nop
nop
nop
nop
sub %rax, %rax
lea addresses_D_ht+0x16e4, %rbp
nop
nop
nop
nop
nop
cmp %rsi, %rsi
movl $0x61626364, (%rbp)
nop
nop
nop
nop
nop
inc %rdi
lea addresses_WC_ht+0x1ba90, %r10
nop
dec %rdi
mov (%r10), %esi
nop
cmp $44753, %rsi
lea addresses_WC_ht+0x15fd4, %rbp
nop
xor $42318, %rdi
movw $0x6162, (%rbp)
nop
nop
nop
nop
dec %rax
lea addresses_A_ht+0x1ded4, %rdi
nop
nop
nop
nop
nop
and %rax, %rax
mov $0x6162636465666768, %rsi
movq %rsi, %xmm6
movups %xmm6, (%rdi)
add $50437, %r10
lea addresses_UC_ht+0xc754, %rbp
clflush (%rbp)
nop
nop
nop
nop
nop
sub %rcx, %rcx
mov $0x6162636465666768, %rsi
movq %rsi, %xmm4
movups %xmm4, (%rbp)
nop
nop
nop
nop
nop
cmp %rcx, %rcx
pop %rsi
pop %rdi
pop %rcx
pop %rbp
pop %rax
pop %r11
pop %r10
ret
.global s_faulty_load
s_faulty_load:
push %r10
push %r11
push %r15
push %r9
push %rax
push %rcx
push %rdi
// Store
lea addresses_PSE+0x125d4, %rax
nop
nop
nop
and $43569, %r9
movw $0x5152, (%rax)
nop
inc %rdi
// Store
lea addresses_WT+0xb0d4, %r11
nop
nop
nop
xor $55875, %rax
mov $0x5152535455565758, %r9
movq %r9, %xmm0
vmovups %ymm0, (%r11)
sub $65122, %r15
// Store
lea addresses_D+0xa0d4, %r11
nop
nop
add $50584, %rcx
mov $0x5152535455565758, %r9
movq %r9, %xmm5
movups %xmm5, (%r11)
// Exception!!!
mov (0), %rax
nop
nop
and %r10, %r10
// Load
lea addresses_A+0x9ad4, %rax
nop
nop
nop
nop
and $19586, %rdi
movb (%rax), %cl
nop
nop
cmp $23758, %rcx
// Store
lea addresses_UC+0x1b064, %r10
nop
nop
nop
dec %rax
mov $0x5152535455565758, %rcx
movq %rcx, %xmm7
movntdq %xmm7, (%r10)
nop
nop
nop
nop
nop
xor $33574, %r15
// Faulty Load
lea addresses_normal+0x78d4, %rdi
nop
sub $33265, %r10
vmovaps (%rdi), %ymm0
vextracti128 $1, %ymm0, %xmm0
vpextrq $1, %xmm0, %rcx
lea oracles, %r11
and $0xff, %rcx
shlq $12, %rcx
mov (%r11,%rcx,1), %rcx
pop %rdi
pop %rcx
pop %rax
pop %r9
pop %r15
pop %r11
pop %r10
ret
/*
<gen_faulty_load>
[REF]
{'OP': 'LOAD', 'src': {'type': 'addresses_normal', 'AVXalign': False, 'congruent': 0, 'size': 16, 'same': True, 'NT': False}}
{'OP': 'STOR', 'dst': {'type': 'addresses_PSE', 'AVXalign': False, 'congruent': 8, 'size': 2, 'same': False, 'NT': True}}
{'OP': 'STOR', 'dst': {'type': 'addresses_WT', 'AVXalign': False, 'congruent': 11, 'size': 32, 'same': False, 'NT': False}}
{'OP': 'STOR', 'dst': {'type': 'addresses_D', 'AVXalign': False, 'congruent': 9, 'size': 16, 'same': False, 'NT': False}}
{'OP': 'LOAD', 'src': {'type': 'addresses_A', 'AVXalign': False, 'congruent': 8, 'size': 1, 'same': False, 'NT': False}}
{'OP': 'STOR', 'dst': {'type': 'addresses_UC', 'AVXalign': False, 'congruent': 2, 'size': 16, 'same': False, 'NT': True}}
[Faulty Load]
{'OP': 'LOAD', 'src': {'type': 'addresses_normal', 'AVXalign': True, 'congruent': 0, 'size': 32, 'same': True, 'NT': False}}
<gen_prepare_buffer>
{'OP': 'REPM', 'src': {'type': 'addresses_normal_ht', 'congruent': 4, 'same': False}, 'dst': {'type': 'addresses_A_ht', 'congruent': 5, 'same': False}}
{'OP': 'STOR', 'dst': {'type': 'addresses_A_ht', 'AVXalign': True, 'congruent': 0, 'size': 1, 'same': True, 'NT': False}}
{'OP': 'LOAD', 'src': {'type': 'addresses_UC_ht', 'AVXalign': False, 'congruent': 5, 'size': 1, 'same': False, 'NT': False}}
{'OP': 'STOR', 'dst': {'type': 'addresses_D_ht', 'AVXalign': False, 'congruent': 2, 'size': 4, 'same': True, 'NT': False}}
{'OP': 'LOAD', 'src': {'type': 'addresses_WC_ht', 'AVXalign': False, 'congruent': 1, 'size': 4, 'same': False, 'NT': False}}
{'OP': 'STOR', 'dst': {'type': 'addresses_WC_ht', 'AVXalign': False, 'congruent': 2, 'size': 2, 'same': False, 'NT': False}}
{'OP': 'STOR', 'dst': {'type': 'addresses_A_ht', 'AVXalign': False, 'congruent': 9, 'size': 16, 'same': False, 'NT': False}}
{'OP': 'STOR', 'dst': {'type': 'addresses_UC_ht', 'AVXalign': False, 'congruent': 6, 'size': 16, 'same': False, 'NT': False}}
{'44': 21829}
44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44
*/
|
;
; Philips VG5000 Routines
;
; Print character to the screen
;
; Jun. 2014 -Joaopa, Stefano Bodrato
;
;
; $Id: fputc_cons.asm,v 1.7 2016/06/16 19:40:21 dom Exp $
;
SECTION code_clib
PUBLIC fputc_cons_native
;
; Entry: char to print
;
DEFC ROWS=25
DEFC COLUMNS=40
defc ROW = $4805
defc COLUMN = $4806
.fputc_cons_native
ld ix,$47FA
ld hl,2
add hl,sp
ld a,(hl)
ld (charput+1),a
cp 12 ; CLS
jr nz,nocls
ld hl,0
ld (ROW),hl
ld bc,ROWS*COLUMNS
.cls
push hl
ld a,32
ld (charput+1),a
.clsloop
push bc
call charput
pop bc
dec bc
ld a,b
or c
jr nz,clsloop
pop hl
ld (ROW),hl
ret
.nocls
.doput
cp 13 ; CR?
jr z,isLF
cp 10 ; LF?
jr nz,NoLF
.isLF
xor a
ld (COLUMN),a ; automatic CR
ld a,(ROW)
inc a
ld (ROW),a
cp ROWS ; Out of screen?
ret nz ; no, return
ld a,ROWS-1
ld (ROW),a
jp scrolluptxt
.NoLF
cp 8 ; BackSpace
jr nz,NoBS
ld hl,COLUMN
cp (hl)
jr z,firstc ; are we in the first column?
dec (hl)
push hl
ld a,32
call charput+2
pop hl
dec (hl)
ret
.firstc
ld a,(ROW)
and a
ret z
dec a
ld (ROW),a
ld a,COLUMNS-1
ld (COLUMN),a
ret
.NoBS
.charput
ld a,0
push af
ld a,(COLUMN)
cp COLUMNS ; top-right column ? In this way we wait..
call z,isLF ; .. to have a char to print before issuing a CR
pop af
ld d,a
ld e,7 ; white on black
ld a,(COLUMN)
ld l,a
ld a,(ROW)
ld h,a
push hl
and a
jr z,zrow
add 7 ; bias the default scroll register settings and so on..
.zrow
ld h,a
push de
ld a,64+128
or e
ld e,a
call $92 ; direct video access
pop de
pop hl
push de
call $a7 ; video buffer access (keep a copy to scroll)
pop de
ld a,d
ld (hl),a
ld a,(COLUMN)
inc a
ld (COLUMN),a
cp COLUMNS ; last column ?
ret nz ; no, return
jp isLF
scrolluptxt:
ld hl,0
ld (ROW),hl
ld bc,ROWS*COLUMNS-COLUMNS
.scloop
ld a,(COLUMN)
ld l,a
ld a,(ROW)
inc a
ld h,a
push bc
call $a7
ld a,(hl)
ld (charput+1),a
call charput
pop bc
dec bc
ld a,b
or c
jr nz,scloop
ld bc,COLUMNS-1
ld hl,(ROW)
jp cls
; cp 12 ; CLS
; jp z,$9e
; ld hl,charput
; call $36aa
;sync:
; ei
; rst 38h
; rst 38h
; rst 38h
; rst 38h
; rst 38h
; rst 38h
; rst 38h
; rst 38h
; di
; ret
|
// Copyright (c) 2000, 2001, 2002, 2003 by David Scherer and others.
// See the file license.txt for complete license terms.
// See the file authors.txt for a complete list of contributors.
#include "python/faces.hpp"
#include <boost/python/tuple.hpp>
#include <map>
#include <set>
#include "wrap_gl.hpp"
#include "python/slice.hpp"
#include "util/gl_enable.hpp"
using boost::python::numeric::array;
namespace cvisual { namespace python {
bool
faces::degenerate() const
{
return count < 3;
}
faces::faces()
{
double* k = normal.data();
k[0] = k[1] = k[2] = 0.0;
}
void faces::set_length(size_t new_len) {
normal.set_length(new_len);
arrayprim_color::set_length(new_len);
}
void
faces::append_rgb( const vector& nv_pos, const vector& nv_normal, float red, float green, float blue)
{
arrayprim_color::append_rgb( nv_pos, red, green, blue );
double* n = normal.data(count-1);
n[0] = nv_normal.x;
n[1] = nv_normal.y;
n[2] = nv_normal.z;
}
void
faces::append( const vector& nv_pos, const vector& nv_normal, const rgb& nv_color)
{
arrayprim_color::append( nv_pos, nv_color );
double* n = normal.data(count-1);
n[0] = nv_normal.x;
n[1] = nv_normal.y;
n[2] = nv_normal.z;
}
void
faces::append( const vector& nv_pos, const vector& nv_normal)
{
arrayprim_color::append( nv_pos );
double* n = normal.data(count-1);
n[0] = nv_normal.x;
n[1] = nv_normal.y;
n[2] = nv_normal.z;
}
void
faces::append( const vector& nv_pos)
{
arrayprim_color::append( nv_pos );
double* n = normal.data(count-1);
n[0] = 0.;
n[1] = 0.;
n[2] = 0.;
}
// Define an ordering for the stl-sorting criteria.
struct stl_cmp_vector
{
//AS added "const" to allow template match for VC++ build
bool operator()( const vector& lhs, const vector& rhs) const {
if (lhs.x < rhs.x)
return true;
else if (lhs.x > rhs.x)
return false;
else
if (lhs.y < rhs.y)
return true;
else if (lhs.y > rhs.y)
return false;
else
if (lhs.z < rhs.z)
return true;
else
return false;
}
};
void
faces::make_normals()
{
if (shape(pos) != shape(normal))
throw std::invalid_argument( "Dimension mismatch between pos and normal.");
// Create normals that are perpendicular to all faces
if (count == 0) return;
using boost::python::make_tuple;
normal[slice(0, count)] = make_tuple( 0, 0, 0);
double* norm_i = normal.data();
const double* pos_i = pos.data();
const double* pos_end = pos.end();
int i = 0;
for ( ; pos_i < pos_end; pos_i+=9, norm_i+=9, i+=9) {
if ((pos_i+9) > pos_end) break;
vector v1 = vector(pos_i+3)-vector(pos_i);
vector v2 = vector(pos_i+6)-vector(pos_i+3);
vector n = v1.cross(v2).norm();
double nx = n.get_x();
double ny = n.get_y();
double nz = n.get_z();
norm_i[0] = norm_i[3] = norm_i[6] = nx;
norm_i[1] = norm_i[4] = norm_i[7] = ny;
norm_i[2] = norm_i[5] = norm_i[8] = nz;
}
}
void
faces::make_twosided()
{
if (shape(pos) != shape(normal))
throw std::invalid_argument( "Dimension mismatch between pos and normal.");
if (shape(pos) != shape(color))
throw std::invalid_argument( "Dimension mismatch between pos and color.");
// Duplicate existing faces with opposite windings and normals
if (count < 3) return;
double* pos_i = pos.data();
double* norm_i = normal.data();
double* color_i = color.data();
// Make sure that there are 3 vertices per triangle
if ((count % 3) == 1) {
append(vector(pos_i+3*(count-1)), vector(norm_i+3*(count-1)), rgb(color_i+3*(count-1)));
// Array may have moved: reestablish the pointers
pos_i = pos.data();
norm_i = normal.data();
color_i = color.data();
}
if ((count % 3) == 2) {
append(vector(pos_i+3*(count-1)), vector(norm_i+3*(count-1)), rgb(color_i+3*(count-1)));
// Array may have moved: reestablish the pointers
pos_i = pos.data();
norm_i = normal.data();
color_i = color.data();
}
int icount = 3*count;
for (int i=0; i<icount; i+=3) {
append(vector(pos_i+i), vector(norm_i+i), rgb(color_i+i));
// Array may have moved: reestablish the pointers
pos_i = pos.data();
norm_i = normal.data();
color_i = color.data();
}
for (int i=0; i<icount; i+=9) {
for (int n=0; n<3; n++) {
pos_i[icount+i+3+n] = pos_i[i+6+n];
pos_i[icount+i+6+n] = pos_i[i+3+n];
norm_i[icount+i+n] = -norm_i[i+n];
norm_i[icount+i+3+n] = -norm_i[i+6+n];
norm_i[icount+i+6+n] = -norm_i[i+3+n];
color_i[icount+i+3+n] = color_i[i+6+n];
color_i[icount+i+6+n] = color_i[i+3+n];
}
}
}
void
faces::smooth()
{
smooth_d(0.95f);
}
void
faces::smooth_d(const float cosangle)
{
if (shape(pos) != shape(normal))
throw std::invalid_argument( "Dimension mismatch between pos and normal.");
// positions -> normals
typedef std::map< const vector, std::set<int>, stl_cmp_vector> vmap;
vmap vertices;
// First, map into sets all indices for the same vertex
const double* pos_i = pos.data();
const double* pos_end = pos.end();
int i = 0;
for ( ; pos_i < pos_end; pos_i+=3, i+=3) {
vertices[vector(pos_i)].insert(i);
}
// Next, in a set of vertices, find those with similar normals
// and average those normals, then find another group of similar normals
// in that set and average those; continue until set is exhausted.
double* norm_i = normal.data();
vmap::iterator iter = vertices.begin();
const vmap::iterator iterend = vertices.end();
for ( ; iter != iterend; iter++) {
while (! (iter->second).empty()) {
std::list<int> similar;
std::set<int>::iterator setiter = (iter->second).begin();
const std::set<int>::iterator setiterend = (iter->second).end();
int pt = *setiter;
vector thisnorm = vector(norm_i+pt).norm();
if (thisnorm == vector(0,0,0) ) {
// Choose a different seed
(iter->second).erase(*setiter);
continue;
}
for ( ; setiter != setiterend; setiter++) {
if (vector(norm_i+*setiter).norm().dot(thisnorm) >= cosangle) {
similar.push_back(*setiter);
}
}
vector average = vector(0,0,0);
std::list<int>::iterator viter = similar.begin();
const std::list<int>::iterator viterend = similar.end();
for ( ; viter != viterend; viter++) {
average += vector(norm_i+*viter).norm();
}
average = average.norm();
double averagex = average.get_x();
double averagey = average.get_y();
double averagez = average.get_z();
for ( viter=similar.begin(); viter != viterend; viter++) {
norm_i[*viter] = averagex;
norm_i[*viter+1] = averagey;
norm_i[*viter+2] = averagez;
(iter->second).erase(*viter);
}
similar.clear();
}
}
}
boost::python::object faces::get_normal() {
return normal[all()];
}
void faces::set_normal( const double_array& n_normal)
{
std::vector<npy_intp> dims = shape(n_normal);
if (dims.size() == 2 && dims[1] == 3) {
if (count == 0) { // This happens if set_normal called before set_pos in constructor
set_length( dims[0] );
}
} else if (dims.size() == 1 && dims[0] == 3) {
if (count == 0) { // This happens if set_normal called before set_pos in constructor
set_length( 1 );
}
}
normal[slice(0, count)] = n_normal;
double* norm_i = normal.data();
}
void faces::set_normal_v( vector v)
{
// We seem never to get here, which I don't understand
using boost::python::make_tuple;
// Broadcast the new normal across the array.
int npoints = count ? count : 1;
normal[slice(0, npoints)] = make_tuple( v.x, v.y, v.z);
}
void
faces::gl_render(view& scene)
{
if (degenerate())
return;
std::vector<vector> spos;
std::vector<rgb> tcolor;
gl_enable_client vertexes( GL_VERTEX_ARRAY);
gl_enable_client normals( GL_NORMAL_ARRAY);
gl_enable_client colors( GL_COLOR_ARRAY);
glNormalPointer( GL_DOUBLE, 0, normal.data() );
/*
// This attempt to minimize loop overhead made no difference in faces rendering speed
if (scene.gcf != 1.0 || (scene.gcfvec[0] != scene.gcfvec[1])) {
double gx = scene.gcfvec[0];
double gy = scene.gcfvec[1];
double gz = scene.gcfvec[2];
std::vector<vector> tmp( count);
spos.swap( tmp);
const double* p = pos.data();
double* s = &spos[0][0];
size_t i;
for (i=0; i<(3*(count-10)); ) { // reduce loop overhead to a minimum
s[i ] = gx*p[i ]; s[i+1 ] = gy*p[i+1 ]; s[i+2 ] = gz*p[i+2];
s[i+3 ] = gx*p[i+3 ]; s[i+4 ] = gy*p[i+4 ]; s[i+5 ] = gz*p[i+5];
s[i+6 ] = gx*p[i+6 ]; s[i+7 ] = gy*p[i+7 ]; s[i+8 ] = gz*p[i+8];
s[i+9 ] = gx*p[i+9 ]; s[i+10] = gy*p[i+10]; s[i+11] = gz*p[i+11];
s[i+12] = gx*p[i+12]; s[i+13] = gy*p[i+13]; s[i+14] = gz*p[i+14];
s[i+15] = gx*p[i+15]; s[i+16] = gy*p[i+16]; s[i+17] = gz*p[i+17];
s[i+18] = gx*p[i+18]; s[i+19] = gy*p[i+19]; s[i+20] = gz*p[i+20];
s[i+21] = gx*p[i+21]; s[i+22] = gy*p[i+22]; s[i+23] = gz*p[i+23];
s[i+24] = gx*p[i+24]; s[i+25] = gy*p[i+25]; s[i+26] = gz*p[i+26];
s[i+27] = gx*p[i+27]; s[i+28] = gy*p[i+28]; s[i+29] = gz*p[i+29];
i += 30;
}
for (; i<3*count;) {
s[i] = gx*p[i]; s[i+1] = gy*p[i+1]; s[i+2] = gz*p[i+2];
i += 3;
}
glVertexPointer( 3, GL_DOUBLE, 0, s);
}
else
glVertexPointer( 3, GL_DOUBLE, 0, pos.data() );
*/
if (scene.gcf != 1.0 || (scene.gcfvec[0] != scene.gcfvec[1])) {
std::vector<vector> tmp( count);
spos.swap( tmp);
const double* pos_i = pos.data();
for (std::vector<vector>::iterator i = spos.begin(); i != spos.end(); ++i) {
*i = vector(pos_i).scale(scene.gcfvec);
pos_i += 3;
}
glVertexPointer( 3, GL_DOUBLE, 0, &*spos.begin());
}
else
glVertexPointer( 3, GL_DOUBLE, 0, pos.data() );
if (scene.anaglyph) {
std::vector<rgb> tmp( count);
tcolor.swap( tmp);
const double* color_i = color.data();
for (std::vector<rgb>::iterator i = tcolor.begin(); i != tcolor.end(); ++i) {
if (scene.coloranaglyph)
*i = rgb(color_i).desaturate();
else
*i = rgb(color_i).grayscale();
color_i += 3;
}
glColorPointer( 3, GL_FLOAT, 0, &*tcolor.begin());
}
else
glColorPointer( 3, GL_DOUBLE, 0, color.data() );
gl_enable cull_face( GL_CULL_FACE);
for (size_t drawn = 0; drawn < count - count%3; drawn += 540) {
glDrawArrays( GL_TRIANGLES, drawn,
std::min( count - count%3 - drawn, (size_t)540));
}
}
void
faces::gl_pick_render(view& scene)
{
gl_render( scene);
}
vector
faces::get_center() const
{
vector ret;
const double* pos_i = pos.data();
const double* pos_end = pos.data( count - count%3 );
while (pos_i < pos_end) {
ret += vector(pos_i);
pos_i += 3; // 3 doubles per vector point
}
if (count)
ret /= count;
return ret;
}
void
faces::grow_extent( extent& world)
{
const double* pos_i = pos.data();
const double* pos_end = pos.data( count - count%3 );
while (pos_i < pos_end) {
world.add_point( vector(pos_i));
pos_i += 3; // 3 doubles per vector point
}
world.add_body();
}
void
faces::get_material_matrix( const view& v, tmatrix& out ) {
if (degenerate()) return;
// TODO: Add some caching for extent with grow_extent etc
vector min_extent, max_extent;
const double* pos_i = pos.data();
const double* pos_end = pos.data( count - count%3 );
min_extent = max_extent = vector( pos_i ); pos_i += 3;
while (pos_i < pos_end)
for(int j=0; j<3; j++) {
if (*pos_i < min_extent[j]) min_extent[j] = *pos_i;
else if (*pos_i > max_extent[j]) max_extent[j] = *pos_i;
pos_i++;
}
out.translate( vector(.5,.5,.5) );
out.scale( vector(1,1,1) * (.999 / (v.gcf * std::max(max_extent.x-min_extent.x, std::max(max_extent.y-min_extent.y, max_extent.z-min_extent.z)))) );
out.translate( -.5 * v.gcf * (min_extent + max_extent) );
}
} } // !namespace cvisual::python
|
.global s_prepare_buffers
s_prepare_buffers:
push %r11
push %r13
push %rax
push %rbp
push %rcx
push %rdi
push %rsi
lea addresses_D_ht+0x1baaa, %rsi
lea addresses_WC_ht+0x1a2aa, %rdi
nop
nop
nop
add %r11, %r11
mov $12, %rcx
rep movsl
nop
add $53315, %rdi
lea addresses_normal_ht+0x32aa, %r11
nop
nop
nop
nop
nop
cmp %r13, %r13
movb $0x61, (%r11)
nop
nop
nop
nop
nop
sub $60117, %rcx
lea addresses_WT_ht+0x1e62a, %rcx
nop
nop
nop
nop
and %rax, %rax
movups (%rcx), %xmm6
vpextrq $1, %xmm6, %r11
nop
nop
nop
nop
inc %rdi
lea addresses_normal_ht+0x1aaaa, %r13
xor %r11, %r11
mov (%r13), %rbp
add $41815, %rdi
pop %rsi
pop %rdi
pop %rcx
pop %rbp
pop %rax
pop %r13
pop %r11
ret
.global s_faulty_load
s_faulty_load:
push %r13
push %r14
push %r15
push %rax
push %rbp
push %rdi
// Faulty Load
lea addresses_PSE+0x192aa, %rax
clflush (%rax)
nop
nop
dec %rbp
movb (%rax), %r14b
lea oracles, %rbp
and $0xff, %r14
shlq $12, %r14
mov (%rbp,%r14,1), %r14
pop %rdi
pop %rbp
pop %rax
pop %r15
pop %r14
pop %r13
ret
/*
<gen_faulty_load>
[REF]
{'OP': 'LOAD', 'src': {'type': 'addresses_PSE', 'size': 2, 'AVXalign': False, 'NT': False, 'congruent': 0, 'same': False}}
[Faulty Load]
{'OP': 'LOAD', 'src': {'type': 'addresses_PSE', 'size': 1, 'AVXalign': False, 'NT': False, 'congruent': 0, 'same': True}}
<gen_prepare_buffer>
{'OP': 'REPM', 'src': {'type': 'addresses_D_ht', 'congruent': 8, 'same': False}, 'dst': {'type': 'addresses_WC_ht', 'congruent': 11, 'same': False}}
{'OP': 'STOR', 'dst': {'type': 'addresses_normal_ht', 'size': 1, 'AVXalign': False, 'NT': False, 'congruent': 11, 'same': False}}
{'OP': 'LOAD', 'src': {'type': 'addresses_WT_ht', 'size': 16, 'AVXalign': False, 'NT': False, 'congruent': 6, 'same': False}}
{'OP': 'LOAD', 'src': {'type': 'addresses_normal_ht', 'size': 8, 'AVXalign': False, 'NT': False, 'congruent': 11, 'same': False}}
{'33': 321}
33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33
*/
|
;
; TestApplication.asm
;
; Created: 10/12/2018 10:12:59 PM
; Author : Jayden
;
; Remove this line if running in Atmel Studio 7
.INCLUDE "../inc/m2560def.inc"
.cseg
; Init
call setup_leds
call setup_adc
loop:
lds r20, ADCSRA
ori r20, 0x40
sts ADCSRA, r20
wait_for_adc:
lds r20, ADCSRA
andi r20, 0x40
brne wait_for_adc
lds r26, ADCL
lds r27, ADCH
cpi r27, 0x03
brlo some_button
; ADCH is 3.
cpi r26, 0x17 ; this will have to be 0x53 for v1.1
brlo some_button
rjmp no_button
no_button:
rjmp done
some_button:
call lights
rjmp done
done: rjmp loop
; subroutines
lights: ldi r16, 0b10000000
l_loop:
sts PORTL, r16
call wait
call shift
brne l_loop
sts PORTL, r16
ldi r16, 0b00001000
b_loop:
out PORTB, r16
call wait
call shift
brne b_loop
out PORTB, r16
ret
wait: ldi r17, 0x0F
l1: ldi r18, 0x6F
l2: ldi r19, 0xFF
l3: nop
nop
nop
nop
nop
nop
dec r19
brne l3
dec r18
brne l2
dec r17
brne l1
ret
shift:
lsr r16
lsr r16
ret
setup_adc:
; configure the ADC
ldi r20, 0x87
sts ADCSRA, r20
ldi r20, 0x00
sts ADCSRB, r20
ldi r20, 0x40
sts ADMUX, r20
ret
setup_leds:
ldi r16, 0xFF
sts DDRL, r16
out DDRB, r16
ret
finish: jmp finish
|
; A021943: Decimal expansion of 1/939.
; Submitted by Jamie Morken(s2.)
; 0,0,1,0,6,4,9,6,2,7,2,6,3,0,4,5,7,9,3,3,9,7,2,3,1,0,9,6,9,1,1,6,0,8,0,9,3,7,1,6,7,1,9,9,1,4,8,0,2,9,8,1,8,9,5,6,3,3,6,5,2,8,2,2,1,5,1,2,2,4,7,0,7,1,3,5,2,5,0,2,6,6,2,4,0,6,8,1,5,7,6,1,4,4,8,3,4,9,3
seq $0,173833 ; 10^n - 3.
div $0,939
mod $0,10
|
;
; Init graphics and clear screen
; Stefano - Sept 2011
;
;
; $Id: clg.asm,v 1.4 2015/01/19 01:32:49 pauloscustodio Exp $
;
INCLUDE "flos.def"
INCLUDE "osca.def"
PUBLIC clg
EXTERN swapgfxbk
EXTERN swapgfxbk1
EXTERN base_graphics
.clg
; Set up a 320x200 pixel, single bitplane
; display window in linear bitmap mode.
ld a,0
ld (vreg_rasthi),a ; select y window reg
ld e,90 ; y display settings for PAL display: 200 lines
;ld e,61 ; y display settings for PAL display: 240 lines
in a,(sys_vreg_read)
bit 5,a
jr z,paltv
ld e,56 ; y display settings for non-PAL display: 200 lines
;ld e,27 ; I'm only guessing this one for 240 lines
.paltv
ld a,e
ld (vreg_window),a ; set y window size/position (200 lines in docs, but I hope to get to 240)
;ld a,$5a
;ld a,$2e
;ld a,64
;ld (vreg_window),a ; set y window size/position (200 lines)
ld a,@00000100
ld (vreg_rasthi),a ; select x window reg
ld a,$8c
ld (vreg_window),a ; set x window size/position (320 pixels)
ld a,0
ld (vreg_yhws_bplcount),a ; set 1 bitplane display
ld a,0
ld (vreg_vidctrl),a ; set bitmap mode + normal border + video enabled
ld a,0
ld (vreg_vidpage),a ; read / writes to VRAM page 0
ld hl,0
ld (bitplane0a_loc),hl ; start address of video datafetch for window [15:0]
ld a,0
ld (bitplane0a_loc+2),a ; start address of video datafetch for window [18:16]
;---------Set up palette -----------------------------------------------------
ld hl,palette ; background = black, colour 1 = white
ld (hl),$ff
inc hl
ld (hl),$0f
inc hl
ld (hl),0
inc hl
ld (hl),0
;--------- Clear VRAM --------------------
call kjt_wait_vrt ; wait for last line of display
call swapgfxbk
ld hl,$2000
ld (base_graphics),hl
ld hl,0
ld d,h
ld e,h
ld b,h
di
add hl,sp
ld sp,$2000+$2000
.clgloop
push de
push de
push de
push de
push de
push de
push de
push de
push de
push de
push de
push de
push de
push de
push de
push de
djnz clgloop
ld sp,hl
jp swapgfxbk1
|
; A213245: Number of nonzero elements in GF(2^n) that are 7th powers.
; 1,3,1,15,31,9,127,255,73,1023,2047,585,8191,16383,4681,65535,131071,37449,524287,1048575,299593,4194303,8388607,2396745,33554431,67108863,19173961,268435455,536870911,153391689,2147483647,4294967295,1227133513,17179869183,34359738367,9817068105,137438953471,274877906943,78536544841,1099511627775,2199023255551,628292358729,8796093022207,17592186044415,5026338869833,70368744177663,140737488355327,40210710958665,562949953421311,1125899906842623,321685687669321,4503599627370495,9007199254740991
add $0,1
mov $1,2
pow $1,$0
sub $1,1
dif $1,7
mov $0,$1
|
//Checking if all elements are same
#include<bits/stdc++.h>
using namespace std;
int main()
{
int n; //no of elements
cin>>n;//taking input
int ip[n+1];
set<int> unq;
for(int i=1;i<=n;i++)
{
cin>>ip[i];
unq.insert(ip[i]);
}
if(unq.size()==1)
cout<<"All"<<n<<" Element are same"<<endl;
else
cout<<"Different Elements Present"<<endl;
} |
;CodeVisionAVR C Compiler V1.25.8 Standard
;(C) Copyright 1998-2007 Pavel Haiduc, HP InfoTech s.r.l.
;http://www.hpinfotech.com
;Chip type : ATmega644
;Program type : Application
;Clock frequency : 4.000000 MHz
;Memory model : Small
;Optimize for : Size
;(s)printf features : int, width
;(s)scanf features : int, width
;External SRAM size : 0
;Data Stack size : 1024 byte(s)
;Heap size : 256 byte(s)
;Promote char to int : No
;char is unsigned : Yes
;8 bit enums : No
;Word align FLASH struct: No
;Enhanced core instructions : On
;Smart register allocation : On
;Automatic register allocation : On
#pragma AVRPART ADMIN PART_NAME ATmega644
#pragma AVRPART MEMORY PROG_FLASH 65536
#pragma AVRPART MEMORY EEPROM 2048
#pragma AVRPART MEMORY INT_SRAM SIZE 4096
#pragma AVRPART MEMORY INT_SRAM START_ADDR 0x100
.EQU EERE=0x0
.EQU EEWE=0x1
.EQU EEMWE=0x2
.EQU UDRE=0x5
.EQU RXC=0x7
.EQU EECR=0x1F
.EQU EEDR=0x20
.EQU EEARL=0x21
.EQU EEARH=0x22
.EQU SPSR0=0x2D
.EQU SPDR0=0x2E
.EQU SMCR=0x33
.EQU MCUSR=0x34
.EQU MCUCR=0x35
.EQU WDTCSR=0x60
.EQU UCSR0A=0xC0
.EQU UDR0=0xC6
.EQU SPL=0x3D
.EQU SPH=0x3E
.EQU SREG=0x3F
.EQU GPIOR0=0x1E
.DEF R0X0=R0
.DEF R0X1=R1
.DEF R0X2=R2
.DEF R0X3=R3
.DEF R0X4=R4
.DEF R0X5=R5
.DEF R0X6=R6
.DEF R0X7=R7
.DEF R0X8=R8
.DEF R0X9=R9
.DEF R0XA=R10
.DEF R0XB=R11
.DEF R0XC=R12
.DEF R0XD=R13
.DEF R0XE=R14
.DEF R0XF=R15
.DEF R0X10=R16
.DEF R0X11=R17
.DEF R0X12=R18
.DEF R0X13=R19
.DEF R0X14=R20
.DEF R0X15=R21
.DEF R0X16=R22
.DEF R0X17=R23
.DEF R0X18=R24
.DEF R0X19=R25
.DEF R0X1A=R26
.DEF R0X1B=R27
.DEF R0X1C=R28
.DEF R0X1D=R29
.DEF R0X1E=R30
.DEF R0X1F=R31
.MACRO __CPD1N
CPI R30,LOW(@0)
LDI R26,HIGH(@0)
CPC R31,R26
LDI R26,BYTE3(@0)
CPC R22,R26
LDI R26,BYTE4(@0)
CPC R23,R26
.ENDM
.MACRO __CPD2N
CPI R26,LOW(@0)
LDI R30,HIGH(@0)
CPC R27,R30
LDI R30,BYTE3(@0)
CPC R24,R30
LDI R30,BYTE4(@0)
CPC R25,R30
.ENDM
.MACRO __CPWRR
CP R@0,R@2
CPC R@1,R@3
.ENDM
.MACRO __CPWRN
CPI R@0,LOW(@2)
LDI R30,HIGH(@2)
CPC R@1,R30
.ENDM
.MACRO __ADDB1MN
SUBI R30,LOW(-@0-(@1))
.ENDM
.MACRO __ADDB2MN
SUBI R26,LOW(-@0-(@1))
.ENDM
.MACRO __ADDW1MN
SUBI R30,LOW(-@0-(@1))
SBCI R31,HIGH(-@0-(@1))
.ENDM
.MACRO __ADDW2MN
SUBI R26,LOW(-@0-(@1))
SBCI R27,HIGH(-@0-(@1))
.ENDM
.MACRO __ADDW1FN
SUBI R30,LOW(-2*@0-(@1))
SBCI R31,HIGH(-2*@0-(@1))
.ENDM
.MACRO __ADDD1FN
SUBI R30,LOW(-2*@0-(@1))
SBCI R31,HIGH(-2*@0-(@1))
SBCI R22,BYTE3(-2*@0-(@1))
.ENDM
.MACRO __ADDD1N
SUBI R30,LOW(-@0)
SBCI R31,HIGH(-@0)
SBCI R22,BYTE3(-@0)
SBCI R23,BYTE4(-@0)
.ENDM
.MACRO __ADDD2N
SUBI R26,LOW(-@0)
SBCI R27,HIGH(-@0)
SBCI R24,BYTE3(-@0)
SBCI R25,BYTE4(-@0)
.ENDM
.MACRO __SUBD1N
SUBI R30,LOW(@0)
SBCI R31,HIGH(@0)
SBCI R22,BYTE3(@0)
SBCI R23,BYTE4(@0)
.ENDM
.MACRO __SUBD2N
SUBI R26,LOW(@0)
SBCI R27,HIGH(@0)
SBCI R24,BYTE3(@0)
SBCI R25,BYTE4(@0)
.ENDM
.MACRO __ANDBMNN
LDS R30,@0+@1
ANDI R30,LOW(@2)
STS @0+@1,R30
.ENDM
.MACRO __ANDWMNN
LDS R30,@0+@1
ANDI R30,LOW(@2)
STS @0+@1,R30
LDS R30,@0+@1+1
ANDI R30,HIGH(@2)
STS @0+@1+1,R30
.ENDM
.MACRO __ANDD1N
ANDI R30,LOW(@0)
ANDI R31,HIGH(@0)
ANDI R22,BYTE3(@0)
ANDI R23,BYTE4(@0)
.ENDM
.MACRO __ORBMNN
LDS R30,@0+@1
ORI R30,LOW(@2)
STS @0+@1,R30
.ENDM
.MACRO __ORWMNN
LDS R30,@0+@1
ORI R30,LOW(@2)
STS @0+@1,R30
LDS R30,@0+@1+1
ORI R30,HIGH(@2)
STS @0+@1+1,R30
.ENDM
.MACRO __ORD1N
ORI R30,LOW(@0)
ORI R31,HIGH(@0)
ORI R22,BYTE3(@0)
ORI R23,BYTE4(@0)
.ENDM
.MACRO __DELAY_USB
LDI R24,LOW(@0)
__DELAY_USB_LOOP:
DEC R24
BRNE __DELAY_USB_LOOP
.ENDM
.MACRO __DELAY_USW
LDI R24,LOW(@0)
LDI R25,HIGH(@0)
__DELAY_USW_LOOP:
SBIW R24,1
BRNE __DELAY_USW_LOOP
.ENDM
.MACRO __CLRD1S
LDI R30,0
STD Y+@0,R30
STD Y+@0+1,R30
STD Y+@0+2,R30
STD Y+@0+3,R30
.ENDM
.MACRO __GETD1S
LDD R30,Y+@0
LDD R31,Y+@0+1
LDD R22,Y+@0+2
LDD R23,Y+@0+3
.ENDM
.MACRO __PUTD1S
STD Y+@0,R30
STD Y+@0+1,R31
STD Y+@0+2,R22
STD Y+@0+3,R23
.ENDM
.MACRO __PUTD2S
STD Y+@0,R26
STD Y+@0+1,R27
STD Y+@0+2,R24
STD Y+@0+3,R25
.ENDM
.MACRO __POINTB1MN
LDI R30,LOW(@0+@1)
.ENDM
.MACRO __POINTW1MN
LDI R30,LOW(@0+@1)
LDI R31,HIGH(@0+@1)
.ENDM
.MACRO __POINTD1M
LDI R30,LOW(@0)
LDI R31,HIGH(@0)
LDI R22,BYTE3(@0)
LDI R23,BYTE4(@0)
.ENDM
.MACRO __POINTW1FN
LDI R30,LOW(2*@0+@1)
LDI R31,HIGH(2*@0+@1)
.ENDM
.MACRO __POINTD1FN
LDI R30,LOW(2*@0+@1)
LDI R31,HIGH(2*@0+@1)
LDI R22,BYTE3(2*@0+@1)
LDI R23,BYTE4(2*@0+@1)
.ENDM
.MACRO __POINTB2MN
LDI R26,LOW(@0+@1)
.ENDM
.MACRO __POINTW2MN
LDI R26,LOW(@0+@1)
LDI R27,HIGH(@0+@1)
.ENDM
.MACRO __POINTBRM
LDI R@0,LOW(@1)
.ENDM
.MACRO __POINTWRM
LDI R@0,LOW(@2)
LDI R@1,HIGH(@2)
.ENDM
.MACRO __POINTBRMN
LDI R@0,LOW(@1+@2)
.ENDM
.MACRO __POINTWRMN
LDI R@0,LOW(@2+@3)
LDI R@1,HIGH(@2+@3)
.ENDM
.MACRO __POINTWRFN
LDI R@0,LOW(@2*2+@3)
LDI R@1,HIGH(@2*2+@3)
.ENDM
.MACRO __GETD1N
LDI R30,LOW(@0)
LDI R31,HIGH(@0)
LDI R22,BYTE3(@0)
LDI R23,BYTE4(@0)
.ENDM
.MACRO __GETD2N
LDI R26,LOW(@0)
LDI R27,HIGH(@0)
LDI R24,BYTE3(@0)
LDI R25,BYTE4(@0)
.ENDM
.MACRO __GETD2S
LDD R26,Y+@0
LDD R27,Y+@0+1
LDD R24,Y+@0+2
LDD R25,Y+@0+3
.ENDM
.MACRO __GETB1MN
LDS R30,@0+@1
.ENDM
.MACRO __GETB1HMN
LDS R31,@0+@1
.ENDM
.MACRO __GETW1MN
LDS R30,@0+@1
LDS R31,@0+@1+1
.ENDM
.MACRO __GETD1MN
LDS R30,@0+@1
LDS R31,@0+@1+1
LDS R22,@0+@1+2
LDS R23,@0+@1+3
.ENDM
.MACRO __GETBRMN
LDS R@0,@1+@2
.ENDM
.MACRO __GETWRMN
LDS R@0,@2+@3
LDS R@1,@2+@3+1
.ENDM
.MACRO __GETWRZ
LDD R@0,Z+@2
LDD R@1,Z+@2+1
.ENDM
.MACRO __GETD2Z
LDD R26,Z+@0
LDD R27,Z+@0+1
LDD R24,Z+@0+2
LDD R25,Z+@0+3
.ENDM
.MACRO __GETB2MN
LDS R26,@0+@1
.ENDM
.MACRO __GETW2MN
LDS R26,@0+@1
LDS R27,@0+@1+1
.ENDM
.MACRO __GETD2MN
LDS R26,@0+@1
LDS R27,@0+@1+1
LDS R24,@0+@1+2
LDS R25,@0+@1+3
.ENDM
.MACRO __PUTB1MN
STS @0+@1,R30
.ENDM
.MACRO __PUTW1MN
STS @0+@1,R30
STS @0+@1+1,R31
.ENDM
.MACRO __PUTD1MN
STS @0+@1,R30
STS @0+@1+1,R31
STS @0+@1+2,R22
STS @0+@1+3,R23
.ENDM
.MACRO __PUTBR0MN
STS @0+@1,R0
.ENDM
.MACRO __PUTDZ2
STD Z+@0,R26
STD Z+@0+1,R27
STD Z+@0+2,R24
STD Z+@0+3,R25
.ENDM
.MACRO __PUTBMRN
STS @0+@1,R@2
.ENDM
.MACRO __PUTWMRN
STS @0+@1,R@2
STS @0+@1+1,R@3
.ENDM
.MACRO __PUTBZR
STD Z+@1,R@0
.ENDM
.MACRO __PUTWZR
STD Z+@2,R@0
STD Z+@2+1,R@1
.ENDM
.MACRO __GETW1R
MOV R30,R@0
MOV R31,R@1
.ENDM
.MACRO __GETW2R
MOV R26,R@0
MOV R27,R@1
.ENDM
.MACRO __GETWRN
LDI R@0,LOW(@2)
LDI R@1,HIGH(@2)
.ENDM
.MACRO __PUTW1R
MOV R@0,R30
MOV R@1,R31
.ENDM
.MACRO __PUTW2R
MOV R@0,R26
MOV R@1,R27
.ENDM
.MACRO __ADDWRN
SUBI R@0,LOW(-@2)
SBCI R@1,HIGH(-@2)
.ENDM
.MACRO __ADDWRR
ADD R@0,R@2
ADC R@1,R@3
.ENDM
.MACRO __SUBWRN
SUBI R@0,LOW(@2)
SBCI R@1,HIGH(@2)
.ENDM
.MACRO __SUBWRR
SUB R@0,R@2
SBC R@1,R@3
.ENDM
.MACRO __ANDWRN
ANDI R@0,LOW(@2)
ANDI R@1,HIGH(@2)
.ENDM
.MACRO __ANDWRR
AND R@0,R@2
AND R@1,R@3
.ENDM
.MACRO __ORWRN
ORI R@0,LOW(@2)
ORI R@1,HIGH(@2)
.ENDM
.MACRO __ORWRR
OR R@0,R@2
OR R@1,R@3
.ENDM
.MACRO __EORWRR
EOR R@0,R@2
EOR R@1,R@3
.ENDM
.MACRO __GETWRS
LDD R@0,Y+@2
LDD R@1,Y+@2+1
.ENDM
.MACRO __PUTWSR
STD Y+@2,R@0
STD Y+@2+1,R@1
.ENDM
.MACRO __MOVEWRR
MOV R@0,R@2
MOV R@1,R@3
.ENDM
.MACRO __INWR
IN R@0,@2
IN R@1,@2+1
.ENDM
.MACRO __OUTWR
OUT @2+1,R@1
OUT @2,R@0
.ENDM
.MACRO __CALL1MN
LDS R30,@0+@1
LDS R31,@0+@1+1
ICALL
.ENDM
.MACRO __CALL1FN
LDI R30,LOW(2*@0+@1)
LDI R31,HIGH(2*@0+@1)
CALL __GETW1PF
ICALL
.ENDM
.MACRO __CALL2EN
LDI R26,LOW(@0+@1)
LDI R27,HIGH(@0+@1)
CALL __EEPROMRDW
ICALL
.ENDM
.MACRO __GETW1STACK
IN R26,SPL
IN R27,SPH
ADIW R26,@0+1
LD R30,X+
LD R31,X
.ENDM
.MACRO __NBST
BST R@0,@1
IN R30,SREG
LDI R31,0x40
EOR R30,R31
OUT SREG,R30
.ENDM
.MACRO __PUTB1SN
LDD R26,Y+@0
LDD R27,Y+@0+1
SUBI R26,LOW(-@1)
SBCI R27,HIGH(-@1)
ST X,R30
.ENDM
.MACRO __PUTW1SN
LDD R26,Y+@0
LDD R27,Y+@0+1
SUBI R26,LOW(-@1)
SBCI R27,HIGH(-@1)
ST X+,R30
ST X,R31
.ENDM
.MACRO __PUTD1SN
LDD R26,Y+@0
LDD R27,Y+@0+1
SUBI R26,LOW(-@1)
SBCI R27,HIGH(-@1)
CALL __PUTDP1
.ENDM
.MACRO __PUTB1SNS
LDD R26,Y+@0
LDD R27,Y+@0+1
ADIW R26,@1
ST X,R30
.ENDM
.MACRO __PUTW1SNS
LDD R26,Y+@0
LDD R27,Y+@0+1
ADIW R26,@1
ST X+,R30
ST X,R31
.ENDM
.MACRO __PUTD1SNS
LDD R26,Y+@0
LDD R27,Y+@0+1
ADIW R26,@1
CALL __PUTDP1
.ENDM
.MACRO __PUTB1PMN
LDS R26,@0
LDS R27,@0+1
SUBI R26,LOW(-@1)
SBCI R27,HIGH(-@1)
ST X,R30
.ENDM
.MACRO __PUTW1PMN
LDS R26,@0
LDS R27,@0+1
SUBI R26,LOW(-@1)
SBCI R27,HIGH(-@1)
ST X+,R30
ST X,R31
.ENDM
.MACRO __PUTD1PMN
LDS R26,@0
LDS R27,@0+1
SUBI R26,LOW(-@1)
SBCI R27,HIGH(-@1)
CALL __PUTDP1
.ENDM
.MACRO __PUTB1PMNS
LDS R26,@0
LDS R27,@0+1
ADIW R26,@1
ST X,R30
.ENDM
.MACRO __PUTW1PMNS
LDS R26,@0
LDS R27,@0+1
ADIW R26,@1
ST X+,R30
ST X,R31
.ENDM
.MACRO __PUTD1PMNS
LDS R26,@0
LDS R27,@0+1
ADIW R26,@1
CALL __PUTDP1
.ENDM
.MACRO __PUTB1RN
MOVW R26,R@0
SUBI R26,LOW(-@1)
SBCI R27,HIGH(-@1)
ST X,R30
.ENDM
.MACRO __PUTW1RN
MOVW R26,R@0
SUBI R26,LOW(-@1)
SBCI R27,HIGH(-@1)
ST X+,R30
ST X,R31
.ENDM
.MACRO __PUTD1RN
MOVW R26,R@0
SUBI R26,LOW(-@1)
SBCI R27,HIGH(-@1)
CALL __PUTDP1
.ENDM
.MACRO __PUTB1RNS
MOVW R26,R@0
ADIW R26,@1
ST X,R30
.ENDM
.MACRO __PUTW1RNS
MOVW R26,R@0
ADIW R26,@1
ST X+,R30
ST X,R31
.ENDM
.MACRO __PUTD1RNS
MOVW R26,R@0
ADIW R26,@1
CALL __PUTDP1
.ENDM
.MACRO __PUTB1RON
MOV R26,R@0
MOV R27,R@1
SUBI R26,LOW(-@2)
SBCI R27,HIGH(-@2)
ST X,R30
.ENDM
.MACRO __PUTW1RON
MOV R26,R@0
MOV R27,R@1
SUBI R26,LOW(-@2)
SBCI R27,HIGH(-@2)
ST X+,R30
ST X,R31
.ENDM
.MACRO __PUTD1RON
MOV R26,R@0
MOV R27,R@1
SUBI R26,LOW(-@2)
SBCI R27,HIGH(-@2)
CALL __PUTDP1
.ENDM
.MACRO __PUTB1RONS
MOV R26,R@0
MOV R27,R@1
ADIW R26,@2
ST X,R30
.ENDM
.MACRO __PUTW1RONS
MOV R26,R@0
MOV R27,R@1
ADIW R26,@2
ST X+,R30
ST X,R31
.ENDM
.MACRO __PUTD1RONS
MOV R26,R@0
MOV R27,R@1
ADIW R26,@2
CALL __PUTDP1
.ENDM
.MACRO __GETB1SX
MOVW R30,R28
SUBI R30,LOW(-@0)
SBCI R31,HIGH(-@0)
LD R30,Z
.ENDM
.MACRO __GETB1HSX
MOVW R30,R28
SUBI R30,LOW(-@0)
SBCI R31,HIGH(-@0)
LD R31,Z
.ENDM
.MACRO __GETW1SX
MOVW R30,R28
SUBI R30,LOW(-@0)
SBCI R31,HIGH(-@0)
LD R0,Z+
LD R31,Z
MOV R30,R0
.ENDM
.MACRO __GETD1SX
MOVW R30,R28
SUBI R30,LOW(-@0)
SBCI R31,HIGH(-@0)
LD R0,Z+
LD R1,Z+
LD R22,Z+
LD R23,Z
MOVW R30,R0
.ENDM
.MACRO __GETB2SX
MOVW R26,R28
SUBI R26,LOW(-@0)
SBCI R27,HIGH(-@0)
LD R26,X
.ENDM
.MACRO __GETW2SX
MOVW R26,R28
SUBI R26,LOW(-@0)
SBCI R27,HIGH(-@0)
LD R0,X+
LD R27,X
MOV R26,R0
.ENDM
.MACRO __GETD2SX
MOVW R26,R28
SUBI R26,LOW(-@0)
SBCI R27,HIGH(-@0)
LD R0,X+
LD R1,X+
LD R24,X+
LD R25,X
MOVW R26,R0
.ENDM
.MACRO __GETBRSX
MOVW R30,R28
SUBI R30,LOW(-@1)
SBCI R31,HIGH(-@1)
LD R@0,Z
.ENDM
.MACRO __GETWRSX
MOVW R30,R28
SUBI R30,LOW(-@2)
SBCI R31,HIGH(-@2)
LD R@0,Z+
LD R@1,Z
.ENDM
.MACRO __LSLW8SX
MOVW R30,R28
SUBI R30,LOW(-@0)
SBCI R31,HIGH(-@0)
LD R31,Z
CLR R30
.ENDM
.MACRO __PUTB1SX
MOVW R26,R28
SUBI R26,LOW(-@0)
SBCI R27,HIGH(-@0)
ST X,R30
.ENDM
.MACRO __PUTW1SX
MOVW R26,R28
SUBI R26,LOW(-@0)
SBCI R27,HIGH(-@0)
ST X+,R30
ST X,R31
.ENDM
.MACRO __PUTD1SX
MOVW R26,R28
SUBI R26,LOW(-@0)
SBCI R27,HIGH(-@0)
ST X+,R30
ST X+,R31
ST X+,R22
ST X,R23
.ENDM
.MACRO __CLRW1SX
MOVW R30,R28
SUBI R30,LOW(-@0)
SBCI R31,HIGH(-@0)
CLR R0
ST Z+,R0
ST Z,R0
.ENDM
.MACRO __CLRD1SX
MOVW R30,R28
SUBI R30,LOW(-@0)
SBCI R31,HIGH(-@0)
CLR R0
ST Z+,R0
ST Z+,R0
ST Z+,R0
ST Z,R0
.ENDM
.MACRO __PUTB2SX
MOVW R30,R28
SUBI R30,LOW(-@0)
SBCI R31,HIGH(-@0)
ST Z,R26
.ENDM
.MACRO __PUTW2SX
MOVW R30,R28
SUBI R30,LOW(-@0)
SBCI R31,HIGH(-@0)
ST Z+,R26
ST Z,R27
.ENDM
.MACRO __PUTD2SX
MOVW R30,R28
SUBI R30,LOW(-@0)
SBCI R31,HIGH(-@0)
ST Z+,R26
ST Z+,R27
ST Z+,R24
ST Z,R25
.ENDM
.MACRO __PUTBSRX
MOVW R30,R28
SUBI R30,LOW(-@0)
SBCI R31,HIGH(-@0)
ST Z,R@1
.ENDM
.MACRO __PUTWSRX
MOVW R30,R28
SUBI R30,LOW(-@2)
SBCI R31,HIGH(-@2)
ST Z+,R@0
ST Z,R@1
.ENDM
.MACRO __PUTB1SNX
MOVW R26,R28
SUBI R26,LOW(-@0)
SBCI R27,HIGH(-@0)
LD R0,X+
LD R27,X
MOV R26,R0
SUBI R26,LOW(-@1)
SBCI R27,HIGH(-@1)
ST X,R30
.ENDM
.MACRO __PUTW1SNX
MOVW R26,R28
SUBI R26,LOW(-@0)
SBCI R27,HIGH(-@0)
LD R0,X+
LD R27,X
MOV R26,R0
SUBI R26,LOW(-@1)
SBCI R27,HIGH(-@1)
ST X+,R30
ST X,R31
.ENDM
.MACRO __PUTD1SNX
MOVW R26,R28
SUBI R26,LOW(-@0)
SBCI R27,HIGH(-@0)
LD R0,X+
LD R27,X
MOV R26,R0
SUBI R26,LOW(-@1)
SBCI R27,HIGH(-@1)
ST X+,R30
ST X+,R31
ST X+,R22
ST X,R23
.ENDM
.MACRO __MULBRR
MULS R@0,R@1
MOVW R30,R0
.ENDM
.MACRO __MULBRRU
MUL R@0,R@1
MOVW R30,R0
.ENDM
.MACRO __MULBRR0
MULS R@0,R@1
.ENDM
.MACRO __MULBRRU0
MUL R@0,R@1
.ENDM
.MACRO __MULBNWRU
LDI R26,@2
MUL R26,R@0
MOVW R30,R0
MUL R26,R@1
ADD R31,R0
.ENDM
.CSEG
.ORG 0
.INCLUDE "sensornode.vec"
.INCLUDE "sensornode.inc"
__RESET:
CLI
CLR R30
OUT EECR,R30
;INTERRUPT VECTORS ARE PLACED
;AT THE START OF FLASH
LDI R31,1
OUT MCUCR,R31
OUT MCUCR,R30
;DISABLE WATCHDOG
LDI R31,0x18
WDR
IN R26,MCUSR
CBR R26,8
OUT MCUSR,R26
STS WDTCSR,R31
STS WDTCSR,R30
;CLEAR R2-R14
LDI R24,13
LDI R26,2
CLR R27
__CLEAR_REG:
ST X+,R30
DEC R24
BRNE __CLEAR_REG
;CLEAR SRAM
LDI R24,LOW(0xF00)
LDI R25,HIGH(0xF00)
LDI R26,LOW(0x100)
LDI R27,HIGH(0x100)
__CLEAR_SRAM:
ST X+,R30
SBIW R24,1
BRNE __CLEAR_SRAM
;GLOBAL VARIABLES INITIALIZATION
LDI R30,LOW(__GLOBAL_INI_TBL*2)
LDI R31,HIGH(__GLOBAL_INI_TBL*2)
__GLOBAL_INI_NEXT:
LPM R24,Z+
LPM R25,Z+
SBIW R24,0
BREQ __GLOBAL_INI_END
LPM R26,Z+
LPM R27,Z+
LPM R0,Z+
LPM R1,Z+
MOVW R22,R30
MOVW R30,R0
__GLOBAL_INI_LOOP:
LPM R0,Z+
ST X+,R0
SBIW R24,1
BRNE __GLOBAL_INI_LOOP
MOVW R30,R22
RJMP __GLOBAL_INI_NEXT
__GLOBAL_INI_END:
;GPIOR0 INITIALIZATION
LDI R30,__GPIOR0_INIT
OUT GPIOR0,R30
;STACK POINTER INITIALIZATION
LDI R30,LOW(0xFFF)
OUT SPL,R30
LDI R30,HIGH(0xFFF)
OUT SPH,R30
;DATA STACK POINTER INITIALIZATION
LDI R28,LOW(0x500)
LDI R29,HIGH(0x500)
JMP _main
.ESEG
.ORG 0
.DSEG
.ORG 0x500
; 1 #include <mega644.h>
; 2 #ifndef __SLEEP_DEFINED__
#ifndef __SLEEP_DEFINED__
; 3 #define __SLEEP_DEFINED__
#define __SLEEP_DEFINED__
; 4 .EQU __se_bit=0x01
.EQU __se_bit=0x01
; 5 .EQU __sm_mask=0x0E
.EQU __sm_mask=0x0E
; 6 .EQU __sm_powerdown=0x04
.EQU __sm_powerdown=0x04
; 7 .EQU __sm_powersave=0x06
.EQU __sm_powersave=0x06
; 8 .EQU __sm_standby=0x0C
.EQU __sm_standby=0x0C
; 9 .EQU __sm_ext_standby=0x0E
.EQU __sm_ext_standby=0x0E
; 10 .EQU __sm_adc_noise_red=0x02
.EQU __sm_adc_noise_red=0x02
; 11 .SET power_ctrl_reg=smcr
.SET power_ctrl_reg=smcr
; 12 #endif
#endif
; 13 #include "cumote_hal.h"
_HAL_LQI:
.BYTE 0x1
_HAL_radio_channel:
.BYTE 0x1
_HAL_transmit_power:
.BYTE 0x1
_HAL_CRC_enabled:
.BYTE 0x1
.CSEG
; t -> Y+0
; 14 MOV R16,R12
; 15 ld R26,y ; load t into r26. y register is stack pointer. t is lowest on stack.
; 16 clr R27 ; promote t to unsigned int
; 17
; 18 cpi R16,0 ; see if r12 is 0
; 19 breq startdelay ; branch to starting delay... overhead is now a bit more than 5 cycles.
; 20 preploop: ;~5 more cycles
; 21 lsl R26 ; multiply t by 2
; 22 rol R27
; 23 dec R16
; 24 cpi R16,0
; 25 brne preploop
; 26 startdelay: ;overhead: t=0...5. t=1...10. t=2...15. t=3...20. t=4...25.
; 27 subi R26,3 ; lo byte
; 28 sbci R27,0 ; hi byte, with carry
; 29 brmi enddelay ; if result is negative, end loop, done with delay.
; 30 enddelay:
.DSEG
_COM_spi_freq:
.BYTE 0x1
_COM_IRQ_pending:
.BYTE 0x1
_COM_IRQ_status:
.BYTE 0x1
.CSEG
_COM_init:
SBI 0x4,5
CBI 0x4,6
SBI 0x4,7
CBI 0x4,2
SBI 0x4,3
SBI 0x4,4
CBI 0x5,3
SBI 0x5,4
CLR R12
LDI R30,LOW(0)
STS _COM_IRQ_status,R30
RCALL _COM_reset_SPI_clock
RET
_COM_reset_SPI_clock:
LDI R30,LOW(80)
OUT 0x2C,R30
LDI R30,LOW(1)
OUT 0x2D,R30
STS _COM_spi_freq,R30
RET
_COM_set_MCU_clock:
ST -Y,R17
; clk -> Y+1
; junk -> R17
LDD R26,Y+1
CPI R26,LOW(0x5)
BRLO _0x13
LDI R30,LOW(4)
STD Y+1,R30
_0x13:
LDI R30,LOW(3)
CALL SUBOPT_0x0
ANDI R17,LOW(240)
LDD R30,Y+1
ANDI R30,LOW(0x7)
OR R17,R30
LDI R30,LOW(3)
ST -Y,R30
ST -Y,R17
RCALL _COM_write_register
LDD R17,Y+0
RJMP _0xF2
; speed -> Y+0
_COM_write_register:
ST -Y,R17
; address -> Y+2
; data -> Y+1
; junk -> R17
CBI 0x5,4
LDD R30,Y+2
ANDI R30,LOW(0x3F)
SUBI R30,-LOW(192)
OUT 0x2E,R30
_0x22:
IN R30,0x2D
SBRS R30,7
RJMP _0x22
IN R17,46
LDD R30,Y+1
OUT 0x2E,R30
_0x25:
IN R30,0x2D
SBRS R30,7
RJMP _0x25
SBI 0x5,4
LDD R17,Y+0
ADIW R28,3
RET
_COM_read_register:
ST -Y,R17
; address -> Y+1
; junk -> R17
CBI 0x5,4
LDD R30,Y+1
ANDI R30,LOW(0x3F)
SUBI R30,-LOW(128)
OUT 0x2E,R30
_0x2C:
IN R30,0x2D
SBRS R30,7
RJMP _0x2C
IN R17,46
LDI R30,LOW(0)
OUT 0x2E,R30
_0x2F:
IN R30,0x2D
SBRS R30,7
RJMP _0x2F
SBI 0x5,4
IN R30,0x2E
LDD R17,Y+0
RJMP _0xF2
_COM_download_frame:
ST -Y,R17
; i -> R17
CALL SUBOPT_0x1
CBI 0x5,4
LDI R30,LOW(96)
OUT 0x2E,R30
_0x36:
IN R30,0x2D
SBRS R30,7
RJMP _0x36
LDS R26,_HAL_CRC_enabled
CPI R26,LOW(0x1)
BRNE _0x39
MOV R30,R9
SUBI R30,-LOW(2)
OUT 0x2E,R30
RJMP _0x3A
_0x39:
OUT 0x2E,R9
_0x3A:
_0x3B:
IN R30,0x2D
SBRS R30,7
RJMP _0x3B
LDI R17,LOW(0)
_0x3F:
CP R17,R9
BRSH _0x40
MOVW R26,R4
CLR R30
ADD R26,R17
ADC R27,R30
LD R30,X
OUT 0x2E,R30
_0x41:
IN R30,0x2D
SBRS R30,7
RJMP _0x41
SUBI R17,-1
RJMP _0x3F
_0x40:
SBI 0x5,4
RJMP _0xF1
; Twait -> R16,R17
; Tradio -> R18,R19
; Tmcu -> R20,R21
; Tspi -> Y+8
; L -> Y+7
; i -> Y+6
_COM_enable_interrupt_IRQ:
LDS R30,105
ORI R30,LOW(0x30)
STS 105,R30
SBI 0x1D,2
RET
_handle_IRQ:
ST -Y,R30
LDI R30,LOW(1)
STS _COM_IRQ_pending,R30
LD R30,Y+
RETI
_COM_IRQ_handler:
LDS R26,_COM_IRQ_pending
CPI R26,LOW(0x1)
BRNE _0x59
LDI R30,LOW(0)
STS _COM_IRQ_pending,R30
LDI R30,LOW(15)
ST -Y,R30
CALL _COM_read_register
STS _COM_IRQ_status,R30
_0x59:
RET
_HAL_initialization:
CLR R4
CLR R5
CLR R6
CLR R7
LDI R30,LOW(0)
STS _HAL_CRC_enabled,R30
__DELAY_USW 510
RCALL _HAL_statemachine_reset
RCALL _HAL_get_radio_channel
STS _HAL_radio_channel,R30
RCALL _HAL_get_transmit_power
STS _HAL_transmit_power,R30
RET
_HAL_statemachine_reset:
RCALL _HAL_get_state
__DELAY_USB 8
TST R11
BRNE _0x61
LDI R30,LOW(2)
ST -Y,R30
LDI R30,LOW(8)
ST -Y,R30
CALL _COM_write_register
__DELAY_USW 510
RJMP _0x62
_0x61:
LDI R30,LOW(2)
ST -Y,R30
LDI R30,LOW(3)
ST -Y,R30
CALL _COM_write_register
__DELAY_USB 8
_0x62:
RCALL _HAL_get_state
RET
_HAL_set_TX_buff_len:
; length -> Y+0
MOV R0,R4
OR R0,R5
BREQ _0x63
ST -Y,R5
ST -Y,R4
CALL _free
_0x63:
LD R26,Y
LDD R27,Y+1
CPI R26,LOW(0x81)
LDI R30,HIGH(0x81)
CPC R27,R30
BRLO _0x64
LDI R30,LOW(128)
MOV R9,R30
_0x64:
LD R30,Y
LDD R31,Y+1
ST -Y,R31
ST -Y,R30
CALL _malloc
MOVW R4,R30
MOV R0,R4
OR R0,R5
BRNE _0x65
CLR R9
RJMP _0x66
_0x65:
LDD R9,Y+0
_0x66:
RJMP _0xF2
; length -> Y+0
_HAL_get_radio_channel:
ST -Y,R17
; tmp -> R17
LDI R30,LOW(8)
CALL SUBOPT_0x0
MOV R30,R17
ANDI R30,LOW(0x1F)
STS _HAL_radio_channel,R30
RJMP _0xF1
_HAL_set_radio_channel:
ST -Y,R17
; channel -> Y+1
; tmp -> R17
LDI R30,LOW(8)
CALL SUBOPT_0x0
LDD R26,Y+1
CPI R26,LOW(0xB)
BRLO _0x6C
CPI R26,LOW(0x1B)
BRLO _0x6B
_0x6C:
LDI R30,LOW(11)
STD Y+1,R30
_0x6B:
MOV R30,R17
ANDI R30,LOW(0xE0)
LDD R26,Y+1
OR R30,R26
MOV R17,R30
LDI R30,LOW(8)
ST -Y,R30
ST -Y,R17
CALL _COM_write_register
LDD R30,Y+1
STS _HAL_radio_channel,R30
LDD R17,Y+0
RJMP _0xF2
_HAL_get_transmit_power:
ST -Y,R17
; tmp -> R17
LDI R30,LOW(5)
CALL SUBOPT_0x0
MOV R30,R17
ANDI R30,LOW(0xF)
STS _HAL_transmit_power,R30
RJMP _0xF1
; tx_pwr -> Y+1
; tmp -> R17
_HAL_get_state:
LDI R30,LOW(1)
ST -Y,R30
CALL _COM_read_register
ANDI R30,LOW(0x1F)
MOV R11,R30
RET
_HAL_set_state:
ST -Y,R17
; state -> Y+1
; i -> R17
LDI R17,35
CALL _HAL_get_state
LDD R30,Y+1
CPI R30,LOW(0x8)
BRNE _0x72
LDI R30,LOW(6)
CP R30,R11
BREQ _0x74
LDI R30,LOW(9)
CP R30,R11
BREQ _0x74
LDI R30,LOW(25)
CP R30,R11
BRNE _0x73
_0x74:
LDI R30,LOW(2)
ST -Y,R30
LDI R30,LOW(8)
RJMP _0xF3
_0x73:
LDI R30,LOW(15)
CP R30,R11
BRNE _0x77
CBI 0x5,3
__DELAY_USW 880
RJMP _0x7A
_0x77:
LDI R30,LOW(2)
ST -Y,R30
LDI R30,LOW(3)
_0xF3:
ST -Y,R30
CALL SUBOPT_0x2
_0x7A:
RJMP _0x71
_0x72:
CPI R30,LOW(0x6)
BRNE _0x7B
LDI R30,LOW(8)
CP R30,R11
BRNE _0x7C
CALL SUBOPT_0x3
CALL _COM_write_register
_0x7D:
SBIS 0x3,2
RJMP _0x7D
LDI R30,LOW(15)
ST -Y,R30
CALL _COM_read_register
RJMP _0x80
_0x7C:
LDI R30,LOW(22)
CP R30,R11
BREQ _0x82
LDI R30,LOW(9)
CP R30,R11
BREQ _0x82
LDI R30,LOW(25)
CP R30,R11
BRNE _0x81
_0x82:
CALL SUBOPT_0x3
CALL SUBOPT_0x2
_0x81:
_0x80:
RJMP _0x71
_0x7B:
CPI R30,LOW(0x9)
BRNE _0x84
LDI R30,LOW(8)
CP R30,R11
BRNE _0x85
CALL SUBOPT_0x1
__DELAY_USB 240
RJMP _0x86
_0x85:
LDI R30,LOW(22)
CP R30,R11
BREQ _0x88
LDI R30,LOW(6)
CP R30,R11
BREQ _0x88
LDI R30,LOW(25)
CP R30,R11
BRNE _0x87
_0x88:
CALL SUBOPT_0x3
CALL SUBOPT_0x2
_0x87:
_0x86:
RJMP _0x71
_0x84:
CPI R30,LOW(0x16)
BRNE _0x8A
LDI R30,LOW(8)
CP R30,R11
BRNE _0x8B
CALL SUBOPT_0x3
CALL _COM_write_register
__DELAY_USB 240
RJMP _0xF4
_0x8B:
LDI R30,LOW(6)
CP R30,R11
BREQ _0x8E
LDI R30,LOW(9)
CP R30,R11
BRNE _0x8D
_0x8E:
RJMP _0xF4
_0x8D:
LDI R30,LOW(25)
CP R30,R11
BRNE _0x91
CALL SUBOPT_0x1
__DELAY_USB 7
_0xF4:
LDI R30,LOW(2)
ST -Y,R30
LDI R30,LOW(22)
ST -Y,R30
CALL SUBOPT_0x2
_0x91:
RJMP _0x71
_0x8A:
CPI R30,LOW(0x19)
BRNE _0x92
LDI R30,LOW(8)
CP R30,R11
BRNE _0x93
CALL SUBOPT_0x1
__DELAY_USB 240
RJMP _0xF5
_0x93:
LDI R30,LOW(6)
CP R30,R11
BREQ _0x96
LDI R30,LOW(9)
CP R30,R11
BRNE _0x95
_0x96:
RJMP _0xF5
_0x95:
LDI R30,LOW(22)
CP R30,R11
BRNE _0x99
CALL SUBOPT_0x3
CALL SUBOPT_0x2
_0xF5:
LDI R30,LOW(2)
ST -Y,R30
LDI R30,LOW(25)
ST -Y,R30
CALL SUBOPT_0x2
_0x99:
RJMP _0x71
_0x92:
CPI R30,LOW(0xF)
BRNE _0xA1
LDI R30,LOW(8)
CP R30,R11
BRNE _0x9B
SBI 0x5,3
LDI R17,LOW(12)
_0x9F:
CPI R17,1
BRLO _0xA0
SUBI R17,1
RJMP _0x9F
_0xA0:
_0x9B:
_0xA1:
_0x71:
CALL _HAL_get_state
LDD R17,Y+0
_0xF2:
ADIW R28,2
RET
; mode -> Y+1
; tmp -> R17
; tmp -> R17
_HAL_transmitframe_pin:
SBI 0x5,3
__DELAY_USB 7
CBI 0x5,3
CALL _COM_download_frame
RET
; junk -> R17
; junk -> R17
; user_csma -> Y+1
; junk -> R17
; junk -> R17
; junk -> R17
; junk -> R17
; hi -> Y+1
; lo -> Y+0
; hi -> Y+1
; lo -> Y+0
; retries -> Y+0
; 31 #include "kxp74.h"
_init_sensor_spi:
SBI 0xA,0
SBI 0xB,0
RET
_set_sensor_clock:
LDI R30,LOW(93)
OUT 0x2C,R30
LDI R30,LOW(0)
OUT 0x2D,R30
RET
_init_sensors:
CALL SUBOPT_0x4
; junk -> R17
LDI R30,LOW(28)
ST -Y,R30
CALL _spi
MOV R17,R30
SBI 0xB,0
RJMP _0xF1
_sensor_standby:
CALL SUBOPT_0x4
; junk -> R17
LDI R30,LOW(24)
ST -Y,R30
CALL _spi
MOV R17,R30
SBI 0xB,0
_0xF1:
LD R17,Y+
RET
_get_sensor:
CALL __SAVELOCR4
; axis -> Y+4
; byte1 -> R17
; byte2 -> R16
; junk -> R19
CBI 0xB,0
LDD R30,Y+4
ST -Y,R30
CALL _spi
MOV R19,R30
__DELAY_USB 67
LDI R30,LOW(0)
ST -Y,R30
CALL _spi
MOV R17,R30
LDI R30,LOW(0)
ST -Y,R30
CALL _spi
MOV R16,R30
SBI 0xB,0
MOV R30,R17
CALL __LOADLOCR4
ADIW R28,5
RET
; 32
; 33 /// This is a test program, transmitting data over channel 13 once every second. Use this to test link before attempting accelerometer interface.
; 34
; 35 unsigned int ms_counter;
.DSEG
_ms_counter:
.BYTE 0x2
; 36
; 37 interrupt [TIM1_COMPA] void handle_tim1(void) { // will use to set sleep duration, eventually.
.CSEG
_handle_tim1:
ST -Y,R0
ST -Y,R26
ST -Y,R27
ST -Y,R30
ST -Y,R31
IN R30,SREG
ST -Y,R30
; 38 if (ms_counter > 0)
CALL SUBOPT_0x5
BRSH _0xC6
; 39 ms_counter--;
LDS R30,_ms_counter
LDS R31,_ms_counter+1
SBIW R30,1
CALL SUBOPT_0x6
; 40 }
_0xC6:
LD R30,Y+
OUT SREG,R30
LD R31,Y+
LD R30,Y+
LD R27,Y+
LD R26,Y+
LD R0,Y+
RETI
; 41
; 42 void main(void) {
_main:
; 43 //unsigned char my_msg[16];
; 44 //unsigned char *string_head; // make sure we keep track of start of array
; 45 unsigned char i;
; 46 unsigned char sensor_val[2];
; 47 unsigned char sample[3];
; 48
; 49 // disable portions of MCU that will not be used
; 50 PRR = 0b11100011; // disable Two Wire Interface, Timer 2, Timer 0, USART, and ADC
SBIW R28,5
; i -> R17
; sensor_val -> Y+3
; sample -> Y+0
LDI R30,LOW(227)
STS 100,R30
; 51
; 52 COM_init();
CALL _COM_init
; 53 COM_set_MCU_clock(3); // set clock to 4 MHz
LDI R30,LOW(3)
ST -Y,R30
CALL _COM_set_MCU_clock
; 54 // COM_write_register(); //
; 55 HAL_initialization();
CALL _HAL_initialization
; 56 COM_enable_interrupt_IRQ();
CALL _COM_enable_interrupt_IRQ
; 57 HAL_set_radio_channel(13);
LDI R30,LOW(13)
ST -Y,R30
CALL _HAL_set_radio_channel
; 58
; 59 // accelerometer setup
; 60 init_sensor_spi();
CALL _init_sensor_spi
; 61 set_sensor_clock();
CALL _set_sensor_clock
; 62 init_sensors();
CALL _init_sensors
; 63
; 64 //back to radio spi clock
; 65 COM_reset_SPI_clock();
CALL _COM_reset_SPI_clock
; 66
; 67 // timer initialization
; 68 TCCR1A = 0b00000000;
LDI R30,LOW(0)
STS 128,R30
; 69 OCR1AH = 1;
LDI R30,LOW(1)
STS 137,R30
; 70 OCR1AL = 0b11110100;
LDI R30,LOW(244)
STS 136,R30
; 71 TCCR1B = 0b00001010; // clk/8... count to 500 for 1ms at 4MHz.
LDI R30,LOW(10)
STS 129,R30
; 72 TCCR1C = 0;
LDI R30,LOW(0)
STS 130,R30
; 73 TIMSK1 = 0b00000010; // interrupt on compare A match
LDI R30,LOW(2)
STS 111,R30
; 74
; 75 ms_counter = 0;
LDI R30,0
STS _ms_counter,R30
STS _ms_counter+1,R30
; 76
; 77 #asm
; 78 sei
sei
; 79 #endasm
; 80
; 81 HAL_set_state(STATUS_TRX_OFF); // initialize radio's state
LDI R30,LOW(8)
ST -Y,R30
CALL _HAL_set_state
; 82
; 83 //HAL_set_TX_buff_len(16); // message is 16 bits long...
; 84 // for (i = 0; i< 16; i++) {
; 85 // HAL_tx_frame[i] = i;
; 86 // }
; 87 // COM_download_frame();
; 88
; 89 HAL_set_TX_buff_len(3); // one byte per axis for now
LDI R30,LOW(3)
LDI R31,HIGH(3)
ST -Y,R31
ST -Y,R30
CALL _HAL_set_TX_buff_len
; 90 while(1) {
_0xC7:
; 91 set_sensor_clock();
CALL _set_sensor_clock
; 92 sensor_standby();
CALL _sensor_standby
; 93 while (ms_counter > 0); // wait for next sample.
_0xCA:
CALL SUBOPT_0x5
BRLO _0xCA
; 94 init_sensors();
CALL _init_sensors
; 95 ms_counter = 5;
LDI R30,LOW(5)
LDI R31,HIGH(5)
CALL SUBOPT_0x6
; 96 while (ms_counter > 0); // wait to come out of standby...
_0xCD:
CALL SUBOPT_0x5
BRLO _0xCD
; 97 // first, sample accelerometer.
; 98
; 99 for (i=0;i<3;i++) { // iterate through axes
LDI R17,LOW(0)
_0xD1:
CPI R17,3
BRSH _0xD2
; 100 HAL_tx_frame[i] = get_sensor(i); // get sample for each axis
MOV R30,R17
LDI R31,0
ADD R30,R4
ADC R31,R5
PUSH R31
PUSH R30
ST -Y,R17
CALL _get_sensor
POP R26
POP R27
ST X,R30
; 101 }
SUBI R17,-1
RJMP _0xD1
_0xD2:
; 102
; 103 COM_reset_SPI_clock();
CALL _COM_reset_SPI_clock
; 104 HAL_transmitframe_pin(); // Should download data, then transmit... [fingers crossed]
CALL _HAL_transmitframe_pin
; 105
; 106 if (COM_IRQ_pending == 1) {
LDS R26,_COM_IRQ_pending
CPI R26,LOW(0x1)
BRNE _0xD3
; 107 COM_IRQ_handler();
CALL _COM_IRQ_handler
; 108 }
; 109
; 110 // now we should try to put chip to sleep... but that's for later.
; 111 ms_counter = 10; // wait 10 ms before transmitting again. Around 100 samples per second...
_0xD3:
LDI R30,LOW(10)
LDI R31,HIGH(10)
CALL SUBOPT_0x6
; 112 }
RJMP _0xC7
; 113 }
_0xD4:
RJMP _0xD4
; 114
; 115 /*
; 116 TODO List:
; 117 1) Test transmission/reception
; 118 2) Test accelerometer spi data capture
; 119 3) Test putting node to sleep
; 120 */
_allocate_block_G2:
SBIW R28,2
CALL __SAVELOCR6
__GETWRN 16,17,4096
MOVW R26,R16
LDI R30,LOW(0)
LDI R31,HIGH(0)
ST X+,R30
ST X,R31
_0xD5:
MOV R0,R16
OR R0,R17
BREQ _0xD7
MOVW R26,R16
CALL __GETW1P
ADD R30,R16
ADC R31,R17
ADIW R30,4
MOVW R20,R30
ADIW R26,2
CALL __GETW1P
MOVW R18,R30
SBIW R30,0
BREQ _0xD8
__PUTWSR 18,19,6
RJMP _0xD9
_0xD8:
LDI R30,LOW(4352)
LDI R31,HIGH(4352)
STD Y+6,R30
STD Y+6+1,R31
_0xD9:
LDD R30,Y+6
LDD R31,Y+6+1
SUB R30,R20
SBC R31,R21
MOVW R26,R30
LDD R30,Y+8
LDD R31,Y+8+1
ADIW R30,4
CP R26,R30
CPC R27,R31
BRLO _0xDA
MOVW R30,R20
__PUTW1RNS 16,2
MOVW R30,R18
__PUTW1RNS 20,2
LDD R30,Y+8
LDD R31,Y+8+1
MOVW R26,R20
ST X+,R30
ST X,R31
__ADDWRN 20,21,4
MOVW R30,R20
RJMP _0xF0
_0xDA:
MOVW R16,R18
RJMP _0xD5
_0xD7:
LDI R30,LOW(0)
LDI R31,HIGH(0)
_0xF0:
CALL __LOADLOCR6
ADIW R28,10
RET
_find_prev_block_G2:
CALL __SAVELOCR4
__GETWRN 16,17,4096
_0xDB:
MOV R0,R16
OR R0,R17
BREQ _0xDD
MOVW R26,R16
ADIW R26,2
CALL __GETW1P
MOVW R18,R30
MOVW R26,R30
LDD R30,Y+4
LDD R31,Y+4+1
CP R30,R26
CPC R31,R27
BRNE _0xDE
MOVW R30,R16
RJMP _0xEF
_0xDE:
MOVW R16,R18
RJMP _0xDB
_0xDD:
LDI R30,LOW(0)
LDI R31,HIGH(0)
_0xEF:
CALL __LOADLOCR4
ADIW R28,6
RET
_realloc:
SBIW R28,2
CALL __SAVELOCR6
LDD R30,Y+10
LDD R31,Y+10+1
SBIW R30,0
BRNE PC+3
JMP _0xDF
SBIW R30,4
MOVW R16,R30
ST -Y,R17
ST -Y,R16
CALL _find_prev_block_G2
MOVW R18,R30
SBIW R30,0
BREQ _0xE0
MOVW R26,R16
ADIW R26,2
CALL __GETW1P
__PUTW1RNS 18,2
LDD R30,Y+8
LDD R31,Y+8+1
SBIW R30,0
BREQ _0xE1
ST -Y,R31
ST -Y,R30
CALL _allocate_block_G2
MOVW R20,R30
SBIW R30,0
BREQ _0xE2
MOVW R26,R16
CALL __GETW1P
STD Y+6,R30
STD Y+6+1,R31
MOVW R26,R30
LDD R30,Y+8
LDD R31,Y+8+1
CP R26,R30
CPC R27,R31
BRSH _0xE3
LDD R30,Y+6
LDD R31,Y+6+1
STD Y+8,R30
STD Y+8+1,R31
_0xE3:
ST -Y,R21
ST -Y,R20
LDD R30,Y+12
LDD R31,Y+12+1
ST -Y,R31
ST -Y,R30
LDD R30,Y+12
LDD R31,Y+12+1
ST -Y,R31
ST -Y,R30
CALL _memmove
MOVW R30,R20
RJMP _0xEE
_0xE2:
MOVW R30,R16
__PUTW1RNS 18,2
_0xE1:
_0xE0:
_0xDF:
LDI R30,LOW(0)
LDI R31,HIGH(0)
_0xEE:
CALL __LOADLOCR6
ADIW R28,12
RET
_malloc:
ST -Y,R17
ST -Y,R16
__GETWRN 16,17,0
LDD R30,Y+2
LDD R31,Y+2+1
SBIW R30,0
BREQ _0xE4
ST -Y,R31
ST -Y,R30
CALL _allocate_block_G2
MOVW R16,R30
SBIW R30,0
BREQ _0xE5
ST -Y,R17
ST -Y,R16
LDI R30,LOW(0)
ST -Y,R30
LDD R30,Y+5
LDD R31,Y+5+1
ST -Y,R31
ST -Y,R30
CALL _memset
_0xE5:
_0xE4:
MOVW R30,R16
LDD R17,Y+1
LDD R16,Y+0
ADIW R28,4
RET
_free:
LD R30,Y
LDD R31,Y+1
ST -Y,R31
ST -Y,R30
LDI R30,LOW(0)
LDI R31,HIGH(0)
ST -Y,R31
ST -Y,R30
CALL _realloc
ADIW R28,2
RET
#ifndef __SLEEP_DEFINED__
#define __SLEEP_DEFINED__
.EQU __se_bit=0x01
.EQU __sm_mask=0x0E
.EQU __sm_powerdown=0x04
.EQU __sm_powersave=0x06
.EQU __sm_standby=0x0C
.EQU __sm_ext_standby=0x0E
.EQU __sm_adc_noise_red=0x02
.SET power_ctrl_reg=smcr
#endif
_spi:
LD R30,Y
OUT 0x2E,R30
_0xE6:
IN R30,0x2D
SBRS R30,7
RJMP _0xE6
IN R30,0x2E
ADIW R28,1
RET
_memmove:
ldd r25,y+1
ld r24,y
adiw r24,0
breq memmove3
ldd r27,y+5
ldd r26,y+4
ldd r31,y+3
ldd r30,y+2
cp r30,r26
cpc r31,r27
breq memmove3
brlt memmove1
memmove0:
ld r22,z+
st x+,r22
sbiw r24,1
brne memmove0
rjmp memmove3
memmove1:
add r26,r24
adc r27,r25
add r30,r24
adc r31,r25
memmove2:
ld r22,-z
st -x,r22
sbiw r24,1
brne memmove2
memmove3:
ldd r31,y+5
ldd r30,y+4
ADIW R28,6
RET
_memset:
ldd r27,y+1
ld r26,y
adiw r26,0
breq memset1
ldd r31,y+4
ldd r30,y+3
ldd r22,y+2
memset0:
st z+,r22
sbiw r26,1
brne memset0
memset1:
ldd r30,y+3
ldd r31,y+4
ADIW R28,5
RET
.DSEG
_p_S59:
.BYTE 0x2
.CSEG
;OPTIMIZER ADDED SUBROUTINE, CALLED 4 TIMES, CODE SIZE REDUCTION:3 WORDS
SUBOPT_0x0:
ST -Y,R30
CALL _COM_read_register
MOV R17,R30
RET
;OPTIMIZER ADDED SUBROUTINE, CALLED 4 TIMES, CODE SIZE REDUCTION:9 WORDS
SUBOPT_0x1:
LDI R30,LOW(2)
ST -Y,R30
LDI R30,LOW(9)
ST -Y,R30
JMP _COM_write_register
;OPTIMIZER ADDED SUBROUTINE, CALLED 6 TIMES, CODE SIZE REDUCTION:12 WORDS
SUBOPT_0x2:
CALL _COM_write_register
__DELAY_USB 7
RET
;OPTIMIZER ADDED SUBROUTINE, CALLED 5 TIMES, CODE SIZE REDUCTION:5 WORDS
SUBOPT_0x3:
LDI R30,LOW(2)
ST -Y,R30
LDI R30,LOW(6)
ST -Y,R30
RET
;OPTIMIZER ADDED SUBROUTINE, CALLED 2 TIMES, CODE SIZE REDUCTION:3 WORDS
SUBOPT_0x4:
ST -Y,R17
LDI R17,0
CBI 0xB,0
LDI R30,LOW(4)
ST -Y,R30
CALL _spi
MOV R17,R30
RET
;OPTIMIZER ADDED SUBROUTINE, CALLED 3 TIMES, CODE SIZE REDUCTION:5 WORDS
SUBOPT_0x5:
LDS R26,_ms_counter
LDS R27,_ms_counter+1
CALL __CPW02
RET
;OPTIMIZER ADDED SUBROUTINE, CALLED 3 TIMES, CODE SIZE REDUCTION:1 WORDS
SUBOPT_0x6:
STS _ms_counter,R30
STS _ms_counter+1,R31
RET
__GETW1P:
LD R30,X+
LD R31,X
SBIW R26,1
RET
__CPW02:
CLR R0
CP R0,R26
CPC R0,R27
RET
__SAVELOCR6:
ST -Y,R21
__SAVELOCR5:
ST -Y,R20
__SAVELOCR4:
ST -Y,R19
__SAVELOCR3:
ST -Y,R18
__SAVELOCR2:
ST -Y,R17
ST -Y,R16
RET
__LOADLOCR6:
LDD R21,Y+5
__LOADLOCR5:
LDD R20,Y+4
__LOADLOCR4:
LDD R19,Y+3
__LOADLOCR3:
LDD R18,Y+2
__LOADLOCR2:
LDD R17,Y+1
LD R16,Y
RET
;END OF CODE MARKER
__END_OF_CODE:
|
#include <gct/command_buffer_allocate_info.hpp>
namespace gct {
command_buffer_allocate_info_t &command_buffer_allocate_info_t::rebuild_chain() {
LIBGCT_EXTENSION_BEGIN_REBUILD_CHAIN
LIBGCT_EXTENSION_END_REBUILD_CHAIN
}
}
|
; 8086 assembly file
; by:czfshine
; date: 2018/04/12 10:54:02
;ไป้ฎ็่พๅ
ฅไธไธชๆ็ฌฆๅท็ๅ่ฟๅถๆฐ๏ผ
;็ถๅๅจไธไธ่ก็จ16่ฟๅถๅฝขๅผ่พๅบๆญคๆฐ
; The Main Data segment
include scan.inc
DATA SEGMENT
DATA ENDS
;entry code segment
CODE SEGMENT
ASSUME CS:CODE ,DS:DATA
START: ;entry point
MOV AX,DATA
MOV DS,AX
mov di,10
call inputnumbybase
cmp di,1
jne put
neg bx
put:
mov si,16
call rebase
MOV AH,4CH ;return
INT 21H
CODE ENDS
END START |
/*
* Copyright (c) 2011-2015 Advanced Micro Devices, Inc.
* All rights reserved.
*
* For use for simulation and test purposes only
*
* 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.
*
* Author: John Kalamatianos, Anthony Gutierrez
*/
#include "gpu-compute/compute_unit.hh"
#include <limits>
#include "base/output.hh"
#include "debug/GPUDisp.hh"
#include "debug/GPUExec.hh"
#include "debug/GPUFetch.hh"
#include "debug/GPUMem.hh"
#include "debug/GPUPort.hh"
#include "debug/GPUPrefetch.hh"
#include "debug/GPUSync.hh"
#include "debug/GPUTLB.hh"
#include "gpu-compute/dispatcher.hh"
#include "gpu-compute/gpu_dyn_inst.hh"
#include "gpu-compute/gpu_static_inst.hh"
#include "gpu-compute/ndrange.hh"
#include "gpu-compute/shader.hh"
#include "gpu-compute/simple_pool_manager.hh"
#include "gpu-compute/vector_register_file.hh"
#include "gpu-compute/wavefront.hh"
#include "mem/page_table.hh"
#include "sim/process.hh"
ComputeUnit::ComputeUnit(const Params *p) : MemObject(p), fetchStage(p),
scoreboardCheckStage(p), scheduleStage(p), execStage(p),
globalMemoryPipe(p), localMemoryPipe(p), rrNextMemID(0), rrNextALUWp(0),
cu_id(p->cu_id), vrf(p->vector_register_file), numSIMDs(p->num_SIMDs),
spBypassPipeLength(p->spbypass_pipe_length),
dpBypassPipeLength(p->dpbypass_pipe_length),
issuePeriod(p->issue_period),
numGlbMemUnits(p->num_global_mem_pipes),
numLocMemUnits(p->num_shared_mem_pipes),
perLaneTLB(p->perLaneTLB), prefetchDepth(p->prefetch_depth),
prefetchStride(p->prefetch_stride), prefetchType(p->prefetch_prev_type),
xact_cas_mode(p->xactCasMode), debugSegFault(p->debugSegFault),
functionalTLB(p->functionalTLB), localMemBarrier(p->localMemBarrier),
countPages(p->countPages), barrier_id(0),
vrfToCoalescerBusWidth(p->vrf_to_coalescer_bus_width),
coalescerToVrfBusWidth(p->coalescer_to_vrf_bus_width),
req_tick_latency(p->mem_req_latency * p->clk_domain->clockPeriod()),
resp_tick_latency(p->mem_resp_latency * p->clk_domain->clockPeriod()),
_masterId(p->system->getMasterId(name() + ".ComputeUnit")),
lds(*p->localDataStore), _cacheLineSize(p->system->cacheLineSize()),
globalSeqNum(0), wavefrontSize(p->wfSize),
kernelLaunchInst(new KernelLaunchStaticInst())
{
/**
* This check is necessary because std::bitset only provides conversion
* to unsigned long or unsigned long long via to_ulong() or to_ullong().
* there are * a few places in the code where to_ullong() is used, however
* if VSZ is larger than a value the host can support then bitset will
* throw a runtime exception. we should remove all use of to_long() or
* to_ullong() so we can have VSZ greater than 64b, however until that is
* done this assert is required.
*/
fatal_if(p->wfSize > std::numeric_limits<unsigned long long>::digits ||
p->wfSize <= 0,
"WF size is larger than the host can support");
fatal_if(!isPowerOf2(wavefrontSize),
"Wavefront size should be a power of 2");
// calculate how many cycles a vector load or store will need to transfer
// its data over the corresponding buses
numCyclesPerStoreTransfer =
(uint32_t)ceil((double)(wfSize() * sizeof(uint32_t)) /
(double)vrfToCoalescerBusWidth);
numCyclesPerLoadTransfer = (wfSize() * sizeof(uint32_t))
/ coalescerToVrfBusWidth;
lastVaddrWF.resize(numSIMDs);
wfList.resize(numSIMDs);
for (int j = 0; j < numSIMDs; ++j) {
lastVaddrWF[j].resize(p->n_wf);
for (int i = 0; i < p->n_wf; ++i) {
lastVaddrWF[j][i].resize(wfSize());
wfList[j].push_back(p->wavefronts[j * p->n_wf + i]);
wfList[j][i]->setParent(this);
for (int k = 0; k < wfSize(); ++k) {
lastVaddrWF[j][i][k] = 0;
}
}
}
lastVaddrSimd.resize(numSIMDs);
for (int i = 0; i < numSIMDs; ++i) {
lastVaddrSimd[i].resize(wfSize(), 0);
}
lastVaddrCU.resize(wfSize());
lds.setParent(this);
if (p->execPolicy == "OLDEST-FIRST") {
exec_policy = EXEC_POLICY::OLDEST;
} else if (p->execPolicy == "ROUND-ROBIN") {
exec_policy = EXEC_POLICY::RR;
} else {
fatal("Invalid WF execution policy (CU)\n");
}
memPort.resize(wfSize());
// resize the tlbPort vectorArray
int tlbPort_width = perLaneTLB ? wfSize() : 1;
tlbPort.resize(tlbPort_width);
cuExitCallback = new CUExitCallback(this);
registerExitCallback(cuExitCallback);
xactCasLoadMap.clear();
lastExecCycle.resize(numSIMDs, 0);
for (int i = 0; i < vrf.size(); ++i) {
vrf[i]->setParent(this);
}
numVecRegsPerSimd = vrf[0]->numRegs();
}
ComputeUnit::~ComputeUnit()
{
// Delete wavefront slots
for (int j = 0; j < numSIMDs; ++j) {
for (int i = 0; i < shader->n_wf; ++i) {
delete wfList[j][i];
}
lastVaddrSimd[j].clear();
}
lastVaddrCU.clear();
readyList.clear();
waveStatusList.clear();
dispatchList.clear();
vectorAluInstAvail.clear();
delete cuExitCallback;
delete ldsPort;
}
void
ComputeUnit::fillKernelState(Wavefront *w, NDRange *ndr)
{
w->resizeRegFiles(ndr->q.cRegCount, ndr->q.sRegCount, ndr->q.dRegCount);
w->workGroupSz[0] = ndr->q.wgSize[0];
w->workGroupSz[1] = ndr->q.wgSize[1];
w->workGroupSz[2] = ndr->q.wgSize[2];
w->wgSz = w->workGroupSz[0] * w->workGroupSz[1] * w->workGroupSz[2];
w->gridSz[0] = ndr->q.gdSize[0];
w->gridSz[1] = ndr->q.gdSize[1];
w->gridSz[2] = ndr->q.gdSize[2];
w->kernelArgs = ndr->q.args;
w->privSizePerItem = ndr->q.privMemPerItem;
w->spillSizePerItem = ndr->q.spillMemPerItem;
w->roBase = ndr->q.roMemStart;
w->roSize = ndr->q.roMemTotal;
w->computeActualWgSz(ndr);
}
void
ComputeUnit::updateEvents() {
if (!timestampVec.empty()) {
uint32_t vecSize = timestampVec.size();
uint32_t i = 0;
while (i < vecSize) {
if (timestampVec[i] <= shader->tick_cnt) {
std::pair<uint32_t, uint32_t> regInfo = regIdxVec[i];
vrf[regInfo.first]->markReg(regInfo.second, sizeof(uint32_t),
statusVec[i]);
timestampVec.erase(timestampVec.begin() + i);
regIdxVec.erase(regIdxVec.begin() + i);
statusVec.erase(statusVec.begin() + i);
--vecSize;
--i;
}
++i;
}
}
for (int i = 0; i< numSIMDs; ++i) {
vrf[i]->updateEvents();
}
}
void
ComputeUnit::startWavefront(Wavefront *w, int waveId, LdsChunk *ldsChunk,
NDRange *ndr)
{
static int _n_wave = 0;
VectorMask init_mask;
init_mask.reset();
for (int k = 0; k < wfSize(); ++k) {
if (k + waveId * wfSize() < w->actualWgSzTotal)
init_mask[k] = 1;
}
w->kernId = ndr->dispatchId;
w->wfId = waveId;
w->initMask = init_mask.to_ullong();
for (int k = 0; k < wfSize(); ++k) {
w->workItemId[0][k] = (k + waveId * wfSize()) % w->actualWgSz[0];
w->workItemId[1][k] = ((k + waveId * wfSize()) / w->actualWgSz[0]) %
w->actualWgSz[1];
w->workItemId[2][k] = (k + waveId * wfSize()) /
(w->actualWgSz[0] * w->actualWgSz[1]);
w->workItemFlatId[k] = w->workItemId[2][k] * w->actualWgSz[0] *
w->actualWgSz[1] + w->workItemId[1][k] * w->actualWgSz[0] +
w->workItemId[0][k];
}
w->barrierSlots = divCeil(w->actualWgSzTotal, wfSize());
w->barCnt.resize(wfSize(), 0);
w->maxBarCnt = 0;
w->oldBarrierCnt = 0;
w->barrierCnt = 0;
w->privBase = ndr->q.privMemStart;
ndr->q.privMemStart += ndr->q.privMemPerItem * wfSize();
w->spillBase = ndr->q.spillMemStart;
ndr->q.spillMemStart += ndr->q.spillMemPerItem * wfSize();
w->pushToReconvergenceStack(0, UINT32_MAX, init_mask.to_ulong());
// WG state
w->wgId = ndr->globalWgId;
w->dispatchId = ndr->dispatchId;
w->workGroupId[0] = w->wgId % ndr->numWg[0];
w->workGroupId[1] = (w->wgId / ndr->numWg[0]) % ndr->numWg[1];
w->workGroupId[2] = w->wgId / (ndr->numWg[0] * ndr->numWg[1]);
w->barrierId = barrier_id;
w->stalledAtBarrier = false;
// set the wavefront context to have a pointer to this section of the LDS
w->ldsChunk = ldsChunk;
int32_t refCount M5_VAR_USED =
lds.increaseRefCounter(w->dispatchId, w->wgId);
DPRINTF(GPUDisp, "CU%d: increase ref ctr wg[%d] to [%d]\n",
cu_id, w->wgId, refCount);
w->instructionBuffer.clear();
if (w->pendingFetch)
w->dropFetch = true;
// is this the last wavefront in the workgroup
// if set the spillWidth to be the remaining work-items
// so that the vector access is correct
if ((waveId + 1) * wfSize() >= w->actualWgSzTotal) {
w->spillWidth = w->actualWgSzTotal - (waveId * wfSize());
} else {
w->spillWidth = wfSize();
}
DPRINTF(GPUDisp, "Scheduling wfDynId/barrier_id %d/%d on CU%d: "
"WF[%d][%d]\n", _n_wave, barrier_id, cu_id, w->simdId, w->wfSlotId);
w->start(++_n_wave, ndr->q.code_ptr);
}
void
ComputeUnit::StartWorkgroup(NDRange *ndr)
{
// reserve the LDS capacity allocated to the work group
// disambiguated by the dispatch ID and workgroup ID, which should be
// globally unique
LdsChunk *ldsChunk = lds.reserveSpace(ndr->dispatchId, ndr->globalWgId,
ndr->q.ldsSize);
// Send L1 cache acquire
// isKernel + isAcquire = Kernel Begin
if (shader->impl_kern_boundary_sync) {
GPUDynInstPtr gpuDynInst =
std::make_shared<GPUDynInst>(this, nullptr, kernelLaunchInst,
getAndIncSeqNum());
gpuDynInst->useContinuation = false;
injectGlobalMemFence(gpuDynInst, true);
}
// calculate the number of 32-bit vector registers required by wavefront
int vregDemand = ndr->q.sRegCount + (2 * ndr->q.dRegCount);
int wave_id = 0;
// Assign WFs by spreading them across SIMDs, 1 WF per SIMD at a time
for (int m = 0; m < shader->n_wf * numSIMDs; ++m) {
Wavefront *w = wfList[m % numSIMDs][m / numSIMDs];
// Check if this wavefront slot is available:
// It must be stopped and not waiting
// for a release to complete S_RETURNING
if (w->status == Wavefront::S_STOPPED) {
fillKernelState(w, ndr);
// if we have scheduled all work items then stop
// scheduling wavefronts
if (wave_id * wfSize() >= w->actualWgSzTotal)
break;
// reserve vector registers for the scheduled wavefront
assert(vectorRegsReserved[m % numSIMDs] <= numVecRegsPerSimd);
uint32_t normSize = 0;
w->startVgprIndex = vrf[m % numSIMDs]->manager->
allocateRegion(vregDemand, &normSize);
w->reservedVectorRegs = normSize;
vectorRegsReserved[m % numSIMDs] += w->reservedVectorRegs;
startWavefront(w, wave_id, ldsChunk, ndr);
++wave_id;
}
}
++barrier_id;
}
int
ComputeUnit::ReadyWorkgroup(NDRange *ndr)
{
// Get true size of workgroup (after clamping to grid size)
int trueWgSize[3];
int trueWgSizeTotal = 1;
for (int d = 0; d < 3; ++d) {
trueWgSize[d] = std::min(ndr->q.wgSize[d], ndr->q.gdSize[d] -
ndr->wgId[d] * ndr->q.wgSize[d]);
trueWgSizeTotal *= trueWgSize[d];
DPRINTF(GPUDisp, "trueWgSize[%d] = %d\n", d, trueWgSize[d]);
}
DPRINTF(GPUDisp, "trueWgSizeTotal = %d\n", trueWgSizeTotal);
// calculate the number of 32-bit vector registers required by each
// work item of the work group
int vregDemandPerWI = ndr->q.sRegCount + (2 * ndr->q.dRegCount);
bool vregAvail = true;
int numWfs = (trueWgSizeTotal + wfSize() - 1) / wfSize();
int freeWfSlots = 0;
// check if the total number of VGPRs required by all WFs of the WG
// fit in the VRFs of all SIMD units
assert((numWfs * vregDemandPerWI) <= (numSIMDs * numVecRegsPerSimd));
int numMappedWfs = 0;
std::vector<int> numWfsPerSimd;
numWfsPerSimd.resize(numSIMDs, 0);
// find how many free WF slots we have across all SIMDs
for (int j = 0; j < shader->n_wf; ++j) {
for (int i = 0; i < numSIMDs; ++i) {
if (wfList[i][j]->status == Wavefront::S_STOPPED) {
// count the number of free WF slots
++freeWfSlots;
if (numMappedWfs < numWfs) {
// count the WFs to be assigned per SIMD
numWfsPerSimd[i]++;
}
numMappedWfs++;
}
}
}
// if there are enough free WF slots then find if there are enough
// free VGPRs per SIMD based on the WF->SIMD mapping
if (freeWfSlots >= numWfs) {
for (int j = 0; j < numSIMDs; ++j) {
// find if there are enough free VGPR regions in the SIMD's VRF
// to accommodate the WFs of the new WG that would be mapped to
// this SIMD unit
vregAvail = vrf[j]->manager->canAllocate(numWfsPerSimd[j],
vregDemandPerWI);
// stop searching if there is at least one SIMD
// whose VRF does not have enough free VGPR pools.
// This is because a WG is scheduled only if ALL
// of its WFs can be scheduled
if (!vregAvail)
break;
}
}
DPRINTF(GPUDisp, "Free WF slots = %d, VGPR Availability = %d\n",
freeWfSlots, vregAvail);
if (!vregAvail) {
++numTimesWgBlockedDueVgprAlloc;
}
// Return true if enough WF slots to submit workgroup and if there are
// enough VGPRs to schedule all WFs to their SIMD units
if (!lds.canReserve(ndr->q.ldsSize)) {
wgBlockedDueLdsAllocation++;
}
// Return true if (a) there are enough free WF slots to submit
// workgrounp and (b) if there are enough VGPRs to schedule all WFs to their
// SIMD units and (c) if there is enough space in LDS
return freeWfSlots >= numWfs && vregAvail && lds.canReserve(ndr->q.ldsSize);
}
int
ComputeUnit::AllAtBarrier(uint32_t _barrier_id, uint32_t bcnt, uint32_t bslots)
{
DPRINTF(GPUSync, "CU%d: Checking for All At Barrier\n", cu_id);
int ccnt = 0;
for (int i_simd = 0; i_simd < numSIMDs; ++i_simd) {
for (int i_wf = 0; i_wf < shader->n_wf; ++i_wf) {
Wavefront *w = wfList[i_simd][i_wf];
if (w->status == Wavefront::S_RUNNING) {
DPRINTF(GPUSync, "Checking WF[%d][%d]\n", i_simd, i_wf);
DPRINTF(GPUSync, "wf->barrier_id = %d, _barrier_id = %d\n",
w->barrierId, _barrier_id);
DPRINTF(GPUSync, "wf->barrier_cnt %d, bcnt = %d\n",
w->barrierCnt, bcnt);
}
if (w->status == Wavefront::S_RUNNING &&
w->barrierId == _barrier_id && w->barrierCnt == bcnt &&
!w->outstandingReqs) {
++ccnt;
DPRINTF(GPUSync, "WF[%d][%d] at barrier, increment ccnt to "
"%d\n", i_simd, i_wf, ccnt);
}
}
}
DPRINTF(GPUSync, "CU%d: returning allAtBarrier ccnt = %d, bslots = %d\n",
cu_id, ccnt, bslots);
return ccnt == bslots;
}
// Check if the current wavefront is blocked on additional resources.
bool
ComputeUnit::cedeSIMD(int simdId, int wfSlotId)
{
bool cede = false;
// If --xact-cas-mode option is enabled in run.py, then xact_cas_ld
// magic instructions will impact the scheduling of wavefronts
if (xact_cas_mode) {
/*
* When a wavefront calls xact_cas_ld, it adds itself to a per address
* queue. All per address queues are managed by the xactCasLoadMap.
*
* A wavefront is not blocked if: it is not in ANY per address queue or
* if it is at the head of a per address queue.
*/
for (auto itMap : xactCasLoadMap) {
std::list<waveIdentifier> curWaveIDQueue = itMap.second.waveIDQueue;
if (!curWaveIDQueue.empty()) {
for (auto it : curWaveIDQueue) {
waveIdentifier cur_wave = it;
if (cur_wave.simdId == simdId &&
cur_wave.wfSlotId == wfSlotId) {
// 2 possibilities
// 1: this WF has a green light
// 2: another WF has a green light
waveIdentifier owner_wave = curWaveIDQueue.front();
if (owner_wave.simdId != cur_wave.simdId ||
owner_wave.wfSlotId != cur_wave.wfSlotId) {
// possibility 2
cede = true;
break;
} else {
// possibility 1
break;
}
}
}
}
}
}
return cede;
}
// Execute one clock worth of work on the ComputeUnit.
void
ComputeUnit::exec()
{
updateEvents();
// Execute pipeline stages in reverse order to simulate
// the pipeline latency
globalMemoryPipe.exec();
localMemoryPipe.exec();
execStage.exec();
scheduleStage.exec();
scoreboardCheckStage.exec();
fetchStage.exec();
totalCycles++;
}
void
ComputeUnit::init()
{
// Initialize CU Bus models
glbMemToVrfBus.init(&shader->tick_cnt, shader->ticks(1));
locMemToVrfBus.init(&shader->tick_cnt, shader->ticks(1));
nextGlbMemBus = 0;
nextLocMemBus = 0;
fatal_if(numGlbMemUnits > 1,
"No support for multiple Global Memory Pipelines exists!!!");
vrfToGlobalMemPipeBus.resize(numGlbMemUnits);
for (int j = 0; j < numGlbMemUnits; ++j) {
vrfToGlobalMemPipeBus[j] = WaitClass();
vrfToGlobalMemPipeBus[j].init(&shader->tick_cnt, shader->ticks(1));
}
fatal_if(numLocMemUnits > 1,
"No support for multiple Local Memory Pipelines exists!!!");
vrfToLocalMemPipeBus.resize(numLocMemUnits);
for (int j = 0; j < numLocMemUnits; ++j) {
vrfToLocalMemPipeBus[j] = WaitClass();
vrfToLocalMemPipeBus[j].init(&shader->tick_cnt, shader->ticks(1));
}
vectorRegsReserved.resize(numSIMDs, 0);
aluPipe.resize(numSIMDs);
wfWait.resize(numSIMDs + numLocMemUnits + numGlbMemUnits);
for (int i = 0; i < numSIMDs + numLocMemUnits + numGlbMemUnits; ++i) {
wfWait[i] = WaitClass();
wfWait[i].init(&shader->tick_cnt, shader->ticks(1));
}
for (int i = 0; i < numSIMDs; ++i) {
aluPipe[i] = WaitClass();
aluPipe[i].init(&shader->tick_cnt, shader->ticks(1));
}
// Setup space for call args
for (int j = 0; j < numSIMDs; ++j) {
for (int i = 0; i < shader->n_wf; ++i) {
wfList[j][i]->initCallArgMem(shader->funcargs_size, wavefrontSize);
}
}
// Initializing pipeline resources
readyList.resize(numSIMDs + numGlbMemUnits + numLocMemUnits);
waveStatusList.resize(numSIMDs);
for (int j = 0; j < numSIMDs; ++j) {
for (int i = 0; i < shader->n_wf; ++i) {
waveStatusList[j].push_back(
std::make_pair(wfList[j][i], BLOCKED));
}
}
for (int j = 0; j < (numSIMDs + numGlbMemUnits + numLocMemUnits); ++j) {
dispatchList.push_back(std::make_pair((Wavefront*)nullptr, EMPTY));
}
fetchStage.init(this);
scoreboardCheckStage.init(this);
scheduleStage.init(this);
execStage.init(this);
globalMemoryPipe.init(this);
localMemoryPipe.init(this);
// initialize state for statistics calculation
vectorAluInstAvail.resize(numSIMDs, false);
shrMemInstAvail = 0;
glbMemInstAvail = 0;
}
bool
ComputeUnit::DataPort::recvTimingResp(PacketPtr pkt)
{
// Ruby has completed the memory op. Schedule the mem_resp_event at the
// appropriate cycle to process the timing memory response
// This delay represents the pipeline delay
SenderState *sender_state = safe_cast<SenderState*>(pkt->senderState);
int index = sender_state->port_index;
GPUDynInstPtr gpuDynInst = sender_state->_gpuDynInst;
// Is the packet returned a Kernel End or Barrier
if (pkt->req->isKernel() && pkt->req->isRelease()) {
Wavefront *w =
computeUnit->wfList[gpuDynInst->simdId][gpuDynInst->wfSlotId];
// Check if we are waiting on Kernel End Release
if (w->status == Wavefront::S_RETURNING) {
DPRINTF(GPUDisp, "CU%d: WF[%d][%d][wv=%d]: WG id completed %d\n",
computeUnit->cu_id, w->simdId, w->wfSlotId,
w->wfDynId, w->kernId);
computeUnit->shader->dispatcher->notifyWgCompl(w);
w->status = Wavefront::S_STOPPED;
} else {
w->outstandingReqs--;
}
DPRINTF(GPUSync, "CU%d: WF[%d][%d]: barrier_cnt = %d\n",
computeUnit->cu_id, gpuDynInst->simdId,
gpuDynInst->wfSlotId, w->barrierCnt);
if (gpuDynInst->useContinuation) {
assert(!gpuDynInst->isNoScope());
gpuDynInst->execContinuation(gpuDynInst->staticInstruction(),
gpuDynInst);
}
delete pkt->senderState;
delete pkt->req;
delete pkt;
return true;
} else if (pkt->req->isKernel() && pkt->req->isAcquire()) {
if (gpuDynInst->useContinuation) {
assert(!gpuDynInst->isNoScope());
gpuDynInst->execContinuation(gpuDynInst->staticInstruction(),
gpuDynInst);
}
delete pkt->senderState;
delete pkt->req;
delete pkt;
return true;
}
ComputeUnit::DataPort::MemRespEvent *mem_resp_event =
new ComputeUnit::DataPort::MemRespEvent(computeUnit->memPort[index],
pkt);
DPRINTF(GPUPort, "CU%d: WF[%d][%d]: index %d, addr %#x received!\n",
computeUnit->cu_id, gpuDynInst->simdId, gpuDynInst->wfSlotId,
index, pkt->req->getPaddr());
computeUnit->schedule(mem_resp_event,
curTick() + computeUnit->resp_tick_latency);
return true;
}
void
ComputeUnit::DataPort::recvReqRetry()
{
int len = retries.size();
assert(len > 0);
for (int i = 0; i < len; ++i) {
PacketPtr pkt = retries.front().first;
GPUDynInstPtr gpuDynInst M5_VAR_USED = retries.front().second;
DPRINTF(GPUMem, "CU%d: WF[%d][%d]: retry mem inst addr %#x\n",
computeUnit->cu_id, gpuDynInst->simdId, gpuDynInst->wfSlotId,
pkt->req->getPaddr());
/** Currently Ruby can return false due to conflicts for the particular
* cache block or address. Thus other requests should be allowed to
* pass and the data port should expect multiple retries. */
if (!sendTimingReq(pkt)) {
DPRINTF(GPUMem, "failed again!\n");
break;
} else {
DPRINTF(GPUMem, "successful!\n");
retries.pop_front();
}
}
}
bool
ComputeUnit::SQCPort::recvTimingResp(PacketPtr pkt)
{
computeUnit->fetchStage.processFetchReturn(pkt);
return true;
}
void
ComputeUnit::SQCPort::recvReqRetry()
{
int len = retries.size();
assert(len > 0);
for (int i = 0; i < len; ++i) {
PacketPtr pkt = retries.front().first;
Wavefront *wavefront M5_VAR_USED = retries.front().second;
DPRINTF(GPUFetch, "CU%d: WF[%d][%d]: retrying FETCH addr %#x\n",
computeUnit->cu_id, wavefront->simdId, wavefront->wfSlotId,
pkt->req->getPaddr());
if (!sendTimingReq(pkt)) {
DPRINTF(GPUFetch, "failed again!\n");
break;
} else {
DPRINTF(GPUFetch, "successful!\n");
retries.pop_front();
}
}
}
void
ComputeUnit::sendRequest(GPUDynInstPtr gpuDynInst, int index, PacketPtr pkt)
{
// There must be a way around this check to do the globalMemStart...
Addr tmp_vaddr = pkt->req->getVaddr();
updatePageDivergenceDist(tmp_vaddr);
pkt->req->setVirt(pkt->req->getAsid(), tmp_vaddr, pkt->req->getSize(),
pkt->req->getFlags(), pkt->req->masterId(),
pkt->req->getPC());
// figure out the type of the request to set read/write
BaseTLB::Mode TLB_mode;
assert(pkt->isRead() || pkt->isWrite());
// Check write before read for atomic operations
// since atomic operations should use BaseTLB::Write
if (pkt->isWrite()){
TLB_mode = BaseTLB::Write;
} else if (pkt->isRead()) {
TLB_mode = BaseTLB::Read;
} else {
fatal("pkt is not a read nor a write\n");
}
tlbCycles -= curTick();
++tlbRequests;
int tlbPort_index = perLaneTLB ? index : 0;
if (shader->timingSim) {
if (debugSegFault) {
Process *p = shader->gpuTc->getProcessPtr();
Addr vaddr = pkt->req->getVaddr();
unsigned size = pkt->getSize();
if ((vaddr + size - 1) % 64 < vaddr % 64) {
panic("CU%d: WF[%d][%d]: Access to addr %#x is unaligned!\n",
cu_id, gpuDynInst->simdId, gpuDynInst->wfSlotId, vaddr);
}
Addr paddr;
if (!p->pTable->translate(vaddr, paddr)) {
if (!p->fixupStackFault(vaddr)) {
panic("CU%d: WF[%d][%d]: Fault on addr %#x!\n",
cu_id, gpuDynInst->simdId, gpuDynInst->wfSlotId,
vaddr);
}
}
}
// This is the SenderState needed upon return
pkt->senderState = new DTLBPort::SenderState(gpuDynInst, index);
// This is the senderState needed by the TLB hierarchy to function
TheISA::GpuTLB::TranslationState *translation_state =
new TheISA::GpuTLB::TranslationState(TLB_mode, shader->gpuTc, false,
pkt->senderState);
pkt->senderState = translation_state;
if (functionalTLB) {
tlbPort[tlbPort_index]->sendFunctional(pkt);
// update the hitLevel distribution
int hit_level = translation_state->hitLevel;
assert(hit_level != -1);
hitsPerTLBLevel[hit_level]++;
// New SenderState for the memory access
X86ISA::GpuTLB::TranslationState *sender_state =
safe_cast<X86ISA::GpuTLB::TranslationState*>(pkt->senderState);
delete sender_state->tlbEntry;
delete sender_state->saved;
delete sender_state;
assert(pkt->req->hasPaddr());
assert(pkt->req->hasSize());
uint8_t *tmpData = pkt->getPtr<uint8_t>();
// this is necessary because the GPU TLB receives packets instead
// of requests. when the translation is complete, all relevent
// fields in the request will be populated, but not in the packet.
// here we create the new packet so we can set the size, addr,
// and proper flags.
PacketPtr oldPkt = pkt;
pkt = new Packet(oldPkt->req, oldPkt->cmd);
delete oldPkt;
pkt->dataStatic(tmpData);
// New SenderState for the memory access
pkt->senderState = new ComputeUnit::DataPort::SenderState(gpuDynInst,
index, nullptr);
gpuDynInst->memStatusVector[pkt->getAddr()].push_back(index);
gpuDynInst->tlbHitLevel[index] = hit_level;
// translation is done. Schedule the mem_req_event at the
// appropriate cycle to send the timing memory request to ruby
ComputeUnit::DataPort::MemReqEvent *mem_req_event =
new ComputeUnit::DataPort::MemReqEvent(memPort[index], pkt);
DPRINTF(GPUPort, "CU%d: WF[%d][%d]: index %d, addr %#x data "
"scheduled\n", cu_id, gpuDynInst->simdId,
gpuDynInst->wfSlotId, index, pkt->req->getPaddr());
schedule(mem_req_event, curTick() + req_tick_latency);
} else if (tlbPort[tlbPort_index]->isStalled()) {
assert(tlbPort[tlbPort_index]->retries.size() > 0);
DPRINTF(GPUTLB, "CU%d: WF[%d][%d]: Translation for addr %#x "
"failed!\n", cu_id, gpuDynInst->simdId, gpuDynInst->wfSlotId,
tmp_vaddr);
tlbPort[tlbPort_index]->retries.push_back(pkt);
} else if (!tlbPort[tlbPort_index]->sendTimingReq(pkt)) {
// Stall the data port;
// No more packet will be issued till
// ruby indicates resources are freed by
// a recvReqRetry() call back on this port.
tlbPort[tlbPort_index]->stallPort();
DPRINTF(GPUTLB, "CU%d: WF[%d][%d]: Translation for addr %#x "
"failed!\n", cu_id, gpuDynInst->simdId, gpuDynInst->wfSlotId,
tmp_vaddr);
tlbPort[tlbPort_index]->retries.push_back(pkt);
} else {
DPRINTF(GPUTLB,
"CU%d: WF[%d][%d]: Translation for addr %#x sent!\n",
cu_id, gpuDynInst->simdId, gpuDynInst->wfSlotId, tmp_vaddr);
}
} else {
if (pkt->cmd == MemCmd::MemFenceReq) {
gpuDynInst->statusBitVector = VectorMask(0);
} else {
gpuDynInst->statusBitVector &= (~(1ll << index));
}
// New SenderState for the memory access
delete pkt->senderState;
// Because it's atomic operation, only need TLB translation state
pkt->senderState = new TheISA::GpuTLB::TranslationState(TLB_mode,
shader->gpuTc);
tlbPort[tlbPort_index]->sendFunctional(pkt);
// the addr of the packet is not modified, so we need to create a new
// packet, or otherwise the memory access will have the old virtual
// address sent in the translation packet, instead of the physical
// address returned by the translation.
PacketPtr new_pkt = new Packet(pkt->req, pkt->cmd);
new_pkt->dataStatic(pkt->getPtr<uint8_t>());
// Translation is done. It is safe to send the packet to memory.
memPort[0]->sendFunctional(new_pkt);
DPRINTF(GPUMem, "CU%d: WF[%d][%d]: index %d: addr %#x\n", cu_id,
gpuDynInst->simdId, gpuDynInst->wfSlotId, index,
new_pkt->req->getPaddr());
// safe_cast the senderState
TheISA::GpuTLB::TranslationState *sender_state =
safe_cast<TheISA::GpuTLB::TranslationState*>(pkt->senderState);
delete sender_state->tlbEntry;
delete new_pkt;
delete pkt->senderState;
delete pkt->req;
delete pkt;
}
}
void
ComputeUnit::sendSyncRequest(GPUDynInstPtr gpuDynInst, int index, PacketPtr pkt)
{
ComputeUnit::DataPort::MemReqEvent *mem_req_event =
new ComputeUnit::DataPort::MemReqEvent(memPort[index], pkt);
// New SenderState for the memory access
pkt->senderState = new ComputeUnit::DataPort::SenderState(gpuDynInst, index,
nullptr);
DPRINTF(GPUPort, "CU%d: WF[%d][%d]: index %d, addr %#x sync scheduled\n",
cu_id, gpuDynInst->simdId, gpuDynInst->wfSlotId, index,
pkt->req->getPaddr());
schedule(mem_req_event, curTick() + req_tick_latency);
}
void
ComputeUnit::injectGlobalMemFence(GPUDynInstPtr gpuDynInst, bool kernelLaunch,
Request* req)
{
assert(gpuDynInst->isGlobalSeg());
if (!req) {
req = new Request(0, 0, 0, 0, masterId(), 0, gpuDynInst->wfDynId);
}
req->setPaddr(0);
if (kernelLaunch) {
req->setFlags(Request::KERNEL);
}
// for non-kernel MemFence operations, memorder flags are set depending
// on which type of request is currently being sent, so this
// should be set by the caller (e.g. if an inst has acq-rel
// semantics, it will send one acquire req an one release req)
gpuDynInst->setRequestFlags(req, kernelLaunch);
// a mem fence must correspond to an acquire/release request
assert(req->isAcquire() || req->isRelease());
// create packet
PacketPtr pkt = new Packet(req, MemCmd::MemFenceReq);
// set packet's sender state
pkt->senderState =
new ComputeUnit::DataPort::SenderState(gpuDynInst, 0, nullptr);
// send the packet
sendSyncRequest(gpuDynInst, 0, pkt);
}
const char*
ComputeUnit::DataPort::MemRespEvent::description() const
{
return "ComputeUnit memory response event";
}
void
ComputeUnit::DataPort::MemRespEvent::process()
{
DataPort::SenderState *sender_state =
safe_cast<DataPort::SenderState*>(pkt->senderState);
GPUDynInstPtr gpuDynInst = sender_state->_gpuDynInst;
ComputeUnit *compute_unit = dataPort->computeUnit;
assert(gpuDynInst);
DPRINTF(GPUPort, "CU%d: WF[%d][%d]: Response for addr %#x, index %d\n",
compute_unit->cu_id, gpuDynInst->simdId, gpuDynInst->wfSlotId,
pkt->req->getPaddr(), dataPort->index);
Addr paddr = pkt->req->getPaddr();
if (pkt->cmd != MemCmd::MemFenceResp) {
int index = gpuDynInst->memStatusVector[paddr].back();
DPRINTF(GPUMem, "Response for addr %#x, index %d\n",
pkt->req->getPaddr(), index);
gpuDynInst->memStatusVector[paddr].pop_back();
gpuDynInst->pAddr = pkt->req->getPaddr();
if (pkt->isRead() || pkt->isWrite()) {
if (gpuDynInst->n_reg <= MAX_REGS_FOR_NON_VEC_MEM_INST) {
gpuDynInst->statusBitVector &= (~(1ULL << index));
} else {
assert(gpuDynInst->statusVector[index] > 0);
gpuDynInst->statusVector[index]--;
if (!gpuDynInst->statusVector[index])
gpuDynInst->statusBitVector &= (~(1ULL << index));
}
DPRINTF(GPUMem, "bitvector is now %#x\n",
gpuDynInst->statusBitVector);
if (gpuDynInst->statusBitVector == VectorMask(0)) {
auto iter = gpuDynInst->memStatusVector.begin();
auto end = gpuDynInst->memStatusVector.end();
while (iter != end) {
assert(iter->second.empty());
++iter;
}
gpuDynInst->memStatusVector.clear();
if (gpuDynInst->n_reg > MAX_REGS_FOR_NON_VEC_MEM_INST)
gpuDynInst->statusVector.clear();
compute_unit->globalMemoryPipe.handleResponse(gpuDynInst);
DPRINTF(GPUMem, "CU%d: WF[%d][%d]: packet totally complete\n",
compute_unit->cu_id, gpuDynInst->simdId,
gpuDynInst->wfSlotId);
// after clearing the status vectors,
// see if there is a continuation to perform
// the continuation may generate more work for
// this memory request
if (gpuDynInst->useContinuation) {
assert(!gpuDynInst->isNoScope());
gpuDynInst->execContinuation(gpuDynInst->staticInstruction(),
gpuDynInst);
}
}
}
} else {
gpuDynInst->statusBitVector = VectorMask(0);
if (gpuDynInst->useContinuation) {
assert(!gpuDynInst->isNoScope());
gpuDynInst->execContinuation(gpuDynInst->staticInstruction(),
gpuDynInst);
}
}
delete pkt->senderState;
delete pkt->req;
delete pkt;
}
ComputeUnit*
ComputeUnitParams::create()
{
return new ComputeUnit(this);
}
bool
ComputeUnit::DTLBPort::recvTimingResp(PacketPtr pkt)
{
Addr line = pkt->req->getPaddr();
DPRINTF(GPUTLB, "CU%d: DTLBPort received %#x->%#x\n", computeUnit->cu_id,
pkt->req->getVaddr(), line);
assert(pkt->senderState);
computeUnit->tlbCycles += curTick();
// pop off the TLB translation state
TheISA::GpuTLB::TranslationState *translation_state =
safe_cast<TheISA::GpuTLB::TranslationState*>(pkt->senderState);
// no PageFaults are permitted for data accesses
if (!translation_state->tlbEntry->valid) {
DTLBPort::SenderState *sender_state =
safe_cast<DTLBPort::SenderState*>(translation_state->saved);
Wavefront *w M5_VAR_USED =
computeUnit->wfList[sender_state->_gpuDynInst->simdId]
[sender_state->_gpuDynInst->wfSlotId];
DPRINTFN("Wave %d couldn't tranlate vaddr %#x\n", w->wfDynId,
pkt->req->getVaddr());
}
assert(translation_state->tlbEntry->valid);
// update the hitLevel distribution
int hit_level = translation_state->hitLevel;
computeUnit->hitsPerTLBLevel[hit_level]++;
delete translation_state->tlbEntry;
assert(!translation_state->ports.size());
pkt->senderState = translation_state->saved;
// for prefetch pkt
BaseTLB::Mode TLB_mode = translation_state->tlbMode;
delete translation_state;
// use the original sender state to know how to close this transaction
DTLBPort::SenderState *sender_state =
safe_cast<DTLBPort::SenderState*>(pkt->senderState);
GPUDynInstPtr gpuDynInst = sender_state->_gpuDynInst;
int mp_index = sender_state->portIndex;
Addr vaddr = pkt->req->getVaddr();
gpuDynInst->memStatusVector[line].push_back(mp_index);
gpuDynInst->tlbHitLevel[mp_index] = hit_level;
MemCmd requestCmd;
if (pkt->cmd == MemCmd::ReadResp) {
requestCmd = MemCmd::ReadReq;
} else if (pkt->cmd == MemCmd::WriteResp) {
requestCmd = MemCmd::WriteReq;
} else if (pkt->cmd == MemCmd::SwapResp) {
requestCmd = MemCmd::SwapReq;
} else {
panic("unsupported response to request conversion %s\n",
pkt->cmd.toString());
}
if (computeUnit->prefetchDepth) {
int simdId = gpuDynInst->simdId;
int wfSlotId = gpuDynInst->wfSlotId;
Addr last = 0;
switch(computeUnit->prefetchType) {
case Enums::PF_CU:
last = computeUnit->lastVaddrCU[mp_index];
break;
case Enums::PF_PHASE:
last = computeUnit->lastVaddrSimd[simdId][mp_index];
break;
case Enums::PF_WF:
last = computeUnit->lastVaddrWF[simdId][wfSlotId][mp_index];
default:
break;
}
DPRINTF(GPUPrefetch, "CU[%d][%d][%d][%d]: %#x was last\n",
computeUnit->cu_id, simdId, wfSlotId, mp_index, last);
int stride = last ? (roundDown(vaddr, TheISA::PageBytes) -
roundDown(last, TheISA::PageBytes)) >> TheISA::PageShift
: 0;
DPRINTF(GPUPrefetch, "Stride is %d\n", stride);
computeUnit->lastVaddrCU[mp_index] = vaddr;
computeUnit->lastVaddrSimd[simdId][mp_index] = vaddr;
computeUnit->lastVaddrWF[simdId][wfSlotId][mp_index] = vaddr;
stride = (computeUnit->prefetchType == Enums::PF_STRIDE) ?
computeUnit->prefetchStride: stride;
DPRINTF(GPUPrefetch, "%#x to: CU[%d][%d][%d][%d]\n", vaddr,
computeUnit->cu_id, simdId, wfSlotId, mp_index);
DPRINTF(GPUPrefetch, "Prefetching from %#x:", vaddr);
// Prefetch Next few pages atomically
for (int pf = 1; pf <= computeUnit->prefetchDepth; ++pf) {
DPRINTF(GPUPrefetch, "%d * %d: %#x\n", pf, stride,
vaddr+stride*pf*TheISA::PageBytes);
if (!stride)
break;
Request *prefetch_req = new Request(0, vaddr + stride * pf *
TheISA::PageBytes,
sizeof(uint8_t), 0,
computeUnit->masterId(),
0, 0, 0);
PacketPtr prefetch_pkt = new Packet(prefetch_req, requestCmd);
uint8_t foo = 0;
prefetch_pkt->dataStatic(&foo);
// Because it's atomic operation, only need TLB translation state
prefetch_pkt->senderState =
new TheISA::GpuTLB::TranslationState(TLB_mode,
computeUnit->shader->gpuTc,
true);
// Currently prefetches are zero-latency, hence the sendFunctional
sendFunctional(prefetch_pkt);
/* safe_cast the senderState */
TheISA::GpuTLB::TranslationState *tlb_state =
safe_cast<TheISA::GpuTLB::TranslationState*>(
prefetch_pkt->senderState);
delete tlb_state->tlbEntry;
delete tlb_state;
delete prefetch_pkt->req;
delete prefetch_pkt;
}
}
// First we must convert the response cmd back to a request cmd so that
// the request can be sent through the cu's master port
PacketPtr new_pkt = new Packet(pkt->req, requestCmd);
new_pkt->dataStatic(pkt->getPtr<uint8_t>());
delete pkt->senderState;
delete pkt;
// New SenderState for the memory access
new_pkt->senderState =
new ComputeUnit::DataPort::SenderState(gpuDynInst, mp_index,
nullptr);
// translation is done. Schedule the mem_req_event at the appropriate
// cycle to send the timing memory request to ruby
ComputeUnit::DataPort::MemReqEvent *mem_req_event =
new ComputeUnit::DataPort::MemReqEvent(computeUnit->memPort[mp_index],
new_pkt);
DPRINTF(GPUPort, "CU%d: WF[%d][%d]: index %d, addr %#x data scheduled\n",
computeUnit->cu_id, gpuDynInst->simdId,
gpuDynInst->wfSlotId, mp_index, new_pkt->req->getPaddr());
computeUnit->schedule(mem_req_event, curTick() +
computeUnit->req_tick_latency);
return true;
}
const char*
ComputeUnit::DataPort::MemReqEvent::description() const
{
return "ComputeUnit memory request event";
}
void
ComputeUnit::DataPort::MemReqEvent::process()
{
SenderState *sender_state = safe_cast<SenderState*>(pkt->senderState);
GPUDynInstPtr gpuDynInst = sender_state->_gpuDynInst;
ComputeUnit *compute_unit M5_VAR_USED = dataPort->computeUnit;
if (!(dataPort->sendTimingReq(pkt))) {
dataPort->retries.push_back(std::make_pair(pkt, gpuDynInst));
DPRINTF(GPUPort,
"CU%d: WF[%d][%d]: index %d, addr %#x data req failed!\n",
compute_unit->cu_id, gpuDynInst->simdId,
gpuDynInst->wfSlotId, dataPort->index,
pkt->req->getPaddr());
} else {
DPRINTF(GPUPort,
"CU%d: WF[%d][%d]: index %d, addr %#x data req sent!\n",
compute_unit->cu_id, gpuDynInst->simdId,
gpuDynInst->wfSlotId, dataPort->index,
pkt->req->getPaddr());
}
}
/*
* The initial translation request could have been rejected,
* if <retries> queue is not Retry sending the translation
* request. sendRetry() is called from the peer port whenever
* a translation completes.
*/
void
ComputeUnit::DTLBPort::recvReqRetry()
{
int len = retries.size();
DPRINTF(GPUTLB, "CU%d: DTLB recvReqRetry - %d pending requests\n",
computeUnit->cu_id, len);
assert(len > 0);
assert(isStalled());
// recvReqRetry is an indication that the resource on which this
// port was stalling on is freed. So, remove the stall first
unstallPort();
for (int i = 0; i < len; ++i) {
PacketPtr pkt = retries.front();
Addr vaddr M5_VAR_USED = pkt->req->getVaddr();
DPRINTF(GPUTLB, "CU%d: retrying D-translaton for address%#x", vaddr);
if (!sendTimingReq(pkt)) {
// Stall port
stallPort();
DPRINTF(GPUTLB, ": failed again\n");
break;
} else {
DPRINTF(GPUTLB, ": successful\n");
retries.pop_front();
}
}
}
bool
ComputeUnit::ITLBPort::recvTimingResp(PacketPtr pkt)
{
Addr line M5_VAR_USED = pkt->req->getPaddr();
DPRINTF(GPUTLB, "CU%d: ITLBPort received %#x->%#x\n",
computeUnit->cu_id, pkt->req->getVaddr(), line);
assert(pkt->senderState);
// pop off the TLB translation state
TheISA::GpuTLB::TranslationState *translation_state =
safe_cast<TheISA::GpuTLB::TranslationState*>(pkt->senderState);
bool success = translation_state->tlbEntry->valid;
delete translation_state->tlbEntry;
assert(!translation_state->ports.size());
pkt->senderState = translation_state->saved;
delete translation_state;
// use the original sender state to know how to close this transaction
ITLBPort::SenderState *sender_state =
safe_cast<ITLBPort::SenderState*>(pkt->senderState);
// get the wavefront associated with this translation request
Wavefront *wavefront = sender_state->wavefront;
delete pkt->senderState;
if (success) {
// pkt is reused in fetch(), don't delete it here. However, we must
// reset the command to be a request so that it can be sent through
// the cu's master port
assert(pkt->cmd == MemCmd::ReadResp);
pkt->cmd = MemCmd::ReadReq;
computeUnit->fetchStage.fetch(pkt, wavefront);
} else {
if (wavefront->dropFetch) {
assert(wavefront->instructionBuffer.empty());
wavefront->dropFetch = false;
}
wavefront->pendingFetch = 0;
}
return true;
}
/*
* The initial translation request could have been rejected, if
* <retries> queue is not empty. Retry sending the translation
* request. sendRetry() is called from the peer port whenever
* a translation completes.
*/
void
ComputeUnit::ITLBPort::recvReqRetry()
{
int len = retries.size();
DPRINTF(GPUTLB, "CU%d: ITLB recvReqRetry - %d pending requests\n", len);
assert(len > 0);
assert(isStalled());
// recvReqRetry is an indication that the resource on which this
// port was stalling on is freed. So, remove the stall first
unstallPort();
for (int i = 0; i < len; ++i) {
PacketPtr pkt = retries.front();
Addr vaddr M5_VAR_USED = pkt->req->getVaddr();
DPRINTF(GPUTLB, "CU%d: retrying I-translaton for address%#x", vaddr);
if (!sendTimingReq(pkt)) {
stallPort(); // Stall port
DPRINTF(GPUTLB, ": failed again\n");
break;
} else {
DPRINTF(GPUTLB, ": successful\n");
retries.pop_front();
}
}
}
void
ComputeUnit::regStats()
{
MemObject::regStats();
vALUInsts
.name(name() + ".valu_insts")
.desc("Number of vector ALU insts issued.")
;
vALUInstsPerWF
.name(name() + ".valu_insts_per_wf")
.desc("The avg. number of vector ALU insts issued per-wavefront.")
;
sALUInsts
.name(name() + ".salu_insts")
.desc("Number of scalar ALU insts issued.")
;
sALUInstsPerWF
.name(name() + ".salu_insts_per_wf")
.desc("The avg. number of scalar ALU insts issued per-wavefront.")
;
instCyclesVALU
.name(name() + ".inst_cycles_valu")
.desc("Number of cycles needed to execute VALU insts.")
;
instCyclesSALU
.name(name() + ".inst_cycles_salu")
.desc("Number of cycles needed to execute SALU insts.")
;
threadCyclesVALU
.name(name() + ".thread_cycles_valu")
.desc("Number of thread cycles used to execute vector ALU ops. "
"Similar to instCyclesVALU but multiplied by the number of "
"active threads.")
;
vALUUtilization
.name(name() + ".valu_utilization")
.desc("Percentage of active vector ALU threads in a wave.")
;
ldsNoFlatInsts
.name(name() + ".lds_no_flat_insts")
.desc("Number of LDS insts issued, not including FLAT "
"accesses that resolve to LDS.")
;
ldsNoFlatInstsPerWF
.name(name() + ".lds_no_flat_insts_per_wf")
.desc("The avg. number of LDS insts (not including FLAT "
"accesses that resolve to LDS) per-wavefront.")
;
flatVMemInsts
.name(name() + ".flat_vmem_insts")
.desc("The number of FLAT insts that resolve to vmem issued.")
;
flatVMemInstsPerWF
.name(name() + ".flat_vmem_insts_per_wf")
.desc("The average number of FLAT insts that resolve to vmem "
"issued per-wavefront.")
;
flatLDSInsts
.name(name() + ".flat_lds_insts")
.desc("The number of FLAT insts that resolve to LDS issued.")
;
flatLDSInstsPerWF
.name(name() + ".flat_lds_insts_per_wf")
.desc("The average number of FLAT insts that resolve to LDS "
"issued per-wavefront.")
;
vectorMemWrites
.name(name() + ".vector_mem_writes")
.desc("Number of vector mem write insts (excluding FLAT insts).")
;
vectorMemWritesPerWF
.name(name() + ".vector_mem_writes_per_wf")
.desc("The average number of vector mem write insts "
"(excluding FLAT insts) per-wavefront.")
;
vectorMemReads
.name(name() + ".vector_mem_reads")
.desc("Number of vector mem read insts (excluding FLAT insts).")
;
vectorMemReadsPerWF
.name(name() + ".vector_mem_reads_per_wf")
.desc("The avg. number of vector mem read insts (excluding "
"FLAT insts) per-wavefront.")
;
scalarMemWrites
.name(name() + ".scalar_mem_writes")
.desc("Number of scalar mem write insts.")
;
scalarMemWritesPerWF
.name(name() + ".scalar_mem_writes_per_wf")
.desc("The average number of scalar mem write insts per-wavefront.")
;
scalarMemReads
.name(name() + ".scalar_mem_reads")
.desc("Number of scalar mem read insts.")
;
scalarMemReadsPerWF
.name(name() + ".scalar_mem_reads_per_wf")
.desc("The average number of scalar mem read insts per-wavefront.")
;
vALUInstsPerWF = vALUInsts / completedWfs;
sALUInstsPerWF = sALUInsts / completedWfs;
vALUUtilization = (threadCyclesVALU / (64 * instCyclesVALU)) * 100;
ldsNoFlatInstsPerWF = ldsNoFlatInsts / completedWfs;
flatVMemInstsPerWF = flatVMemInsts / completedWfs;
flatLDSInstsPerWF = flatLDSInsts / completedWfs;
vectorMemWritesPerWF = vectorMemWrites / completedWfs;
vectorMemReadsPerWF = vectorMemReads / completedWfs;
scalarMemWritesPerWF = scalarMemWrites / completedWfs;
scalarMemReadsPerWF = scalarMemReads / completedWfs;
tlbCycles
.name(name() + ".tlb_cycles")
.desc("total number of cycles for all uncoalesced requests")
;
tlbRequests
.name(name() + ".tlb_requests")
.desc("number of uncoalesced requests")
;
tlbLatency
.name(name() + ".avg_translation_latency")
.desc("Avg. translation latency for data translations")
;
tlbLatency = tlbCycles / tlbRequests;
hitsPerTLBLevel
.init(4)
.name(name() + ".TLB_hits_distribution")
.desc("TLB hits distribution (0 for page table, x for Lx-TLB")
;
// fixed number of TLB levels
for (int i = 0; i < 4; ++i) {
if (!i)
hitsPerTLBLevel.subname(i,"page_table");
else
hitsPerTLBLevel.subname(i, csprintf("L%d_TLB",i));
}
execRateDist
.init(0, 10, 2)
.name(name() + ".inst_exec_rate")
.desc("Instruction Execution Rate: Number of executed vector "
"instructions per cycle")
;
ldsBankConflictDist
.init(0, wfSize(), 2)
.name(name() + ".lds_bank_conflicts")
.desc("Number of bank conflicts per LDS memory packet")
;
ldsBankAccesses
.name(name() + ".lds_bank_access_cnt")
.desc("Total number of LDS bank accesses")
;
pageDivergenceDist
// A wavefront can touch up to N pages per memory instruction where
// N is equal to the wavefront size
// The number of pages per bin can be configured (here it's 4).
.init(1, wfSize(), 4)
.name(name() + ".page_divergence_dist")
.desc("pages touched per wf (over all mem. instr.)")
;
controlFlowDivergenceDist
.init(1, wfSize(), 4)
.name(name() + ".warp_execution_dist")
.desc("number of lanes active per instruction (oval all instructions)")
;
activeLanesPerGMemInstrDist
.init(1, wfSize(), 4)
.name(name() + ".gmem_lanes_execution_dist")
.desc("number of active lanes per global memory instruction")
;
activeLanesPerLMemInstrDist
.init(1, wfSize(), 4)
.name(name() + ".lmem_lanes_execution_dist")
.desc("number of active lanes per local memory instruction")
;
numInstrExecuted
.name(name() + ".num_instr_executed")
.desc("number of instructions executed")
;
numVecOpsExecuted
.name(name() + ".num_vec_ops_executed")
.desc("number of vec ops executed (e.g. WF size/inst)")
;
totalCycles
.name(name() + ".num_total_cycles")
.desc("number of cycles the CU ran for")
;
ipc
.name(name() + ".ipc")
.desc("Instructions per cycle (this CU only)")
;
vpc
.name(name() + ".vpc")
.desc("Vector Operations per cycle (this CU only)")
;
numALUInstsExecuted
.name(name() + ".num_alu_insts_executed")
.desc("Number of dynamic non-GM memory insts executed")
;
wgBlockedDueLdsAllocation
.name(name() + ".wg_blocked_due_lds_alloc")
.desc("Workgroup blocked due to LDS capacity")
;
ipc = numInstrExecuted / totalCycles;
vpc = numVecOpsExecuted / totalCycles;
numTimesWgBlockedDueVgprAlloc
.name(name() + ".times_wg_blocked_due_vgpr_alloc")
.desc("Number of times WGs are blocked due to VGPR allocation per SIMD")
;
dynamicGMemInstrCnt
.name(name() + ".global_mem_instr_cnt")
.desc("dynamic global memory instructions count")
;
dynamicLMemInstrCnt
.name(name() + ".local_mem_instr_cnt")
.desc("dynamic local memory intruction count")
;
numALUInstsExecuted = numInstrExecuted - dynamicGMemInstrCnt -
dynamicLMemInstrCnt;
completedWfs
.name(name() + ".num_completed_wfs")
.desc("number of completed wavefronts")
;
numCASOps
.name(name() + ".num_CAS_ops")
.desc("number of compare and swap operations")
;
numFailedCASOps
.name(name() + ".num_failed_CAS_ops")
.desc("number of compare and swap operations that failed")
;
// register stats of pipeline stages
fetchStage.regStats();
scoreboardCheckStage.regStats();
scheduleStage.regStats();
execStage.regStats();
// register stats of memory pipeline
globalMemoryPipe.regStats();
localMemoryPipe.regStats();
}
void
ComputeUnit::updateInstStats(GPUDynInstPtr gpuDynInst)
{
if (gpuDynInst->isScalar()) {
if (gpuDynInst->isALU() && !gpuDynInst->isWaitcnt()) {
sALUInsts++;
instCyclesSALU++;
} else if (gpuDynInst->isLoad()) {
scalarMemReads++;
} else if (gpuDynInst->isStore()) {
scalarMemWrites++;
}
} else {
if (gpuDynInst->isALU()) {
vALUInsts++;
instCyclesVALU++;
threadCyclesVALU += gpuDynInst->wavefront()->execMask().count();
} else if (gpuDynInst->isFlat()) {
if (gpuDynInst->isLocalMem()) {
flatLDSInsts++;
} else {
flatVMemInsts++;
}
} else if (gpuDynInst->isLocalMem()) {
ldsNoFlatInsts++;
} else if (gpuDynInst->isLoad()) {
vectorMemReads++;
} else if (gpuDynInst->isStore()) {
vectorMemWrites++;
}
}
}
void
ComputeUnit::updatePageDivergenceDist(Addr addr)
{
Addr virt_page_addr = roundDown(addr, TheISA::PageBytes);
if (!pagesTouched.count(virt_page_addr))
pagesTouched[virt_page_addr] = 1;
else
pagesTouched[virt_page_addr]++;
}
void
ComputeUnit::CUExitCallback::process()
{
if (computeUnit->countPages) {
std::ostream *page_stat_file =
simout.create(computeUnit->name().c_str())->stream();
*page_stat_file << "page, wavefront accesses, workitem accesses" <<
std::endl;
for (auto iter : computeUnit->pageAccesses) {
*page_stat_file << std::hex << iter.first << ",";
*page_stat_file << std::dec << iter.second.first << ",";
*page_stat_file << std::dec << iter.second.second << std::endl;
}
}
}
bool
ComputeUnit::isDone() const
{
for (int i = 0; i < numSIMDs; ++i) {
if (!isSimdDone(i)) {
return false;
}
}
bool glbMemBusRdy = true;
for (int j = 0; j < numGlbMemUnits; ++j) {
glbMemBusRdy &= vrfToGlobalMemPipeBus[j].rdy();
}
bool locMemBusRdy = true;
for (int j = 0; j < numLocMemUnits; ++j) {
locMemBusRdy &= vrfToLocalMemPipeBus[j].rdy();
}
if (!globalMemoryPipe.isGMLdRespFIFOWrRdy() ||
!globalMemoryPipe.isGMStRespFIFOWrRdy() ||
!globalMemoryPipe.isGMReqFIFOWrRdy() || !localMemoryPipe.isLMReqFIFOWrRdy()
|| !localMemoryPipe.isLMRespFIFOWrRdy() || !locMemToVrfBus.rdy() ||
!glbMemToVrfBus.rdy() || !locMemBusRdy || !glbMemBusRdy) {
return false;
}
return true;
}
int32_t
ComputeUnit::getRefCounter(const uint32_t dispatchId, const uint32_t wgId) const
{
return lds.getRefCounter(dispatchId, wgId);
}
bool
ComputeUnit::isSimdDone(uint32_t simdId) const
{
assert(simdId < numSIMDs);
for (int i=0; i < numGlbMemUnits; ++i) {
if (!vrfToGlobalMemPipeBus[i].rdy())
return false;
}
for (int i=0; i < numLocMemUnits; ++i) {
if (!vrfToLocalMemPipeBus[i].rdy())
return false;
}
if (!aluPipe[simdId].rdy()) {
return false;
}
for (int i_wf = 0; i_wf < shader->n_wf; ++i_wf){
if (wfList[simdId][i_wf]->status != Wavefront::S_STOPPED) {
return false;
}
}
return true;
}
/**
* send a general request to the LDS
* make sure to look at the return value here as your request might be
* NACK'd and returning false means that you have to have some backup plan
*/
bool
ComputeUnit::sendToLds(GPUDynInstPtr gpuDynInst)
{
// this is just a request to carry the GPUDynInstPtr
// back and forth
Request *newRequest = new Request();
newRequest->setPaddr(0x0);
// ReadReq is not evaluted by the LDS but the Packet ctor requires this
PacketPtr newPacket = new Packet(newRequest, MemCmd::ReadReq);
// This is the SenderState needed upon return
newPacket->senderState = new LDSPort::SenderState(gpuDynInst);
return ldsPort->sendTimingReq(newPacket);
}
/**
* get the result of packets sent to the LDS when they return
*/
bool
ComputeUnit::LDSPort::recvTimingResp(PacketPtr packet)
{
const ComputeUnit::LDSPort::SenderState *senderState =
dynamic_cast<ComputeUnit::LDSPort::SenderState *>(packet->senderState);
fatal_if(!senderState, "did not get the right sort of sender state");
GPUDynInstPtr gpuDynInst = senderState->getMemInst();
delete packet->senderState;
delete packet->req;
delete packet;
computeUnit->localMemoryPipe.getLMRespFIFO().push(gpuDynInst);
return true;
}
/**
* attempt to send this packet, either the port is already stalled, the request
* is nack'd and must stall or the request goes through
* when a request cannot be sent, add it to the retries queue
*/
bool
ComputeUnit::LDSPort::sendTimingReq(PacketPtr pkt)
{
ComputeUnit::LDSPort::SenderState *sender_state =
dynamic_cast<ComputeUnit::LDSPort::SenderState*>(pkt->senderState);
fatal_if(!sender_state, "packet without a valid sender state");
GPUDynInstPtr gpuDynInst M5_VAR_USED = sender_state->getMemInst();
if (isStalled()) {
fatal_if(retries.empty(), "must have retries waiting to be stalled");
retries.push(pkt);
DPRINTF(GPUPort, "CU%d: WF[%d][%d]: LDS send failed!\n",
computeUnit->cu_id, gpuDynInst->simdId,
gpuDynInst->wfSlotId);
return false;
} else if (!MasterPort::sendTimingReq(pkt)) {
// need to stall the LDS port until a recvReqRetry() is received
// this indicates that there is more space
stallPort();
retries.push(pkt);
DPRINTF(GPUPort, "CU%d: WF[%d][%d]: addr %#x lds req failed!\n",
computeUnit->cu_id, gpuDynInst->simdId,
gpuDynInst->wfSlotId, pkt->req->getPaddr());
return false;
} else {
DPRINTF(GPUPort, "CU%d: WF[%d][%d]: addr %#x lds req sent!\n",
computeUnit->cu_id, gpuDynInst->simdId,
gpuDynInst->wfSlotId, pkt->req->getPaddr());
return true;
}
}
/**
* the bus is telling the port that there is now space so retrying stalled
* requests should work now
* this allows the port to have a request be nack'd and then have the receiver
* say when there is space, rather than simply retrying the send every cycle
*/
void
ComputeUnit::LDSPort::recvReqRetry()
{
auto queueSize = retries.size();
DPRINTF(GPUPort, "CU%d: LDSPort recvReqRetry - %d pending requests\n",
computeUnit->cu_id, queueSize);
fatal_if(queueSize < 1,
"why was there a recvReqRetry() with no pending reqs?");
fatal_if(!isStalled(),
"recvReqRetry() happened when the port was not stalled");
unstallPort();
while (!retries.empty()) {
PacketPtr packet = retries.front();
DPRINTF(GPUPort, "CU%d: retrying LDS send\n", computeUnit->cu_id);
if (!MasterPort::sendTimingReq(packet)) {
// Stall port
stallPort();
DPRINTF(GPUPort, ": LDS send failed again\n");
break;
} else {
DPRINTF(GPUTLB, ": LDS send successful\n");
retries.pop();
}
}
}
|
.global s_prepare_buffers
s_prepare_buffers:
push %r10
push %r14
push %r15
push %r9
push %rbp
push %rcx
push %rdi
push %rsi
lea addresses_WC_ht+0x27bb, %rsi
lea addresses_WC_ht+0x1b72b, %rdi
nop
xor $5861, %r14
mov $49, %rcx
rep movsq
nop
sub %rsi, %rsi
lea addresses_UC_ht+0x1fbb, %rbp
nop
cmp %rsi, %rsi
mov $0x6162636465666768, %r10
movq %r10, %xmm0
movups %xmm0, (%rbp)
nop
nop
nop
nop
dec %r14
lea addresses_normal_ht+0x1658b, %rsi
lea addresses_WC_ht+0x7153, %rdi
clflush (%rsi)
nop
nop
nop
and $14022, %rbp
mov $102, %rcx
rep movsl
nop
nop
nop
nop
cmp $59074, %rcx
lea addresses_WT_ht+0xfbbb, %r14
sub $12694, %r9
mov $0x6162636465666768, %r10
movq %r10, (%r14)
nop
nop
nop
nop
sub $50331, %r14
lea addresses_UC_ht+0x1bdbb, %r9
cmp %rcx, %rcx
movl $0x61626364, (%r9)
nop
nop
xor $8455, %rcx
lea addresses_normal_ht+0x11bbb, %rdi
dec %rsi
mov $0x6162636465666768, %rbp
movq %rbp, (%rdi)
nop
nop
nop
nop
and $60490, %rdi
lea addresses_D_ht+0x15c3b, %r14
nop
nop
and %r9, %r9
movb (%r14), %r10b
nop
nop
cmp %rcx, %rcx
lea addresses_UC_ht+0xe5fb, %rcx
nop
nop
nop
nop
and $61222, %r9
mov (%rcx), %bp
nop
nop
nop
nop
xor %r9, %r9
lea addresses_UC_ht+0xf85b, %r14
nop
xor $1205, %r9
mov $0x6162636465666768, %rsi
movq %rsi, (%r14)
nop
nop
nop
and %r9, %r9
lea addresses_WT_ht+0x8363, %r9
add %rdi, %rdi
movb $0x61, (%r9)
nop
cmp %r9, %r9
lea addresses_A_ht+0x3bb, %rsi
lea addresses_D_ht+0x1d1bb, %rdi
nop
sub %r15, %r15
mov $0, %rcx
rep movsw
nop
nop
inc %rsi
pop %rsi
pop %rdi
pop %rcx
pop %rbp
pop %r9
pop %r15
pop %r14
pop %r10
ret
.global s_faulty_load
s_faulty_load:
push %r10
push %r11
push %r14
push %r8
push %rax
push %rdx
// Faulty Load
lea addresses_A+0x193bb, %r14
nop
nop
nop
add %r11, %r11
movups (%r14), %xmm1
vpextrq $1, %xmm1, %r8
lea oracles, %r11
and $0xff, %r8
shlq $12, %r8
mov (%r11,%r8,1), %r8
pop %rdx
pop %rax
pop %r8
pop %r14
pop %r11
pop %r10
ret
/*
<gen_faulty_load>
[REF]
{'OP': 'LOAD', 'src': {'type': 'addresses_A', 'size': 16, 'AVXalign': False, 'NT': False, 'congruent': 0, 'same': False}}
[Faulty Load]
{'OP': 'LOAD', 'src': {'type': 'addresses_A', 'size': 16, 'AVXalign': False, 'NT': False, 'congruent': 0, 'same': True}}
<gen_prepare_buffer>
{'OP': 'REPM', 'src': {'type': 'addresses_WC_ht', 'congruent': 10, 'same': False}, 'dst': {'type': 'addresses_WC_ht', 'congruent': 4, 'same': False}}
{'OP': 'STOR', 'dst': {'type': 'addresses_UC_ht', 'size': 16, 'AVXalign': False, 'NT': False, 'congruent': 10, 'same': False}}
{'OP': 'REPM', 'src': {'type': 'addresses_normal_ht', 'congruent': 3, 'same': False}, 'dst': {'type': 'addresses_WC_ht', 'congruent': 3, 'same': False}}
{'OP': 'STOR', 'dst': {'type': 'addresses_WT_ht', 'size': 8, 'AVXalign': False, 'NT': True, 'congruent': 7, 'same': False}}
{'OP': 'STOR', 'dst': {'type': 'addresses_UC_ht', 'size': 4, 'AVXalign': False, 'NT': False, 'congruent': 9, 'same': False}}
{'OP': 'STOR', 'dst': {'type': 'addresses_normal_ht', 'size': 8, 'AVXalign': False, 'NT': False, 'congruent': 11, 'same': False}}
{'OP': 'LOAD', 'src': {'type': 'addresses_D_ht', 'size': 1, 'AVXalign': True, 'NT': False, 'congruent': 3, 'same': True}}
{'OP': 'LOAD', 'src': {'type': 'addresses_UC_ht', 'size': 2, 'AVXalign': False, 'NT': False, 'congruent': 5, 'same': False}}
{'OP': 'STOR', 'dst': {'type': 'addresses_UC_ht', 'size': 8, 'AVXalign': True, 'NT': True, 'congruent': 5, 'same': False}}
{'OP': 'STOR', 'dst': {'type': 'addresses_WT_ht', 'size': 1, 'AVXalign': False, 'NT': False, 'congruent': 3, 'same': False}}
{'OP': 'REPM', 'src': {'type': 'addresses_A_ht', 'congruent': 11, 'same': False}, 'dst': {'type': 'addresses_D_ht', 'congruent': 8, 'same': False}}
{'35': 21829}
35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35
*/
|
segment .text
global sum
sum:
push B
push A
call test
enter 0,0
mov EAX,[EBP+8]
add EAX,[EBP+12]
leave
ret |
;
; Emulate CP/M BDOS calls 2 and 9
;
ioport equ 1
;
;
.8080
;
.org 0000h
hlt ; Halt on warm reboot
;
.org 0005h
jmp bdos
;
.org 0f000h
bdos:
mov a,c
cpi 2
jz outc
cpi 9
jz outs
ret
;
;
outc:
mov a,e
out ioport
ret
;
;
outs:
ldax d
cpi '$'
rz
out ioport
inx d
jmp outs
; |
//==================================================================================================
/*!
@file
Copyright 2016 NumScale SAS
Distributed under the Boost Software License, Version 1.0.
(See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt)
*/
//==================================================================================================
#include <boost/simd/pack.hpp>
#include <boost/simd/function/maxnum.hpp>
#include <boost/simd/constant/nan.hpp>
#include <boost/simd/constant/one.hpp>
#include <boost/simd/meta/cardinal_of.hpp>
#include <simd_test.hpp>
template <typename T, std::size_t N, typename Env>
void test(Env& runtime)
{
namespace bs = boost::simd;
using p_t = bs::pack<T, N>;
T a1[N], a2[N], b[N];
for(std::size_t i = 0; i < N; ++i)
{
a1[i] = (i%2) ? T(i) : T(-i);
a2[i] = (i%2) ? T(i+N) : T(-(i+N));
b[i] = bs::maxnum(a1[i], a2[i]);
}
p_t aa1(&a1[0], &a1[0]+N);
p_t aa2(&a2[0], &a2[0]+N);
p_t bb(&b[0], &b[0]+N);
STF_IEEE_EQUAL(bs::maxnum(aa1, aa2), bb);
}
STF_CASE_TPL("Check maxnum on pack" , STF_NUMERIC_TYPES)
{
namespace bs = boost::simd;
using p_t = bs::pack<T>;
static const std::size_t N = bs::cardinal_of<p_t>::value;
test<T, N>(runtime);
test<T, N/2>(runtime);
test<T, N*2>(runtime);
}
STF_CASE_TPL("Check maxnum on nans pack" , STF_IEEE_TYPES)
{
namespace bs = boost::simd;
static const std::size_t N = bs::pack<T>::static_size;
{
using p_t = bs::pack<T, N>;
p_t n = bs::Nan<p_t>();
p_t o = bs::One<p_t>();
STF_IEEE_EQUAL(bs::maxnum(n, o), o);
STF_IEEE_EQUAL(bs::maxnum(o, n), o);
}
}
|
#include <mbgl/platform/log.hpp>
#include <mbgl/storage/file_source.hpp>
#include <mbgl/style/conversion/geojson.hpp>
#include <mbgl/style/source_observer.hpp>
#include <mbgl/style/sources/geojson_source_impl.hpp>
#include <mbgl/tile/geojson_tile.hpp>
#include <mbgl/util/rapidjson.hpp>
#include <mapbox/geojson.hpp>
#include <mapbox/geojson/rapidjson.hpp>
#include <mapbox/geojsonvt.hpp>
#include <mapbox/geojsonvt/convert.hpp>
#include <supercluster.hpp>
#include <rapidjson/error/en.h>
#include <sstream>
namespace mbgl {
namespace style {
namespace conversion {
template <>
Result<GeoJSON> convertGeoJSON(const JSValue& value) {
try {
return mapbox::geojson::convert(value);
} catch (const std::exception& ex) {
return Error{ ex.what() };
}
}
} // namespace conversion
GeoJSONSource::Impl::Impl(std::string id_, Source& base_, const GeoJSONOptions options_)
: Source::Impl(SourceType::GeoJSON, std::move(id_), base_), options(options_) {
}
GeoJSONSource::Impl::~Impl() = default;
void GeoJSONSource::Impl::setURL(std::string url) {
urlOrGeoJSON = std::move(url);
}
std::string GeoJSONSource::Impl::getURL() {
assert(urlOrGeoJSON.is<std::string>());
return urlOrGeoJSON.get<std::string>();
}
void GeoJSONSource::Impl::setGeoJSON(const GeoJSON& geoJSON) {
double scale = util::EXTENT / util::tileSize;
if (!options.cluster) {
mapbox::geojsonvt::Options vtOptions;
vtOptions.maxZoom = options.maxzoom;
vtOptions.extent = util::EXTENT;
vtOptions.buffer = std::round(scale * options.buffer);
vtOptions.tolerance = scale * options.tolerance;
urlOrGeoJSON = std::make_unique<mapbox::geojsonvt::GeoJSONVT>(geoJSON, vtOptions);
} else {
mapbox::supercluster::Options clusterOptions;
clusterOptions.maxZoom = options.clusterMaxZoom;
clusterOptions.extent = util::EXTENT;
clusterOptions.radius = std::round(scale * options.clusterRadius);
const auto& features = geoJSON.get<mapbox::geometry::feature_collection<double>>();
urlOrGeoJSON =
std::make_unique<mapbox::supercluster::Supercluster>(features, clusterOptions);
}
}
void GeoJSONSource::Impl::load(FileSource& fileSource) {
if (!urlOrGeoJSON.is<std::string>()) {
loaded = true;
return;
}
if (req) {
return;
}
const std::string& url = urlOrGeoJSON.get<std::string>();
req = fileSource.request(Resource::source(url), [this](Response res) {
if (res.error) {
observer->onSourceError(
base, std::make_exception_ptr(std::runtime_error(res.error->message)));
} else if (res.notModified) {
return;
} else if (res.noContent) {
observer->onSourceError(
base, std::make_exception_ptr(std::runtime_error("unexpectedly empty GeoJSON")));
} else {
rapidjson::GenericDocument<rapidjson::UTF8<>, rapidjson::CrtAllocator> d;
d.Parse<0>(res.data->c_str());
if (d.HasParseError()) {
std::stringstream message;
message << d.GetErrorOffset() << " - "
<< rapidjson::GetParseError_En(d.GetParseError());
observer->onSourceError(base,
std::make_exception_ptr(std::runtime_error(message.str())));
return;
}
invalidateTiles();
conversion::Result<GeoJSON> geoJSON = conversion::convertGeoJSON<JSValue>(d);
if (!geoJSON) {
Log::Error(Event::ParseStyle, "Failed to parse GeoJSON data: %s",
geoJSON.error().message.c_str());
// Create an empty GeoJSON VT object to make sure we're not infinitely waiting for
// tiles to load.
setGeoJSON(GeoJSON{ FeatureCollection{} });
} else {
setGeoJSON(*geoJSON);
}
loaded = true;
observer->onSourceLoaded(base);
}
});
}
Range<uint8_t> GeoJSONSource::Impl::getZoomRange() {
assert(loaded);
return { 0, options.maxzoom };
}
std::unique_ptr<Tile> GeoJSONSource::Impl::createTile(const OverscaledTileID& tileID,
const UpdateParameters& parameters) {
assert(loaded);
if (urlOrGeoJSON.is<GeoJSONVTPointer>()) {
return std::make_unique<GeoJSONTile>(tileID, base.getID(), parameters,
*urlOrGeoJSON.get<GeoJSONVTPointer>());
} else {
assert(urlOrGeoJSON.is<SuperclusterPointer>());
return std::make_unique<GeoJSONTile>(tileID, base.getID(), parameters,
*urlOrGeoJSON.get<SuperclusterPointer>());
}
}
} // namespace style
} // namespace mbgl
|
; ******************************************************************************
; ******************************************************************************
;
; Name : unary.asm
; Purpose : Unary functions
; Author : Paul Robson (paul@robsons.org.uk)
; Created : 12th November 2019
;
; ******************************************************************************
; ******************************************************************************
; ******************************************************************************
;
; Unary Absolute
;
; ******************************************************************************
Unary_Absolute: ;; [abs]
StartCommand
lda highStack,x
bmi Unary_Negate_Code
NextCommand
; ******************************************************************************
;
; Unary Negation
;
; ******************************************************************************
Unary_Negate: ;; [negate]
StartCommand
Unary_Negate_Code:
sec
lda #0
sbc lowStack,x
sta lowStack,x
;
lda #0
sbc highStack,x
sta highStack,x
NextCommand
; ******************************************************************************
;
; Unary 1's Complement
;
; ******************************************************************************
Unary_Not: ;; [not]
StartCommand
lda lowStack,x
eor #$FF
sta lowStack,x
;
lda highStack,x
eor #$FF
sta highStack,x
NextCommand
; ******************************************************************************
;
; Unary Increment
;
; ******************************************************************************
Unary_Increment: ;; [++]
StartCommand
inc lowStack,x
bne _UIExit
inc highStack,x
_UIExit:
NextCommand
; ******************************************************************************
;
; Unary Increment
;
; ******************************************************************************
Unary_Decrement: ;; [--]
StartCommand
lda lowStack,x
bne _UDNoBorrow
dec highStack,x
_UDNoBorrow:
dec lowStack,x
NextCommand
; ******************************************************************************
;
; Byte Swap
;
; ******************************************************************************
Unary_BSwap: ;; [bswap]
StartCommand
lda lowStack,x
pha
lda highStack,x
sta lowStack,x
pla
sta highStack,x
NextCommand
; ******************************************************************************
;
; Left Shift Logical
;
; ******************************************************************************
Unary_Shl: ;; [<<]
StartCommand
asl lowStack,x
rol highStack,x
NextCommand
; ******************************************************************************
;
; Right Shift Logical
;
; ******************************************************************************
Unary_Shr: ;; [>>]
StartCommand
lsr highStack,x
ror lowStack,x
NextCommand
; ******************************************************************************
;
; Sign of TOS
;
; ******************************************************************************
Unary_Sgn: ;; [sgn]
StartCommand
lda highStack,x ; check bit 7.
bpl _USNotNeg
lda #$FF ; if -ve set to -1
sta lowStack,x
sta highStack,x
bra _USExit
;
_USNotNeg:
ora lowStack,x ; A = Low|High
stz lowStack,x ; Zero result
stz highStack,x
cmp #0 ; if 0 return 0
beq _USExit
inc lowStack,x ; else return 1.
_USExit:
NextCommand
; ******************************************************************************
;
; Unary Random Number Generator
;
; ******************************************************************************
Random_Handler: ;; [rnd]
StartCommand
lda randomSeed
ora randomSeed+1
bne _RH_NoInit
lda #$7C
sta randomSeed
lda #$A1
sta randomSeed+1
_RH_NoInit:
lda randomSeed
lsr a
rol randomSeed+1
bcc _RH_NoEor
eor #$B4
_RH_NoEor:
sta randomSeed
eor randomSeed+1
;
inx
sta highStack,x
lda randomSeed
sta lowStack,x
NextCommand
|
; A135318: a(n) = a(n-2) + 2*a(n-4), with a[0..3] = [1, 1, 1, 2].
; 1,1,1,2,3,4,5,8,11,16,21,32,43,64,85,128,171,256,341,512,683,1024,1365,2048,2731,4096,5461,8192,10923,16384,21845,32768,43691,65536,87381,131072,174763,262144,349525,524288,699051,1048576,1398101,2097152,2796203,4194304,5592405,8388608,11184811,16777216,22369621,33554432,44739243,67108864,89478485,134217728,178956971,268435456,357913941,536870912,715827883,1073741824,1431655765,2147483648,2863311531,4294967296,5726623061,8589934592,11453246123,17179869184,22906492245,34359738368,45812984491
seq $0,209721 ; 1/4 the number of (n+1) X 3 0..2 arrays with every 2 X 2 subblock having distinct clockwise edge differences.
div $0,3
|
_usertests๏ผ ๆไปถๆ ผๅผ elf32-i386
Disassembly of section .text:
00000000 <opentest>:
// simple file system tests
void
opentest(void)
{
0: 55 push %ebp
1: 89 e5 mov %esp,%ebp
3: 83 ec 18 sub $0x18,%esp
int fd;
printf(stdout, "open test\n");
6: a1 a4 5e 00 00 mov 0x5ea4,%eax
b: 83 ec 08 sub $0x8,%esp
e: 68 66 41 00 00 push $0x4166
13: 50 push %eax
14: e8 81 3d 00 00 call 3d9a <printf>
19: 83 c4 10 add $0x10,%esp
fd = open("echo", 0);
1c: 83 ec 08 sub $0x8,%esp
1f: 6a 00 push $0x0
21: 68 50 41 00 00 push $0x4150
26: e8 18 3c 00 00 call 3c43 <open>
2b: 83 c4 10 add $0x10,%esp
2e: 89 45 f4 mov %eax,-0xc(%ebp)
if(fd < 0){
31: 83 7d f4 00 cmpl $0x0,-0xc(%ebp)
35: 79 1b jns 52 <opentest+0x52>
printf(stdout, "open echo failed!\n");
37: a1 a4 5e 00 00 mov 0x5ea4,%eax
3c: 83 ec 08 sub $0x8,%esp
3f: 68 71 41 00 00 push $0x4171
44: 50 push %eax
45: e8 50 3d 00 00 call 3d9a <printf>
4a: 83 c4 10 add $0x10,%esp
exit();
4d: e8 b1 3b 00 00 call 3c03 <exit>
}
close(fd);
52: 83 ec 0c sub $0xc,%esp
55: ff 75 f4 pushl -0xc(%ebp)
58: e8 ce 3b 00 00 call 3c2b <close>
5d: 83 c4 10 add $0x10,%esp
fd = open("doesnotexist", 0);
60: 83 ec 08 sub $0x8,%esp
63: 6a 00 push $0x0
65: 68 84 41 00 00 push $0x4184
6a: e8 d4 3b 00 00 call 3c43 <open>
6f: 83 c4 10 add $0x10,%esp
72: 89 45 f4 mov %eax,-0xc(%ebp)
if(fd >= 0){
75: 83 7d f4 00 cmpl $0x0,-0xc(%ebp)
79: 78 1b js 96 <opentest+0x96>
printf(stdout, "open doesnotexist succeeded!\n");
7b: a1 a4 5e 00 00 mov 0x5ea4,%eax
80: 83 ec 08 sub $0x8,%esp
83: 68 91 41 00 00 push $0x4191
88: 50 push %eax
89: e8 0c 3d 00 00 call 3d9a <printf>
8e: 83 c4 10 add $0x10,%esp
exit();
91: e8 6d 3b 00 00 call 3c03 <exit>
}
printf(stdout, "open test ok\n");
96: a1 a4 5e 00 00 mov 0x5ea4,%eax
9b: 83 ec 08 sub $0x8,%esp
9e: 68 af 41 00 00 push $0x41af
a3: 50 push %eax
a4: e8 f1 3c 00 00 call 3d9a <printf>
a9: 83 c4 10 add $0x10,%esp
}
ac: 90 nop
ad: c9 leave
ae: c3 ret
000000af <writetest>:
void
writetest(void)
{
af: 55 push %ebp
b0: 89 e5 mov %esp,%ebp
b2: 83 ec 18 sub $0x18,%esp
int fd;
int i;
printf(stdout, "small file test\n");
b5: a1 a4 5e 00 00 mov 0x5ea4,%eax
ba: 83 ec 08 sub $0x8,%esp
bd: 68 bd 41 00 00 push $0x41bd
c2: 50 push %eax
c3: e8 d2 3c 00 00 call 3d9a <printf>
c8: 83 c4 10 add $0x10,%esp
fd = open("small", O_CREATE|O_RDWR);
cb: 83 ec 08 sub $0x8,%esp
ce: 68 02 02 00 00 push $0x202
d3: 68 ce 41 00 00 push $0x41ce
d8: e8 66 3b 00 00 call 3c43 <open>
dd: 83 c4 10 add $0x10,%esp
e0: 89 45 f0 mov %eax,-0x10(%ebp)
if(fd >= 0){
e3: 83 7d f0 00 cmpl $0x0,-0x10(%ebp)
e7: 78 22 js 10b <writetest+0x5c>
printf(stdout, "creat small succeeded; ok\n");
e9: a1 a4 5e 00 00 mov 0x5ea4,%eax
ee: 83 ec 08 sub $0x8,%esp
f1: 68 d4 41 00 00 push $0x41d4
f6: 50 push %eax
f7: e8 9e 3c 00 00 call 3d9a <printf>
fc: 83 c4 10 add $0x10,%esp
} else {
printf(stdout, "error: creat small failed!\n");
exit();
}
for(i = 0; i < 100; i++){
ff: c7 45 f4 00 00 00 00 movl $0x0,-0xc(%ebp)
106: e9 8f 00 00 00 jmp 19a <writetest+0xeb>
printf(stdout, "small file test\n");
fd = open("small", O_CREATE|O_RDWR);
if(fd >= 0){
printf(stdout, "creat small succeeded; ok\n");
} else {
printf(stdout, "error: creat small failed!\n");
10b: a1 a4 5e 00 00 mov 0x5ea4,%eax
110: 83 ec 08 sub $0x8,%esp
113: 68 ef 41 00 00 push $0x41ef
118: 50 push %eax
119: e8 7c 3c 00 00 call 3d9a <printf>
11e: 83 c4 10 add $0x10,%esp
exit();
121: e8 dd 3a 00 00 call 3c03 <exit>
}
for(i = 0; i < 100; i++){
if(write(fd, "aaaaaaaaaa", 10) != 10){
126: 83 ec 04 sub $0x4,%esp
129: 6a 0a push $0xa
12b: 68 0b 42 00 00 push $0x420b
130: ff 75 f0 pushl -0x10(%ebp)
133: e8 eb 3a 00 00 call 3c23 <write>
138: 83 c4 10 add $0x10,%esp
13b: 83 f8 0a cmp $0xa,%eax
13e: 74 1e je 15e <writetest+0xaf>
printf(stdout, "error: write aa %d new file failed\n", i);
140: a1 a4 5e 00 00 mov 0x5ea4,%eax
145: 83 ec 04 sub $0x4,%esp
148: ff 75 f4 pushl -0xc(%ebp)
14b: 68 18 42 00 00 push $0x4218
150: 50 push %eax
151: e8 44 3c 00 00 call 3d9a <printf>
156: 83 c4 10 add $0x10,%esp
exit();
159: e8 a5 3a 00 00 call 3c03 <exit>
}
if(write(fd, "bbbbbbbbbb", 10) != 10){
15e: 83 ec 04 sub $0x4,%esp
161: 6a 0a push $0xa
163: 68 3c 42 00 00 push $0x423c
168: ff 75 f0 pushl -0x10(%ebp)
16b: e8 b3 3a 00 00 call 3c23 <write>
170: 83 c4 10 add $0x10,%esp
173: 83 f8 0a cmp $0xa,%eax
176: 74 1e je 196 <writetest+0xe7>
printf(stdout, "error: write bb %d new file failed\n", i);
178: a1 a4 5e 00 00 mov 0x5ea4,%eax
17d: 83 ec 04 sub $0x4,%esp
180: ff 75 f4 pushl -0xc(%ebp)
183: 68 48 42 00 00 push $0x4248
188: 50 push %eax
189: e8 0c 3c 00 00 call 3d9a <printf>
18e: 83 c4 10 add $0x10,%esp
exit();
191: e8 6d 3a 00 00 call 3c03 <exit>
printf(stdout, "creat small succeeded; ok\n");
} else {
printf(stdout, "error: creat small failed!\n");
exit();
}
for(i = 0; i < 100; i++){
196: 83 45 f4 01 addl $0x1,-0xc(%ebp)
19a: 83 7d f4 63 cmpl $0x63,-0xc(%ebp)
19e: 7e 86 jle 126 <writetest+0x77>
if(write(fd, "bbbbbbbbbb", 10) != 10){
printf(stdout, "error: write bb %d new file failed\n", i);
exit();
}
}
printf(stdout, "writes ok\n");
1a0: a1 a4 5e 00 00 mov 0x5ea4,%eax
1a5: 83 ec 08 sub $0x8,%esp
1a8: 68 6c 42 00 00 push $0x426c
1ad: 50 push %eax
1ae: e8 e7 3b 00 00 call 3d9a <printf>
1b3: 83 c4 10 add $0x10,%esp
close(fd);
1b6: 83 ec 0c sub $0xc,%esp
1b9: ff 75 f0 pushl -0x10(%ebp)
1bc: e8 6a 3a 00 00 call 3c2b <close>
1c1: 83 c4 10 add $0x10,%esp
fd = open("small", O_RDONLY);
1c4: 83 ec 08 sub $0x8,%esp
1c7: 6a 00 push $0x0
1c9: 68 ce 41 00 00 push $0x41ce
1ce: e8 70 3a 00 00 call 3c43 <open>
1d3: 83 c4 10 add $0x10,%esp
1d6: 89 45 f0 mov %eax,-0x10(%ebp)
if(fd >= 0){
1d9: 83 7d f0 00 cmpl $0x0,-0x10(%ebp)
1dd: 78 3c js 21b <writetest+0x16c>
printf(stdout, "open small succeeded ok\n");
1df: a1 a4 5e 00 00 mov 0x5ea4,%eax
1e4: 83 ec 08 sub $0x8,%esp
1e7: 68 77 42 00 00 push $0x4277
1ec: 50 push %eax
1ed: e8 a8 3b 00 00 call 3d9a <printf>
1f2: 83 c4 10 add $0x10,%esp
} else {
printf(stdout, "error: open small failed!\n");
exit();
}
i = read(fd, buf, 2000);
1f5: 83 ec 04 sub $0x4,%esp
1f8: 68 d0 07 00 00 push $0x7d0
1fd: 68 80 86 00 00 push $0x8680
202: ff 75 f0 pushl -0x10(%ebp)
205: e8 11 3a 00 00 call 3c1b <read>
20a: 83 c4 10 add $0x10,%esp
20d: 89 45 f4 mov %eax,-0xc(%ebp)
if(i == 2000){
210: 81 7d f4 d0 07 00 00 cmpl $0x7d0,-0xc(%ebp)
217: 75 57 jne 270 <writetest+0x1c1>
219: eb 1b jmp 236 <writetest+0x187>
close(fd);
fd = open("small", O_RDONLY);
if(fd >= 0){
printf(stdout, "open small succeeded ok\n");
} else {
printf(stdout, "error: open small failed!\n");
21b: a1 a4 5e 00 00 mov 0x5ea4,%eax
220: 83 ec 08 sub $0x8,%esp
223: 68 90 42 00 00 push $0x4290
228: 50 push %eax
229: e8 6c 3b 00 00 call 3d9a <printf>
22e: 83 c4 10 add $0x10,%esp
exit();
231: e8 cd 39 00 00 call 3c03 <exit>
}
i = read(fd, buf, 2000);
if(i == 2000){
printf(stdout, "read succeeded ok\n");
236: a1 a4 5e 00 00 mov 0x5ea4,%eax
23b: 83 ec 08 sub $0x8,%esp
23e: 68 ab 42 00 00 push $0x42ab
243: 50 push %eax
244: e8 51 3b 00 00 call 3d9a <printf>
249: 83 c4 10 add $0x10,%esp
} else {
printf(stdout, "read failed\n");
exit();
}
close(fd);
24c: 83 ec 0c sub $0xc,%esp
24f: ff 75 f0 pushl -0x10(%ebp)
252: e8 d4 39 00 00 call 3c2b <close>
257: 83 c4 10 add $0x10,%esp
if(unlink("small") < 0){
25a: 83 ec 0c sub $0xc,%esp
25d: 68 ce 41 00 00 push $0x41ce
262: e8 ec 39 00 00 call 3c53 <unlink>
267: 83 c4 10 add $0x10,%esp
26a: 85 c0 test %eax,%eax
26c: 79 38 jns 2a6 <writetest+0x1f7>
26e: eb 1b jmp 28b <writetest+0x1dc>
}
i = read(fd, buf, 2000);
if(i == 2000){
printf(stdout, "read succeeded ok\n");
} else {
printf(stdout, "read failed\n");
270: a1 a4 5e 00 00 mov 0x5ea4,%eax
275: 83 ec 08 sub $0x8,%esp
278: 68 be 42 00 00 push $0x42be
27d: 50 push %eax
27e: e8 17 3b 00 00 call 3d9a <printf>
283: 83 c4 10 add $0x10,%esp
exit();
286: e8 78 39 00 00 call 3c03 <exit>
}
close(fd);
if(unlink("small") < 0){
printf(stdout, "unlink small failed\n");
28b: a1 a4 5e 00 00 mov 0x5ea4,%eax
290: 83 ec 08 sub $0x8,%esp
293: 68 cb 42 00 00 push $0x42cb
298: 50 push %eax
299: e8 fc 3a 00 00 call 3d9a <printf>
29e: 83 c4 10 add $0x10,%esp
exit();
2a1: e8 5d 39 00 00 call 3c03 <exit>
}
printf(stdout, "small file test ok\n");
2a6: a1 a4 5e 00 00 mov 0x5ea4,%eax
2ab: 83 ec 08 sub $0x8,%esp
2ae: 68 e0 42 00 00 push $0x42e0
2b3: 50 push %eax
2b4: e8 e1 3a 00 00 call 3d9a <printf>
2b9: 83 c4 10 add $0x10,%esp
}
2bc: 90 nop
2bd: c9 leave
2be: c3 ret
000002bf <writetest1>:
void
writetest1(void)
{
2bf: 55 push %ebp
2c0: 89 e5 mov %esp,%ebp
2c2: 83 ec 18 sub $0x18,%esp
int i, fd, n;
printf(stdout, "big files test\n");
2c5: a1 a4 5e 00 00 mov 0x5ea4,%eax
2ca: 83 ec 08 sub $0x8,%esp
2cd: 68 f4 42 00 00 push $0x42f4
2d2: 50 push %eax
2d3: e8 c2 3a 00 00 call 3d9a <printf>
2d8: 83 c4 10 add $0x10,%esp
fd = open("big", O_CREATE|O_RDWR);
2db: 83 ec 08 sub $0x8,%esp
2de: 68 02 02 00 00 push $0x202
2e3: 68 04 43 00 00 push $0x4304
2e8: e8 56 39 00 00 call 3c43 <open>
2ed: 83 c4 10 add $0x10,%esp
2f0: 89 45 ec mov %eax,-0x14(%ebp)
if(fd < 0){
2f3: 83 7d ec 00 cmpl $0x0,-0x14(%ebp)
2f7: 79 1b jns 314 <writetest1+0x55>
printf(stdout, "error: creat big failed!\n");
2f9: a1 a4 5e 00 00 mov 0x5ea4,%eax
2fe: 83 ec 08 sub $0x8,%esp
301: 68 08 43 00 00 push $0x4308
306: 50 push %eax
307: e8 8e 3a 00 00 call 3d9a <printf>
30c: 83 c4 10 add $0x10,%esp
exit();
30f: e8 ef 38 00 00 call 3c03 <exit>
}
for(i = 0; i < MAXFILE; i++){
314: c7 45 f4 00 00 00 00 movl $0x0,-0xc(%ebp)
31b: eb 4b jmp 368 <writetest1+0xa9>
((int*)buf)[0] = i;
31d: ba 80 86 00 00 mov $0x8680,%edx
322: 8b 45 f4 mov -0xc(%ebp),%eax
325: 89 02 mov %eax,(%edx)
if(write(fd, buf, 512) != 512){
327: 83 ec 04 sub $0x4,%esp
32a: 68 00 02 00 00 push $0x200
32f: 68 80 86 00 00 push $0x8680
334: ff 75 ec pushl -0x14(%ebp)
337: e8 e7 38 00 00 call 3c23 <write>
33c: 83 c4 10 add $0x10,%esp
33f: 3d 00 02 00 00 cmp $0x200,%eax
344: 74 1e je 364 <writetest1+0xa5>
printf(stdout, "error: write big file failed\n", i);
346: a1 a4 5e 00 00 mov 0x5ea4,%eax
34b: 83 ec 04 sub $0x4,%esp
34e: ff 75 f4 pushl -0xc(%ebp)
351: 68 22 43 00 00 push $0x4322
356: 50 push %eax
357: e8 3e 3a 00 00 call 3d9a <printf>
35c: 83 c4 10 add $0x10,%esp
exit();
35f: e8 9f 38 00 00 call 3c03 <exit>
if(fd < 0){
printf(stdout, "error: creat big failed!\n");
exit();
}
for(i = 0; i < MAXFILE; i++){
364: 83 45 f4 01 addl $0x1,-0xc(%ebp)
368: 8b 45 f4 mov -0xc(%ebp),%eax
36b: 3d 8b 00 00 00 cmp $0x8b,%eax
370: 76 ab jbe 31d <writetest1+0x5e>
printf(stdout, "error: write big file failed\n", i);
exit();
}
}
close(fd);
372: 83 ec 0c sub $0xc,%esp
375: ff 75 ec pushl -0x14(%ebp)
378: e8 ae 38 00 00 call 3c2b <close>
37d: 83 c4 10 add $0x10,%esp
fd = open("big", O_RDONLY);
380: 83 ec 08 sub $0x8,%esp
383: 6a 00 push $0x0
385: 68 04 43 00 00 push $0x4304
38a: e8 b4 38 00 00 call 3c43 <open>
38f: 83 c4 10 add $0x10,%esp
392: 89 45 ec mov %eax,-0x14(%ebp)
if(fd < 0){
395: 83 7d ec 00 cmpl $0x0,-0x14(%ebp)
399: 79 1b jns 3b6 <writetest1+0xf7>
printf(stdout, "error: open big failed!\n");
39b: a1 a4 5e 00 00 mov 0x5ea4,%eax
3a0: 83 ec 08 sub $0x8,%esp
3a3: 68 40 43 00 00 push $0x4340
3a8: 50 push %eax
3a9: e8 ec 39 00 00 call 3d9a <printf>
3ae: 83 c4 10 add $0x10,%esp
exit();
3b1: e8 4d 38 00 00 call 3c03 <exit>
}
n = 0;
3b6: c7 45 f0 00 00 00 00 movl $0x0,-0x10(%ebp)
for(;;){
i = read(fd, buf, 512);
3bd: 83 ec 04 sub $0x4,%esp
3c0: 68 00 02 00 00 push $0x200
3c5: 68 80 86 00 00 push $0x8680
3ca: ff 75 ec pushl -0x14(%ebp)
3cd: e8 49 38 00 00 call 3c1b <read>
3d2: 83 c4 10 add $0x10,%esp
3d5: 89 45 f4 mov %eax,-0xc(%ebp)
if(i == 0){
3d8: 83 7d f4 00 cmpl $0x0,-0xc(%ebp)
3dc: 75 27 jne 405 <writetest1+0x146>
if(n == MAXFILE - 1){
3de: 81 7d f0 8b 00 00 00 cmpl $0x8b,-0x10(%ebp)
3e5: 75 7d jne 464 <writetest1+0x1a5>
printf(stdout, "read only %d blocks from big", n);
3e7: a1 a4 5e 00 00 mov 0x5ea4,%eax
3ec: 83 ec 04 sub $0x4,%esp
3ef: ff 75 f0 pushl -0x10(%ebp)
3f2: 68 59 43 00 00 push $0x4359
3f7: 50 push %eax
3f8: e8 9d 39 00 00 call 3d9a <printf>
3fd: 83 c4 10 add $0x10,%esp
exit();
400: e8 fe 37 00 00 call 3c03 <exit>
}
break;
} else if(i != 512){
405: 81 7d f4 00 02 00 00 cmpl $0x200,-0xc(%ebp)
40c: 74 1e je 42c <writetest1+0x16d>
printf(stdout, "read failed %d\n", i);
40e: a1 a4 5e 00 00 mov 0x5ea4,%eax
413: 83 ec 04 sub $0x4,%esp
416: ff 75 f4 pushl -0xc(%ebp)
419: 68 76 43 00 00 push $0x4376
41e: 50 push %eax
41f: e8 76 39 00 00 call 3d9a <printf>
424: 83 c4 10 add $0x10,%esp
exit();
427: e8 d7 37 00 00 call 3c03 <exit>
}
if(((int*)buf)[0] != n){
42c: b8 80 86 00 00 mov $0x8680,%eax
431: 8b 00 mov (%eax),%eax
433: 3b 45 f0 cmp -0x10(%ebp),%eax
436: 74 23 je 45b <writetest1+0x19c>
printf(stdout, "read content of block %d is %d\n",
n, ((int*)buf)[0]);
438: b8 80 86 00 00 mov $0x8680,%eax
} else if(i != 512){
printf(stdout, "read failed %d\n", i);
exit();
}
if(((int*)buf)[0] != n){
printf(stdout, "read content of block %d is %d\n",
43d: 8b 10 mov (%eax),%edx
43f: a1 a4 5e 00 00 mov 0x5ea4,%eax
444: 52 push %edx
445: ff 75 f0 pushl -0x10(%ebp)
448: 68 88 43 00 00 push $0x4388
44d: 50 push %eax
44e: e8 47 39 00 00 call 3d9a <printf>
453: 83 c4 10 add $0x10,%esp
n, ((int*)buf)[0]);
exit();
456: e8 a8 37 00 00 call 3c03 <exit>
}
n++;
45b: 83 45 f0 01 addl $0x1,-0x10(%ebp)
}
45f: e9 59 ff ff ff jmp 3bd <writetest1+0xfe>
if(i == 0){
if(n == MAXFILE - 1){
printf(stdout, "read only %d blocks from big", n);
exit();
}
break;
464: 90 nop
n, ((int*)buf)[0]);
exit();
}
n++;
}
close(fd);
465: 83 ec 0c sub $0xc,%esp
468: ff 75 ec pushl -0x14(%ebp)
46b: e8 bb 37 00 00 call 3c2b <close>
470: 83 c4 10 add $0x10,%esp
if(unlink("big") < 0){
473: 83 ec 0c sub $0xc,%esp
476: 68 04 43 00 00 push $0x4304
47b: e8 d3 37 00 00 call 3c53 <unlink>
480: 83 c4 10 add $0x10,%esp
483: 85 c0 test %eax,%eax
485: 79 1b jns 4a2 <writetest1+0x1e3>
printf(stdout, "unlink big failed\n");
487: a1 a4 5e 00 00 mov 0x5ea4,%eax
48c: 83 ec 08 sub $0x8,%esp
48f: 68 a8 43 00 00 push $0x43a8
494: 50 push %eax
495: e8 00 39 00 00 call 3d9a <printf>
49a: 83 c4 10 add $0x10,%esp
exit();
49d: e8 61 37 00 00 call 3c03 <exit>
}
printf(stdout, "big files ok\n");
4a2: a1 a4 5e 00 00 mov 0x5ea4,%eax
4a7: 83 ec 08 sub $0x8,%esp
4aa: 68 bb 43 00 00 push $0x43bb
4af: 50 push %eax
4b0: e8 e5 38 00 00 call 3d9a <printf>
4b5: 83 c4 10 add $0x10,%esp
}
4b8: 90 nop
4b9: c9 leave
4ba: c3 ret
000004bb <createtest>:
void
createtest(void)
{
4bb: 55 push %ebp
4bc: 89 e5 mov %esp,%ebp
4be: 83 ec 18 sub $0x18,%esp
int i, fd;
printf(stdout, "many creates, followed by unlink test\n");
4c1: a1 a4 5e 00 00 mov 0x5ea4,%eax
4c6: 83 ec 08 sub $0x8,%esp
4c9: 68 cc 43 00 00 push $0x43cc
4ce: 50 push %eax
4cf: e8 c6 38 00 00 call 3d9a <printf>
4d4: 83 c4 10 add $0x10,%esp
name[0] = 'a';
4d7: c6 05 80 a6 00 00 61 movb $0x61,0xa680
name[2] = '\0';
4de: c6 05 82 a6 00 00 00 movb $0x0,0xa682
for(i = 0; i < 52; i++){
4e5: c7 45 f4 00 00 00 00 movl $0x0,-0xc(%ebp)
4ec: eb 35 jmp 523 <createtest+0x68>
name[1] = '0' + i;
4ee: 8b 45 f4 mov -0xc(%ebp),%eax
4f1: 83 c0 30 add $0x30,%eax
4f4: a2 81 a6 00 00 mov %al,0xa681
fd = open(name, O_CREATE|O_RDWR);
4f9: 83 ec 08 sub $0x8,%esp
4fc: 68 02 02 00 00 push $0x202
501: 68 80 a6 00 00 push $0xa680
506: e8 38 37 00 00 call 3c43 <open>
50b: 83 c4 10 add $0x10,%esp
50e: 89 45 f0 mov %eax,-0x10(%ebp)
close(fd);
511: 83 ec 0c sub $0xc,%esp
514: ff 75 f0 pushl -0x10(%ebp)
517: e8 0f 37 00 00 call 3c2b <close>
51c: 83 c4 10 add $0x10,%esp
printf(stdout, "many creates, followed by unlink test\n");
name[0] = 'a';
name[2] = '\0';
for(i = 0; i < 52; i++){
51f: 83 45 f4 01 addl $0x1,-0xc(%ebp)
523: 83 7d f4 33 cmpl $0x33,-0xc(%ebp)
527: 7e c5 jle 4ee <createtest+0x33>
name[1] = '0' + i;
fd = open(name, O_CREATE|O_RDWR);
close(fd);
}
name[0] = 'a';
529: c6 05 80 a6 00 00 61 movb $0x61,0xa680
name[2] = '\0';
530: c6 05 82 a6 00 00 00 movb $0x0,0xa682
for(i = 0; i < 52; i++){
537: c7 45 f4 00 00 00 00 movl $0x0,-0xc(%ebp)
53e: eb 1f jmp 55f <createtest+0xa4>
name[1] = '0' + i;
540: 8b 45 f4 mov -0xc(%ebp),%eax
543: 83 c0 30 add $0x30,%eax
546: a2 81 a6 00 00 mov %al,0xa681
unlink(name);
54b: 83 ec 0c sub $0xc,%esp
54e: 68 80 a6 00 00 push $0xa680
553: e8 fb 36 00 00 call 3c53 <unlink>
558: 83 c4 10 add $0x10,%esp
fd = open(name, O_CREATE|O_RDWR);
close(fd);
}
name[0] = 'a';
name[2] = '\0';
for(i = 0; i < 52; i++){
55b: 83 45 f4 01 addl $0x1,-0xc(%ebp)
55f: 83 7d f4 33 cmpl $0x33,-0xc(%ebp)
563: 7e db jle 540 <createtest+0x85>
name[1] = '0' + i;
unlink(name);
}
printf(stdout, "many creates, followed by unlink; ok\n");
565: a1 a4 5e 00 00 mov 0x5ea4,%eax
56a: 83 ec 08 sub $0x8,%esp
56d: 68 f4 43 00 00 push $0x43f4
572: 50 push %eax
573: e8 22 38 00 00 call 3d9a <printf>
578: 83 c4 10 add $0x10,%esp
}
57b: 90 nop
57c: c9 leave
57d: c3 ret
0000057e <dirtest>:
void dirtest(void)
{
57e: 55 push %ebp
57f: 89 e5 mov %esp,%ebp
581: 83 ec 08 sub $0x8,%esp
printf(stdout, "mkdir test\n");
584: a1 a4 5e 00 00 mov 0x5ea4,%eax
589: 83 ec 08 sub $0x8,%esp
58c: 68 1a 44 00 00 push $0x441a
591: 50 push %eax
592: e8 03 38 00 00 call 3d9a <printf>
597: 83 c4 10 add $0x10,%esp
if(mkdir("dir0") < 0){
59a: 83 ec 0c sub $0xc,%esp
59d: 68 26 44 00 00 push $0x4426
5a2: e8 c4 36 00 00 call 3c6b <mkdir>
5a7: 83 c4 10 add $0x10,%esp
5aa: 85 c0 test %eax,%eax
5ac: 79 1b jns 5c9 <dirtest+0x4b>
printf(stdout, "mkdir failed\n");
5ae: a1 a4 5e 00 00 mov 0x5ea4,%eax
5b3: 83 ec 08 sub $0x8,%esp
5b6: 68 2b 44 00 00 push $0x442b
5bb: 50 push %eax
5bc: e8 d9 37 00 00 call 3d9a <printf>
5c1: 83 c4 10 add $0x10,%esp
exit();
5c4: e8 3a 36 00 00 call 3c03 <exit>
}
if(chdir("dir0") < 0){
5c9: 83 ec 0c sub $0xc,%esp
5cc: 68 26 44 00 00 push $0x4426
5d1: e8 9d 36 00 00 call 3c73 <chdir>
5d6: 83 c4 10 add $0x10,%esp
5d9: 85 c0 test %eax,%eax
5db: 79 1b jns 5f8 <dirtest+0x7a>
printf(stdout, "chdir dir0 failed\n");
5dd: a1 a4 5e 00 00 mov 0x5ea4,%eax
5e2: 83 ec 08 sub $0x8,%esp
5e5: 68 39 44 00 00 push $0x4439
5ea: 50 push %eax
5eb: e8 aa 37 00 00 call 3d9a <printf>
5f0: 83 c4 10 add $0x10,%esp
exit();
5f3: e8 0b 36 00 00 call 3c03 <exit>
}
if(chdir("..") < 0){
5f8: 83 ec 0c sub $0xc,%esp
5fb: 68 4c 44 00 00 push $0x444c
600: e8 6e 36 00 00 call 3c73 <chdir>
605: 83 c4 10 add $0x10,%esp
608: 85 c0 test %eax,%eax
60a: 79 1b jns 627 <dirtest+0xa9>
printf(stdout, "chdir .. failed\n");
60c: a1 a4 5e 00 00 mov 0x5ea4,%eax
611: 83 ec 08 sub $0x8,%esp
614: 68 4f 44 00 00 push $0x444f
619: 50 push %eax
61a: e8 7b 37 00 00 call 3d9a <printf>
61f: 83 c4 10 add $0x10,%esp
exit();
622: e8 dc 35 00 00 call 3c03 <exit>
}
if(unlink("dir0") < 0){
627: 83 ec 0c sub $0xc,%esp
62a: 68 26 44 00 00 push $0x4426
62f: e8 1f 36 00 00 call 3c53 <unlink>
634: 83 c4 10 add $0x10,%esp
637: 85 c0 test %eax,%eax
639: 79 1b jns 656 <dirtest+0xd8>
printf(stdout, "unlink dir0 failed\n");
63b: a1 a4 5e 00 00 mov 0x5ea4,%eax
640: 83 ec 08 sub $0x8,%esp
643: 68 60 44 00 00 push $0x4460
648: 50 push %eax
649: e8 4c 37 00 00 call 3d9a <printf>
64e: 83 c4 10 add $0x10,%esp
exit();
651: e8 ad 35 00 00 call 3c03 <exit>
}
printf(stdout, "mkdir test\n");
656: a1 a4 5e 00 00 mov 0x5ea4,%eax
65b: 83 ec 08 sub $0x8,%esp
65e: 68 1a 44 00 00 push $0x441a
663: 50 push %eax
664: e8 31 37 00 00 call 3d9a <printf>
669: 83 c4 10 add $0x10,%esp
}
66c: 90 nop
66d: c9 leave
66e: c3 ret
0000066f <exectest>:
void
exectest(void)
{
66f: 55 push %ebp
670: 89 e5 mov %esp,%ebp
672: 83 ec 08 sub $0x8,%esp
printf(stdout, "exec test\n");
675: a1 a4 5e 00 00 mov 0x5ea4,%eax
67a: 83 ec 08 sub $0x8,%esp
67d: 68 74 44 00 00 push $0x4474
682: 50 push %eax
683: e8 12 37 00 00 call 3d9a <printf>
688: 83 c4 10 add $0x10,%esp
if(exec("echo", echoargv) < 0){
68b: 83 ec 08 sub $0x8,%esp
68e: 68 90 5e 00 00 push $0x5e90
693: 68 50 41 00 00 push $0x4150
698: e8 9e 35 00 00 call 3c3b <exec>
69d: 83 c4 10 add $0x10,%esp
6a0: 85 c0 test %eax,%eax
6a2: 79 1b jns 6bf <exectest+0x50>
printf(stdout, "exec echo failed\n");
6a4: a1 a4 5e 00 00 mov 0x5ea4,%eax
6a9: 83 ec 08 sub $0x8,%esp
6ac: 68 7f 44 00 00 push $0x447f
6b1: 50 push %eax
6b2: e8 e3 36 00 00 call 3d9a <printf>
6b7: 83 c4 10 add $0x10,%esp
exit();
6ba: e8 44 35 00 00 call 3c03 <exit>
}
}
6bf: 90 nop
6c0: c9 leave
6c1: c3 ret
000006c2 <pipe1>:
// simple fork and pipe read/write
void
pipe1(void)
{
6c2: 55 push %ebp
6c3: 89 e5 mov %esp,%ebp
6c5: 83 ec 28 sub $0x28,%esp
int fds[2], pid;
int seq, i, n, cc, total;
if(pipe(fds) != 0){
6c8: 83 ec 0c sub $0xc,%esp
6cb: 8d 45 d8 lea -0x28(%ebp),%eax
6ce: 50 push %eax
6cf: e8 3f 35 00 00 call 3c13 <pipe>
6d4: 83 c4 10 add $0x10,%esp
6d7: 85 c0 test %eax,%eax
6d9: 74 17 je 6f2 <pipe1+0x30>
printf(1, "pipe() failed\n");
6db: 83 ec 08 sub $0x8,%esp
6de: 68 91 44 00 00 push $0x4491
6e3: 6a 01 push $0x1
6e5: e8 b0 36 00 00 call 3d9a <printf>
6ea: 83 c4 10 add $0x10,%esp
exit();
6ed: e8 11 35 00 00 call 3c03 <exit>
}
pid = fork();
6f2: e8 04 35 00 00 call 3bfb <fork>
6f7: 89 45 e0 mov %eax,-0x20(%ebp)
seq = 0;
6fa: c7 45 f4 00 00 00 00 movl $0x0,-0xc(%ebp)
if(pid == 0){
701: 83 7d e0 00 cmpl $0x0,-0x20(%ebp)
705: 0f 85 89 00 00 00 jne 794 <pipe1+0xd2>
close(fds[0]);
70b: 8b 45 d8 mov -0x28(%ebp),%eax
70e: 83 ec 0c sub $0xc,%esp
711: 50 push %eax
712: e8 14 35 00 00 call 3c2b <close>
717: 83 c4 10 add $0x10,%esp
for(n = 0; n < 5; n++){
71a: c7 45 ec 00 00 00 00 movl $0x0,-0x14(%ebp)
721: eb 66 jmp 789 <pipe1+0xc7>
for(i = 0; i < 1033; i++)
723: c7 45 f0 00 00 00 00 movl $0x0,-0x10(%ebp)
72a: eb 19 jmp 745 <pipe1+0x83>
buf[i] = seq++;
72c: 8b 45 f4 mov -0xc(%ebp),%eax
72f: 8d 50 01 lea 0x1(%eax),%edx
732: 89 55 f4 mov %edx,-0xc(%ebp)
735: 89 c2 mov %eax,%edx
737: 8b 45 f0 mov -0x10(%ebp),%eax
73a: 05 80 86 00 00 add $0x8680,%eax
73f: 88 10 mov %dl,(%eax)
pid = fork();
seq = 0;
if(pid == 0){
close(fds[0]);
for(n = 0; n < 5; n++){
for(i = 0; i < 1033; i++)
741: 83 45 f0 01 addl $0x1,-0x10(%ebp)
745: 81 7d f0 08 04 00 00 cmpl $0x408,-0x10(%ebp)
74c: 7e de jle 72c <pipe1+0x6a>
buf[i] = seq++;
if(write(fds[1], buf, 1033) != 1033){
74e: 8b 45 dc mov -0x24(%ebp),%eax
751: 83 ec 04 sub $0x4,%esp
754: 68 09 04 00 00 push $0x409
759: 68 80 86 00 00 push $0x8680
75e: 50 push %eax
75f: e8 bf 34 00 00 call 3c23 <write>
764: 83 c4 10 add $0x10,%esp
767: 3d 09 04 00 00 cmp $0x409,%eax
76c: 74 17 je 785 <pipe1+0xc3>
printf(1, "pipe1 oops 1\n");
76e: 83 ec 08 sub $0x8,%esp
771: 68 a0 44 00 00 push $0x44a0
776: 6a 01 push $0x1
778: e8 1d 36 00 00 call 3d9a <printf>
77d: 83 c4 10 add $0x10,%esp
exit();
780: e8 7e 34 00 00 call 3c03 <exit>
}
pid = fork();
seq = 0;
if(pid == 0){
close(fds[0]);
for(n = 0; n < 5; n++){
785: 83 45 ec 01 addl $0x1,-0x14(%ebp)
789: 83 7d ec 04 cmpl $0x4,-0x14(%ebp)
78d: 7e 94 jle 723 <pipe1+0x61>
if(write(fds[1], buf, 1033) != 1033){
printf(1, "pipe1 oops 1\n");
exit();
}
}
exit();
78f: e8 6f 34 00 00 call 3c03 <exit>
} else if(pid > 0){
794: 83 7d e0 00 cmpl $0x0,-0x20(%ebp)
798: 0f 8e f4 00 00 00 jle 892 <pipe1+0x1d0>
close(fds[1]);
79e: 8b 45 dc mov -0x24(%ebp),%eax
7a1: 83 ec 0c sub $0xc,%esp
7a4: 50 push %eax
7a5: e8 81 34 00 00 call 3c2b <close>
7aa: 83 c4 10 add $0x10,%esp
total = 0;
7ad: c7 45 e4 00 00 00 00 movl $0x0,-0x1c(%ebp)
cc = 1;
7b4: c7 45 e8 01 00 00 00 movl $0x1,-0x18(%ebp)
while((n = read(fds[0], buf, cc)) > 0){
7bb: eb 66 jmp 823 <pipe1+0x161>
for(i = 0; i < n; i++){
7bd: c7 45 f0 00 00 00 00 movl $0x0,-0x10(%ebp)
7c4: eb 3b jmp 801 <pipe1+0x13f>
if((buf[i] & 0xff) != (seq++ & 0xff)){
7c6: 8b 45 f0 mov -0x10(%ebp),%eax
7c9: 05 80 86 00 00 add $0x8680,%eax
7ce: 0f b6 00 movzbl (%eax),%eax
7d1: 0f be c8 movsbl %al,%ecx
7d4: 8b 45 f4 mov -0xc(%ebp),%eax
7d7: 8d 50 01 lea 0x1(%eax),%edx
7da: 89 55 f4 mov %edx,-0xc(%ebp)
7dd: 31 c8 xor %ecx,%eax
7df: 0f b6 c0 movzbl %al,%eax
7e2: 85 c0 test %eax,%eax
7e4: 74 17 je 7fd <pipe1+0x13b>
printf(1, "pipe1 oops 2\n");
7e6: 83 ec 08 sub $0x8,%esp
7e9: 68 ae 44 00 00 push $0x44ae
7ee: 6a 01 push $0x1
7f0: e8 a5 35 00 00 call 3d9a <printf>
7f5: 83 c4 10 add $0x10,%esp
7f8: e9 ac 00 00 00 jmp 8a9 <pipe1+0x1e7>
} else if(pid > 0){
close(fds[1]);
total = 0;
cc = 1;
while((n = read(fds[0], buf, cc)) > 0){
for(i = 0; i < n; i++){
7fd: 83 45 f0 01 addl $0x1,-0x10(%ebp)
801: 8b 45 f0 mov -0x10(%ebp),%eax
804: 3b 45 ec cmp -0x14(%ebp),%eax
807: 7c bd jl 7c6 <pipe1+0x104>
if((buf[i] & 0xff) != (seq++ & 0xff)){
printf(1, "pipe1 oops 2\n");
return;
}
}
total += n;
809: 8b 45 ec mov -0x14(%ebp),%eax
80c: 01 45 e4 add %eax,-0x1c(%ebp)
cc = cc * 2;
80f: d1 65 e8 shll -0x18(%ebp)
if(cc > sizeof(buf))
812: 8b 45 e8 mov -0x18(%ebp),%eax
815: 3d 00 20 00 00 cmp $0x2000,%eax
81a: 76 07 jbe 823 <pipe1+0x161>
cc = sizeof(buf);
81c: c7 45 e8 00 20 00 00 movl $0x2000,-0x18(%ebp)
exit();
} else if(pid > 0){
close(fds[1]);
total = 0;
cc = 1;
while((n = read(fds[0], buf, cc)) > 0){
823: 8b 45 d8 mov -0x28(%ebp),%eax
826: 83 ec 04 sub $0x4,%esp
829: ff 75 e8 pushl -0x18(%ebp)
82c: 68 80 86 00 00 push $0x8680
831: 50 push %eax
832: e8 e4 33 00 00 call 3c1b <read>
837: 83 c4 10 add $0x10,%esp
83a: 89 45 ec mov %eax,-0x14(%ebp)
83d: 83 7d ec 00 cmpl $0x0,-0x14(%ebp)
841: 0f 8f 76 ff ff ff jg 7bd <pipe1+0xfb>
total += n;
cc = cc * 2;
if(cc > sizeof(buf))
cc = sizeof(buf);
}
if(total != 5 * 1033){
847: 81 7d e4 2d 14 00 00 cmpl $0x142d,-0x1c(%ebp)
84e: 74 1a je 86a <pipe1+0x1a8>
printf(1, "pipe1 oops 3 total %d\n", total);
850: 83 ec 04 sub $0x4,%esp
853: ff 75 e4 pushl -0x1c(%ebp)
856: 68 bc 44 00 00 push $0x44bc
85b: 6a 01 push $0x1
85d: e8 38 35 00 00 call 3d9a <printf>
862: 83 c4 10 add $0x10,%esp
exit();
865: e8 99 33 00 00 call 3c03 <exit>
}
close(fds[0]);
86a: 8b 45 d8 mov -0x28(%ebp),%eax
86d: 83 ec 0c sub $0xc,%esp
870: 50 push %eax
871: e8 b5 33 00 00 call 3c2b <close>
876: 83 c4 10 add $0x10,%esp
wait();
879: e8 8d 33 00 00 call 3c0b <wait>
} else {
printf(1, "fork() failed\n");
exit();
}
printf(1, "pipe1 ok\n");
87e: 83 ec 08 sub $0x8,%esp
881: 68 e2 44 00 00 push $0x44e2
886: 6a 01 push $0x1
888: e8 0d 35 00 00 call 3d9a <printf>
88d: 83 c4 10 add $0x10,%esp
890: eb 17 jmp 8a9 <pipe1+0x1e7>
exit();
}
close(fds[0]);
wait();
} else {
printf(1, "fork() failed\n");
892: 83 ec 08 sub $0x8,%esp
895: 68 d3 44 00 00 push $0x44d3
89a: 6a 01 push $0x1
89c: e8 f9 34 00 00 call 3d9a <printf>
8a1: 83 c4 10 add $0x10,%esp
exit();
8a4: e8 5a 33 00 00 call 3c03 <exit>
}
printf(1, "pipe1 ok\n");
}
8a9: c9 leave
8aa: c3 ret
000008ab <preempt>:
// meant to be run w/ at most two CPUs
void
preempt(void)
{
8ab: 55 push %ebp
8ac: 89 e5 mov %esp,%ebp
8ae: 83 ec 28 sub $0x28,%esp
int pid1, pid2, pid3;
int pfds[2];
printf(1, "preempt: ");
8b1: 83 ec 08 sub $0x8,%esp
8b4: 68 ec 44 00 00 push $0x44ec
8b9: 6a 01 push $0x1
8bb: e8 da 34 00 00 call 3d9a <printf>
8c0: 83 c4 10 add $0x10,%esp
pid1 = fork();
8c3: e8 33 33 00 00 call 3bfb <fork>
8c8: 89 45 f4 mov %eax,-0xc(%ebp)
if(pid1 == 0)
8cb: 83 7d f4 00 cmpl $0x0,-0xc(%ebp)
8cf: 75 02 jne 8d3 <preempt+0x28>
for(;;)
;
8d1: eb fe jmp 8d1 <preempt+0x26>
pid2 = fork();
8d3: e8 23 33 00 00 call 3bfb <fork>
8d8: 89 45 f0 mov %eax,-0x10(%ebp)
if(pid2 == 0)
8db: 83 7d f0 00 cmpl $0x0,-0x10(%ebp)
8df: 75 02 jne 8e3 <preempt+0x38>
for(;;)
;
8e1: eb fe jmp 8e1 <preempt+0x36>
pipe(pfds);
8e3: 83 ec 0c sub $0xc,%esp
8e6: 8d 45 e4 lea -0x1c(%ebp),%eax
8e9: 50 push %eax
8ea: e8 24 33 00 00 call 3c13 <pipe>
8ef: 83 c4 10 add $0x10,%esp
pid3 = fork();
8f2: e8 04 33 00 00 call 3bfb <fork>
8f7: 89 45 ec mov %eax,-0x14(%ebp)
if(pid3 == 0){
8fa: 83 7d ec 00 cmpl $0x0,-0x14(%ebp)
8fe: 75 4d jne 94d <preempt+0xa2>
close(pfds[0]);
900: 8b 45 e4 mov -0x1c(%ebp),%eax
903: 83 ec 0c sub $0xc,%esp
906: 50 push %eax
907: e8 1f 33 00 00 call 3c2b <close>
90c: 83 c4 10 add $0x10,%esp
if(write(pfds[1], "x", 1) != 1)
90f: 8b 45 e8 mov -0x18(%ebp),%eax
912: 83 ec 04 sub $0x4,%esp
915: 6a 01 push $0x1
917: 68 f6 44 00 00 push $0x44f6
91c: 50 push %eax
91d: e8 01 33 00 00 call 3c23 <write>
922: 83 c4 10 add $0x10,%esp
925: 83 f8 01 cmp $0x1,%eax
928: 74 12 je 93c <preempt+0x91>
printf(1, "preempt write error");
92a: 83 ec 08 sub $0x8,%esp
92d: 68 f8 44 00 00 push $0x44f8
932: 6a 01 push $0x1
934: e8 61 34 00 00 call 3d9a <printf>
939: 83 c4 10 add $0x10,%esp
close(pfds[1]);
93c: 8b 45 e8 mov -0x18(%ebp),%eax
93f: 83 ec 0c sub $0xc,%esp
942: 50 push %eax
943: e8 e3 32 00 00 call 3c2b <close>
948: 83 c4 10 add $0x10,%esp
for(;;)
;
94b: eb fe jmp 94b <preempt+0xa0>
}
close(pfds[1]);
94d: 8b 45 e8 mov -0x18(%ebp),%eax
950: 83 ec 0c sub $0xc,%esp
953: 50 push %eax
954: e8 d2 32 00 00 call 3c2b <close>
959: 83 c4 10 add $0x10,%esp
if(read(pfds[0], buf, sizeof(buf)) != 1){
95c: 8b 45 e4 mov -0x1c(%ebp),%eax
95f: 83 ec 04 sub $0x4,%esp
962: 68 00 20 00 00 push $0x2000
967: 68 80 86 00 00 push $0x8680
96c: 50 push %eax
96d: e8 a9 32 00 00 call 3c1b <read>
972: 83 c4 10 add $0x10,%esp
975: 83 f8 01 cmp $0x1,%eax
978: 74 14 je 98e <preempt+0xe3>
printf(1, "preempt read error");
97a: 83 ec 08 sub $0x8,%esp
97d: 68 0c 45 00 00 push $0x450c
982: 6a 01 push $0x1
984: e8 11 34 00 00 call 3d9a <printf>
989: 83 c4 10 add $0x10,%esp
98c: eb 7e jmp a0c <preempt+0x161>
return;
}
close(pfds[0]);
98e: 8b 45 e4 mov -0x1c(%ebp),%eax
991: 83 ec 0c sub $0xc,%esp
994: 50 push %eax
995: e8 91 32 00 00 call 3c2b <close>
99a: 83 c4 10 add $0x10,%esp
printf(1, "kill... ");
99d: 83 ec 08 sub $0x8,%esp
9a0: 68 1f 45 00 00 push $0x451f
9a5: 6a 01 push $0x1
9a7: e8 ee 33 00 00 call 3d9a <printf>
9ac: 83 c4 10 add $0x10,%esp
kill(pid1);
9af: 83 ec 0c sub $0xc,%esp
9b2: ff 75 f4 pushl -0xc(%ebp)
9b5: e8 79 32 00 00 call 3c33 <kill>
9ba: 83 c4 10 add $0x10,%esp
kill(pid2);
9bd: 83 ec 0c sub $0xc,%esp
9c0: ff 75 f0 pushl -0x10(%ebp)
9c3: e8 6b 32 00 00 call 3c33 <kill>
9c8: 83 c4 10 add $0x10,%esp
kill(pid3);
9cb: 83 ec 0c sub $0xc,%esp
9ce: ff 75 ec pushl -0x14(%ebp)
9d1: e8 5d 32 00 00 call 3c33 <kill>
9d6: 83 c4 10 add $0x10,%esp
printf(1, "wait... ");
9d9: 83 ec 08 sub $0x8,%esp
9dc: 68 28 45 00 00 push $0x4528
9e1: 6a 01 push $0x1
9e3: e8 b2 33 00 00 call 3d9a <printf>
9e8: 83 c4 10 add $0x10,%esp
wait();
9eb: e8 1b 32 00 00 call 3c0b <wait>
wait();
9f0: e8 16 32 00 00 call 3c0b <wait>
wait();
9f5: e8 11 32 00 00 call 3c0b <wait>
printf(1, "preempt ok\n");
9fa: 83 ec 08 sub $0x8,%esp
9fd: 68 31 45 00 00 push $0x4531
a02: 6a 01 push $0x1
a04: e8 91 33 00 00 call 3d9a <printf>
a09: 83 c4 10 add $0x10,%esp
}
a0c: c9 leave
a0d: c3 ret
00000a0e <exitwait>:
// try to find any races between exit and wait
void
exitwait(void)
{
a0e: 55 push %ebp
a0f: 89 e5 mov %esp,%ebp
a11: 83 ec 18 sub $0x18,%esp
int i, pid;
for(i = 0; i < 100; i++){
a14: c7 45 f4 00 00 00 00 movl $0x0,-0xc(%ebp)
a1b: eb 4f jmp a6c <exitwait+0x5e>
pid = fork();
a1d: e8 d9 31 00 00 call 3bfb <fork>
a22: 89 45 f0 mov %eax,-0x10(%ebp)
if(pid < 0){
a25: 83 7d f0 00 cmpl $0x0,-0x10(%ebp)
a29: 79 14 jns a3f <exitwait+0x31>
printf(1, "fork failed\n");
a2b: 83 ec 08 sub $0x8,%esp
a2e: 68 3d 45 00 00 push $0x453d
a33: 6a 01 push $0x1
a35: e8 60 33 00 00 call 3d9a <printf>
a3a: 83 c4 10 add $0x10,%esp
return;
a3d: eb 45 jmp a84 <exitwait+0x76>
}
if(pid){
a3f: 83 7d f0 00 cmpl $0x0,-0x10(%ebp)
a43: 74 1e je a63 <exitwait+0x55>
if(wait() != pid){
a45: e8 c1 31 00 00 call 3c0b <wait>
a4a: 3b 45 f0 cmp -0x10(%ebp),%eax
a4d: 74 19 je a68 <exitwait+0x5a>
printf(1, "wait wrong pid\n");
a4f: 83 ec 08 sub $0x8,%esp
a52: 68 4a 45 00 00 push $0x454a
a57: 6a 01 push $0x1
a59: e8 3c 33 00 00 call 3d9a <printf>
a5e: 83 c4 10 add $0x10,%esp
return;
a61: eb 21 jmp a84 <exitwait+0x76>
}
} else {
exit();
a63: e8 9b 31 00 00 call 3c03 <exit>
void
exitwait(void)
{
int i, pid;
for(i = 0; i < 100; i++){
a68: 83 45 f4 01 addl $0x1,-0xc(%ebp)
a6c: 83 7d f4 63 cmpl $0x63,-0xc(%ebp)
a70: 7e ab jle a1d <exitwait+0xf>
}
} else {
exit();
}
}
printf(1, "exitwait ok\n");
a72: 83 ec 08 sub $0x8,%esp
a75: 68 5a 45 00 00 push $0x455a
a7a: 6a 01 push $0x1
a7c: e8 19 33 00 00 call 3d9a <printf>
a81: 83 c4 10 add $0x10,%esp
}
a84: c9 leave
a85: c3 ret
00000a86 <mem>:
void
mem(void)
{
a86: 55 push %ebp
a87: 89 e5 mov %esp,%ebp
a89: 83 ec 18 sub $0x18,%esp
void *m1, *m2;
int pid, ppid;
printf(1, "mem test\n");
a8c: 83 ec 08 sub $0x8,%esp
a8f: 68 67 45 00 00 push $0x4567
a94: 6a 01 push $0x1
a96: e8 ff 32 00 00 call 3d9a <printf>
a9b: 83 c4 10 add $0x10,%esp
ppid = getpid();
a9e: e8 e0 31 00 00 call 3c83 <getpid>
aa3: 89 45 f0 mov %eax,-0x10(%ebp)
if((pid = fork()) == 0){
aa6: e8 50 31 00 00 call 3bfb <fork>
aab: 89 45 ec mov %eax,-0x14(%ebp)
aae: 83 7d ec 00 cmpl $0x0,-0x14(%ebp)
ab2: 0f 85 b7 00 00 00 jne b6f <mem+0xe9>
m1 = 0;
ab8: c7 45 f4 00 00 00 00 movl $0x0,-0xc(%ebp)
while((m2 = malloc(10001)) != 0){
abf: eb 0e jmp acf <mem+0x49>
*(char**)m2 = m1;
ac1: 8b 45 e8 mov -0x18(%ebp),%eax
ac4: 8b 55 f4 mov -0xc(%ebp),%edx
ac7: 89 10 mov %edx,(%eax)
m1 = m2;
ac9: 8b 45 e8 mov -0x18(%ebp),%eax
acc: 89 45 f4 mov %eax,-0xc(%ebp)
printf(1, "mem test\n");
ppid = getpid();
if((pid = fork()) == 0){
m1 = 0;
while((m2 = malloc(10001)) != 0){
acf: 83 ec 0c sub $0xc,%esp
ad2: 68 11 27 00 00 push $0x2711
ad7: e8 91 35 00 00 call 406d <malloc>
adc: 83 c4 10 add $0x10,%esp
adf: 89 45 e8 mov %eax,-0x18(%ebp)
ae2: 83 7d e8 00 cmpl $0x0,-0x18(%ebp)
ae6: 75 d9 jne ac1 <mem+0x3b>
*(char**)m2 = m1;
m1 = m2;
}
while(m1){
ae8: eb 1c jmp b06 <mem+0x80>
m2 = *(char**)m1;
aea: 8b 45 f4 mov -0xc(%ebp),%eax
aed: 8b 00 mov (%eax),%eax
aef: 89 45 e8 mov %eax,-0x18(%ebp)
free(m1);
af2: 83 ec 0c sub $0xc,%esp
af5: ff 75 f4 pushl -0xc(%ebp)
af8: e8 2e 34 00 00 call 3f2b <free>
afd: 83 c4 10 add $0x10,%esp
m1 = m2;
b00: 8b 45 e8 mov -0x18(%ebp),%eax
b03: 89 45 f4 mov %eax,-0xc(%ebp)
m1 = 0;
while((m2 = malloc(10001)) != 0){
*(char**)m2 = m1;
m1 = m2;
}
while(m1){
b06: 83 7d f4 00 cmpl $0x0,-0xc(%ebp)
b0a: 75 de jne aea <mem+0x64>
m2 = *(char**)m1;
free(m1);
m1 = m2;
}
m1 = malloc(1024*20);
b0c: 83 ec 0c sub $0xc,%esp
b0f: 68 00 50 00 00 push $0x5000
b14: e8 54 35 00 00 call 406d <malloc>
b19: 83 c4 10 add $0x10,%esp
b1c: 89 45 f4 mov %eax,-0xc(%ebp)
if(m1 == 0){
b1f: 83 7d f4 00 cmpl $0x0,-0xc(%ebp)
b23: 75 25 jne b4a <mem+0xc4>
printf(1, "couldn't allocate mem?!!\n");
b25: 83 ec 08 sub $0x8,%esp
b28: 68 71 45 00 00 push $0x4571
b2d: 6a 01 push $0x1
b2f: e8 66 32 00 00 call 3d9a <printf>
b34: 83 c4 10 add $0x10,%esp
kill(ppid);
b37: 83 ec 0c sub $0xc,%esp
b3a: ff 75 f0 pushl -0x10(%ebp)
b3d: e8 f1 30 00 00 call 3c33 <kill>
b42: 83 c4 10 add $0x10,%esp
exit();
b45: e8 b9 30 00 00 call 3c03 <exit>
}
free(m1);
b4a: 83 ec 0c sub $0xc,%esp
b4d: ff 75 f4 pushl -0xc(%ebp)
b50: e8 d6 33 00 00 call 3f2b <free>
b55: 83 c4 10 add $0x10,%esp
printf(1, "mem ok\n");
b58: 83 ec 08 sub $0x8,%esp
b5b: 68 8b 45 00 00 push $0x458b
b60: 6a 01 push $0x1
b62: e8 33 32 00 00 call 3d9a <printf>
b67: 83 c4 10 add $0x10,%esp
exit();
b6a: e8 94 30 00 00 call 3c03 <exit>
} else {
wait();
b6f: e8 97 30 00 00 call 3c0b <wait>
}
}
b74: 90 nop
b75: c9 leave
b76: c3 ret
00000b77 <sharedfd>:
// two processes write to the same file descriptor
// is the offset shared? does inode locking work?
void
sharedfd(void)
{
b77: 55 push %ebp
b78: 89 e5 mov %esp,%ebp
b7a: 83 ec 38 sub $0x38,%esp
int fd, pid, i, n, nc, np;
char buf[10];
printf(1, "sharedfd test\n");
b7d: 83 ec 08 sub $0x8,%esp
b80: 68 93 45 00 00 push $0x4593
b85: 6a 01 push $0x1
b87: e8 0e 32 00 00 call 3d9a <printf>
b8c: 83 c4 10 add $0x10,%esp
unlink("sharedfd");
b8f: 83 ec 0c sub $0xc,%esp
b92: 68 a2 45 00 00 push $0x45a2
b97: e8 b7 30 00 00 call 3c53 <unlink>
b9c: 83 c4 10 add $0x10,%esp
fd = open("sharedfd", O_CREATE|O_RDWR);
b9f: 83 ec 08 sub $0x8,%esp
ba2: 68 02 02 00 00 push $0x202
ba7: 68 a2 45 00 00 push $0x45a2
bac: e8 92 30 00 00 call 3c43 <open>
bb1: 83 c4 10 add $0x10,%esp
bb4: 89 45 e8 mov %eax,-0x18(%ebp)
if(fd < 0){
bb7: 83 7d e8 00 cmpl $0x0,-0x18(%ebp)
bbb: 79 17 jns bd4 <sharedfd+0x5d>
printf(1, "fstests: cannot open sharedfd for writing");
bbd: 83 ec 08 sub $0x8,%esp
bc0: 68 ac 45 00 00 push $0x45ac
bc5: 6a 01 push $0x1
bc7: e8 ce 31 00 00 call 3d9a <printf>
bcc: 83 c4 10 add $0x10,%esp
return;
bcf: e9 84 01 00 00 jmp d58 <sharedfd+0x1e1>
}
pid = fork();
bd4: e8 22 30 00 00 call 3bfb <fork>
bd9: 89 45 e4 mov %eax,-0x1c(%ebp)
memset(buf, pid==0?'c':'p', sizeof(buf));
bdc: 83 7d e4 00 cmpl $0x0,-0x1c(%ebp)
be0: 75 07 jne be9 <sharedfd+0x72>
be2: b8 63 00 00 00 mov $0x63,%eax
be7: eb 05 jmp bee <sharedfd+0x77>
be9: b8 70 00 00 00 mov $0x70,%eax
bee: 83 ec 04 sub $0x4,%esp
bf1: 6a 0a push $0xa
bf3: 50 push %eax
bf4: 8d 45 d6 lea -0x2a(%ebp),%eax
bf7: 50 push %eax
bf8: e8 6b 2e 00 00 call 3a68 <memset>
bfd: 83 c4 10 add $0x10,%esp
for(i = 0; i < 1000; i++){
c00: c7 45 f4 00 00 00 00 movl $0x0,-0xc(%ebp)
c07: eb 31 jmp c3a <sharedfd+0xc3>
if(write(fd, buf, sizeof(buf)) != sizeof(buf)){
c09: 83 ec 04 sub $0x4,%esp
c0c: 6a 0a push $0xa
c0e: 8d 45 d6 lea -0x2a(%ebp),%eax
c11: 50 push %eax
c12: ff 75 e8 pushl -0x18(%ebp)
c15: e8 09 30 00 00 call 3c23 <write>
c1a: 83 c4 10 add $0x10,%esp
c1d: 83 f8 0a cmp $0xa,%eax
c20: 74 14 je c36 <sharedfd+0xbf>
printf(1, "fstests: write sharedfd failed\n");
c22: 83 ec 08 sub $0x8,%esp
c25: 68 d8 45 00 00 push $0x45d8
c2a: 6a 01 push $0x1
c2c: e8 69 31 00 00 call 3d9a <printf>
c31: 83 c4 10 add $0x10,%esp
break;
c34: eb 0d jmp c43 <sharedfd+0xcc>
printf(1, "fstests: cannot open sharedfd for writing");
return;
}
pid = fork();
memset(buf, pid==0?'c':'p', sizeof(buf));
for(i = 0; i < 1000; i++){
c36: 83 45 f4 01 addl $0x1,-0xc(%ebp)
c3a: 81 7d f4 e7 03 00 00 cmpl $0x3e7,-0xc(%ebp)
c41: 7e c6 jle c09 <sharedfd+0x92>
if(write(fd, buf, sizeof(buf)) != sizeof(buf)){
printf(1, "fstests: write sharedfd failed\n");
break;
}
}
if(pid == 0)
c43: 83 7d e4 00 cmpl $0x0,-0x1c(%ebp)
c47: 75 05 jne c4e <sharedfd+0xd7>
exit();
c49: e8 b5 2f 00 00 call 3c03 <exit>
else
wait();
c4e: e8 b8 2f 00 00 call 3c0b <wait>
close(fd);
c53: 83 ec 0c sub $0xc,%esp
c56: ff 75 e8 pushl -0x18(%ebp)
c59: e8 cd 2f 00 00 call 3c2b <close>
c5e: 83 c4 10 add $0x10,%esp
fd = open("sharedfd", 0);
c61: 83 ec 08 sub $0x8,%esp
c64: 6a 00 push $0x0
c66: 68 a2 45 00 00 push $0x45a2
c6b: e8 d3 2f 00 00 call 3c43 <open>
c70: 83 c4 10 add $0x10,%esp
c73: 89 45 e8 mov %eax,-0x18(%ebp)
if(fd < 0){
c76: 83 7d e8 00 cmpl $0x0,-0x18(%ebp)
c7a: 79 17 jns c93 <sharedfd+0x11c>
printf(1, "fstests: cannot open sharedfd for reading\n");
c7c: 83 ec 08 sub $0x8,%esp
c7f: 68 f8 45 00 00 push $0x45f8
c84: 6a 01 push $0x1
c86: e8 0f 31 00 00 call 3d9a <printf>
c8b: 83 c4 10 add $0x10,%esp
return;
c8e: e9 c5 00 00 00 jmp d58 <sharedfd+0x1e1>
}
nc = np = 0;
c93: c7 45 ec 00 00 00 00 movl $0x0,-0x14(%ebp)
c9a: 8b 45 ec mov -0x14(%ebp),%eax
c9d: 89 45 f0 mov %eax,-0x10(%ebp)
while((n = read(fd, buf, sizeof(buf))) > 0){
ca0: eb 3b jmp cdd <sharedfd+0x166>
for(i = 0; i < sizeof(buf); i++){
ca2: c7 45 f4 00 00 00 00 movl $0x0,-0xc(%ebp)
ca9: eb 2a jmp cd5 <sharedfd+0x15e>
if(buf[i] == 'c')
cab: 8d 55 d6 lea -0x2a(%ebp),%edx
cae: 8b 45 f4 mov -0xc(%ebp),%eax
cb1: 01 d0 add %edx,%eax
cb3: 0f b6 00 movzbl (%eax),%eax
cb6: 3c 63 cmp $0x63,%al
cb8: 75 04 jne cbe <sharedfd+0x147>
nc++;
cba: 83 45 f0 01 addl $0x1,-0x10(%ebp)
if(buf[i] == 'p')
cbe: 8d 55 d6 lea -0x2a(%ebp),%edx
cc1: 8b 45 f4 mov -0xc(%ebp),%eax
cc4: 01 d0 add %edx,%eax
cc6: 0f b6 00 movzbl (%eax),%eax
cc9: 3c 70 cmp $0x70,%al
ccb: 75 04 jne cd1 <sharedfd+0x15a>
np++;
ccd: 83 45 ec 01 addl $0x1,-0x14(%ebp)
printf(1, "fstests: cannot open sharedfd for reading\n");
return;
}
nc = np = 0;
while((n = read(fd, buf, sizeof(buf))) > 0){
for(i = 0; i < sizeof(buf); i++){
cd1: 83 45 f4 01 addl $0x1,-0xc(%ebp)
cd5: 8b 45 f4 mov -0xc(%ebp),%eax
cd8: 83 f8 09 cmp $0x9,%eax
cdb: 76 ce jbe cab <sharedfd+0x134>
if(fd < 0){
printf(1, "fstests: cannot open sharedfd for reading\n");
return;
}
nc = np = 0;
while((n = read(fd, buf, sizeof(buf))) > 0){
cdd: 83 ec 04 sub $0x4,%esp
ce0: 6a 0a push $0xa
ce2: 8d 45 d6 lea -0x2a(%ebp),%eax
ce5: 50 push %eax
ce6: ff 75 e8 pushl -0x18(%ebp)
ce9: e8 2d 2f 00 00 call 3c1b <read>
cee: 83 c4 10 add $0x10,%esp
cf1: 89 45 e0 mov %eax,-0x20(%ebp)
cf4: 83 7d e0 00 cmpl $0x0,-0x20(%ebp)
cf8: 7f a8 jg ca2 <sharedfd+0x12b>
nc++;
if(buf[i] == 'p')
np++;
}
}
close(fd);
cfa: 83 ec 0c sub $0xc,%esp
cfd: ff 75 e8 pushl -0x18(%ebp)
d00: e8 26 2f 00 00 call 3c2b <close>
d05: 83 c4 10 add $0x10,%esp
unlink("sharedfd");
d08: 83 ec 0c sub $0xc,%esp
d0b: 68 a2 45 00 00 push $0x45a2
d10: e8 3e 2f 00 00 call 3c53 <unlink>
d15: 83 c4 10 add $0x10,%esp
if(nc == 10000 && np == 10000){
d18: 81 7d f0 10 27 00 00 cmpl $0x2710,-0x10(%ebp)
d1f: 75 1d jne d3e <sharedfd+0x1c7>
d21: 81 7d ec 10 27 00 00 cmpl $0x2710,-0x14(%ebp)
d28: 75 14 jne d3e <sharedfd+0x1c7>
printf(1, "sharedfd ok\n");
d2a: 83 ec 08 sub $0x8,%esp
d2d: 68 23 46 00 00 push $0x4623
d32: 6a 01 push $0x1
d34: e8 61 30 00 00 call 3d9a <printf>
d39: 83 c4 10 add $0x10,%esp
d3c: eb 1a jmp d58 <sharedfd+0x1e1>
} else {
printf(1, "sharedfd oops %d %d\n", nc, np);
d3e: ff 75 ec pushl -0x14(%ebp)
d41: ff 75 f0 pushl -0x10(%ebp)
d44: 68 30 46 00 00 push $0x4630
d49: 6a 01 push $0x1
d4b: e8 4a 30 00 00 call 3d9a <printf>
d50: 83 c4 10 add $0x10,%esp
exit();
d53: e8 ab 2e 00 00 call 3c03 <exit>
}
}
d58: c9 leave
d59: c3 ret
00000d5a <twofiles>:
// two processes write two different files at the same
// time, to test block allocation.
void
twofiles(void)
{
d5a: 55 push %ebp
d5b: 89 e5 mov %esp,%ebp
d5d: 83 ec 28 sub $0x28,%esp
int fd, pid, i, j, n, total;
char *fname;
printf(1, "twofiles test\n");
d60: 83 ec 08 sub $0x8,%esp
d63: 68 45 46 00 00 push $0x4645
d68: 6a 01 push $0x1
d6a: e8 2b 30 00 00 call 3d9a <printf>
d6f: 83 c4 10 add $0x10,%esp
unlink("f1");
d72: 83 ec 0c sub $0xc,%esp
d75: 68 54 46 00 00 push $0x4654
d7a: e8 d4 2e 00 00 call 3c53 <unlink>
d7f: 83 c4 10 add $0x10,%esp
unlink("f2");
d82: 83 ec 0c sub $0xc,%esp
d85: 68 57 46 00 00 push $0x4657
d8a: e8 c4 2e 00 00 call 3c53 <unlink>
d8f: 83 c4 10 add $0x10,%esp
pid = fork();
d92: e8 64 2e 00 00 call 3bfb <fork>
d97: 89 45 e8 mov %eax,-0x18(%ebp)
if(pid < 0){
d9a: 83 7d e8 00 cmpl $0x0,-0x18(%ebp)
d9e: 79 17 jns db7 <twofiles+0x5d>
printf(1, "fork failed\n");
da0: 83 ec 08 sub $0x8,%esp
da3: 68 3d 45 00 00 push $0x453d
da8: 6a 01 push $0x1
daa: e8 eb 2f 00 00 call 3d9a <printf>
daf: 83 c4 10 add $0x10,%esp
exit();
db2: e8 4c 2e 00 00 call 3c03 <exit>
}
fname = pid ? "f1" : "f2";
db7: 83 7d e8 00 cmpl $0x0,-0x18(%ebp)
dbb: 74 07 je dc4 <twofiles+0x6a>
dbd: b8 54 46 00 00 mov $0x4654,%eax
dc2: eb 05 jmp dc9 <twofiles+0x6f>
dc4: b8 57 46 00 00 mov $0x4657,%eax
dc9: 89 45 e4 mov %eax,-0x1c(%ebp)
fd = open(fname, O_CREATE | O_RDWR);
dcc: 83 ec 08 sub $0x8,%esp
dcf: 68 02 02 00 00 push $0x202
dd4: ff 75 e4 pushl -0x1c(%ebp)
dd7: e8 67 2e 00 00 call 3c43 <open>
ddc: 83 c4 10 add $0x10,%esp
ddf: 89 45 e0 mov %eax,-0x20(%ebp)
if(fd < 0){
de2: 83 7d e0 00 cmpl $0x0,-0x20(%ebp)
de6: 79 17 jns dff <twofiles+0xa5>
printf(1, "create failed\n");
de8: 83 ec 08 sub $0x8,%esp
deb: 68 5a 46 00 00 push $0x465a
df0: 6a 01 push $0x1
df2: e8 a3 2f 00 00 call 3d9a <printf>
df7: 83 c4 10 add $0x10,%esp
exit();
dfa: e8 04 2e 00 00 call 3c03 <exit>
}
memset(buf, pid?'p':'c', 512);
dff: 83 7d e8 00 cmpl $0x0,-0x18(%ebp)
e03: 74 07 je e0c <twofiles+0xb2>
e05: b8 70 00 00 00 mov $0x70,%eax
e0a: eb 05 jmp e11 <twofiles+0xb7>
e0c: b8 63 00 00 00 mov $0x63,%eax
e11: 83 ec 04 sub $0x4,%esp
e14: 68 00 02 00 00 push $0x200
e19: 50 push %eax
e1a: 68 80 86 00 00 push $0x8680
e1f: e8 44 2c 00 00 call 3a68 <memset>
e24: 83 c4 10 add $0x10,%esp
for(i = 0; i < 12; i++){
e27: c7 45 f4 00 00 00 00 movl $0x0,-0xc(%ebp)
e2e: eb 42 jmp e72 <twofiles+0x118>
if((n = write(fd, buf, 500)) != 500){
e30: 83 ec 04 sub $0x4,%esp
e33: 68 f4 01 00 00 push $0x1f4
e38: 68 80 86 00 00 push $0x8680
e3d: ff 75 e0 pushl -0x20(%ebp)
e40: e8 de 2d 00 00 call 3c23 <write>
e45: 83 c4 10 add $0x10,%esp
e48: 89 45 dc mov %eax,-0x24(%ebp)
e4b: 81 7d dc f4 01 00 00 cmpl $0x1f4,-0x24(%ebp)
e52: 74 1a je e6e <twofiles+0x114>
printf(1, "write failed %d\n", n);
e54: 83 ec 04 sub $0x4,%esp
e57: ff 75 dc pushl -0x24(%ebp)
e5a: 68 69 46 00 00 push $0x4669
e5f: 6a 01 push $0x1
e61: e8 34 2f 00 00 call 3d9a <printf>
e66: 83 c4 10 add $0x10,%esp
exit();
e69: e8 95 2d 00 00 call 3c03 <exit>
printf(1, "create failed\n");
exit();
}
memset(buf, pid?'p':'c', 512);
for(i = 0; i < 12; i++){
e6e: 83 45 f4 01 addl $0x1,-0xc(%ebp)
e72: 83 7d f4 0b cmpl $0xb,-0xc(%ebp)
e76: 7e b8 jle e30 <twofiles+0xd6>
if((n = write(fd, buf, 500)) != 500){
printf(1, "write failed %d\n", n);
exit();
}
}
close(fd);
e78: 83 ec 0c sub $0xc,%esp
e7b: ff 75 e0 pushl -0x20(%ebp)
e7e: e8 a8 2d 00 00 call 3c2b <close>
e83: 83 c4 10 add $0x10,%esp
if(pid)
e86: 83 7d e8 00 cmpl $0x0,-0x18(%ebp)
e8a: 74 11 je e9d <twofiles+0x143>
wait();
e8c: e8 7a 2d 00 00 call 3c0b <wait>
else
exit();
for(i = 0; i < 2; i++){
e91: c7 45 f4 00 00 00 00 movl $0x0,-0xc(%ebp)
e98: e9 dd 00 00 00 jmp f7a <twofiles+0x220>
}
close(fd);
if(pid)
wait();
else
exit();
e9d: e8 61 2d 00 00 call 3c03 <exit>
for(i = 0; i < 2; i++){
fd = open(i?"f1":"f2", 0);
ea2: 83 7d f4 00 cmpl $0x0,-0xc(%ebp)
ea6: 74 07 je eaf <twofiles+0x155>
ea8: b8 54 46 00 00 mov $0x4654,%eax
ead: eb 05 jmp eb4 <twofiles+0x15a>
eaf: b8 57 46 00 00 mov $0x4657,%eax
eb4: 83 ec 08 sub $0x8,%esp
eb7: 6a 00 push $0x0
eb9: 50 push %eax
eba: e8 84 2d 00 00 call 3c43 <open>
ebf: 83 c4 10 add $0x10,%esp
ec2: 89 45 e0 mov %eax,-0x20(%ebp)
total = 0;
ec5: c7 45 ec 00 00 00 00 movl $0x0,-0x14(%ebp)
while((n = read(fd, buf, sizeof(buf))) > 0){
ecc: eb 56 jmp f24 <twofiles+0x1ca>
for(j = 0; j < n; j++){
ece: c7 45 f0 00 00 00 00 movl $0x0,-0x10(%ebp)
ed5: eb 3f jmp f16 <twofiles+0x1bc>
if(buf[j] != (i?'p':'c')){
ed7: 8b 45 f0 mov -0x10(%ebp),%eax
eda: 05 80 86 00 00 add $0x8680,%eax
edf: 0f b6 00 movzbl (%eax),%eax
ee2: 0f be c0 movsbl %al,%eax
ee5: 83 7d f4 00 cmpl $0x0,-0xc(%ebp)
ee9: 74 07 je ef2 <twofiles+0x198>
eeb: ba 70 00 00 00 mov $0x70,%edx
ef0: eb 05 jmp ef7 <twofiles+0x19d>
ef2: ba 63 00 00 00 mov $0x63,%edx
ef7: 39 d0 cmp %edx,%eax
ef9: 74 17 je f12 <twofiles+0x1b8>
printf(1, "wrong char\n");
efb: 83 ec 08 sub $0x8,%esp
efe: 68 7a 46 00 00 push $0x467a
f03: 6a 01 push $0x1
f05: e8 90 2e 00 00 call 3d9a <printf>
f0a: 83 c4 10 add $0x10,%esp
exit();
f0d: e8 f1 2c 00 00 call 3c03 <exit>
for(i = 0; i < 2; i++){
fd = open(i?"f1":"f2", 0);
total = 0;
while((n = read(fd, buf, sizeof(buf))) > 0){
for(j = 0; j < n; j++){
f12: 83 45 f0 01 addl $0x1,-0x10(%ebp)
f16: 8b 45 f0 mov -0x10(%ebp),%eax
f19: 3b 45 dc cmp -0x24(%ebp),%eax
f1c: 7c b9 jl ed7 <twofiles+0x17d>
if(buf[j] != (i?'p':'c')){
printf(1, "wrong char\n");
exit();
}
}
total += n;
f1e: 8b 45 dc mov -0x24(%ebp),%eax
f21: 01 45 ec add %eax,-0x14(%ebp)
exit();
for(i = 0; i < 2; i++){
fd = open(i?"f1":"f2", 0);
total = 0;
while((n = read(fd, buf, sizeof(buf))) > 0){
f24: 83 ec 04 sub $0x4,%esp
f27: 68 00 20 00 00 push $0x2000
f2c: 68 80 86 00 00 push $0x8680
f31: ff 75 e0 pushl -0x20(%ebp)
f34: e8 e2 2c 00 00 call 3c1b <read>
f39: 83 c4 10 add $0x10,%esp
f3c: 89 45 dc mov %eax,-0x24(%ebp)
f3f: 83 7d dc 00 cmpl $0x0,-0x24(%ebp)
f43: 7f 89 jg ece <twofiles+0x174>
exit();
}
}
total += n;
}
close(fd);
f45: 83 ec 0c sub $0xc,%esp
f48: ff 75 e0 pushl -0x20(%ebp)
f4b: e8 db 2c 00 00 call 3c2b <close>
f50: 83 c4 10 add $0x10,%esp
if(total != 12*500){
f53: 81 7d ec 70 17 00 00 cmpl $0x1770,-0x14(%ebp)
f5a: 74 1a je f76 <twofiles+0x21c>
printf(1, "wrong length %d\n", total);
f5c: 83 ec 04 sub $0x4,%esp
f5f: ff 75 ec pushl -0x14(%ebp)
f62: 68 86 46 00 00 push $0x4686
f67: 6a 01 push $0x1
f69: e8 2c 2e 00 00 call 3d9a <printf>
f6e: 83 c4 10 add $0x10,%esp
exit();
f71: e8 8d 2c 00 00 call 3c03 <exit>
if(pid)
wait();
else
exit();
for(i = 0; i < 2; i++){
f76: 83 45 f4 01 addl $0x1,-0xc(%ebp)
f7a: 83 7d f4 01 cmpl $0x1,-0xc(%ebp)
f7e: 0f 8e 1e ff ff ff jle ea2 <twofiles+0x148>
printf(1, "wrong length %d\n", total);
exit();
}
}
unlink("f1");
f84: 83 ec 0c sub $0xc,%esp
f87: 68 54 46 00 00 push $0x4654
f8c: e8 c2 2c 00 00 call 3c53 <unlink>
f91: 83 c4 10 add $0x10,%esp
unlink("f2");
f94: 83 ec 0c sub $0xc,%esp
f97: 68 57 46 00 00 push $0x4657
f9c: e8 b2 2c 00 00 call 3c53 <unlink>
fa1: 83 c4 10 add $0x10,%esp
printf(1, "twofiles ok\n");
fa4: 83 ec 08 sub $0x8,%esp
fa7: 68 97 46 00 00 push $0x4697
fac: 6a 01 push $0x1
fae: e8 e7 2d 00 00 call 3d9a <printf>
fb3: 83 c4 10 add $0x10,%esp
}
fb6: 90 nop
fb7: c9 leave
fb8: c3 ret
00000fb9 <createdelete>:
// two processes create and delete different files in same directory
void
createdelete(void)
{
fb9: 55 push %ebp
fba: 89 e5 mov %esp,%ebp
fbc: 83 ec 38 sub $0x38,%esp
enum { N = 20 };
int pid, i, fd;
char name[32];
printf(1, "createdelete test\n");
fbf: 83 ec 08 sub $0x8,%esp
fc2: 68 a4 46 00 00 push $0x46a4
fc7: 6a 01 push $0x1
fc9: e8 cc 2d 00 00 call 3d9a <printf>
fce: 83 c4 10 add $0x10,%esp
pid = fork();
fd1: e8 25 2c 00 00 call 3bfb <fork>
fd6: 89 45 f0 mov %eax,-0x10(%ebp)
if(pid < 0){
fd9: 83 7d f0 00 cmpl $0x0,-0x10(%ebp)
fdd: 79 17 jns ff6 <createdelete+0x3d>
printf(1, "fork failed\n");
fdf: 83 ec 08 sub $0x8,%esp
fe2: 68 3d 45 00 00 push $0x453d
fe7: 6a 01 push $0x1
fe9: e8 ac 2d 00 00 call 3d9a <printf>
fee: 83 c4 10 add $0x10,%esp
exit();
ff1: e8 0d 2c 00 00 call 3c03 <exit>
}
name[0] = pid ? 'p' : 'c';
ff6: 83 7d f0 00 cmpl $0x0,-0x10(%ebp)
ffa: 74 07 je 1003 <createdelete+0x4a>
ffc: b8 70 00 00 00 mov $0x70,%eax
1001: eb 05 jmp 1008 <createdelete+0x4f>
1003: b8 63 00 00 00 mov $0x63,%eax
1008: 88 45 cc mov %al,-0x34(%ebp)
name[2] = '\0';
100b: c6 45 ce 00 movb $0x0,-0x32(%ebp)
for(i = 0; i < N; i++){
100f: c7 45 f4 00 00 00 00 movl $0x0,-0xc(%ebp)
1016: e9 9b 00 00 00 jmp 10b6 <createdelete+0xfd>
name[1] = '0' + i;
101b: 8b 45 f4 mov -0xc(%ebp),%eax
101e: 83 c0 30 add $0x30,%eax
1021: 88 45 cd mov %al,-0x33(%ebp)
fd = open(name, O_CREATE | O_RDWR);
1024: 83 ec 08 sub $0x8,%esp
1027: 68 02 02 00 00 push $0x202
102c: 8d 45 cc lea -0x34(%ebp),%eax
102f: 50 push %eax
1030: e8 0e 2c 00 00 call 3c43 <open>
1035: 83 c4 10 add $0x10,%esp
1038: 89 45 ec mov %eax,-0x14(%ebp)
if(fd < 0){
103b: 83 7d ec 00 cmpl $0x0,-0x14(%ebp)
103f: 79 17 jns 1058 <createdelete+0x9f>
printf(1, "create failed\n");
1041: 83 ec 08 sub $0x8,%esp
1044: 68 5a 46 00 00 push $0x465a
1049: 6a 01 push $0x1
104b: e8 4a 2d 00 00 call 3d9a <printf>
1050: 83 c4 10 add $0x10,%esp
exit();
1053: e8 ab 2b 00 00 call 3c03 <exit>
}
close(fd);
1058: 83 ec 0c sub $0xc,%esp
105b: ff 75 ec pushl -0x14(%ebp)
105e: e8 c8 2b 00 00 call 3c2b <close>
1063: 83 c4 10 add $0x10,%esp
if(i > 0 && (i % 2 ) == 0){
1066: 83 7d f4 00 cmpl $0x0,-0xc(%ebp)
106a: 7e 46 jle 10b2 <createdelete+0xf9>
106c: 8b 45 f4 mov -0xc(%ebp),%eax
106f: 83 e0 01 and $0x1,%eax
1072: 85 c0 test %eax,%eax
1074: 75 3c jne 10b2 <createdelete+0xf9>
name[1] = '0' + (i / 2);
1076: 8b 45 f4 mov -0xc(%ebp),%eax
1079: 89 c2 mov %eax,%edx
107b: c1 ea 1f shr $0x1f,%edx
107e: 01 d0 add %edx,%eax
1080: d1 f8 sar %eax
1082: 83 c0 30 add $0x30,%eax
1085: 88 45 cd mov %al,-0x33(%ebp)
if(unlink(name) < 0){
1088: 83 ec 0c sub $0xc,%esp
108b: 8d 45 cc lea -0x34(%ebp),%eax
108e: 50 push %eax
108f: e8 bf 2b 00 00 call 3c53 <unlink>
1094: 83 c4 10 add $0x10,%esp
1097: 85 c0 test %eax,%eax
1099: 79 17 jns 10b2 <createdelete+0xf9>
printf(1, "unlink failed\n");
109b: 83 ec 08 sub $0x8,%esp
109e: 68 b7 46 00 00 push $0x46b7
10a3: 6a 01 push $0x1
10a5: e8 f0 2c 00 00 call 3d9a <printf>
10aa: 83 c4 10 add $0x10,%esp
exit();
10ad: e8 51 2b 00 00 call 3c03 <exit>
exit();
}
name[0] = pid ? 'p' : 'c';
name[2] = '\0';
for(i = 0; i < N; i++){
10b2: 83 45 f4 01 addl $0x1,-0xc(%ebp)
10b6: 83 7d f4 13 cmpl $0x13,-0xc(%ebp)
10ba: 0f 8e 5b ff ff ff jle 101b <createdelete+0x62>
exit();
}
}
}
if(pid==0)
10c0: 83 7d f0 00 cmpl $0x0,-0x10(%ebp)
10c4: 75 05 jne 10cb <createdelete+0x112>
exit();
10c6: e8 38 2b 00 00 call 3c03 <exit>
else
wait();
10cb: e8 3b 2b 00 00 call 3c0b <wait>
for(i = 0; i < N; i++){
10d0: c7 45 f4 00 00 00 00 movl $0x0,-0xc(%ebp)
10d7: e9 22 01 00 00 jmp 11fe <createdelete+0x245>
name[0] = 'p';
10dc: c6 45 cc 70 movb $0x70,-0x34(%ebp)
name[1] = '0' + i;
10e0: 8b 45 f4 mov -0xc(%ebp),%eax
10e3: 83 c0 30 add $0x30,%eax
10e6: 88 45 cd mov %al,-0x33(%ebp)
fd = open(name, 0);
10e9: 83 ec 08 sub $0x8,%esp
10ec: 6a 00 push $0x0
10ee: 8d 45 cc lea -0x34(%ebp),%eax
10f1: 50 push %eax
10f2: e8 4c 2b 00 00 call 3c43 <open>
10f7: 83 c4 10 add $0x10,%esp
10fa: 89 45 ec mov %eax,-0x14(%ebp)
if((i == 0 || i >= N/2) && fd < 0){
10fd: 83 7d f4 00 cmpl $0x0,-0xc(%ebp)
1101: 74 06 je 1109 <createdelete+0x150>
1103: 83 7d f4 09 cmpl $0x9,-0xc(%ebp)
1107: 7e 21 jle 112a <createdelete+0x171>
1109: 83 7d ec 00 cmpl $0x0,-0x14(%ebp)
110d: 79 1b jns 112a <createdelete+0x171>
printf(1, "oops createdelete %s didn't exist\n", name);
110f: 83 ec 04 sub $0x4,%esp
1112: 8d 45 cc lea -0x34(%ebp),%eax
1115: 50 push %eax
1116: 68 c8 46 00 00 push $0x46c8
111b: 6a 01 push $0x1
111d: e8 78 2c 00 00 call 3d9a <printf>
1122: 83 c4 10 add $0x10,%esp
exit();
1125: e8 d9 2a 00 00 call 3c03 <exit>
} else if((i >= 1 && i < N/2) && fd >= 0){
112a: 83 7d f4 00 cmpl $0x0,-0xc(%ebp)
112e: 7e 27 jle 1157 <createdelete+0x19e>
1130: 83 7d f4 09 cmpl $0x9,-0xc(%ebp)
1134: 7f 21 jg 1157 <createdelete+0x19e>
1136: 83 7d ec 00 cmpl $0x0,-0x14(%ebp)
113a: 78 1b js 1157 <createdelete+0x19e>
printf(1, "oops createdelete %s did exist\n", name);
113c: 83 ec 04 sub $0x4,%esp
113f: 8d 45 cc lea -0x34(%ebp),%eax
1142: 50 push %eax
1143: 68 ec 46 00 00 push $0x46ec
1148: 6a 01 push $0x1
114a: e8 4b 2c 00 00 call 3d9a <printf>
114f: 83 c4 10 add $0x10,%esp
exit();
1152: e8 ac 2a 00 00 call 3c03 <exit>
}
if(fd >= 0)
1157: 83 7d ec 00 cmpl $0x0,-0x14(%ebp)
115b: 78 0e js 116b <createdelete+0x1b2>
close(fd);
115d: 83 ec 0c sub $0xc,%esp
1160: ff 75 ec pushl -0x14(%ebp)
1163: e8 c3 2a 00 00 call 3c2b <close>
1168: 83 c4 10 add $0x10,%esp
name[0] = 'c';
116b: c6 45 cc 63 movb $0x63,-0x34(%ebp)
name[1] = '0' + i;
116f: 8b 45 f4 mov -0xc(%ebp),%eax
1172: 83 c0 30 add $0x30,%eax
1175: 88 45 cd mov %al,-0x33(%ebp)
fd = open(name, 0);
1178: 83 ec 08 sub $0x8,%esp
117b: 6a 00 push $0x0
117d: 8d 45 cc lea -0x34(%ebp),%eax
1180: 50 push %eax
1181: e8 bd 2a 00 00 call 3c43 <open>
1186: 83 c4 10 add $0x10,%esp
1189: 89 45 ec mov %eax,-0x14(%ebp)
if((i == 0 || i >= N/2) && fd < 0){
118c: 83 7d f4 00 cmpl $0x0,-0xc(%ebp)
1190: 74 06 je 1198 <createdelete+0x1df>
1192: 83 7d f4 09 cmpl $0x9,-0xc(%ebp)
1196: 7e 21 jle 11b9 <createdelete+0x200>
1198: 83 7d ec 00 cmpl $0x0,-0x14(%ebp)
119c: 79 1b jns 11b9 <createdelete+0x200>
printf(1, "oops createdelete %s didn't exist\n", name);
119e: 83 ec 04 sub $0x4,%esp
11a1: 8d 45 cc lea -0x34(%ebp),%eax
11a4: 50 push %eax
11a5: 68 c8 46 00 00 push $0x46c8
11aa: 6a 01 push $0x1
11ac: e8 e9 2b 00 00 call 3d9a <printf>
11b1: 83 c4 10 add $0x10,%esp
exit();
11b4: e8 4a 2a 00 00 call 3c03 <exit>
} else if((i >= 1 && i < N/2) && fd >= 0){
11b9: 83 7d f4 00 cmpl $0x0,-0xc(%ebp)
11bd: 7e 27 jle 11e6 <createdelete+0x22d>
11bf: 83 7d f4 09 cmpl $0x9,-0xc(%ebp)
11c3: 7f 21 jg 11e6 <createdelete+0x22d>
11c5: 83 7d ec 00 cmpl $0x0,-0x14(%ebp)
11c9: 78 1b js 11e6 <createdelete+0x22d>
printf(1, "oops createdelete %s did exist\n", name);
11cb: 83 ec 04 sub $0x4,%esp
11ce: 8d 45 cc lea -0x34(%ebp),%eax
11d1: 50 push %eax
11d2: 68 ec 46 00 00 push $0x46ec
11d7: 6a 01 push $0x1
11d9: e8 bc 2b 00 00 call 3d9a <printf>
11de: 83 c4 10 add $0x10,%esp
exit();
11e1: e8 1d 2a 00 00 call 3c03 <exit>
}
if(fd >= 0)
11e6: 83 7d ec 00 cmpl $0x0,-0x14(%ebp)
11ea: 78 0e js 11fa <createdelete+0x241>
close(fd);
11ec: 83 ec 0c sub $0xc,%esp
11ef: ff 75 ec pushl -0x14(%ebp)
11f2: e8 34 2a 00 00 call 3c2b <close>
11f7: 83 c4 10 add $0x10,%esp
if(pid==0)
exit();
else
wait();
for(i = 0; i < N; i++){
11fa: 83 45 f4 01 addl $0x1,-0xc(%ebp)
11fe: 83 7d f4 13 cmpl $0x13,-0xc(%ebp)
1202: 0f 8e d4 fe ff ff jle 10dc <createdelete+0x123>
}
if(fd >= 0)
close(fd);
}
for(i = 0; i < N; i++){
1208: c7 45 f4 00 00 00 00 movl $0x0,-0xc(%ebp)
120f: eb 33 jmp 1244 <createdelete+0x28b>
name[0] = 'p';
1211: c6 45 cc 70 movb $0x70,-0x34(%ebp)
name[1] = '0' + i;
1215: 8b 45 f4 mov -0xc(%ebp),%eax
1218: 83 c0 30 add $0x30,%eax
121b: 88 45 cd mov %al,-0x33(%ebp)
unlink(name);
121e: 83 ec 0c sub $0xc,%esp
1221: 8d 45 cc lea -0x34(%ebp),%eax
1224: 50 push %eax
1225: e8 29 2a 00 00 call 3c53 <unlink>
122a: 83 c4 10 add $0x10,%esp
name[0] = 'c';
122d: c6 45 cc 63 movb $0x63,-0x34(%ebp)
unlink(name);
1231: 83 ec 0c sub $0xc,%esp
1234: 8d 45 cc lea -0x34(%ebp),%eax
1237: 50 push %eax
1238: e8 16 2a 00 00 call 3c53 <unlink>
123d: 83 c4 10 add $0x10,%esp
}
if(fd >= 0)
close(fd);
}
for(i = 0; i < N; i++){
1240: 83 45 f4 01 addl $0x1,-0xc(%ebp)
1244: 83 7d f4 13 cmpl $0x13,-0xc(%ebp)
1248: 7e c7 jle 1211 <createdelete+0x258>
unlink(name);
name[0] = 'c';
unlink(name);
}
printf(1, "createdelete ok\n");
124a: 83 ec 08 sub $0x8,%esp
124d: 68 0c 47 00 00 push $0x470c
1252: 6a 01 push $0x1
1254: e8 41 2b 00 00 call 3d9a <printf>
1259: 83 c4 10 add $0x10,%esp
}
125c: 90 nop
125d: c9 leave
125e: c3 ret
0000125f <unlinkread>:
// can I unlink a file and still read it?
void
unlinkread(void)
{
125f: 55 push %ebp
1260: 89 e5 mov %esp,%ebp
1262: 83 ec 18 sub $0x18,%esp
int fd, fd1;
printf(1, "unlinkread test\n");
1265: 83 ec 08 sub $0x8,%esp
1268: 68 1d 47 00 00 push $0x471d
126d: 6a 01 push $0x1
126f: e8 26 2b 00 00 call 3d9a <printf>
1274: 83 c4 10 add $0x10,%esp
fd = open("unlinkread", O_CREATE | O_RDWR);
1277: 83 ec 08 sub $0x8,%esp
127a: 68 02 02 00 00 push $0x202
127f: 68 2e 47 00 00 push $0x472e
1284: e8 ba 29 00 00 call 3c43 <open>
1289: 83 c4 10 add $0x10,%esp
128c: 89 45 f4 mov %eax,-0xc(%ebp)
if(fd < 0){
128f: 83 7d f4 00 cmpl $0x0,-0xc(%ebp)
1293: 79 17 jns 12ac <unlinkread+0x4d>
printf(1, "create unlinkread failed\n");
1295: 83 ec 08 sub $0x8,%esp
1298: 68 39 47 00 00 push $0x4739
129d: 6a 01 push $0x1
129f: e8 f6 2a 00 00 call 3d9a <printf>
12a4: 83 c4 10 add $0x10,%esp
exit();
12a7: e8 57 29 00 00 call 3c03 <exit>
}
write(fd, "hello", 5);
12ac: 83 ec 04 sub $0x4,%esp
12af: 6a 05 push $0x5
12b1: 68 53 47 00 00 push $0x4753
12b6: ff 75 f4 pushl -0xc(%ebp)
12b9: e8 65 29 00 00 call 3c23 <write>
12be: 83 c4 10 add $0x10,%esp
close(fd);
12c1: 83 ec 0c sub $0xc,%esp
12c4: ff 75 f4 pushl -0xc(%ebp)
12c7: e8 5f 29 00 00 call 3c2b <close>
12cc: 83 c4 10 add $0x10,%esp
fd = open("unlinkread", O_RDWR);
12cf: 83 ec 08 sub $0x8,%esp
12d2: 6a 02 push $0x2
12d4: 68 2e 47 00 00 push $0x472e
12d9: e8 65 29 00 00 call 3c43 <open>
12de: 83 c4 10 add $0x10,%esp
12e1: 89 45 f4 mov %eax,-0xc(%ebp)
if(fd < 0){
12e4: 83 7d f4 00 cmpl $0x0,-0xc(%ebp)
12e8: 79 17 jns 1301 <unlinkread+0xa2>
printf(1, "open unlinkread failed\n");
12ea: 83 ec 08 sub $0x8,%esp
12ed: 68 59 47 00 00 push $0x4759
12f2: 6a 01 push $0x1
12f4: e8 a1 2a 00 00 call 3d9a <printf>
12f9: 83 c4 10 add $0x10,%esp
exit();
12fc: e8 02 29 00 00 call 3c03 <exit>
}
if(unlink("unlinkread") != 0){
1301: 83 ec 0c sub $0xc,%esp
1304: 68 2e 47 00 00 push $0x472e
1309: e8 45 29 00 00 call 3c53 <unlink>
130e: 83 c4 10 add $0x10,%esp
1311: 85 c0 test %eax,%eax
1313: 74 17 je 132c <unlinkread+0xcd>
printf(1, "unlink unlinkread failed\n");
1315: 83 ec 08 sub $0x8,%esp
1318: 68 71 47 00 00 push $0x4771
131d: 6a 01 push $0x1
131f: e8 76 2a 00 00 call 3d9a <printf>
1324: 83 c4 10 add $0x10,%esp
exit();
1327: e8 d7 28 00 00 call 3c03 <exit>
}
fd1 = open("unlinkread", O_CREATE | O_RDWR);
132c: 83 ec 08 sub $0x8,%esp
132f: 68 02 02 00 00 push $0x202
1334: 68 2e 47 00 00 push $0x472e
1339: e8 05 29 00 00 call 3c43 <open>
133e: 83 c4 10 add $0x10,%esp
1341: 89 45 f0 mov %eax,-0x10(%ebp)
write(fd1, "yyy", 3);
1344: 83 ec 04 sub $0x4,%esp
1347: 6a 03 push $0x3
1349: 68 8b 47 00 00 push $0x478b
134e: ff 75 f0 pushl -0x10(%ebp)
1351: e8 cd 28 00 00 call 3c23 <write>
1356: 83 c4 10 add $0x10,%esp
close(fd1);
1359: 83 ec 0c sub $0xc,%esp
135c: ff 75 f0 pushl -0x10(%ebp)
135f: e8 c7 28 00 00 call 3c2b <close>
1364: 83 c4 10 add $0x10,%esp
if(read(fd, buf, sizeof(buf)) != 5){
1367: 83 ec 04 sub $0x4,%esp
136a: 68 00 20 00 00 push $0x2000
136f: 68 80 86 00 00 push $0x8680
1374: ff 75 f4 pushl -0xc(%ebp)
1377: e8 9f 28 00 00 call 3c1b <read>
137c: 83 c4 10 add $0x10,%esp
137f: 83 f8 05 cmp $0x5,%eax
1382: 74 17 je 139b <unlinkread+0x13c>
printf(1, "unlinkread read failed");
1384: 83 ec 08 sub $0x8,%esp
1387: 68 8f 47 00 00 push $0x478f
138c: 6a 01 push $0x1
138e: e8 07 2a 00 00 call 3d9a <printf>
1393: 83 c4 10 add $0x10,%esp
exit();
1396: e8 68 28 00 00 call 3c03 <exit>
}
if(buf[0] != 'h'){
139b: 0f b6 05 80 86 00 00 movzbl 0x8680,%eax
13a2: 3c 68 cmp $0x68,%al
13a4: 74 17 je 13bd <unlinkread+0x15e>
printf(1, "unlinkread wrong data\n");
13a6: 83 ec 08 sub $0x8,%esp
13a9: 68 a6 47 00 00 push $0x47a6
13ae: 6a 01 push $0x1
13b0: e8 e5 29 00 00 call 3d9a <printf>
13b5: 83 c4 10 add $0x10,%esp
exit();
13b8: e8 46 28 00 00 call 3c03 <exit>
}
if(write(fd, buf, 10) != 10){
13bd: 83 ec 04 sub $0x4,%esp
13c0: 6a 0a push $0xa
13c2: 68 80 86 00 00 push $0x8680
13c7: ff 75 f4 pushl -0xc(%ebp)
13ca: e8 54 28 00 00 call 3c23 <write>
13cf: 83 c4 10 add $0x10,%esp
13d2: 83 f8 0a cmp $0xa,%eax
13d5: 74 17 je 13ee <unlinkread+0x18f>
printf(1, "unlinkread write failed\n");
13d7: 83 ec 08 sub $0x8,%esp
13da: 68 bd 47 00 00 push $0x47bd
13df: 6a 01 push $0x1
13e1: e8 b4 29 00 00 call 3d9a <printf>
13e6: 83 c4 10 add $0x10,%esp
exit();
13e9: e8 15 28 00 00 call 3c03 <exit>
}
close(fd);
13ee: 83 ec 0c sub $0xc,%esp
13f1: ff 75 f4 pushl -0xc(%ebp)
13f4: e8 32 28 00 00 call 3c2b <close>
13f9: 83 c4 10 add $0x10,%esp
unlink("unlinkread");
13fc: 83 ec 0c sub $0xc,%esp
13ff: 68 2e 47 00 00 push $0x472e
1404: e8 4a 28 00 00 call 3c53 <unlink>
1409: 83 c4 10 add $0x10,%esp
printf(1, "unlinkread ok\n");
140c: 83 ec 08 sub $0x8,%esp
140f: 68 d6 47 00 00 push $0x47d6
1414: 6a 01 push $0x1
1416: e8 7f 29 00 00 call 3d9a <printf>
141b: 83 c4 10 add $0x10,%esp
}
141e: 90 nop
141f: c9 leave
1420: c3 ret
00001421 <linktest>:
void
linktest(void)
{
1421: 55 push %ebp
1422: 89 e5 mov %esp,%ebp
1424: 83 ec 18 sub $0x18,%esp
int fd;
printf(1, "linktest\n");
1427: 83 ec 08 sub $0x8,%esp
142a: 68 e5 47 00 00 push $0x47e5
142f: 6a 01 push $0x1
1431: e8 64 29 00 00 call 3d9a <printf>
1436: 83 c4 10 add $0x10,%esp
unlink("lf1");
1439: 83 ec 0c sub $0xc,%esp
143c: 68 ef 47 00 00 push $0x47ef
1441: e8 0d 28 00 00 call 3c53 <unlink>
1446: 83 c4 10 add $0x10,%esp
unlink("lf2");
1449: 83 ec 0c sub $0xc,%esp
144c: 68 f3 47 00 00 push $0x47f3
1451: e8 fd 27 00 00 call 3c53 <unlink>
1456: 83 c4 10 add $0x10,%esp
fd = open("lf1", O_CREATE|O_RDWR);
1459: 83 ec 08 sub $0x8,%esp
145c: 68 02 02 00 00 push $0x202
1461: 68 ef 47 00 00 push $0x47ef
1466: e8 d8 27 00 00 call 3c43 <open>
146b: 83 c4 10 add $0x10,%esp
146e: 89 45 f4 mov %eax,-0xc(%ebp)
if(fd < 0){
1471: 83 7d f4 00 cmpl $0x0,-0xc(%ebp)
1475: 79 17 jns 148e <linktest+0x6d>
printf(1, "create lf1 failed\n");
1477: 83 ec 08 sub $0x8,%esp
147a: 68 f7 47 00 00 push $0x47f7
147f: 6a 01 push $0x1
1481: e8 14 29 00 00 call 3d9a <printf>
1486: 83 c4 10 add $0x10,%esp
exit();
1489: e8 75 27 00 00 call 3c03 <exit>
}
if(write(fd, "hello", 5) != 5){
148e: 83 ec 04 sub $0x4,%esp
1491: 6a 05 push $0x5
1493: 68 53 47 00 00 push $0x4753
1498: ff 75 f4 pushl -0xc(%ebp)
149b: e8 83 27 00 00 call 3c23 <write>
14a0: 83 c4 10 add $0x10,%esp
14a3: 83 f8 05 cmp $0x5,%eax
14a6: 74 17 je 14bf <linktest+0x9e>
printf(1, "write lf1 failed\n");
14a8: 83 ec 08 sub $0x8,%esp
14ab: 68 0a 48 00 00 push $0x480a
14b0: 6a 01 push $0x1
14b2: e8 e3 28 00 00 call 3d9a <printf>
14b7: 83 c4 10 add $0x10,%esp
exit();
14ba: e8 44 27 00 00 call 3c03 <exit>
}
close(fd);
14bf: 83 ec 0c sub $0xc,%esp
14c2: ff 75 f4 pushl -0xc(%ebp)
14c5: e8 61 27 00 00 call 3c2b <close>
14ca: 83 c4 10 add $0x10,%esp
if(link("lf1", "lf2") < 0){
14cd: 83 ec 08 sub $0x8,%esp
14d0: 68 f3 47 00 00 push $0x47f3
14d5: 68 ef 47 00 00 push $0x47ef
14da: e8 84 27 00 00 call 3c63 <link>
14df: 83 c4 10 add $0x10,%esp
14e2: 85 c0 test %eax,%eax
14e4: 79 17 jns 14fd <linktest+0xdc>
printf(1, "link lf1 lf2 failed\n");
14e6: 83 ec 08 sub $0x8,%esp
14e9: 68 1c 48 00 00 push $0x481c
14ee: 6a 01 push $0x1
14f0: e8 a5 28 00 00 call 3d9a <printf>
14f5: 83 c4 10 add $0x10,%esp
exit();
14f8: e8 06 27 00 00 call 3c03 <exit>
}
unlink("lf1");
14fd: 83 ec 0c sub $0xc,%esp
1500: 68 ef 47 00 00 push $0x47ef
1505: e8 49 27 00 00 call 3c53 <unlink>
150a: 83 c4 10 add $0x10,%esp
if(open("lf1", 0) >= 0){
150d: 83 ec 08 sub $0x8,%esp
1510: 6a 00 push $0x0
1512: 68 ef 47 00 00 push $0x47ef
1517: e8 27 27 00 00 call 3c43 <open>
151c: 83 c4 10 add $0x10,%esp
151f: 85 c0 test %eax,%eax
1521: 78 17 js 153a <linktest+0x119>
printf(1, "unlinked lf1 but it is still there!\n");
1523: 83 ec 08 sub $0x8,%esp
1526: 68 34 48 00 00 push $0x4834
152b: 6a 01 push $0x1
152d: e8 68 28 00 00 call 3d9a <printf>
1532: 83 c4 10 add $0x10,%esp
exit();
1535: e8 c9 26 00 00 call 3c03 <exit>
}
fd = open("lf2", 0);
153a: 83 ec 08 sub $0x8,%esp
153d: 6a 00 push $0x0
153f: 68 f3 47 00 00 push $0x47f3
1544: e8 fa 26 00 00 call 3c43 <open>
1549: 83 c4 10 add $0x10,%esp
154c: 89 45 f4 mov %eax,-0xc(%ebp)
if(fd < 0){
154f: 83 7d f4 00 cmpl $0x0,-0xc(%ebp)
1553: 79 17 jns 156c <linktest+0x14b>
printf(1, "open lf2 failed\n");
1555: 83 ec 08 sub $0x8,%esp
1558: 68 59 48 00 00 push $0x4859
155d: 6a 01 push $0x1
155f: e8 36 28 00 00 call 3d9a <printf>
1564: 83 c4 10 add $0x10,%esp
exit();
1567: e8 97 26 00 00 call 3c03 <exit>
}
if(read(fd, buf, sizeof(buf)) != 5){
156c: 83 ec 04 sub $0x4,%esp
156f: 68 00 20 00 00 push $0x2000
1574: 68 80 86 00 00 push $0x8680
1579: ff 75 f4 pushl -0xc(%ebp)
157c: e8 9a 26 00 00 call 3c1b <read>
1581: 83 c4 10 add $0x10,%esp
1584: 83 f8 05 cmp $0x5,%eax
1587: 74 17 je 15a0 <linktest+0x17f>
printf(1, "read lf2 failed\n");
1589: 83 ec 08 sub $0x8,%esp
158c: 68 6a 48 00 00 push $0x486a
1591: 6a 01 push $0x1
1593: e8 02 28 00 00 call 3d9a <printf>
1598: 83 c4 10 add $0x10,%esp
exit();
159b: e8 63 26 00 00 call 3c03 <exit>
}
close(fd);
15a0: 83 ec 0c sub $0xc,%esp
15a3: ff 75 f4 pushl -0xc(%ebp)
15a6: e8 80 26 00 00 call 3c2b <close>
15ab: 83 c4 10 add $0x10,%esp
if(link("lf2", "lf2") >= 0){
15ae: 83 ec 08 sub $0x8,%esp
15b1: 68 f3 47 00 00 push $0x47f3
15b6: 68 f3 47 00 00 push $0x47f3
15bb: e8 a3 26 00 00 call 3c63 <link>
15c0: 83 c4 10 add $0x10,%esp
15c3: 85 c0 test %eax,%eax
15c5: 78 17 js 15de <linktest+0x1bd>
printf(1, "link lf2 lf2 succeeded! oops\n");
15c7: 83 ec 08 sub $0x8,%esp
15ca: 68 7b 48 00 00 push $0x487b
15cf: 6a 01 push $0x1
15d1: e8 c4 27 00 00 call 3d9a <printf>
15d6: 83 c4 10 add $0x10,%esp
exit();
15d9: e8 25 26 00 00 call 3c03 <exit>
}
unlink("lf2");
15de: 83 ec 0c sub $0xc,%esp
15e1: 68 f3 47 00 00 push $0x47f3
15e6: e8 68 26 00 00 call 3c53 <unlink>
15eb: 83 c4 10 add $0x10,%esp
if(link("lf2", "lf1") >= 0){
15ee: 83 ec 08 sub $0x8,%esp
15f1: 68 ef 47 00 00 push $0x47ef
15f6: 68 f3 47 00 00 push $0x47f3
15fb: e8 63 26 00 00 call 3c63 <link>
1600: 83 c4 10 add $0x10,%esp
1603: 85 c0 test %eax,%eax
1605: 78 17 js 161e <linktest+0x1fd>
printf(1, "link non-existant succeeded! oops\n");
1607: 83 ec 08 sub $0x8,%esp
160a: 68 9c 48 00 00 push $0x489c
160f: 6a 01 push $0x1
1611: e8 84 27 00 00 call 3d9a <printf>
1616: 83 c4 10 add $0x10,%esp
exit();
1619: e8 e5 25 00 00 call 3c03 <exit>
}
if(link(".", "lf1") >= 0){
161e: 83 ec 08 sub $0x8,%esp
1621: 68 ef 47 00 00 push $0x47ef
1626: 68 bf 48 00 00 push $0x48bf
162b: e8 33 26 00 00 call 3c63 <link>
1630: 83 c4 10 add $0x10,%esp
1633: 85 c0 test %eax,%eax
1635: 78 17 js 164e <linktest+0x22d>
printf(1, "link . lf1 succeeded! oops\n");
1637: 83 ec 08 sub $0x8,%esp
163a: 68 c1 48 00 00 push $0x48c1
163f: 6a 01 push $0x1
1641: e8 54 27 00 00 call 3d9a <printf>
1646: 83 c4 10 add $0x10,%esp
exit();
1649: e8 b5 25 00 00 call 3c03 <exit>
}
printf(1, "linktest ok\n");
164e: 83 ec 08 sub $0x8,%esp
1651: 68 dd 48 00 00 push $0x48dd
1656: 6a 01 push $0x1
1658: e8 3d 27 00 00 call 3d9a <printf>
165d: 83 c4 10 add $0x10,%esp
}
1660: 90 nop
1661: c9 leave
1662: c3 ret
00001663 <concreate>:
// test concurrent create/link/unlink of the same file
void
concreate(void)
{
1663: 55 push %ebp
1664: 89 e5 mov %esp,%ebp
1666: 83 ec 58 sub $0x58,%esp
struct {
ushort inum;
char name[14];
} de;
printf(1, "concreate test\n");
1669: 83 ec 08 sub $0x8,%esp
166c: 68 ea 48 00 00 push $0x48ea
1671: 6a 01 push $0x1
1673: e8 22 27 00 00 call 3d9a <printf>
1678: 83 c4 10 add $0x10,%esp
file[0] = 'C';
167b: c6 45 e5 43 movb $0x43,-0x1b(%ebp)
file[2] = '\0';
167f: c6 45 e7 00 movb $0x0,-0x19(%ebp)
for(i = 0; i < 40; i++){
1683: c7 45 f4 00 00 00 00 movl $0x0,-0xc(%ebp)
168a: e9 fc 00 00 00 jmp 178b <concreate+0x128>
file[1] = '0' + i;
168f: 8b 45 f4 mov -0xc(%ebp),%eax
1692: 83 c0 30 add $0x30,%eax
1695: 88 45 e6 mov %al,-0x1a(%ebp)
unlink(file);
1698: 83 ec 0c sub $0xc,%esp
169b: 8d 45 e5 lea -0x1b(%ebp),%eax
169e: 50 push %eax
169f: e8 af 25 00 00 call 3c53 <unlink>
16a4: 83 c4 10 add $0x10,%esp
pid = fork();
16a7: e8 4f 25 00 00 call 3bfb <fork>
16ac: 89 45 ec mov %eax,-0x14(%ebp)
if(pid && (i % 3) == 1){
16af: 83 7d ec 00 cmpl $0x0,-0x14(%ebp)
16b3: 74 3b je 16f0 <concreate+0x8d>
16b5: 8b 4d f4 mov -0xc(%ebp),%ecx
16b8: ba 56 55 55 55 mov $0x55555556,%edx
16bd: 89 c8 mov %ecx,%eax
16bf: f7 ea imul %edx
16c1: 89 c8 mov %ecx,%eax
16c3: c1 f8 1f sar $0x1f,%eax
16c6: 29 c2 sub %eax,%edx
16c8: 89 d0 mov %edx,%eax
16ca: 01 c0 add %eax,%eax
16cc: 01 d0 add %edx,%eax
16ce: 29 c1 sub %eax,%ecx
16d0: 89 ca mov %ecx,%edx
16d2: 83 fa 01 cmp $0x1,%edx
16d5: 75 19 jne 16f0 <concreate+0x8d>
link("C0", file);
16d7: 83 ec 08 sub $0x8,%esp
16da: 8d 45 e5 lea -0x1b(%ebp),%eax
16dd: 50 push %eax
16de: 68 fa 48 00 00 push $0x48fa
16e3: e8 7b 25 00 00 call 3c63 <link>
16e8: 83 c4 10 add $0x10,%esp
16eb: e9 87 00 00 00 jmp 1777 <concreate+0x114>
} else if(pid == 0 && (i % 5) == 1){
16f0: 83 7d ec 00 cmpl $0x0,-0x14(%ebp)
16f4: 75 3b jne 1731 <concreate+0xce>
16f6: 8b 4d f4 mov -0xc(%ebp),%ecx
16f9: ba 67 66 66 66 mov $0x66666667,%edx
16fe: 89 c8 mov %ecx,%eax
1700: f7 ea imul %edx
1702: d1 fa sar %edx
1704: 89 c8 mov %ecx,%eax
1706: c1 f8 1f sar $0x1f,%eax
1709: 29 c2 sub %eax,%edx
170b: 89 d0 mov %edx,%eax
170d: c1 e0 02 shl $0x2,%eax
1710: 01 d0 add %edx,%eax
1712: 29 c1 sub %eax,%ecx
1714: 89 ca mov %ecx,%edx
1716: 83 fa 01 cmp $0x1,%edx
1719: 75 16 jne 1731 <concreate+0xce>
link("C0", file);
171b: 83 ec 08 sub $0x8,%esp
171e: 8d 45 e5 lea -0x1b(%ebp),%eax
1721: 50 push %eax
1722: 68 fa 48 00 00 push $0x48fa
1727: e8 37 25 00 00 call 3c63 <link>
172c: 83 c4 10 add $0x10,%esp
172f: eb 46 jmp 1777 <concreate+0x114>
} else {
fd = open(file, O_CREATE | O_RDWR);
1731: 83 ec 08 sub $0x8,%esp
1734: 68 02 02 00 00 push $0x202
1739: 8d 45 e5 lea -0x1b(%ebp),%eax
173c: 50 push %eax
173d: e8 01 25 00 00 call 3c43 <open>
1742: 83 c4 10 add $0x10,%esp
1745: 89 45 e8 mov %eax,-0x18(%ebp)
if(fd < 0){
1748: 83 7d e8 00 cmpl $0x0,-0x18(%ebp)
174c: 79 1b jns 1769 <concreate+0x106>
printf(1, "concreate create %s failed\n", file);
174e: 83 ec 04 sub $0x4,%esp
1751: 8d 45 e5 lea -0x1b(%ebp),%eax
1754: 50 push %eax
1755: 68 fd 48 00 00 push $0x48fd
175a: 6a 01 push $0x1
175c: e8 39 26 00 00 call 3d9a <printf>
1761: 83 c4 10 add $0x10,%esp
exit();
1764: e8 9a 24 00 00 call 3c03 <exit>
}
close(fd);
1769: 83 ec 0c sub $0xc,%esp
176c: ff 75 e8 pushl -0x18(%ebp)
176f: e8 b7 24 00 00 call 3c2b <close>
1774: 83 c4 10 add $0x10,%esp
}
if(pid == 0)
1777: 83 7d ec 00 cmpl $0x0,-0x14(%ebp)
177b: 75 05 jne 1782 <concreate+0x11f>
exit();
177d: e8 81 24 00 00 call 3c03 <exit>
else
wait();
1782: e8 84 24 00 00 call 3c0b <wait>
} de;
printf(1, "concreate test\n");
file[0] = 'C';
file[2] = '\0';
for(i = 0; i < 40; i++){
1787: 83 45 f4 01 addl $0x1,-0xc(%ebp)
178b: 83 7d f4 27 cmpl $0x27,-0xc(%ebp)
178f: 0f 8e fa fe ff ff jle 168f <concreate+0x2c>
exit();
else
wait();
}
memset(fa, 0, sizeof(fa));
1795: 83 ec 04 sub $0x4,%esp
1798: 6a 28 push $0x28
179a: 6a 00 push $0x0
179c: 8d 45 bd lea -0x43(%ebp),%eax
179f: 50 push %eax
17a0: e8 c3 22 00 00 call 3a68 <memset>
17a5: 83 c4 10 add $0x10,%esp
fd = open(".", 0);
17a8: 83 ec 08 sub $0x8,%esp
17ab: 6a 00 push $0x0
17ad: 68 bf 48 00 00 push $0x48bf
17b2: e8 8c 24 00 00 call 3c43 <open>
17b7: 83 c4 10 add $0x10,%esp
17ba: 89 45 e8 mov %eax,-0x18(%ebp)
n = 0;
17bd: c7 45 f0 00 00 00 00 movl $0x0,-0x10(%ebp)
while(read(fd, &de, sizeof(de)) > 0){
17c4: e9 93 00 00 00 jmp 185c <concreate+0x1f9>
if(de.inum == 0)
17c9: 0f b7 45 ac movzwl -0x54(%ebp),%eax
17cd: 66 85 c0 test %ax,%ax
17d0: 75 05 jne 17d7 <concreate+0x174>
continue;
17d2: e9 85 00 00 00 jmp 185c <concreate+0x1f9>
if(de.name[0] == 'C' && de.name[2] == '\0'){
17d7: 0f b6 45 ae movzbl -0x52(%ebp),%eax
17db: 3c 43 cmp $0x43,%al
17dd: 75 7d jne 185c <concreate+0x1f9>
17df: 0f b6 45 b0 movzbl -0x50(%ebp),%eax
17e3: 84 c0 test %al,%al
17e5: 75 75 jne 185c <concreate+0x1f9>
i = de.name[1] - '0';
17e7: 0f b6 45 af movzbl -0x51(%ebp),%eax
17eb: 0f be c0 movsbl %al,%eax
17ee: 83 e8 30 sub $0x30,%eax
17f1: 89 45 f4 mov %eax,-0xc(%ebp)
if(i < 0 || i >= sizeof(fa)){
17f4: 83 7d f4 00 cmpl $0x0,-0xc(%ebp)
17f8: 78 08 js 1802 <concreate+0x19f>
17fa: 8b 45 f4 mov -0xc(%ebp),%eax
17fd: 83 f8 27 cmp $0x27,%eax
1800: 76 1e jbe 1820 <concreate+0x1bd>
printf(1, "concreate weird file %s\n", de.name);
1802: 83 ec 04 sub $0x4,%esp
1805: 8d 45 ac lea -0x54(%ebp),%eax
1808: 83 c0 02 add $0x2,%eax
180b: 50 push %eax
180c: 68 19 49 00 00 push $0x4919
1811: 6a 01 push $0x1
1813: e8 82 25 00 00 call 3d9a <printf>
1818: 83 c4 10 add $0x10,%esp
exit();
181b: e8 e3 23 00 00 call 3c03 <exit>
}
if(fa[i]){
1820: 8d 55 bd lea -0x43(%ebp),%edx
1823: 8b 45 f4 mov -0xc(%ebp),%eax
1826: 01 d0 add %edx,%eax
1828: 0f b6 00 movzbl (%eax),%eax
182b: 84 c0 test %al,%al
182d: 74 1e je 184d <concreate+0x1ea>
printf(1, "concreate duplicate file %s\n", de.name);
182f: 83 ec 04 sub $0x4,%esp
1832: 8d 45 ac lea -0x54(%ebp),%eax
1835: 83 c0 02 add $0x2,%eax
1838: 50 push %eax
1839: 68 32 49 00 00 push $0x4932
183e: 6a 01 push $0x1
1840: e8 55 25 00 00 call 3d9a <printf>
1845: 83 c4 10 add $0x10,%esp
exit();
1848: e8 b6 23 00 00 call 3c03 <exit>
}
fa[i] = 1;
184d: 8d 55 bd lea -0x43(%ebp),%edx
1850: 8b 45 f4 mov -0xc(%ebp),%eax
1853: 01 d0 add %edx,%eax
1855: c6 00 01 movb $0x1,(%eax)
n++;
1858: 83 45 f0 01 addl $0x1,-0x10(%ebp)
}
memset(fa, 0, sizeof(fa));
fd = open(".", 0);
n = 0;
while(read(fd, &de, sizeof(de)) > 0){
185c: 83 ec 04 sub $0x4,%esp
185f: 6a 10 push $0x10
1861: 8d 45 ac lea -0x54(%ebp),%eax
1864: 50 push %eax
1865: ff 75 e8 pushl -0x18(%ebp)
1868: e8 ae 23 00 00 call 3c1b <read>
186d: 83 c4 10 add $0x10,%esp
1870: 85 c0 test %eax,%eax
1872: 0f 8f 51 ff ff ff jg 17c9 <concreate+0x166>
}
fa[i] = 1;
n++;
}
}
close(fd);
1878: 83 ec 0c sub $0xc,%esp
187b: ff 75 e8 pushl -0x18(%ebp)
187e: e8 a8 23 00 00 call 3c2b <close>
1883: 83 c4 10 add $0x10,%esp
if(n != 40){
1886: 83 7d f0 28 cmpl $0x28,-0x10(%ebp)
188a: 74 17 je 18a3 <concreate+0x240>
printf(1, "concreate not enough files in directory listing\n");
188c: 83 ec 08 sub $0x8,%esp
188f: 68 50 49 00 00 push $0x4950
1894: 6a 01 push $0x1
1896: e8 ff 24 00 00 call 3d9a <printf>
189b: 83 c4 10 add $0x10,%esp
exit();
189e: e8 60 23 00 00 call 3c03 <exit>
}
for(i = 0; i < 40; i++){
18a3: c7 45 f4 00 00 00 00 movl $0x0,-0xc(%ebp)
18aa: e9 45 01 00 00 jmp 19f4 <concreate+0x391>
file[1] = '0' + i;
18af: 8b 45 f4 mov -0xc(%ebp),%eax
18b2: 83 c0 30 add $0x30,%eax
18b5: 88 45 e6 mov %al,-0x1a(%ebp)
pid = fork();
18b8: e8 3e 23 00 00 call 3bfb <fork>
18bd: 89 45 ec mov %eax,-0x14(%ebp)
if(pid < 0){
18c0: 83 7d ec 00 cmpl $0x0,-0x14(%ebp)
18c4: 79 17 jns 18dd <concreate+0x27a>
printf(1, "fork failed\n");
18c6: 83 ec 08 sub $0x8,%esp
18c9: 68 3d 45 00 00 push $0x453d
18ce: 6a 01 push $0x1
18d0: e8 c5 24 00 00 call 3d9a <printf>
18d5: 83 c4 10 add $0x10,%esp
exit();
18d8: e8 26 23 00 00 call 3c03 <exit>
}
if(((i % 3) == 0 && pid == 0) ||
18dd: 8b 4d f4 mov -0xc(%ebp),%ecx
18e0: ba 56 55 55 55 mov $0x55555556,%edx
18e5: 89 c8 mov %ecx,%eax
18e7: f7 ea imul %edx
18e9: 89 c8 mov %ecx,%eax
18eb: c1 f8 1f sar $0x1f,%eax
18ee: 29 c2 sub %eax,%edx
18f0: 89 d0 mov %edx,%eax
18f2: 89 c2 mov %eax,%edx
18f4: 01 d2 add %edx,%edx
18f6: 01 c2 add %eax,%edx
18f8: 89 c8 mov %ecx,%eax
18fa: 29 d0 sub %edx,%eax
18fc: 85 c0 test %eax,%eax
18fe: 75 06 jne 1906 <concreate+0x2a3>
1900: 83 7d ec 00 cmpl $0x0,-0x14(%ebp)
1904: 74 28 je 192e <concreate+0x2cb>
((i % 3) == 1 && pid != 0)){
1906: 8b 4d f4 mov -0xc(%ebp),%ecx
1909: ba 56 55 55 55 mov $0x55555556,%edx
190e: 89 c8 mov %ecx,%eax
1910: f7 ea imul %edx
1912: 89 c8 mov %ecx,%eax
1914: c1 f8 1f sar $0x1f,%eax
1917: 29 c2 sub %eax,%edx
1919: 89 d0 mov %edx,%eax
191b: 01 c0 add %eax,%eax
191d: 01 d0 add %edx,%eax
191f: 29 c1 sub %eax,%ecx
1921: 89 ca mov %ecx,%edx
pid = fork();
if(pid < 0){
printf(1, "fork failed\n");
exit();
}
if(((i % 3) == 0 && pid == 0) ||
1923: 83 fa 01 cmp $0x1,%edx
1926: 75 7c jne 19a4 <concreate+0x341>
((i % 3) == 1 && pid != 0)){
1928: 83 7d ec 00 cmpl $0x0,-0x14(%ebp)
192c: 74 76 je 19a4 <concreate+0x341>
close(open(file, 0));
192e: 83 ec 08 sub $0x8,%esp
1931: 6a 00 push $0x0
1933: 8d 45 e5 lea -0x1b(%ebp),%eax
1936: 50 push %eax
1937: e8 07 23 00 00 call 3c43 <open>
193c: 83 c4 10 add $0x10,%esp
193f: 83 ec 0c sub $0xc,%esp
1942: 50 push %eax
1943: e8 e3 22 00 00 call 3c2b <close>
1948: 83 c4 10 add $0x10,%esp
close(open(file, 0));
194b: 83 ec 08 sub $0x8,%esp
194e: 6a 00 push $0x0
1950: 8d 45 e5 lea -0x1b(%ebp),%eax
1953: 50 push %eax
1954: e8 ea 22 00 00 call 3c43 <open>
1959: 83 c4 10 add $0x10,%esp
195c: 83 ec 0c sub $0xc,%esp
195f: 50 push %eax
1960: e8 c6 22 00 00 call 3c2b <close>
1965: 83 c4 10 add $0x10,%esp
close(open(file, 0));
1968: 83 ec 08 sub $0x8,%esp
196b: 6a 00 push $0x0
196d: 8d 45 e5 lea -0x1b(%ebp),%eax
1970: 50 push %eax
1971: e8 cd 22 00 00 call 3c43 <open>
1976: 83 c4 10 add $0x10,%esp
1979: 83 ec 0c sub $0xc,%esp
197c: 50 push %eax
197d: e8 a9 22 00 00 call 3c2b <close>
1982: 83 c4 10 add $0x10,%esp
close(open(file, 0));
1985: 83 ec 08 sub $0x8,%esp
1988: 6a 00 push $0x0
198a: 8d 45 e5 lea -0x1b(%ebp),%eax
198d: 50 push %eax
198e: e8 b0 22 00 00 call 3c43 <open>
1993: 83 c4 10 add $0x10,%esp
1996: 83 ec 0c sub $0xc,%esp
1999: 50 push %eax
199a: e8 8c 22 00 00 call 3c2b <close>
199f: 83 c4 10 add $0x10,%esp
19a2: eb 3c jmp 19e0 <concreate+0x37d>
} else {
unlink(file);
19a4: 83 ec 0c sub $0xc,%esp
19a7: 8d 45 e5 lea -0x1b(%ebp),%eax
19aa: 50 push %eax
19ab: e8 a3 22 00 00 call 3c53 <unlink>
19b0: 83 c4 10 add $0x10,%esp
unlink(file);
19b3: 83 ec 0c sub $0xc,%esp
19b6: 8d 45 e5 lea -0x1b(%ebp),%eax
19b9: 50 push %eax
19ba: e8 94 22 00 00 call 3c53 <unlink>
19bf: 83 c4 10 add $0x10,%esp
unlink(file);
19c2: 83 ec 0c sub $0xc,%esp
19c5: 8d 45 e5 lea -0x1b(%ebp),%eax
19c8: 50 push %eax
19c9: e8 85 22 00 00 call 3c53 <unlink>
19ce: 83 c4 10 add $0x10,%esp
unlink(file);
19d1: 83 ec 0c sub $0xc,%esp
19d4: 8d 45 e5 lea -0x1b(%ebp),%eax
19d7: 50 push %eax
19d8: e8 76 22 00 00 call 3c53 <unlink>
19dd: 83 c4 10 add $0x10,%esp
}
if(pid == 0)
19e0: 83 7d ec 00 cmpl $0x0,-0x14(%ebp)
19e4: 75 05 jne 19eb <concreate+0x388>
exit();
19e6: e8 18 22 00 00 call 3c03 <exit>
else
wait();
19eb: e8 1b 22 00 00 call 3c0b <wait>
if(n != 40){
printf(1, "concreate not enough files in directory listing\n");
exit();
}
for(i = 0; i < 40; i++){
19f0: 83 45 f4 01 addl $0x1,-0xc(%ebp)
19f4: 83 7d f4 27 cmpl $0x27,-0xc(%ebp)
19f8: 0f 8e b1 fe ff ff jle 18af <concreate+0x24c>
exit();
else
wait();
}
printf(1, "concreate ok\n");
19fe: 83 ec 08 sub $0x8,%esp
1a01: 68 81 49 00 00 push $0x4981
1a06: 6a 01 push $0x1
1a08: e8 8d 23 00 00 call 3d9a <printf>
1a0d: 83 c4 10 add $0x10,%esp
}
1a10: 90 nop
1a11: c9 leave
1a12: c3 ret
00001a13 <linkunlink>:
// another concurrent link/unlink/create test,
// to look for deadlocks.
void
linkunlink()
{
1a13: 55 push %ebp
1a14: 89 e5 mov %esp,%ebp
1a16: 83 ec 18 sub $0x18,%esp
int pid, i;
printf(1, "linkunlink test\n");
1a19: 83 ec 08 sub $0x8,%esp
1a1c: 68 8f 49 00 00 push $0x498f
1a21: 6a 01 push $0x1
1a23: e8 72 23 00 00 call 3d9a <printf>
1a28: 83 c4 10 add $0x10,%esp
unlink("x");
1a2b: 83 ec 0c sub $0xc,%esp
1a2e: 68 f6 44 00 00 push $0x44f6
1a33: e8 1b 22 00 00 call 3c53 <unlink>
1a38: 83 c4 10 add $0x10,%esp
pid = fork();
1a3b: e8 bb 21 00 00 call 3bfb <fork>
1a40: 89 45 ec mov %eax,-0x14(%ebp)
if(pid < 0){
1a43: 83 7d ec 00 cmpl $0x0,-0x14(%ebp)
1a47: 79 17 jns 1a60 <linkunlink+0x4d>
printf(1, "fork failed\n");
1a49: 83 ec 08 sub $0x8,%esp
1a4c: 68 3d 45 00 00 push $0x453d
1a51: 6a 01 push $0x1
1a53: e8 42 23 00 00 call 3d9a <printf>
1a58: 83 c4 10 add $0x10,%esp
exit();
1a5b: e8 a3 21 00 00 call 3c03 <exit>
}
unsigned int x = (pid ? 1 : 97);
1a60: 83 7d ec 00 cmpl $0x0,-0x14(%ebp)
1a64: 74 07 je 1a6d <linkunlink+0x5a>
1a66: b8 01 00 00 00 mov $0x1,%eax
1a6b: eb 05 jmp 1a72 <linkunlink+0x5f>
1a6d: b8 61 00 00 00 mov $0x61,%eax
1a72: 89 45 f0 mov %eax,-0x10(%ebp)
for(i = 0; i < 100; i++){
1a75: c7 45 f4 00 00 00 00 movl $0x0,-0xc(%ebp)
1a7c: e9 9a 00 00 00 jmp 1b1b <linkunlink+0x108>
x = x * 1103515245 + 12345;
1a81: 8b 45 f0 mov -0x10(%ebp),%eax
1a84: 69 c0 6d 4e c6 41 imul $0x41c64e6d,%eax,%eax
1a8a: 05 39 30 00 00 add $0x3039,%eax
1a8f: 89 45 f0 mov %eax,-0x10(%ebp)
if((x % 3) == 0){
1a92: 8b 4d f0 mov -0x10(%ebp),%ecx
1a95: ba ab aa aa aa mov $0xaaaaaaab,%edx
1a9a: 89 c8 mov %ecx,%eax
1a9c: f7 e2 mul %edx
1a9e: 89 d0 mov %edx,%eax
1aa0: d1 e8 shr %eax
1aa2: 89 c2 mov %eax,%edx
1aa4: 01 d2 add %edx,%edx
1aa6: 01 c2 add %eax,%edx
1aa8: 89 c8 mov %ecx,%eax
1aaa: 29 d0 sub %edx,%eax
1aac: 85 c0 test %eax,%eax
1aae: 75 23 jne 1ad3 <linkunlink+0xc0>
close(open("x", O_RDWR | O_CREATE));
1ab0: 83 ec 08 sub $0x8,%esp
1ab3: 68 02 02 00 00 push $0x202
1ab8: 68 f6 44 00 00 push $0x44f6
1abd: e8 81 21 00 00 call 3c43 <open>
1ac2: 83 c4 10 add $0x10,%esp
1ac5: 83 ec 0c sub $0xc,%esp
1ac8: 50 push %eax
1ac9: e8 5d 21 00 00 call 3c2b <close>
1ace: 83 c4 10 add $0x10,%esp
1ad1: eb 44 jmp 1b17 <linkunlink+0x104>
} else if((x % 3) == 1){
1ad3: 8b 4d f0 mov -0x10(%ebp),%ecx
1ad6: ba ab aa aa aa mov $0xaaaaaaab,%edx
1adb: 89 c8 mov %ecx,%eax
1add: f7 e2 mul %edx
1adf: d1 ea shr %edx
1ae1: 89 d0 mov %edx,%eax
1ae3: 01 c0 add %eax,%eax
1ae5: 01 d0 add %edx,%eax
1ae7: 29 c1 sub %eax,%ecx
1ae9: 89 ca mov %ecx,%edx
1aeb: 83 fa 01 cmp $0x1,%edx
1aee: 75 17 jne 1b07 <linkunlink+0xf4>
link("cat", "x");
1af0: 83 ec 08 sub $0x8,%esp
1af3: 68 f6 44 00 00 push $0x44f6
1af8: 68 a0 49 00 00 push $0x49a0
1afd: e8 61 21 00 00 call 3c63 <link>
1b02: 83 c4 10 add $0x10,%esp
1b05: eb 10 jmp 1b17 <linkunlink+0x104>
} else {
unlink("x");
1b07: 83 ec 0c sub $0xc,%esp
1b0a: 68 f6 44 00 00 push $0x44f6
1b0f: e8 3f 21 00 00 call 3c53 <unlink>
1b14: 83 c4 10 add $0x10,%esp
printf(1, "fork failed\n");
exit();
}
unsigned int x = (pid ? 1 : 97);
for(i = 0; i < 100; i++){
1b17: 83 45 f4 01 addl $0x1,-0xc(%ebp)
1b1b: 83 7d f4 63 cmpl $0x63,-0xc(%ebp)
1b1f: 0f 8e 5c ff ff ff jle 1a81 <linkunlink+0x6e>
} else {
unlink("x");
}
}
if(pid)
1b25: 83 7d ec 00 cmpl $0x0,-0x14(%ebp)
1b29: 74 07 je 1b32 <linkunlink+0x11f>
wait();
1b2b: e8 db 20 00 00 call 3c0b <wait>
1b30: eb 05 jmp 1b37 <linkunlink+0x124>
else
exit();
1b32: e8 cc 20 00 00 call 3c03 <exit>
printf(1, "linkunlink ok\n");
1b37: 83 ec 08 sub $0x8,%esp
1b3a: 68 a4 49 00 00 push $0x49a4
1b3f: 6a 01 push $0x1
1b41: e8 54 22 00 00 call 3d9a <printf>
1b46: 83 c4 10 add $0x10,%esp
}
1b49: 90 nop
1b4a: c9 leave
1b4b: c3 ret
00001b4c <bigdir>:
// directory that uses indirect blocks
void
bigdir(void)
{
1b4c: 55 push %ebp
1b4d: 89 e5 mov %esp,%ebp
1b4f: 83 ec 28 sub $0x28,%esp
int i, fd;
char name[10];
printf(1, "bigdir test\n");
1b52: 83 ec 08 sub $0x8,%esp
1b55: 68 b3 49 00 00 push $0x49b3
1b5a: 6a 01 push $0x1
1b5c: e8 39 22 00 00 call 3d9a <printf>
1b61: 83 c4 10 add $0x10,%esp
unlink("bd");
1b64: 83 ec 0c sub $0xc,%esp
1b67: 68 c0 49 00 00 push $0x49c0
1b6c: e8 e2 20 00 00 call 3c53 <unlink>
1b71: 83 c4 10 add $0x10,%esp
fd = open("bd", O_CREATE);
1b74: 83 ec 08 sub $0x8,%esp
1b77: 68 00 02 00 00 push $0x200
1b7c: 68 c0 49 00 00 push $0x49c0
1b81: e8 bd 20 00 00 call 3c43 <open>
1b86: 83 c4 10 add $0x10,%esp
1b89: 89 45 f0 mov %eax,-0x10(%ebp)
if(fd < 0){
1b8c: 83 7d f0 00 cmpl $0x0,-0x10(%ebp)
1b90: 79 17 jns 1ba9 <bigdir+0x5d>
printf(1, "bigdir create failed\n");
1b92: 83 ec 08 sub $0x8,%esp
1b95: 68 c3 49 00 00 push $0x49c3
1b9a: 6a 01 push $0x1
1b9c: e8 f9 21 00 00 call 3d9a <printf>
1ba1: 83 c4 10 add $0x10,%esp
exit();
1ba4: e8 5a 20 00 00 call 3c03 <exit>
}
close(fd);
1ba9: 83 ec 0c sub $0xc,%esp
1bac: ff 75 f0 pushl -0x10(%ebp)
1baf: e8 77 20 00 00 call 3c2b <close>
1bb4: 83 c4 10 add $0x10,%esp
for(i = 0; i < 500; i++){
1bb7: c7 45 f4 00 00 00 00 movl $0x0,-0xc(%ebp)
1bbe: eb 63 jmp 1c23 <bigdir+0xd7>
name[0] = 'x';
1bc0: c6 45 e6 78 movb $0x78,-0x1a(%ebp)
name[1] = '0' + (i / 64);
1bc4: 8b 45 f4 mov -0xc(%ebp),%eax
1bc7: 8d 50 3f lea 0x3f(%eax),%edx
1bca: 85 c0 test %eax,%eax
1bcc: 0f 48 c2 cmovs %edx,%eax
1bcf: c1 f8 06 sar $0x6,%eax
1bd2: 83 c0 30 add $0x30,%eax
1bd5: 88 45 e7 mov %al,-0x19(%ebp)
name[2] = '0' + (i % 64);
1bd8: 8b 45 f4 mov -0xc(%ebp),%eax
1bdb: 99 cltd
1bdc: c1 ea 1a shr $0x1a,%edx
1bdf: 01 d0 add %edx,%eax
1be1: 83 e0 3f and $0x3f,%eax
1be4: 29 d0 sub %edx,%eax
1be6: 83 c0 30 add $0x30,%eax
1be9: 88 45 e8 mov %al,-0x18(%ebp)
name[3] = '\0';
1bec: c6 45 e9 00 movb $0x0,-0x17(%ebp)
if(link("bd", name) != 0){
1bf0: 83 ec 08 sub $0x8,%esp
1bf3: 8d 45 e6 lea -0x1a(%ebp),%eax
1bf6: 50 push %eax
1bf7: 68 c0 49 00 00 push $0x49c0
1bfc: e8 62 20 00 00 call 3c63 <link>
1c01: 83 c4 10 add $0x10,%esp
1c04: 85 c0 test %eax,%eax
1c06: 74 17 je 1c1f <bigdir+0xd3>
printf(1, "bigdir link failed\n");
1c08: 83 ec 08 sub $0x8,%esp
1c0b: 68 d9 49 00 00 push $0x49d9
1c10: 6a 01 push $0x1
1c12: e8 83 21 00 00 call 3d9a <printf>
1c17: 83 c4 10 add $0x10,%esp
exit();
1c1a: e8 e4 1f 00 00 call 3c03 <exit>
printf(1, "bigdir create failed\n");
exit();
}
close(fd);
for(i = 0; i < 500; i++){
1c1f: 83 45 f4 01 addl $0x1,-0xc(%ebp)
1c23: 81 7d f4 f3 01 00 00 cmpl $0x1f3,-0xc(%ebp)
1c2a: 7e 94 jle 1bc0 <bigdir+0x74>
printf(1, "bigdir link failed\n");
exit();
}
}
unlink("bd");
1c2c: 83 ec 0c sub $0xc,%esp
1c2f: 68 c0 49 00 00 push $0x49c0
1c34: e8 1a 20 00 00 call 3c53 <unlink>
1c39: 83 c4 10 add $0x10,%esp
for(i = 0; i < 500; i++){
1c3c: c7 45 f4 00 00 00 00 movl $0x0,-0xc(%ebp)
1c43: eb 5e jmp 1ca3 <bigdir+0x157>
name[0] = 'x';
1c45: c6 45 e6 78 movb $0x78,-0x1a(%ebp)
name[1] = '0' + (i / 64);
1c49: 8b 45 f4 mov -0xc(%ebp),%eax
1c4c: 8d 50 3f lea 0x3f(%eax),%edx
1c4f: 85 c0 test %eax,%eax
1c51: 0f 48 c2 cmovs %edx,%eax
1c54: c1 f8 06 sar $0x6,%eax
1c57: 83 c0 30 add $0x30,%eax
1c5a: 88 45 e7 mov %al,-0x19(%ebp)
name[2] = '0' + (i % 64);
1c5d: 8b 45 f4 mov -0xc(%ebp),%eax
1c60: 99 cltd
1c61: c1 ea 1a shr $0x1a,%edx
1c64: 01 d0 add %edx,%eax
1c66: 83 e0 3f and $0x3f,%eax
1c69: 29 d0 sub %edx,%eax
1c6b: 83 c0 30 add $0x30,%eax
1c6e: 88 45 e8 mov %al,-0x18(%ebp)
name[3] = '\0';
1c71: c6 45 e9 00 movb $0x0,-0x17(%ebp)
if(unlink(name) != 0){
1c75: 83 ec 0c sub $0xc,%esp
1c78: 8d 45 e6 lea -0x1a(%ebp),%eax
1c7b: 50 push %eax
1c7c: e8 d2 1f 00 00 call 3c53 <unlink>
1c81: 83 c4 10 add $0x10,%esp
1c84: 85 c0 test %eax,%eax
1c86: 74 17 je 1c9f <bigdir+0x153>
printf(1, "bigdir unlink failed");
1c88: 83 ec 08 sub $0x8,%esp
1c8b: 68 ed 49 00 00 push $0x49ed
1c90: 6a 01 push $0x1
1c92: e8 03 21 00 00 call 3d9a <printf>
1c97: 83 c4 10 add $0x10,%esp
exit();
1c9a: e8 64 1f 00 00 call 3c03 <exit>
exit();
}
}
unlink("bd");
for(i = 0; i < 500; i++){
1c9f: 83 45 f4 01 addl $0x1,-0xc(%ebp)
1ca3: 81 7d f4 f3 01 00 00 cmpl $0x1f3,-0xc(%ebp)
1caa: 7e 99 jle 1c45 <bigdir+0xf9>
printf(1, "bigdir unlink failed");
exit();
}
}
printf(1, "bigdir ok\n");
1cac: 83 ec 08 sub $0x8,%esp
1caf: 68 02 4a 00 00 push $0x4a02
1cb4: 6a 01 push $0x1
1cb6: e8 df 20 00 00 call 3d9a <printf>
1cbb: 83 c4 10 add $0x10,%esp
}
1cbe: 90 nop
1cbf: c9 leave
1cc0: c3 ret
00001cc1 <subdir>:
void
subdir(void)
{
1cc1: 55 push %ebp
1cc2: 89 e5 mov %esp,%ebp
1cc4: 83 ec 18 sub $0x18,%esp
int fd, cc;
printf(1, "subdir test\n");
1cc7: 83 ec 08 sub $0x8,%esp
1cca: 68 0d 4a 00 00 push $0x4a0d
1ccf: 6a 01 push $0x1
1cd1: e8 c4 20 00 00 call 3d9a <printf>
1cd6: 83 c4 10 add $0x10,%esp
unlink("ff");
1cd9: 83 ec 0c sub $0xc,%esp
1cdc: 68 1a 4a 00 00 push $0x4a1a
1ce1: e8 6d 1f 00 00 call 3c53 <unlink>
1ce6: 83 c4 10 add $0x10,%esp
if(mkdir("dd") != 0){
1ce9: 83 ec 0c sub $0xc,%esp
1cec: 68 1d 4a 00 00 push $0x4a1d
1cf1: e8 75 1f 00 00 call 3c6b <mkdir>
1cf6: 83 c4 10 add $0x10,%esp
1cf9: 85 c0 test %eax,%eax
1cfb: 74 17 je 1d14 <subdir+0x53>
printf(1, "subdir mkdir dd failed\n");
1cfd: 83 ec 08 sub $0x8,%esp
1d00: 68 20 4a 00 00 push $0x4a20
1d05: 6a 01 push $0x1
1d07: e8 8e 20 00 00 call 3d9a <printf>
1d0c: 83 c4 10 add $0x10,%esp
exit();
1d0f: e8 ef 1e 00 00 call 3c03 <exit>
}
fd = open("dd/ff", O_CREATE | O_RDWR);
1d14: 83 ec 08 sub $0x8,%esp
1d17: 68 02 02 00 00 push $0x202
1d1c: 68 38 4a 00 00 push $0x4a38
1d21: e8 1d 1f 00 00 call 3c43 <open>
1d26: 83 c4 10 add $0x10,%esp
1d29: 89 45 f4 mov %eax,-0xc(%ebp)
if(fd < 0){
1d2c: 83 7d f4 00 cmpl $0x0,-0xc(%ebp)
1d30: 79 17 jns 1d49 <subdir+0x88>
printf(1, "create dd/ff failed\n");
1d32: 83 ec 08 sub $0x8,%esp
1d35: 68 3e 4a 00 00 push $0x4a3e
1d3a: 6a 01 push $0x1
1d3c: e8 59 20 00 00 call 3d9a <printf>
1d41: 83 c4 10 add $0x10,%esp
exit();
1d44: e8 ba 1e 00 00 call 3c03 <exit>
}
write(fd, "ff", 2);
1d49: 83 ec 04 sub $0x4,%esp
1d4c: 6a 02 push $0x2
1d4e: 68 1a 4a 00 00 push $0x4a1a
1d53: ff 75 f4 pushl -0xc(%ebp)
1d56: e8 c8 1e 00 00 call 3c23 <write>
1d5b: 83 c4 10 add $0x10,%esp
close(fd);
1d5e: 83 ec 0c sub $0xc,%esp
1d61: ff 75 f4 pushl -0xc(%ebp)
1d64: e8 c2 1e 00 00 call 3c2b <close>
1d69: 83 c4 10 add $0x10,%esp
if(unlink("dd") >= 0){
1d6c: 83 ec 0c sub $0xc,%esp
1d6f: 68 1d 4a 00 00 push $0x4a1d
1d74: e8 da 1e 00 00 call 3c53 <unlink>
1d79: 83 c4 10 add $0x10,%esp
1d7c: 85 c0 test %eax,%eax
1d7e: 78 17 js 1d97 <subdir+0xd6>
printf(1, "unlink dd (non-empty dir) succeeded!\n");
1d80: 83 ec 08 sub $0x8,%esp
1d83: 68 54 4a 00 00 push $0x4a54
1d88: 6a 01 push $0x1
1d8a: e8 0b 20 00 00 call 3d9a <printf>
1d8f: 83 c4 10 add $0x10,%esp
exit();
1d92: e8 6c 1e 00 00 call 3c03 <exit>
}
if(mkdir("/dd/dd") != 0){
1d97: 83 ec 0c sub $0xc,%esp
1d9a: 68 7a 4a 00 00 push $0x4a7a
1d9f: e8 c7 1e 00 00 call 3c6b <mkdir>
1da4: 83 c4 10 add $0x10,%esp
1da7: 85 c0 test %eax,%eax
1da9: 74 17 je 1dc2 <subdir+0x101>
printf(1, "subdir mkdir dd/dd failed\n");
1dab: 83 ec 08 sub $0x8,%esp
1dae: 68 81 4a 00 00 push $0x4a81
1db3: 6a 01 push $0x1
1db5: e8 e0 1f 00 00 call 3d9a <printf>
1dba: 83 c4 10 add $0x10,%esp
exit();
1dbd: e8 41 1e 00 00 call 3c03 <exit>
}
fd = open("dd/dd/ff", O_CREATE | O_RDWR);
1dc2: 83 ec 08 sub $0x8,%esp
1dc5: 68 02 02 00 00 push $0x202
1dca: 68 9c 4a 00 00 push $0x4a9c
1dcf: e8 6f 1e 00 00 call 3c43 <open>
1dd4: 83 c4 10 add $0x10,%esp
1dd7: 89 45 f4 mov %eax,-0xc(%ebp)
if(fd < 0){
1dda: 83 7d f4 00 cmpl $0x0,-0xc(%ebp)
1dde: 79 17 jns 1df7 <subdir+0x136>
printf(1, "create dd/dd/ff failed\n");
1de0: 83 ec 08 sub $0x8,%esp
1de3: 68 a5 4a 00 00 push $0x4aa5
1de8: 6a 01 push $0x1
1dea: e8 ab 1f 00 00 call 3d9a <printf>
1def: 83 c4 10 add $0x10,%esp
exit();
1df2: e8 0c 1e 00 00 call 3c03 <exit>
}
write(fd, "FF", 2);
1df7: 83 ec 04 sub $0x4,%esp
1dfa: 6a 02 push $0x2
1dfc: 68 bd 4a 00 00 push $0x4abd
1e01: ff 75 f4 pushl -0xc(%ebp)
1e04: e8 1a 1e 00 00 call 3c23 <write>
1e09: 83 c4 10 add $0x10,%esp
close(fd);
1e0c: 83 ec 0c sub $0xc,%esp
1e0f: ff 75 f4 pushl -0xc(%ebp)
1e12: e8 14 1e 00 00 call 3c2b <close>
1e17: 83 c4 10 add $0x10,%esp
fd = open("dd/dd/../ff", 0);
1e1a: 83 ec 08 sub $0x8,%esp
1e1d: 6a 00 push $0x0
1e1f: 68 c0 4a 00 00 push $0x4ac0
1e24: e8 1a 1e 00 00 call 3c43 <open>
1e29: 83 c4 10 add $0x10,%esp
1e2c: 89 45 f4 mov %eax,-0xc(%ebp)
if(fd < 0){
1e2f: 83 7d f4 00 cmpl $0x0,-0xc(%ebp)
1e33: 79 17 jns 1e4c <subdir+0x18b>
printf(1, "open dd/dd/../ff failed\n");
1e35: 83 ec 08 sub $0x8,%esp
1e38: 68 cc 4a 00 00 push $0x4acc
1e3d: 6a 01 push $0x1
1e3f: e8 56 1f 00 00 call 3d9a <printf>
1e44: 83 c4 10 add $0x10,%esp
exit();
1e47: e8 b7 1d 00 00 call 3c03 <exit>
}
cc = read(fd, buf, sizeof(buf));
1e4c: 83 ec 04 sub $0x4,%esp
1e4f: 68 00 20 00 00 push $0x2000
1e54: 68 80 86 00 00 push $0x8680
1e59: ff 75 f4 pushl -0xc(%ebp)
1e5c: e8 ba 1d 00 00 call 3c1b <read>
1e61: 83 c4 10 add $0x10,%esp
1e64: 89 45 f0 mov %eax,-0x10(%ebp)
if(cc != 2 || buf[0] != 'f'){
1e67: 83 7d f0 02 cmpl $0x2,-0x10(%ebp)
1e6b: 75 0b jne 1e78 <subdir+0x1b7>
1e6d: 0f b6 05 80 86 00 00 movzbl 0x8680,%eax
1e74: 3c 66 cmp $0x66,%al
1e76: 74 17 je 1e8f <subdir+0x1ce>
printf(1, "dd/dd/../ff wrong content\n");
1e78: 83 ec 08 sub $0x8,%esp
1e7b: 68 e5 4a 00 00 push $0x4ae5
1e80: 6a 01 push $0x1
1e82: e8 13 1f 00 00 call 3d9a <printf>
1e87: 83 c4 10 add $0x10,%esp
exit();
1e8a: e8 74 1d 00 00 call 3c03 <exit>
}
close(fd);
1e8f: 83 ec 0c sub $0xc,%esp
1e92: ff 75 f4 pushl -0xc(%ebp)
1e95: e8 91 1d 00 00 call 3c2b <close>
1e9a: 83 c4 10 add $0x10,%esp
if(link("dd/dd/ff", "dd/dd/ffff") != 0){
1e9d: 83 ec 08 sub $0x8,%esp
1ea0: 68 00 4b 00 00 push $0x4b00
1ea5: 68 9c 4a 00 00 push $0x4a9c
1eaa: e8 b4 1d 00 00 call 3c63 <link>
1eaf: 83 c4 10 add $0x10,%esp
1eb2: 85 c0 test %eax,%eax
1eb4: 74 17 je 1ecd <subdir+0x20c>
printf(1, "link dd/dd/ff dd/dd/ffff failed\n");
1eb6: 83 ec 08 sub $0x8,%esp
1eb9: 68 0c 4b 00 00 push $0x4b0c
1ebe: 6a 01 push $0x1
1ec0: e8 d5 1e 00 00 call 3d9a <printf>
1ec5: 83 c4 10 add $0x10,%esp
exit();
1ec8: e8 36 1d 00 00 call 3c03 <exit>
}
if(unlink("dd/dd/ff") != 0){
1ecd: 83 ec 0c sub $0xc,%esp
1ed0: 68 9c 4a 00 00 push $0x4a9c
1ed5: e8 79 1d 00 00 call 3c53 <unlink>
1eda: 83 c4 10 add $0x10,%esp
1edd: 85 c0 test %eax,%eax
1edf: 74 17 je 1ef8 <subdir+0x237>
printf(1, "unlink dd/dd/ff failed\n");
1ee1: 83 ec 08 sub $0x8,%esp
1ee4: 68 2d 4b 00 00 push $0x4b2d
1ee9: 6a 01 push $0x1
1eeb: e8 aa 1e 00 00 call 3d9a <printf>
1ef0: 83 c4 10 add $0x10,%esp
exit();
1ef3: e8 0b 1d 00 00 call 3c03 <exit>
}
if(open("dd/dd/ff", O_RDONLY) >= 0){
1ef8: 83 ec 08 sub $0x8,%esp
1efb: 6a 00 push $0x0
1efd: 68 9c 4a 00 00 push $0x4a9c
1f02: e8 3c 1d 00 00 call 3c43 <open>
1f07: 83 c4 10 add $0x10,%esp
1f0a: 85 c0 test %eax,%eax
1f0c: 78 17 js 1f25 <subdir+0x264>
printf(1, "open (unlinked) dd/dd/ff succeeded\n");
1f0e: 83 ec 08 sub $0x8,%esp
1f11: 68 48 4b 00 00 push $0x4b48
1f16: 6a 01 push $0x1
1f18: e8 7d 1e 00 00 call 3d9a <printf>
1f1d: 83 c4 10 add $0x10,%esp
exit();
1f20: e8 de 1c 00 00 call 3c03 <exit>
}
if(chdir("dd") != 0){
1f25: 83 ec 0c sub $0xc,%esp
1f28: 68 1d 4a 00 00 push $0x4a1d
1f2d: e8 41 1d 00 00 call 3c73 <chdir>
1f32: 83 c4 10 add $0x10,%esp
1f35: 85 c0 test %eax,%eax
1f37: 74 17 je 1f50 <subdir+0x28f>
printf(1, "chdir dd failed\n");
1f39: 83 ec 08 sub $0x8,%esp
1f3c: 68 6c 4b 00 00 push $0x4b6c
1f41: 6a 01 push $0x1
1f43: e8 52 1e 00 00 call 3d9a <printf>
1f48: 83 c4 10 add $0x10,%esp
exit();
1f4b: e8 b3 1c 00 00 call 3c03 <exit>
}
if(chdir("dd/../../dd") != 0){
1f50: 83 ec 0c sub $0xc,%esp
1f53: 68 7d 4b 00 00 push $0x4b7d
1f58: e8 16 1d 00 00 call 3c73 <chdir>
1f5d: 83 c4 10 add $0x10,%esp
1f60: 85 c0 test %eax,%eax
1f62: 74 17 je 1f7b <subdir+0x2ba>
printf(1, "chdir dd/../../dd failed\n");
1f64: 83 ec 08 sub $0x8,%esp
1f67: 68 89 4b 00 00 push $0x4b89
1f6c: 6a 01 push $0x1
1f6e: e8 27 1e 00 00 call 3d9a <printf>
1f73: 83 c4 10 add $0x10,%esp
exit();
1f76: e8 88 1c 00 00 call 3c03 <exit>
}
if(chdir("dd/../../../dd") != 0){
1f7b: 83 ec 0c sub $0xc,%esp
1f7e: 68 a3 4b 00 00 push $0x4ba3
1f83: e8 eb 1c 00 00 call 3c73 <chdir>
1f88: 83 c4 10 add $0x10,%esp
1f8b: 85 c0 test %eax,%eax
1f8d: 74 17 je 1fa6 <subdir+0x2e5>
printf(1, "chdir dd/../../dd failed\n");
1f8f: 83 ec 08 sub $0x8,%esp
1f92: 68 89 4b 00 00 push $0x4b89
1f97: 6a 01 push $0x1
1f99: e8 fc 1d 00 00 call 3d9a <printf>
1f9e: 83 c4 10 add $0x10,%esp
exit();
1fa1: e8 5d 1c 00 00 call 3c03 <exit>
}
if(chdir("./..") != 0){
1fa6: 83 ec 0c sub $0xc,%esp
1fa9: 68 b2 4b 00 00 push $0x4bb2
1fae: e8 c0 1c 00 00 call 3c73 <chdir>
1fb3: 83 c4 10 add $0x10,%esp
1fb6: 85 c0 test %eax,%eax
1fb8: 74 17 je 1fd1 <subdir+0x310>
printf(1, "chdir ./.. failed\n");
1fba: 83 ec 08 sub $0x8,%esp
1fbd: 68 b7 4b 00 00 push $0x4bb7
1fc2: 6a 01 push $0x1
1fc4: e8 d1 1d 00 00 call 3d9a <printf>
1fc9: 83 c4 10 add $0x10,%esp
exit();
1fcc: e8 32 1c 00 00 call 3c03 <exit>
}
fd = open("dd/dd/ffff", 0);
1fd1: 83 ec 08 sub $0x8,%esp
1fd4: 6a 00 push $0x0
1fd6: 68 00 4b 00 00 push $0x4b00
1fdb: e8 63 1c 00 00 call 3c43 <open>
1fe0: 83 c4 10 add $0x10,%esp
1fe3: 89 45 f4 mov %eax,-0xc(%ebp)
if(fd < 0){
1fe6: 83 7d f4 00 cmpl $0x0,-0xc(%ebp)
1fea: 79 17 jns 2003 <subdir+0x342>
printf(1, "open dd/dd/ffff failed\n");
1fec: 83 ec 08 sub $0x8,%esp
1fef: 68 ca 4b 00 00 push $0x4bca
1ff4: 6a 01 push $0x1
1ff6: e8 9f 1d 00 00 call 3d9a <printf>
1ffb: 83 c4 10 add $0x10,%esp
exit();
1ffe: e8 00 1c 00 00 call 3c03 <exit>
}
if(read(fd, buf, sizeof(buf)) != 2){
2003: 83 ec 04 sub $0x4,%esp
2006: 68 00 20 00 00 push $0x2000
200b: 68 80 86 00 00 push $0x8680
2010: ff 75 f4 pushl -0xc(%ebp)
2013: e8 03 1c 00 00 call 3c1b <read>
2018: 83 c4 10 add $0x10,%esp
201b: 83 f8 02 cmp $0x2,%eax
201e: 74 17 je 2037 <subdir+0x376>
printf(1, "read dd/dd/ffff wrong len\n");
2020: 83 ec 08 sub $0x8,%esp
2023: 68 e2 4b 00 00 push $0x4be2
2028: 6a 01 push $0x1
202a: e8 6b 1d 00 00 call 3d9a <printf>
202f: 83 c4 10 add $0x10,%esp
exit();
2032: e8 cc 1b 00 00 call 3c03 <exit>
}
close(fd);
2037: 83 ec 0c sub $0xc,%esp
203a: ff 75 f4 pushl -0xc(%ebp)
203d: e8 e9 1b 00 00 call 3c2b <close>
2042: 83 c4 10 add $0x10,%esp
if(open("dd/dd/ff", O_RDONLY) >= 0){
2045: 83 ec 08 sub $0x8,%esp
2048: 6a 00 push $0x0
204a: 68 9c 4a 00 00 push $0x4a9c
204f: e8 ef 1b 00 00 call 3c43 <open>
2054: 83 c4 10 add $0x10,%esp
2057: 85 c0 test %eax,%eax
2059: 78 17 js 2072 <subdir+0x3b1>
printf(1, "open (unlinked) dd/dd/ff succeeded!\n");
205b: 83 ec 08 sub $0x8,%esp
205e: 68 00 4c 00 00 push $0x4c00
2063: 6a 01 push $0x1
2065: e8 30 1d 00 00 call 3d9a <printf>
206a: 83 c4 10 add $0x10,%esp
exit();
206d: e8 91 1b 00 00 call 3c03 <exit>
}
if(open("dd/ff/ff", O_CREATE|O_RDWR) >= 0){
2072: 83 ec 08 sub $0x8,%esp
2075: 68 02 02 00 00 push $0x202
207a: 68 25 4c 00 00 push $0x4c25
207f: e8 bf 1b 00 00 call 3c43 <open>
2084: 83 c4 10 add $0x10,%esp
2087: 85 c0 test %eax,%eax
2089: 78 17 js 20a2 <subdir+0x3e1>
printf(1, "create dd/ff/ff succeeded!\n");
208b: 83 ec 08 sub $0x8,%esp
208e: 68 2e 4c 00 00 push $0x4c2e
2093: 6a 01 push $0x1
2095: e8 00 1d 00 00 call 3d9a <printf>
209a: 83 c4 10 add $0x10,%esp
exit();
209d: e8 61 1b 00 00 call 3c03 <exit>
}
if(open("dd/xx/ff", O_CREATE|O_RDWR) >= 0){
20a2: 83 ec 08 sub $0x8,%esp
20a5: 68 02 02 00 00 push $0x202
20aa: 68 4a 4c 00 00 push $0x4c4a
20af: e8 8f 1b 00 00 call 3c43 <open>
20b4: 83 c4 10 add $0x10,%esp
20b7: 85 c0 test %eax,%eax
20b9: 78 17 js 20d2 <subdir+0x411>
printf(1, "create dd/xx/ff succeeded!\n");
20bb: 83 ec 08 sub $0x8,%esp
20be: 68 53 4c 00 00 push $0x4c53
20c3: 6a 01 push $0x1
20c5: e8 d0 1c 00 00 call 3d9a <printf>
20ca: 83 c4 10 add $0x10,%esp
exit();
20cd: e8 31 1b 00 00 call 3c03 <exit>
}
if(open("dd", O_CREATE) >= 0){
20d2: 83 ec 08 sub $0x8,%esp
20d5: 68 00 02 00 00 push $0x200
20da: 68 1d 4a 00 00 push $0x4a1d
20df: e8 5f 1b 00 00 call 3c43 <open>
20e4: 83 c4 10 add $0x10,%esp
20e7: 85 c0 test %eax,%eax
20e9: 78 17 js 2102 <subdir+0x441>
printf(1, "create dd succeeded!\n");
20eb: 83 ec 08 sub $0x8,%esp
20ee: 68 6f 4c 00 00 push $0x4c6f
20f3: 6a 01 push $0x1
20f5: e8 a0 1c 00 00 call 3d9a <printf>
20fa: 83 c4 10 add $0x10,%esp
exit();
20fd: e8 01 1b 00 00 call 3c03 <exit>
}
if(open("dd", O_RDWR) >= 0){
2102: 83 ec 08 sub $0x8,%esp
2105: 6a 02 push $0x2
2107: 68 1d 4a 00 00 push $0x4a1d
210c: e8 32 1b 00 00 call 3c43 <open>
2111: 83 c4 10 add $0x10,%esp
2114: 85 c0 test %eax,%eax
2116: 78 17 js 212f <subdir+0x46e>
printf(1, "open dd rdwr succeeded!\n");
2118: 83 ec 08 sub $0x8,%esp
211b: 68 85 4c 00 00 push $0x4c85
2120: 6a 01 push $0x1
2122: e8 73 1c 00 00 call 3d9a <printf>
2127: 83 c4 10 add $0x10,%esp
exit();
212a: e8 d4 1a 00 00 call 3c03 <exit>
}
if(open("dd", O_WRONLY) >= 0){
212f: 83 ec 08 sub $0x8,%esp
2132: 6a 01 push $0x1
2134: 68 1d 4a 00 00 push $0x4a1d
2139: e8 05 1b 00 00 call 3c43 <open>
213e: 83 c4 10 add $0x10,%esp
2141: 85 c0 test %eax,%eax
2143: 78 17 js 215c <subdir+0x49b>
printf(1, "open dd wronly succeeded!\n");
2145: 83 ec 08 sub $0x8,%esp
2148: 68 9e 4c 00 00 push $0x4c9e
214d: 6a 01 push $0x1
214f: e8 46 1c 00 00 call 3d9a <printf>
2154: 83 c4 10 add $0x10,%esp
exit();
2157: e8 a7 1a 00 00 call 3c03 <exit>
}
if(link("dd/ff/ff", "dd/dd/xx") == 0){
215c: 83 ec 08 sub $0x8,%esp
215f: 68 b9 4c 00 00 push $0x4cb9
2164: 68 25 4c 00 00 push $0x4c25
2169: e8 f5 1a 00 00 call 3c63 <link>
216e: 83 c4 10 add $0x10,%esp
2171: 85 c0 test %eax,%eax
2173: 75 17 jne 218c <subdir+0x4cb>
printf(1, "link dd/ff/ff dd/dd/xx succeeded!\n");
2175: 83 ec 08 sub $0x8,%esp
2178: 68 c4 4c 00 00 push $0x4cc4
217d: 6a 01 push $0x1
217f: e8 16 1c 00 00 call 3d9a <printf>
2184: 83 c4 10 add $0x10,%esp
exit();
2187: e8 77 1a 00 00 call 3c03 <exit>
}
if(link("dd/xx/ff", "dd/dd/xx") == 0){
218c: 83 ec 08 sub $0x8,%esp
218f: 68 b9 4c 00 00 push $0x4cb9
2194: 68 4a 4c 00 00 push $0x4c4a
2199: e8 c5 1a 00 00 call 3c63 <link>
219e: 83 c4 10 add $0x10,%esp
21a1: 85 c0 test %eax,%eax
21a3: 75 17 jne 21bc <subdir+0x4fb>
printf(1, "link dd/xx/ff dd/dd/xx succeeded!\n");
21a5: 83 ec 08 sub $0x8,%esp
21a8: 68 e8 4c 00 00 push $0x4ce8
21ad: 6a 01 push $0x1
21af: e8 e6 1b 00 00 call 3d9a <printf>
21b4: 83 c4 10 add $0x10,%esp
exit();
21b7: e8 47 1a 00 00 call 3c03 <exit>
}
if(link("dd/ff", "dd/dd/ffff") == 0){
21bc: 83 ec 08 sub $0x8,%esp
21bf: 68 00 4b 00 00 push $0x4b00
21c4: 68 38 4a 00 00 push $0x4a38
21c9: e8 95 1a 00 00 call 3c63 <link>
21ce: 83 c4 10 add $0x10,%esp
21d1: 85 c0 test %eax,%eax
21d3: 75 17 jne 21ec <subdir+0x52b>
printf(1, "link dd/ff dd/dd/ffff succeeded!\n");
21d5: 83 ec 08 sub $0x8,%esp
21d8: 68 0c 4d 00 00 push $0x4d0c
21dd: 6a 01 push $0x1
21df: e8 b6 1b 00 00 call 3d9a <printf>
21e4: 83 c4 10 add $0x10,%esp
exit();
21e7: e8 17 1a 00 00 call 3c03 <exit>
}
if(mkdir("dd/ff/ff") == 0){
21ec: 83 ec 0c sub $0xc,%esp
21ef: 68 25 4c 00 00 push $0x4c25
21f4: e8 72 1a 00 00 call 3c6b <mkdir>
21f9: 83 c4 10 add $0x10,%esp
21fc: 85 c0 test %eax,%eax
21fe: 75 17 jne 2217 <subdir+0x556>
printf(1, "mkdir dd/ff/ff succeeded!\n");
2200: 83 ec 08 sub $0x8,%esp
2203: 68 2e 4d 00 00 push $0x4d2e
2208: 6a 01 push $0x1
220a: e8 8b 1b 00 00 call 3d9a <printf>
220f: 83 c4 10 add $0x10,%esp
exit();
2212: e8 ec 19 00 00 call 3c03 <exit>
}
if(mkdir("dd/xx/ff") == 0){
2217: 83 ec 0c sub $0xc,%esp
221a: 68 4a 4c 00 00 push $0x4c4a
221f: e8 47 1a 00 00 call 3c6b <mkdir>
2224: 83 c4 10 add $0x10,%esp
2227: 85 c0 test %eax,%eax
2229: 75 17 jne 2242 <subdir+0x581>
printf(1, "mkdir dd/xx/ff succeeded!\n");
222b: 83 ec 08 sub $0x8,%esp
222e: 68 49 4d 00 00 push $0x4d49
2233: 6a 01 push $0x1
2235: e8 60 1b 00 00 call 3d9a <printf>
223a: 83 c4 10 add $0x10,%esp
exit();
223d: e8 c1 19 00 00 call 3c03 <exit>
}
if(mkdir("dd/dd/ffff") == 0){
2242: 83 ec 0c sub $0xc,%esp
2245: 68 00 4b 00 00 push $0x4b00
224a: e8 1c 1a 00 00 call 3c6b <mkdir>
224f: 83 c4 10 add $0x10,%esp
2252: 85 c0 test %eax,%eax
2254: 75 17 jne 226d <subdir+0x5ac>
printf(1, "mkdir dd/dd/ffff succeeded!\n");
2256: 83 ec 08 sub $0x8,%esp
2259: 68 64 4d 00 00 push $0x4d64
225e: 6a 01 push $0x1
2260: e8 35 1b 00 00 call 3d9a <printf>
2265: 83 c4 10 add $0x10,%esp
exit();
2268: e8 96 19 00 00 call 3c03 <exit>
}
if(unlink("dd/xx/ff") == 0){
226d: 83 ec 0c sub $0xc,%esp
2270: 68 4a 4c 00 00 push $0x4c4a
2275: e8 d9 19 00 00 call 3c53 <unlink>
227a: 83 c4 10 add $0x10,%esp
227d: 85 c0 test %eax,%eax
227f: 75 17 jne 2298 <subdir+0x5d7>
printf(1, "unlink dd/xx/ff succeeded!\n");
2281: 83 ec 08 sub $0x8,%esp
2284: 68 81 4d 00 00 push $0x4d81
2289: 6a 01 push $0x1
228b: e8 0a 1b 00 00 call 3d9a <printf>
2290: 83 c4 10 add $0x10,%esp
exit();
2293: e8 6b 19 00 00 call 3c03 <exit>
}
if(unlink("dd/ff/ff") == 0){
2298: 83 ec 0c sub $0xc,%esp
229b: 68 25 4c 00 00 push $0x4c25
22a0: e8 ae 19 00 00 call 3c53 <unlink>
22a5: 83 c4 10 add $0x10,%esp
22a8: 85 c0 test %eax,%eax
22aa: 75 17 jne 22c3 <subdir+0x602>
printf(1, "unlink dd/ff/ff succeeded!\n");
22ac: 83 ec 08 sub $0x8,%esp
22af: 68 9d 4d 00 00 push $0x4d9d
22b4: 6a 01 push $0x1
22b6: e8 df 1a 00 00 call 3d9a <printf>
22bb: 83 c4 10 add $0x10,%esp
exit();
22be: e8 40 19 00 00 call 3c03 <exit>
}
if(chdir("dd/ff") == 0){
22c3: 83 ec 0c sub $0xc,%esp
22c6: 68 38 4a 00 00 push $0x4a38
22cb: e8 a3 19 00 00 call 3c73 <chdir>
22d0: 83 c4 10 add $0x10,%esp
22d3: 85 c0 test %eax,%eax
22d5: 75 17 jne 22ee <subdir+0x62d>
printf(1, "chdir dd/ff succeeded!\n");
22d7: 83 ec 08 sub $0x8,%esp
22da: 68 b9 4d 00 00 push $0x4db9
22df: 6a 01 push $0x1
22e1: e8 b4 1a 00 00 call 3d9a <printf>
22e6: 83 c4 10 add $0x10,%esp
exit();
22e9: e8 15 19 00 00 call 3c03 <exit>
}
if(chdir("dd/xx") == 0){
22ee: 83 ec 0c sub $0xc,%esp
22f1: 68 d1 4d 00 00 push $0x4dd1
22f6: e8 78 19 00 00 call 3c73 <chdir>
22fb: 83 c4 10 add $0x10,%esp
22fe: 85 c0 test %eax,%eax
2300: 75 17 jne 2319 <subdir+0x658>
printf(1, "chdir dd/xx succeeded!\n");
2302: 83 ec 08 sub $0x8,%esp
2305: 68 d7 4d 00 00 push $0x4dd7
230a: 6a 01 push $0x1
230c: e8 89 1a 00 00 call 3d9a <printf>
2311: 83 c4 10 add $0x10,%esp
exit();
2314: e8 ea 18 00 00 call 3c03 <exit>
}
if(unlink("dd/dd/ffff") != 0){
2319: 83 ec 0c sub $0xc,%esp
231c: 68 00 4b 00 00 push $0x4b00
2321: e8 2d 19 00 00 call 3c53 <unlink>
2326: 83 c4 10 add $0x10,%esp
2329: 85 c0 test %eax,%eax
232b: 74 17 je 2344 <subdir+0x683>
printf(1, "unlink dd/dd/ff failed\n");
232d: 83 ec 08 sub $0x8,%esp
2330: 68 2d 4b 00 00 push $0x4b2d
2335: 6a 01 push $0x1
2337: e8 5e 1a 00 00 call 3d9a <printf>
233c: 83 c4 10 add $0x10,%esp
exit();
233f: e8 bf 18 00 00 call 3c03 <exit>
}
if(unlink("dd/ff") != 0){
2344: 83 ec 0c sub $0xc,%esp
2347: 68 38 4a 00 00 push $0x4a38
234c: e8 02 19 00 00 call 3c53 <unlink>
2351: 83 c4 10 add $0x10,%esp
2354: 85 c0 test %eax,%eax
2356: 74 17 je 236f <subdir+0x6ae>
printf(1, "unlink dd/ff failed\n");
2358: 83 ec 08 sub $0x8,%esp
235b: 68 ef 4d 00 00 push $0x4def
2360: 6a 01 push $0x1
2362: e8 33 1a 00 00 call 3d9a <printf>
2367: 83 c4 10 add $0x10,%esp
exit();
236a: e8 94 18 00 00 call 3c03 <exit>
}
if(unlink("dd") == 0){
236f: 83 ec 0c sub $0xc,%esp
2372: 68 1d 4a 00 00 push $0x4a1d
2377: e8 d7 18 00 00 call 3c53 <unlink>
237c: 83 c4 10 add $0x10,%esp
237f: 85 c0 test %eax,%eax
2381: 75 17 jne 239a <subdir+0x6d9>
printf(1, "unlink non-empty dd succeeded!\n");
2383: 83 ec 08 sub $0x8,%esp
2386: 68 04 4e 00 00 push $0x4e04
238b: 6a 01 push $0x1
238d: e8 08 1a 00 00 call 3d9a <printf>
2392: 83 c4 10 add $0x10,%esp
exit();
2395: e8 69 18 00 00 call 3c03 <exit>
}
if(unlink("dd/dd") < 0){
239a: 83 ec 0c sub $0xc,%esp
239d: 68 24 4e 00 00 push $0x4e24
23a2: e8 ac 18 00 00 call 3c53 <unlink>
23a7: 83 c4 10 add $0x10,%esp
23aa: 85 c0 test %eax,%eax
23ac: 79 17 jns 23c5 <subdir+0x704>
printf(1, "unlink dd/dd failed\n");
23ae: 83 ec 08 sub $0x8,%esp
23b1: 68 2a 4e 00 00 push $0x4e2a
23b6: 6a 01 push $0x1
23b8: e8 dd 19 00 00 call 3d9a <printf>
23bd: 83 c4 10 add $0x10,%esp
exit();
23c0: e8 3e 18 00 00 call 3c03 <exit>
}
if(unlink("dd") < 0){
23c5: 83 ec 0c sub $0xc,%esp
23c8: 68 1d 4a 00 00 push $0x4a1d
23cd: e8 81 18 00 00 call 3c53 <unlink>
23d2: 83 c4 10 add $0x10,%esp
23d5: 85 c0 test %eax,%eax
23d7: 79 17 jns 23f0 <subdir+0x72f>
printf(1, "unlink dd failed\n");
23d9: 83 ec 08 sub $0x8,%esp
23dc: 68 3f 4e 00 00 push $0x4e3f
23e1: 6a 01 push $0x1
23e3: e8 b2 19 00 00 call 3d9a <printf>
23e8: 83 c4 10 add $0x10,%esp
exit();
23eb: e8 13 18 00 00 call 3c03 <exit>
}
printf(1, "subdir ok\n");
23f0: 83 ec 08 sub $0x8,%esp
23f3: 68 51 4e 00 00 push $0x4e51
23f8: 6a 01 push $0x1
23fa: e8 9b 19 00 00 call 3d9a <printf>
23ff: 83 c4 10 add $0x10,%esp
}
2402: 90 nop
2403: c9 leave
2404: c3 ret
00002405 <bigwrite>:
// test writes that are larger than the log.
void
bigwrite(void)
{
2405: 55 push %ebp
2406: 89 e5 mov %esp,%ebp
2408: 83 ec 18 sub $0x18,%esp
int fd, sz;
printf(1, "bigwrite test\n");
240b: 83 ec 08 sub $0x8,%esp
240e: 68 5c 4e 00 00 push $0x4e5c
2413: 6a 01 push $0x1
2415: e8 80 19 00 00 call 3d9a <printf>
241a: 83 c4 10 add $0x10,%esp
unlink("bigwrite");
241d: 83 ec 0c sub $0xc,%esp
2420: 68 6b 4e 00 00 push $0x4e6b
2425: e8 29 18 00 00 call 3c53 <unlink>
242a: 83 c4 10 add $0x10,%esp
for(sz = 499; sz < 12*512; sz += 471){
242d: c7 45 f4 f3 01 00 00 movl $0x1f3,-0xc(%ebp)
2434: e9 a8 00 00 00 jmp 24e1 <bigwrite+0xdc>
fd = open("bigwrite", O_CREATE | O_RDWR);
2439: 83 ec 08 sub $0x8,%esp
243c: 68 02 02 00 00 push $0x202
2441: 68 6b 4e 00 00 push $0x4e6b
2446: e8 f8 17 00 00 call 3c43 <open>
244b: 83 c4 10 add $0x10,%esp
244e: 89 45 ec mov %eax,-0x14(%ebp)
if(fd < 0){
2451: 83 7d ec 00 cmpl $0x0,-0x14(%ebp)
2455: 79 17 jns 246e <bigwrite+0x69>
printf(1, "cannot create bigwrite\n");
2457: 83 ec 08 sub $0x8,%esp
245a: 68 74 4e 00 00 push $0x4e74
245f: 6a 01 push $0x1
2461: e8 34 19 00 00 call 3d9a <printf>
2466: 83 c4 10 add $0x10,%esp
exit();
2469: e8 95 17 00 00 call 3c03 <exit>
}
int i;
for(i = 0; i < 2; i++){
246e: c7 45 f0 00 00 00 00 movl $0x0,-0x10(%ebp)
2475: eb 3f jmp 24b6 <bigwrite+0xb1>
int cc = write(fd, buf, sz);
2477: 83 ec 04 sub $0x4,%esp
247a: ff 75 f4 pushl -0xc(%ebp)
247d: 68 80 86 00 00 push $0x8680
2482: ff 75 ec pushl -0x14(%ebp)
2485: e8 99 17 00 00 call 3c23 <write>
248a: 83 c4 10 add $0x10,%esp
248d: 89 45 e8 mov %eax,-0x18(%ebp)
if(cc != sz){
2490: 8b 45 e8 mov -0x18(%ebp),%eax
2493: 3b 45 f4 cmp -0xc(%ebp),%eax
2496: 74 1a je 24b2 <bigwrite+0xad>
printf(1, "write(%d) ret %d\n", sz, cc);
2498: ff 75 e8 pushl -0x18(%ebp)
249b: ff 75 f4 pushl -0xc(%ebp)
249e: 68 8c 4e 00 00 push $0x4e8c
24a3: 6a 01 push $0x1
24a5: e8 f0 18 00 00 call 3d9a <printf>
24aa: 83 c4 10 add $0x10,%esp
exit();
24ad: e8 51 17 00 00 call 3c03 <exit>
if(fd < 0){
printf(1, "cannot create bigwrite\n");
exit();
}
int i;
for(i = 0; i < 2; i++){
24b2: 83 45 f0 01 addl $0x1,-0x10(%ebp)
24b6: 83 7d f0 01 cmpl $0x1,-0x10(%ebp)
24ba: 7e bb jle 2477 <bigwrite+0x72>
if(cc != sz){
printf(1, "write(%d) ret %d\n", sz, cc);
exit();
}
}
close(fd);
24bc: 83 ec 0c sub $0xc,%esp
24bf: ff 75 ec pushl -0x14(%ebp)
24c2: e8 64 17 00 00 call 3c2b <close>
24c7: 83 c4 10 add $0x10,%esp
unlink("bigwrite");
24ca: 83 ec 0c sub $0xc,%esp
24cd: 68 6b 4e 00 00 push $0x4e6b
24d2: e8 7c 17 00 00 call 3c53 <unlink>
24d7: 83 c4 10 add $0x10,%esp
int fd, sz;
printf(1, "bigwrite test\n");
unlink("bigwrite");
for(sz = 499; sz < 12*512; sz += 471){
24da: 81 45 f4 d7 01 00 00 addl $0x1d7,-0xc(%ebp)
24e1: 81 7d f4 ff 17 00 00 cmpl $0x17ff,-0xc(%ebp)
24e8: 0f 8e 4b ff ff ff jle 2439 <bigwrite+0x34>
}
close(fd);
unlink("bigwrite");
}
printf(1, "bigwrite ok\n");
24ee: 83 ec 08 sub $0x8,%esp
24f1: 68 9e 4e 00 00 push $0x4e9e
24f6: 6a 01 push $0x1
24f8: e8 9d 18 00 00 call 3d9a <printf>
24fd: 83 c4 10 add $0x10,%esp
}
2500: 90 nop
2501: c9 leave
2502: c3 ret
00002503 <bigfile>:
void
bigfile(void)
{
2503: 55 push %ebp
2504: 89 e5 mov %esp,%ebp
2506: 83 ec 18 sub $0x18,%esp
int fd, i, total, cc;
printf(1, "bigfile test\n");
2509: 83 ec 08 sub $0x8,%esp
250c: 68 ab 4e 00 00 push $0x4eab
2511: 6a 01 push $0x1
2513: e8 82 18 00 00 call 3d9a <printf>
2518: 83 c4 10 add $0x10,%esp
unlink("bigfile");
251b: 83 ec 0c sub $0xc,%esp
251e: 68 b9 4e 00 00 push $0x4eb9
2523: e8 2b 17 00 00 call 3c53 <unlink>
2528: 83 c4 10 add $0x10,%esp
fd = open("bigfile", O_CREATE | O_RDWR);
252b: 83 ec 08 sub $0x8,%esp
252e: 68 02 02 00 00 push $0x202
2533: 68 b9 4e 00 00 push $0x4eb9
2538: e8 06 17 00 00 call 3c43 <open>
253d: 83 c4 10 add $0x10,%esp
2540: 89 45 ec mov %eax,-0x14(%ebp)
if(fd < 0){
2543: 83 7d ec 00 cmpl $0x0,-0x14(%ebp)
2547: 79 17 jns 2560 <bigfile+0x5d>
printf(1, "cannot create bigfile");
2549: 83 ec 08 sub $0x8,%esp
254c: 68 c1 4e 00 00 push $0x4ec1
2551: 6a 01 push $0x1
2553: e8 42 18 00 00 call 3d9a <printf>
2558: 83 c4 10 add $0x10,%esp
exit();
255b: e8 a3 16 00 00 call 3c03 <exit>
}
for(i = 0; i < 20; i++){
2560: c7 45 f4 00 00 00 00 movl $0x0,-0xc(%ebp)
2567: eb 52 jmp 25bb <bigfile+0xb8>
memset(buf, i, 600);
2569: 83 ec 04 sub $0x4,%esp
256c: 68 58 02 00 00 push $0x258
2571: ff 75 f4 pushl -0xc(%ebp)
2574: 68 80 86 00 00 push $0x8680
2579: e8 ea 14 00 00 call 3a68 <memset>
257e: 83 c4 10 add $0x10,%esp
if(write(fd, buf, 600) != 600){
2581: 83 ec 04 sub $0x4,%esp
2584: 68 58 02 00 00 push $0x258
2589: 68 80 86 00 00 push $0x8680
258e: ff 75 ec pushl -0x14(%ebp)
2591: e8 8d 16 00 00 call 3c23 <write>
2596: 83 c4 10 add $0x10,%esp
2599: 3d 58 02 00 00 cmp $0x258,%eax
259e: 74 17 je 25b7 <bigfile+0xb4>
printf(1, "write bigfile failed\n");
25a0: 83 ec 08 sub $0x8,%esp
25a3: 68 d7 4e 00 00 push $0x4ed7
25a8: 6a 01 push $0x1
25aa: e8 eb 17 00 00 call 3d9a <printf>
25af: 83 c4 10 add $0x10,%esp
exit();
25b2: e8 4c 16 00 00 call 3c03 <exit>
fd = open("bigfile", O_CREATE | O_RDWR);
if(fd < 0){
printf(1, "cannot create bigfile");
exit();
}
for(i = 0; i < 20; i++){
25b7: 83 45 f4 01 addl $0x1,-0xc(%ebp)
25bb: 83 7d f4 13 cmpl $0x13,-0xc(%ebp)
25bf: 7e a8 jle 2569 <bigfile+0x66>
if(write(fd, buf, 600) != 600){
printf(1, "write bigfile failed\n");
exit();
}
}
close(fd);
25c1: 83 ec 0c sub $0xc,%esp
25c4: ff 75 ec pushl -0x14(%ebp)
25c7: e8 5f 16 00 00 call 3c2b <close>
25cc: 83 c4 10 add $0x10,%esp
fd = open("bigfile", 0);
25cf: 83 ec 08 sub $0x8,%esp
25d2: 6a 00 push $0x0
25d4: 68 b9 4e 00 00 push $0x4eb9
25d9: e8 65 16 00 00 call 3c43 <open>
25de: 83 c4 10 add $0x10,%esp
25e1: 89 45 ec mov %eax,-0x14(%ebp)
if(fd < 0){
25e4: 83 7d ec 00 cmpl $0x0,-0x14(%ebp)
25e8: 79 17 jns 2601 <bigfile+0xfe>
printf(1, "cannot open bigfile\n");
25ea: 83 ec 08 sub $0x8,%esp
25ed: 68 ed 4e 00 00 push $0x4eed
25f2: 6a 01 push $0x1
25f4: e8 a1 17 00 00 call 3d9a <printf>
25f9: 83 c4 10 add $0x10,%esp
exit();
25fc: e8 02 16 00 00 call 3c03 <exit>
}
total = 0;
2601: c7 45 f0 00 00 00 00 movl $0x0,-0x10(%ebp)
for(i = 0; ; i++){
2608: c7 45 f4 00 00 00 00 movl $0x0,-0xc(%ebp)
cc = read(fd, buf, 300);
260f: 83 ec 04 sub $0x4,%esp
2612: 68 2c 01 00 00 push $0x12c
2617: 68 80 86 00 00 push $0x8680
261c: ff 75 ec pushl -0x14(%ebp)
261f: e8 f7 15 00 00 call 3c1b <read>
2624: 83 c4 10 add $0x10,%esp
2627: 89 45 e8 mov %eax,-0x18(%ebp)
if(cc < 0){
262a: 83 7d e8 00 cmpl $0x0,-0x18(%ebp)
262e: 79 17 jns 2647 <bigfile+0x144>
printf(1, "read bigfile failed\n");
2630: 83 ec 08 sub $0x8,%esp
2633: 68 02 4f 00 00 push $0x4f02
2638: 6a 01 push $0x1
263a: e8 5b 17 00 00 call 3d9a <printf>
263f: 83 c4 10 add $0x10,%esp
exit();
2642: e8 bc 15 00 00 call 3c03 <exit>
}
if(cc == 0)
2647: 83 7d e8 00 cmpl $0x0,-0x18(%ebp)
264b: 74 7a je 26c7 <bigfile+0x1c4>
break;
if(cc != 300){
264d: 81 7d e8 2c 01 00 00 cmpl $0x12c,-0x18(%ebp)
2654: 74 17 je 266d <bigfile+0x16a>
printf(1, "short read bigfile\n");
2656: 83 ec 08 sub $0x8,%esp
2659: 68 17 4f 00 00 push $0x4f17
265e: 6a 01 push $0x1
2660: e8 35 17 00 00 call 3d9a <printf>
2665: 83 c4 10 add $0x10,%esp
exit();
2668: e8 96 15 00 00 call 3c03 <exit>
}
if(buf[0] != i/2 || buf[299] != i/2){
266d: 0f b6 05 80 86 00 00 movzbl 0x8680,%eax
2674: 0f be d0 movsbl %al,%edx
2677: 8b 45 f4 mov -0xc(%ebp),%eax
267a: 89 c1 mov %eax,%ecx
267c: c1 e9 1f shr $0x1f,%ecx
267f: 01 c8 add %ecx,%eax
2681: d1 f8 sar %eax
2683: 39 c2 cmp %eax,%edx
2685: 75 1a jne 26a1 <bigfile+0x19e>
2687: 0f b6 05 ab 87 00 00 movzbl 0x87ab,%eax
268e: 0f be d0 movsbl %al,%edx
2691: 8b 45 f4 mov -0xc(%ebp),%eax
2694: 89 c1 mov %eax,%ecx
2696: c1 e9 1f shr $0x1f,%ecx
2699: 01 c8 add %ecx,%eax
269b: d1 f8 sar %eax
269d: 39 c2 cmp %eax,%edx
269f: 74 17 je 26b8 <bigfile+0x1b5>
printf(1, "read bigfile wrong data\n");
26a1: 83 ec 08 sub $0x8,%esp
26a4: 68 2b 4f 00 00 push $0x4f2b
26a9: 6a 01 push $0x1
26ab: e8 ea 16 00 00 call 3d9a <printf>
26b0: 83 c4 10 add $0x10,%esp
exit();
26b3: e8 4b 15 00 00 call 3c03 <exit>
}
total += cc;
26b8: 8b 45 e8 mov -0x18(%ebp),%eax
26bb: 01 45 f0 add %eax,-0x10(%ebp)
if(fd < 0){
printf(1, "cannot open bigfile\n");
exit();
}
total = 0;
for(i = 0; ; i++){
26be: 83 45 f4 01 addl $0x1,-0xc(%ebp)
if(buf[0] != i/2 || buf[299] != i/2){
printf(1, "read bigfile wrong data\n");
exit();
}
total += cc;
}
26c2: e9 48 ff ff ff jmp 260f <bigfile+0x10c>
if(cc < 0){
printf(1, "read bigfile failed\n");
exit();
}
if(cc == 0)
break;
26c7: 90 nop
printf(1, "read bigfile wrong data\n");
exit();
}
total += cc;
}
close(fd);
26c8: 83 ec 0c sub $0xc,%esp
26cb: ff 75 ec pushl -0x14(%ebp)
26ce: e8 58 15 00 00 call 3c2b <close>
26d3: 83 c4 10 add $0x10,%esp
if(total != 20*600){
26d6: 81 7d f0 e0 2e 00 00 cmpl $0x2ee0,-0x10(%ebp)
26dd: 74 17 je 26f6 <bigfile+0x1f3>
printf(1, "read bigfile wrong total\n");
26df: 83 ec 08 sub $0x8,%esp
26e2: 68 44 4f 00 00 push $0x4f44
26e7: 6a 01 push $0x1
26e9: e8 ac 16 00 00 call 3d9a <printf>
26ee: 83 c4 10 add $0x10,%esp
exit();
26f1: e8 0d 15 00 00 call 3c03 <exit>
}
unlink("bigfile");
26f6: 83 ec 0c sub $0xc,%esp
26f9: 68 b9 4e 00 00 push $0x4eb9
26fe: e8 50 15 00 00 call 3c53 <unlink>
2703: 83 c4 10 add $0x10,%esp
printf(1, "bigfile test ok\n");
2706: 83 ec 08 sub $0x8,%esp
2709: 68 5e 4f 00 00 push $0x4f5e
270e: 6a 01 push $0x1
2710: e8 85 16 00 00 call 3d9a <printf>
2715: 83 c4 10 add $0x10,%esp
}
2718: 90 nop
2719: c9 leave
271a: c3 ret
0000271b <fourteen>:
void
fourteen(void)
{
271b: 55 push %ebp
271c: 89 e5 mov %esp,%ebp
271e: 83 ec 18 sub $0x18,%esp
int fd;
// DIRSIZ is 14.
printf(1, "fourteen test\n");
2721: 83 ec 08 sub $0x8,%esp
2724: 68 6f 4f 00 00 push $0x4f6f
2729: 6a 01 push $0x1
272b: e8 6a 16 00 00 call 3d9a <printf>
2730: 83 c4 10 add $0x10,%esp
if(mkdir("12345678901234") != 0){
2733: 83 ec 0c sub $0xc,%esp
2736: 68 7e 4f 00 00 push $0x4f7e
273b: e8 2b 15 00 00 call 3c6b <mkdir>
2740: 83 c4 10 add $0x10,%esp
2743: 85 c0 test %eax,%eax
2745: 74 17 je 275e <fourteen+0x43>
printf(1, "mkdir 12345678901234 failed\n");
2747: 83 ec 08 sub $0x8,%esp
274a: 68 8d 4f 00 00 push $0x4f8d
274f: 6a 01 push $0x1
2751: e8 44 16 00 00 call 3d9a <printf>
2756: 83 c4 10 add $0x10,%esp
exit();
2759: e8 a5 14 00 00 call 3c03 <exit>
}
if(mkdir("12345678901234/123456789012345") != 0){
275e: 83 ec 0c sub $0xc,%esp
2761: 68 ac 4f 00 00 push $0x4fac
2766: e8 00 15 00 00 call 3c6b <mkdir>
276b: 83 c4 10 add $0x10,%esp
276e: 85 c0 test %eax,%eax
2770: 74 17 je 2789 <fourteen+0x6e>
printf(1, "mkdir 12345678901234/123456789012345 failed\n");
2772: 83 ec 08 sub $0x8,%esp
2775: 68 cc 4f 00 00 push $0x4fcc
277a: 6a 01 push $0x1
277c: e8 19 16 00 00 call 3d9a <printf>
2781: 83 c4 10 add $0x10,%esp
exit();
2784: e8 7a 14 00 00 call 3c03 <exit>
}
fd = open("123456789012345/123456789012345/123456789012345", O_CREATE);
2789: 83 ec 08 sub $0x8,%esp
278c: 68 00 02 00 00 push $0x200
2791: 68 fc 4f 00 00 push $0x4ffc
2796: e8 a8 14 00 00 call 3c43 <open>
279b: 83 c4 10 add $0x10,%esp
279e: 89 45 f4 mov %eax,-0xc(%ebp)
if(fd < 0){
27a1: 83 7d f4 00 cmpl $0x0,-0xc(%ebp)
27a5: 79 17 jns 27be <fourteen+0xa3>
printf(1, "create 123456789012345/123456789012345/123456789012345 failed\n");
27a7: 83 ec 08 sub $0x8,%esp
27aa: 68 2c 50 00 00 push $0x502c
27af: 6a 01 push $0x1
27b1: e8 e4 15 00 00 call 3d9a <printf>
27b6: 83 c4 10 add $0x10,%esp
exit();
27b9: e8 45 14 00 00 call 3c03 <exit>
}
close(fd);
27be: 83 ec 0c sub $0xc,%esp
27c1: ff 75 f4 pushl -0xc(%ebp)
27c4: e8 62 14 00 00 call 3c2b <close>
27c9: 83 c4 10 add $0x10,%esp
fd = open("12345678901234/12345678901234/12345678901234", 0);
27cc: 83 ec 08 sub $0x8,%esp
27cf: 6a 00 push $0x0
27d1: 68 6c 50 00 00 push $0x506c
27d6: e8 68 14 00 00 call 3c43 <open>
27db: 83 c4 10 add $0x10,%esp
27de: 89 45 f4 mov %eax,-0xc(%ebp)
if(fd < 0){
27e1: 83 7d f4 00 cmpl $0x0,-0xc(%ebp)
27e5: 79 17 jns 27fe <fourteen+0xe3>
printf(1, "open 12345678901234/12345678901234/12345678901234 failed\n");
27e7: 83 ec 08 sub $0x8,%esp
27ea: 68 9c 50 00 00 push $0x509c
27ef: 6a 01 push $0x1
27f1: e8 a4 15 00 00 call 3d9a <printf>
27f6: 83 c4 10 add $0x10,%esp
exit();
27f9: e8 05 14 00 00 call 3c03 <exit>
}
close(fd);
27fe: 83 ec 0c sub $0xc,%esp
2801: ff 75 f4 pushl -0xc(%ebp)
2804: e8 22 14 00 00 call 3c2b <close>
2809: 83 c4 10 add $0x10,%esp
if(mkdir("12345678901234/12345678901234") == 0){
280c: 83 ec 0c sub $0xc,%esp
280f: 68 d6 50 00 00 push $0x50d6
2814: e8 52 14 00 00 call 3c6b <mkdir>
2819: 83 c4 10 add $0x10,%esp
281c: 85 c0 test %eax,%eax
281e: 75 17 jne 2837 <fourteen+0x11c>
printf(1, "mkdir 12345678901234/12345678901234 succeeded!\n");
2820: 83 ec 08 sub $0x8,%esp
2823: 68 f4 50 00 00 push $0x50f4
2828: 6a 01 push $0x1
282a: e8 6b 15 00 00 call 3d9a <printf>
282f: 83 c4 10 add $0x10,%esp
exit();
2832: e8 cc 13 00 00 call 3c03 <exit>
}
if(mkdir("123456789012345/12345678901234") == 0){
2837: 83 ec 0c sub $0xc,%esp
283a: 68 24 51 00 00 push $0x5124
283f: e8 27 14 00 00 call 3c6b <mkdir>
2844: 83 c4 10 add $0x10,%esp
2847: 85 c0 test %eax,%eax
2849: 75 17 jne 2862 <fourteen+0x147>
printf(1, "mkdir 12345678901234/123456789012345 succeeded!\n");
284b: 83 ec 08 sub $0x8,%esp
284e: 68 44 51 00 00 push $0x5144
2853: 6a 01 push $0x1
2855: e8 40 15 00 00 call 3d9a <printf>
285a: 83 c4 10 add $0x10,%esp
exit();
285d: e8 a1 13 00 00 call 3c03 <exit>
}
printf(1, "fourteen ok\n");
2862: 83 ec 08 sub $0x8,%esp
2865: 68 75 51 00 00 push $0x5175
286a: 6a 01 push $0x1
286c: e8 29 15 00 00 call 3d9a <printf>
2871: 83 c4 10 add $0x10,%esp
}
2874: 90 nop
2875: c9 leave
2876: c3 ret
00002877 <rmdot>:
void
rmdot(void)
{
2877: 55 push %ebp
2878: 89 e5 mov %esp,%ebp
287a: 83 ec 08 sub $0x8,%esp
printf(1, "rmdot test\n");
287d: 83 ec 08 sub $0x8,%esp
2880: 68 82 51 00 00 push $0x5182
2885: 6a 01 push $0x1
2887: e8 0e 15 00 00 call 3d9a <printf>
288c: 83 c4 10 add $0x10,%esp
if(mkdir("dots") != 0){
288f: 83 ec 0c sub $0xc,%esp
2892: 68 8e 51 00 00 push $0x518e
2897: e8 cf 13 00 00 call 3c6b <mkdir>
289c: 83 c4 10 add $0x10,%esp
289f: 85 c0 test %eax,%eax
28a1: 74 17 je 28ba <rmdot+0x43>
printf(1, "mkdir dots failed\n");
28a3: 83 ec 08 sub $0x8,%esp
28a6: 68 93 51 00 00 push $0x5193
28ab: 6a 01 push $0x1
28ad: e8 e8 14 00 00 call 3d9a <printf>
28b2: 83 c4 10 add $0x10,%esp
exit();
28b5: e8 49 13 00 00 call 3c03 <exit>
}
if(chdir("dots") != 0){
28ba: 83 ec 0c sub $0xc,%esp
28bd: 68 8e 51 00 00 push $0x518e
28c2: e8 ac 13 00 00 call 3c73 <chdir>
28c7: 83 c4 10 add $0x10,%esp
28ca: 85 c0 test %eax,%eax
28cc: 74 17 je 28e5 <rmdot+0x6e>
printf(1, "chdir dots failed\n");
28ce: 83 ec 08 sub $0x8,%esp
28d1: 68 a6 51 00 00 push $0x51a6
28d6: 6a 01 push $0x1
28d8: e8 bd 14 00 00 call 3d9a <printf>
28dd: 83 c4 10 add $0x10,%esp
exit();
28e0: e8 1e 13 00 00 call 3c03 <exit>
}
if(unlink(".") == 0){
28e5: 83 ec 0c sub $0xc,%esp
28e8: 68 bf 48 00 00 push $0x48bf
28ed: e8 61 13 00 00 call 3c53 <unlink>
28f2: 83 c4 10 add $0x10,%esp
28f5: 85 c0 test %eax,%eax
28f7: 75 17 jne 2910 <rmdot+0x99>
printf(1, "rm . worked!\n");
28f9: 83 ec 08 sub $0x8,%esp
28fc: 68 b9 51 00 00 push $0x51b9
2901: 6a 01 push $0x1
2903: e8 92 14 00 00 call 3d9a <printf>
2908: 83 c4 10 add $0x10,%esp
exit();
290b: e8 f3 12 00 00 call 3c03 <exit>
}
if(unlink("..") == 0){
2910: 83 ec 0c sub $0xc,%esp
2913: 68 4c 44 00 00 push $0x444c
2918: e8 36 13 00 00 call 3c53 <unlink>
291d: 83 c4 10 add $0x10,%esp
2920: 85 c0 test %eax,%eax
2922: 75 17 jne 293b <rmdot+0xc4>
printf(1, "rm .. worked!\n");
2924: 83 ec 08 sub $0x8,%esp
2927: 68 c7 51 00 00 push $0x51c7
292c: 6a 01 push $0x1
292e: e8 67 14 00 00 call 3d9a <printf>
2933: 83 c4 10 add $0x10,%esp
exit();
2936: e8 c8 12 00 00 call 3c03 <exit>
}
if(chdir("/") != 0){
293b: 83 ec 0c sub $0xc,%esp
293e: 68 d6 51 00 00 push $0x51d6
2943: e8 2b 13 00 00 call 3c73 <chdir>
2948: 83 c4 10 add $0x10,%esp
294b: 85 c0 test %eax,%eax
294d: 74 17 je 2966 <rmdot+0xef>
printf(1, "chdir / failed\n");
294f: 83 ec 08 sub $0x8,%esp
2952: 68 d8 51 00 00 push $0x51d8
2957: 6a 01 push $0x1
2959: e8 3c 14 00 00 call 3d9a <printf>
295e: 83 c4 10 add $0x10,%esp
exit();
2961: e8 9d 12 00 00 call 3c03 <exit>
}
if(unlink("dots/.") == 0){
2966: 83 ec 0c sub $0xc,%esp
2969: 68 e8 51 00 00 push $0x51e8
296e: e8 e0 12 00 00 call 3c53 <unlink>
2973: 83 c4 10 add $0x10,%esp
2976: 85 c0 test %eax,%eax
2978: 75 17 jne 2991 <rmdot+0x11a>
printf(1, "unlink dots/. worked!\n");
297a: 83 ec 08 sub $0x8,%esp
297d: 68 ef 51 00 00 push $0x51ef
2982: 6a 01 push $0x1
2984: e8 11 14 00 00 call 3d9a <printf>
2989: 83 c4 10 add $0x10,%esp
exit();
298c: e8 72 12 00 00 call 3c03 <exit>
}
if(unlink("dots/..") == 0){
2991: 83 ec 0c sub $0xc,%esp
2994: 68 06 52 00 00 push $0x5206
2999: e8 b5 12 00 00 call 3c53 <unlink>
299e: 83 c4 10 add $0x10,%esp
29a1: 85 c0 test %eax,%eax
29a3: 75 17 jne 29bc <rmdot+0x145>
printf(1, "unlink dots/.. worked!\n");
29a5: 83 ec 08 sub $0x8,%esp
29a8: 68 0e 52 00 00 push $0x520e
29ad: 6a 01 push $0x1
29af: e8 e6 13 00 00 call 3d9a <printf>
29b4: 83 c4 10 add $0x10,%esp
exit();
29b7: e8 47 12 00 00 call 3c03 <exit>
}
if(unlink("dots") != 0){
29bc: 83 ec 0c sub $0xc,%esp
29bf: 68 8e 51 00 00 push $0x518e
29c4: e8 8a 12 00 00 call 3c53 <unlink>
29c9: 83 c4 10 add $0x10,%esp
29cc: 85 c0 test %eax,%eax
29ce: 74 17 je 29e7 <rmdot+0x170>
printf(1, "unlink dots failed!\n");
29d0: 83 ec 08 sub $0x8,%esp
29d3: 68 26 52 00 00 push $0x5226
29d8: 6a 01 push $0x1
29da: e8 bb 13 00 00 call 3d9a <printf>
29df: 83 c4 10 add $0x10,%esp
exit();
29e2: e8 1c 12 00 00 call 3c03 <exit>
}
printf(1, "rmdot ok\n");
29e7: 83 ec 08 sub $0x8,%esp
29ea: 68 3b 52 00 00 push $0x523b
29ef: 6a 01 push $0x1
29f1: e8 a4 13 00 00 call 3d9a <printf>
29f6: 83 c4 10 add $0x10,%esp
}
29f9: 90 nop
29fa: c9 leave
29fb: c3 ret
000029fc <dirfile>:
void
dirfile(void)
{
29fc: 55 push %ebp
29fd: 89 e5 mov %esp,%ebp
29ff: 83 ec 18 sub $0x18,%esp
int fd;
printf(1, "dir vs file\n");
2a02: 83 ec 08 sub $0x8,%esp
2a05: 68 45 52 00 00 push $0x5245
2a0a: 6a 01 push $0x1
2a0c: e8 89 13 00 00 call 3d9a <printf>
2a11: 83 c4 10 add $0x10,%esp
fd = open("dirfile", O_CREATE);
2a14: 83 ec 08 sub $0x8,%esp
2a17: 68 00 02 00 00 push $0x200
2a1c: 68 52 52 00 00 push $0x5252
2a21: e8 1d 12 00 00 call 3c43 <open>
2a26: 83 c4 10 add $0x10,%esp
2a29: 89 45 f4 mov %eax,-0xc(%ebp)
if(fd < 0){
2a2c: 83 7d f4 00 cmpl $0x0,-0xc(%ebp)
2a30: 79 17 jns 2a49 <dirfile+0x4d>
printf(1, "create dirfile failed\n");
2a32: 83 ec 08 sub $0x8,%esp
2a35: 68 5a 52 00 00 push $0x525a
2a3a: 6a 01 push $0x1
2a3c: e8 59 13 00 00 call 3d9a <printf>
2a41: 83 c4 10 add $0x10,%esp
exit();
2a44: e8 ba 11 00 00 call 3c03 <exit>
}
close(fd);
2a49: 83 ec 0c sub $0xc,%esp
2a4c: ff 75 f4 pushl -0xc(%ebp)
2a4f: e8 d7 11 00 00 call 3c2b <close>
2a54: 83 c4 10 add $0x10,%esp
if(chdir("dirfile") == 0){
2a57: 83 ec 0c sub $0xc,%esp
2a5a: 68 52 52 00 00 push $0x5252
2a5f: e8 0f 12 00 00 call 3c73 <chdir>
2a64: 83 c4 10 add $0x10,%esp
2a67: 85 c0 test %eax,%eax
2a69: 75 17 jne 2a82 <dirfile+0x86>
printf(1, "chdir dirfile succeeded!\n");
2a6b: 83 ec 08 sub $0x8,%esp
2a6e: 68 71 52 00 00 push $0x5271
2a73: 6a 01 push $0x1
2a75: e8 20 13 00 00 call 3d9a <printf>
2a7a: 83 c4 10 add $0x10,%esp
exit();
2a7d: e8 81 11 00 00 call 3c03 <exit>
}
fd = open("dirfile/xx", 0);
2a82: 83 ec 08 sub $0x8,%esp
2a85: 6a 00 push $0x0
2a87: 68 8b 52 00 00 push $0x528b
2a8c: e8 b2 11 00 00 call 3c43 <open>
2a91: 83 c4 10 add $0x10,%esp
2a94: 89 45 f4 mov %eax,-0xc(%ebp)
if(fd >= 0){
2a97: 83 7d f4 00 cmpl $0x0,-0xc(%ebp)
2a9b: 78 17 js 2ab4 <dirfile+0xb8>
printf(1, "create dirfile/xx succeeded!\n");
2a9d: 83 ec 08 sub $0x8,%esp
2aa0: 68 96 52 00 00 push $0x5296
2aa5: 6a 01 push $0x1
2aa7: e8 ee 12 00 00 call 3d9a <printf>
2aac: 83 c4 10 add $0x10,%esp
exit();
2aaf: e8 4f 11 00 00 call 3c03 <exit>
}
fd = open("dirfile/xx", O_CREATE);
2ab4: 83 ec 08 sub $0x8,%esp
2ab7: 68 00 02 00 00 push $0x200
2abc: 68 8b 52 00 00 push $0x528b
2ac1: e8 7d 11 00 00 call 3c43 <open>
2ac6: 83 c4 10 add $0x10,%esp
2ac9: 89 45 f4 mov %eax,-0xc(%ebp)
if(fd >= 0){
2acc: 83 7d f4 00 cmpl $0x0,-0xc(%ebp)
2ad0: 78 17 js 2ae9 <dirfile+0xed>
printf(1, "create dirfile/xx succeeded!\n");
2ad2: 83 ec 08 sub $0x8,%esp
2ad5: 68 96 52 00 00 push $0x5296
2ada: 6a 01 push $0x1
2adc: e8 b9 12 00 00 call 3d9a <printf>
2ae1: 83 c4 10 add $0x10,%esp
exit();
2ae4: e8 1a 11 00 00 call 3c03 <exit>
}
if(mkdir("dirfile/xx") == 0){
2ae9: 83 ec 0c sub $0xc,%esp
2aec: 68 8b 52 00 00 push $0x528b
2af1: e8 75 11 00 00 call 3c6b <mkdir>
2af6: 83 c4 10 add $0x10,%esp
2af9: 85 c0 test %eax,%eax
2afb: 75 17 jne 2b14 <dirfile+0x118>
printf(1, "mkdir dirfile/xx succeeded!\n");
2afd: 83 ec 08 sub $0x8,%esp
2b00: 68 b4 52 00 00 push $0x52b4
2b05: 6a 01 push $0x1
2b07: e8 8e 12 00 00 call 3d9a <printf>
2b0c: 83 c4 10 add $0x10,%esp
exit();
2b0f: e8 ef 10 00 00 call 3c03 <exit>
}
if(unlink("dirfile/xx") == 0){
2b14: 83 ec 0c sub $0xc,%esp
2b17: 68 8b 52 00 00 push $0x528b
2b1c: e8 32 11 00 00 call 3c53 <unlink>
2b21: 83 c4 10 add $0x10,%esp
2b24: 85 c0 test %eax,%eax
2b26: 75 17 jne 2b3f <dirfile+0x143>
printf(1, "unlink dirfile/xx succeeded!\n");
2b28: 83 ec 08 sub $0x8,%esp
2b2b: 68 d1 52 00 00 push $0x52d1
2b30: 6a 01 push $0x1
2b32: e8 63 12 00 00 call 3d9a <printf>
2b37: 83 c4 10 add $0x10,%esp
exit();
2b3a: e8 c4 10 00 00 call 3c03 <exit>
}
if(link("README", "dirfile/xx") == 0){
2b3f: 83 ec 08 sub $0x8,%esp
2b42: 68 8b 52 00 00 push $0x528b
2b47: 68 ef 52 00 00 push $0x52ef
2b4c: e8 12 11 00 00 call 3c63 <link>
2b51: 83 c4 10 add $0x10,%esp
2b54: 85 c0 test %eax,%eax
2b56: 75 17 jne 2b6f <dirfile+0x173>
printf(1, "link to dirfile/xx succeeded!\n");
2b58: 83 ec 08 sub $0x8,%esp
2b5b: 68 f8 52 00 00 push $0x52f8
2b60: 6a 01 push $0x1
2b62: e8 33 12 00 00 call 3d9a <printf>
2b67: 83 c4 10 add $0x10,%esp
exit();
2b6a: e8 94 10 00 00 call 3c03 <exit>
}
if(unlink("dirfile") != 0){
2b6f: 83 ec 0c sub $0xc,%esp
2b72: 68 52 52 00 00 push $0x5252
2b77: e8 d7 10 00 00 call 3c53 <unlink>
2b7c: 83 c4 10 add $0x10,%esp
2b7f: 85 c0 test %eax,%eax
2b81: 74 17 je 2b9a <dirfile+0x19e>
printf(1, "unlink dirfile failed!\n");
2b83: 83 ec 08 sub $0x8,%esp
2b86: 68 17 53 00 00 push $0x5317
2b8b: 6a 01 push $0x1
2b8d: e8 08 12 00 00 call 3d9a <printf>
2b92: 83 c4 10 add $0x10,%esp
exit();
2b95: e8 69 10 00 00 call 3c03 <exit>
}
fd = open(".", O_RDWR);
2b9a: 83 ec 08 sub $0x8,%esp
2b9d: 6a 02 push $0x2
2b9f: 68 bf 48 00 00 push $0x48bf
2ba4: e8 9a 10 00 00 call 3c43 <open>
2ba9: 83 c4 10 add $0x10,%esp
2bac: 89 45 f4 mov %eax,-0xc(%ebp)
if(fd >= 0){
2baf: 83 7d f4 00 cmpl $0x0,-0xc(%ebp)
2bb3: 78 17 js 2bcc <dirfile+0x1d0>
printf(1, "open . for writing succeeded!\n");
2bb5: 83 ec 08 sub $0x8,%esp
2bb8: 68 30 53 00 00 push $0x5330
2bbd: 6a 01 push $0x1
2bbf: e8 d6 11 00 00 call 3d9a <printf>
2bc4: 83 c4 10 add $0x10,%esp
exit();
2bc7: e8 37 10 00 00 call 3c03 <exit>
}
fd = open(".", 0);
2bcc: 83 ec 08 sub $0x8,%esp
2bcf: 6a 00 push $0x0
2bd1: 68 bf 48 00 00 push $0x48bf
2bd6: e8 68 10 00 00 call 3c43 <open>
2bdb: 83 c4 10 add $0x10,%esp
2bde: 89 45 f4 mov %eax,-0xc(%ebp)
if(write(fd, "x", 1) > 0){
2be1: 83 ec 04 sub $0x4,%esp
2be4: 6a 01 push $0x1
2be6: 68 f6 44 00 00 push $0x44f6
2beb: ff 75 f4 pushl -0xc(%ebp)
2bee: e8 30 10 00 00 call 3c23 <write>
2bf3: 83 c4 10 add $0x10,%esp
2bf6: 85 c0 test %eax,%eax
2bf8: 7e 17 jle 2c11 <dirfile+0x215>
printf(1, "write . succeeded!\n");
2bfa: 83 ec 08 sub $0x8,%esp
2bfd: 68 4f 53 00 00 push $0x534f
2c02: 6a 01 push $0x1
2c04: e8 91 11 00 00 call 3d9a <printf>
2c09: 83 c4 10 add $0x10,%esp
exit();
2c0c: e8 f2 0f 00 00 call 3c03 <exit>
}
close(fd);
2c11: 83 ec 0c sub $0xc,%esp
2c14: ff 75 f4 pushl -0xc(%ebp)
2c17: e8 0f 10 00 00 call 3c2b <close>
2c1c: 83 c4 10 add $0x10,%esp
printf(1, "dir vs file OK\n");
2c1f: 83 ec 08 sub $0x8,%esp
2c22: 68 63 53 00 00 push $0x5363
2c27: 6a 01 push $0x1
2c29: e8 6c 11 00 00 call 3d9a <printf>
2c2e: 83 c4 10 add $0x10,%esp
}
2c31: 90 nop
2c32: c9 leave
2c33: c3 ret
00002c34 <iref>:
// test that iput() is called at the end of _namei()
void
iref(void)
{
2c34: 55 push %ebp
2c35: 89 e5 mov %esp,%ebp
2c37: 83 ec 18 sub $0x18,%esp
int i, fd;
printf(1, "empty file name\n");
2c3a: 83 ec 08 sub $0x8,%esp
2c3d: 68 73 53 00 00 push $0x5373
2c42: 6a 01 push $0x1
2c44: e8 51 11 00 00 call 3d9a <printf>
2c49: 83 c4 10 add $0x10,%esp
// the 50 is NINODE
for(i = 0; i < 50 + 1; i++){
2c4c: c7 45 f4 00 00 00 00 movl $0x0,-0xc(%ebp)
2c53: e9 e7 00 00 00 jmp 2d3f <iref+0x10b>
if(mkdir("irefd") != 0){
2c58: 83 ec 0c sub $0xc,%esp
2c5b: 68 84 53 00 00 push $0x5384
2c60: e8 06 10 00 00 call 3c6b <mkdir>
2c65: 83 c4 10 add $0x10,%esp
2c68: 85 c0 test %eax,%eax
2c6a: 74 17 je 2c83 <iref+0x4f>
printf(1, "mkdir irefd failed\n");
2c6c: 83 ec 08 sub $0x8,%esp
2c6f: 68 8a 53 00 00 push $0x538a
2c74: 6a 01 push $0x1
2c76: e8 1f 11 00 00 call 3d9a <printf>
2c7b: 83 c4 10 add $0x10,%esp
exit();
2c7e: e8 80 0f 00 00 call 3c03 <exit>
}
if(chdir("irefd") != 0){
2c83: 83 ec 0c sub $0xc,%esp
2c86: 68 84 53 00 00 push $0x5384
2c8b: e8 e3 0f 00 00 call 3c73 <chdir>
2c90: 83 c4 10 add $0x10,%esp
2c93: 85 c0 test %eax,%eax
2c95: 74 17 je 2cae <iref+0x7a>
printf(1, "chdir irefd failed\n");
2c97: 83 ec 08 sub $0x8,%esp
2c9a: 68 9e 53 00 00 push $0x539e
2c9f: 6a 01 push $0x1
2ca1: e8 f4 10 00 00 call 3d9a <printf>
2ca6: 83 c4 10 add $0x10,%esp
exit();
2ca9: e8 55 0f 00 00 call 3c03 <exit>
}
mkdir("");
2cae: 83 ec 0c sub $0xc,%esp
2cb1: 68 b2 53 00 00 push $0x53b2
2cb6: e8 b0 0f 00 00 call 3c6b <mkdir>
2cbb: 83 c4 10 add $0x10,%esp
link("README", "");
2cbe: 83 ec 08 sub $0x8,%esp
2cc1: 68 b2 53 00 00 push $0x53b2
2cc6: 68 ef 52 00 00 push $0x52ef
2ccb: e8 93 0f 00 00 call 3c63 <link>
2cd0: 83 c4 10 add $0x10,%esp
fd = open("", O_CREATE);
2cd3: 83 ec 08 sub $0x8,%esp
2cd6: 68 00 02 00 00 push $0x200
2cdb: 68 b2 53 00 00 push $0x53b2
2ce0: e8 5e 0f 00 00 call 3c43 <open>
2ce5: 83 c4 10 add $0x10,%esp
2ce8: 89 45 f0 mov %eax,-0x10(%ebp)
if(fd >= 0)
2ceb: 83 7d f0 00 cmpl $0x0,-0x10(%ebp)
2cef: 78 0e js 2cff <iref+0xcb>
close(fd);
2cf1: 83 ec 0c sub $0xc,%esp
2cf4: ff 75 f0 pushl -0x10(%ebp)
2cf7: e8 2f 0f 00 00 call 3c2b <close>
2cfc: 83 c4 10 add $0x10,%esp
fd = open("xx", O_CREATE);
2cff: 83 ec 08 sub $0x8,%esp
2d02: 68 00 02 00 00 push $0x200
2d07: 68 b3 53 00 00 push $0x53b3
2d0c: e8 32 0f 00 00 call 3c43 <open>
2d11: 83 c4 10 add $0x10,%esp
2d14: 89 45 f0 mov %eax,-0x10(%ebp)
if(fd >= 0)
2d17: 83 7d f0 00 cmpl $0x0,-0x10(%ebp)
2d1b: 78 0e js 2d2b <iref+0xf7>
close(fd);
2d1d: 83 ec 0c sub $0xc,%esp
2d20: ff 75 f0 pushl -0x10(%ebp)
2d23: e8 03 0f 00 00 call 3c2b <close>
2d28: 83 c4 10 add $0x10,%esp
unlink("xx");
2d2b: 83 ec 0c sub $0xc,%esp
2d2e: 68 b3 53 00 00 push $0x53b3
2d33: e8 1b 0f 00 00 call 3c53 <unlink>
2d38: 83 c4 10 add $0x10,%esp
int i, fd;
printf(1, "empty file name\n");
// the 50 is NINODE
for(i = 0; i < 50 + 1; i++){
2d3b: 83 45 f4 01 addl $0x1,-0xc(%ebp)
2d3f: 83 7d f4 32 cmpl $0x32,-0xc(%ebp)
2d43: 0f 8e 0f ff ff ff jle 2c58 <iref+0x24>
if(fd >= 0)
close(fd);
unlink("xx");
}
chdir("/");
2d49: 83 ec 0c sub $0xc,%esp
2d4c: 68 d6 51 00 00 push $0x51d6
2d51: e8 1d 0f 00 00 call 3c73 <chdir>
2d56: 83 c4 10 add $0x10,%esp
printf(1, "empty file name OK\n");
2d59: 83 ec 08 sub $0x8,%esp
2d5c: 68 b6 53 00 00 push $0x53b6
2d61: 6a 01 push $0x1
2d63: e8 32 10 00 00 call 3d9a <printf>
2d68: 83 c4 10 add $0x10,%esp
}
2d6b: 90 nop
2d6c: c9 leave
2d6d: c3 ret
00002d6e <forktest>:
// test that fork fails gracefully
// the forktest binary also does this, but it runs out of proc entries first.
// inside the bigger usertests binary, we run out of memory first.
void
forktest(void)
{
2d6e: 55 push %ebp
2d6f: 89 e5 mov %esp,%ebp
2d71: 83 ec 18 sub $0x18,%esp
int n, pid;
printf(1, "fork test\n");
2d74: 83 ec 08 sub $0x8,%esp
2d77: 68 ca 53 00 00 push $0x53ca
2d7c: 6a 01 push $0x1
2d7e: e8 17 10 00 00 call 3d9a <printf>
2d83: 83 c4 10 add $0x10,%esp
for(n=0; n<1000; n++){
2d86: c7 45 f4 00 00 00 00 movl $0x0,-0xc(%ebp)
2d8d: eb 1d jmp 2dac <forktest+0x3e>
pid = fork();
2d8f: e8 67 0e 00 00 call 3bfb <fork>
2d94: 89 45 f0 mov %eax,-0x10(%ebp)
if(pid < 0)
2d97: 83 7d f0 00 cmpl $0x0,-0x10(%ebp)
2d9b: 78 1a js 2db7 <forktest+0x49>
break;
if(pid == 0)
2d9d: 83 7d f0 00 cmpl $0x0,-0x10(%ebp)
2da1: 75 05 jne 2da8 <forktest+0x3a>
exit();
2da3: e8 5b 0e 00 00 call 3c03 <exit>
{
int n, pid;
printf(1, "fork test\n");
for(n=0; n<1000; n++){
2da8: 83 45 f4 01 addl $0x1,-0xc(%ebp)
2dac: 81 7d f4 e7 03 00 00 cmpl $0x3e7,-0xc(%ebp)
2db3: 7e da jle 2d8f <forktest+0x21>
2db5: eb 01 jmp 2db8 <forktest+0x4a>
pid = fork();
if(pid < 0)
break;
2db7: 90 nop
if(pid == 0)
exit();
}
if(n == 1000){
2db8: 81 7d f4 e8 03 00 00 cmpl $0x3e8,-0xc(%ebp)
2dbf: 75 3b jne 2dfc <forktest+0x8e>
printf(1, "fork claimed to work 1000 times!\n");
2dc1: 83 ec 08 sub $0x8,%esp
2dc4: 68 d8 53 00 00 push $0x53d8
2dc9: 6a 01 push $0x1
2dcb: e8 ca 0f 00 00 call 3d9a <printf>
2dd0: 83 c4 10 add $0x10,%esp
exit();
2dd3: e8 2b 0e 00 00 call 3c03 <exit>
}
for(; n > 0; n--){
if(wait() < 0){
2dd8: e8 2e 0e 00 00 call 3c0b <wait>
2ddd: 85 c0 test %eax,%eax
2ddf: 79 17 jns 2df8 <forktest+0x8a>
printf(1, "wait stopped early\n");
2de1: 83 ec 08 sub $0x8,%esp
2de4: 68 fa 53 00 00 push $0x53fa
2de9: 6a 01 push $0x1
2deb: e8 aa 0f 00 00 call 3d9a <printf>
2df0: 83 c4 10 add $0x10,%esp
exit();
2df3: e8 0b 0e 00 00 call 3c03 <exit>
if(n == 1000){
printf(1, "fork claimed to work 1000 times!\n");
exit();
}
for(; n > 0; n--){
2df8: 83 6d f4 01 subl $0x1,-0xc(%ebp)
2dfc: 83 7d f4 00 cmpl $0x0,-0xc(%ebp)
2e00: 7f d6 jg 2dd8 <forktest+0x6a>
printf(1, "wait stopped early\n");
exit();
}
}
if(wait() != -1){
2e02: e8 04 0e 00 00 call 3c0b <wait>
2e07: 83 f8 ff cmp $0xffffffff,%eax
2e0a: 74 17 je 2e23 <forktest+0xb5>
printf(1, "wait got too many\n");
2e0c: 83 ec 08 sub $0x8,%esp
2e0f: 68 0e 54 00 00 push $0x540e
2e14: 6a 01 push $0x1
2e16: e8 7f 0f 00 00 call 3d9a <printf>
2e1b: 83 c4 10 add $0x10,%esp
exit();
2e1e: e8 e0 0d 00 00 call 3c03 <exit>
}
printf(1, "fork test OK\n");
2e23: 83 ec 08 sub $0x8,%esp
2e26: 68 21 54 00 00 push $0x5421
2e2b: 6a 01 push $0x1
2e2d: e8 68 0f 00 00 call 3d9a <printf>
2e32: 83 c4 10 add $0x10,%esp
}
2e35: 90 nop
2e36: c9 leave
2e37: c3 ret
00002e38 <sbrktest>:
void
sbrktest(void)
{
2e38: 55 push %ebp
2e39: 89 e5 mov %esp,%ebp
2e3b: 53 push %ebx
2e3c: 83 ec 64 sub $0x64,%esp
int fds[2], pid, pids[10], ppid;
char *a, *b, *c, *lastaddr, *oldbrk, *p, scratch;
uint amt;
printf(stdout, "sbrk test\n");
2e3f: a1 a4 5e 00 00 mov 0x5ea4,%eax
2e44: 83 ec 08 sub $0x8,%esp
2e47: 68 2f 54 00 00 push $0x542f
2e4c: 50 push %eax
2e4d: e8 48 0f 00 00 call 3d9a <printf>
2e52: 83 c4 10 add $0x10,%esp
oldbrk = sbrk(0);
2e55: 83 ec 0c sub $0xc,%esp
2e58: 6a 00 push $0x0
2e5a: e8 2c 0e 00 00 call 3c8b <sbrk>
2e5f: 83 c4 10 add $0x10,%esp
2e62: 89 45 ec mov %eax,-0x14(%ebp)
// can one sbrk() less than a page?
a = sbrk(0);
2e65: 83 ec 0c sub $0xc,%esp
2e68: 6a 00 push $0x0
2e6a: e8 1c 0e 00 00 call 3c8b <sbrk>
2e6f: 83 c4 10 add $0x10,%esp
2e72: 89 45 f4 mov %eax,-0xc(%ebp)
int i;
for(i = 0; i < 5000; i++){
2e75: c7 45 f0 00 00 00 00 movl $0x0,-0x10(%ebp)
2e7c: eb 4f jmp 2ecd <sbrktest+0x95>
b = sbrk(1);
2e7e: 83 ec 0c sub $0xc,%esp
2e81: 6a 01 push $0x1
2e83: e8 03 0e 00 00 call 3c8b <sbrk>
2e88: 83 c4 10 add $0x10,%esp
2e8b: 89 45 e8 mov %eax,-0x18(%ebp)
if(b != a){
2e8e: 8b 45 e8 mov -0x18(%ebp),%eax
2e91: 3b 45 f4 cmp -0xc(%ebp),%eax
2e94: 74 24 je 2eba <sbrktest+0x82>
printf(stdout, "sbrk test failed %d %x %x\n", i, a, b);
2e96: a1 a4 5e 00 00 mov 0x5ea4,%eax
2e9b: 83 ec 0c sub $0xc,%esp
2e9e: ff 75 e8 pushl -0x18(%ebp)
2ea1: ff 75 f4 pushl -0xc(%ebp)
2ea4: ff 75 f0 pushl -0x10(%ebp)
2ea7: 68 3a 54 00 00 push $0x543a
2eac: 50 push %eax
2ead: e8 e8 0e 00 00 call 3d9a <printf>
2eb2: 83 c4 20 add $0x20,%esp
exit();
2eb5: e8 49 0d 00 00 call 3c03 <exit>
}
*b = 1;
2eba: 8b 45 e8 mov -0x18(%ebp),%eax
2ebd: c6 00 01 movb $0x1,(%eax)
a = b + 1;
2ec0: 8b 45 e8 mov -0x18(%ebp),%eax
2ec3: 83 c0 01 add $0x1,%eax
2ec6: 89 45 f4 mov %eax,-0xc(%ebp)
oldbrk = sbrk(0);
// can one sbrk() less than a page?
a = sbrk(0);
int i;
for(i = 0; i < 5000; i++){
2ec9: 83 45 f0 01 addl $0x1,-0x10(%ebp)
2ecd: 81 7d f0 87 13 00 00 cmpl $0x1387,-0x10(%ebp)
2ed4: 7e a8 jle 2e7e <sbrktest+0x46>
exit();
}
*b = 1;
a = b + 1;
}
pid = fork();
2ed6: e8 20 0d 00 00 call 3bfb <fork>
2edb: 89 45 e4 mov %eax,-0x1c(%ebp)
if(pid < 0){
2ede: 83 7d e4 00 cmpl $0x0,-0x1c(%ebp)
2ee2: 79 1b jns 2eff <sbrktest+0xc7>
printf(stdout, "sbrk test fork failed\n");
2ee4: a1 a4 5e 00 00 mov 0x5ea4,%eax
2ee9: 83 ec 08 sub $0x8,%esp
2eec: 68 55 54 00 00 push $0x5455
2ef1: 50 push %eax
2ef2: e8 a3 0e 00 00 call 3d9a <printf>
2ef7: 83 c4 10 add $0x10,%esp
exit();
2efa: e8 04 0d 00 00 call 3c03 <exit>
}
c = sbrk(1);
2eff: 83 ec 0c sub $0xc,%esp
2f02: 6a 01 push $0x1
2f04: e8 82 0d 00 00 call 3c8b <sbrk>
2f09: 83 c4 10 add $0x10,%esp
2f0c: 89 45 e0 mov %eax,-0x20(%ebp)
c = sbrk(1);
2f0f: 83 ec 0c sub $0xc,%esp
2f12: 6a 01 push $0x1
2f14: e8 72 0d 00 00 call 3c8b <sbrk>
2f19: 83 c4 10 add $0x10,%esp
2f1c: 89 45 e0 mov %eax,-0x20(%ebp)
if(c != a + 1){
2f1f: 8b 45 f4 mov -0xc(%ebp),%eax
2f22: 83 c0 01 add $0x1,%eax
2f25: 3b 45 e0 cmp -0x20(%ebp),%eax
2f28: 74 1b je 2f45 <sbrktest+0x10d>
printf(stdout, "sbrk test failed post-fork\n");
2f2a: a1 a4 5e 00 00 mov 0x5ea4,%eax
2f2f: 83 ec 08 sub $0x8,%esp
2f32: 68 6c 54 00 00 push $0x546c
2f37: 50 push %eax
2f38: e8 5d 0e 00 00 call 3d9a <printf>
2f3d: 83 c4 10 add $0x10,%esp
exit();
2f40: e8 be 0c 00 00 call 3c03 <exit>
}
if(pid == 0)
2f45: 83 7d e4 00 cmpl $0x0,-0x1c(%ebp)
2f49: 75 05 jne 2f50 <sbrktest+0x118>
exit();
2f4b: e8 b3 0c 00 00 call 3c03 <exit>
wait();
2f50: e8 b6 0c 00 00 call 3c0b <wait>
// can one grow address space to something big?
#define BIG (100*1024*1024)
a = sbrk(0);
2f55: 83 ec 0c sub $0xc,%esp
2f58: 6a 00 push $0x0
2f5a: e8 2c 0d 00 00 call 3c8b <sbrk>
2f5f: 83 c4 10 add $0x10,%esp
2f62: 89 45 f4 mov %eax,-0xc(%ebp)
amt = (BIG) - (uint)a;
2f65: 8b 45 f4 mov -0xc(%ebp),%eax
2f68: ba 00 00 40 06 mov $0x6400000,%edx
2f6d: 29 c2 sub %eax,%edx
2f6f: 89 d0 mov %edx,%eax
2f71: 89 45 dc mov %eax,-0x24(%ebp)
p = sbrk(amt);
2f74: 8b 45 dc mov -0x24(%ebp),%eax
2f77: 83 ec 0c sub $0xc,%esp
2f7a: 50 push %eax
2f7b: e8 0b 0d 00 00 call 3c8b <sbrk>
2f80: 83 c4 10 add $0x10,%esp
2f83: 89 45 d8 mov %eax,-0x28(%ebp)
if (p != a) {
2f86: 8b 45 d8 mov -0x28(%ebp),%eax
2f89: 3b 45 f4 cmp -0xc(%ebp),%eax
2f8c: 74 1b je 2fa9 <sbrktest+0x171>
printf(stdout, "sbrk test failed to grow big address space; enough phys mem?\n");
2f8e: a1 a4 5e 00 00 mov 0x5ea4,%eax
2f93: 83 ec 08 sub $0x8,%esp
2f96: 68 88 54 00 00 push $0x5488
2f9b: 50 push %eax
2f9c: e8 f9 0d 00 00 call 3d9a <printf>
2fa1: 83 c4 10 add $0x10,%esp
exit();
2fa4: e8 5a 0c 00 00 call 3c03 <exit>
}
lastaddr = (char*) (BIG-1);
2fa9: c7 45 d4 ff ff 3f 06 movl $0x63fffff,-0x2c(%ebp)
*lastaddr = 99;
2fb0: 8b 45 d4 mov -0x2c(%ebp),%eax
2fb3: c6 00 63 movb $0x63,(%eax)
// can one de-allocate?
a = sbrk(0);
2fb6: 83 ec 0c sub $0xc,%esp
2fb9: 6a 00 push $0x0
2fbb: e8 cb 0c 00 00 call 3c8b <sbrk>
2fc0: 83 c4 10 add $0x10,%esp
2fc3: 89 45 f4 mov %eax,-0xc(%ebp)
c = sbrk(-4096);
2fc6: 83 ec 0c sub $0xc,%esp
2fc9: 68 00 f0 ff ff push $0xfffff000
2fce: e8 b8 0c 00 00 call 3c8b <sbrk>
2fd3: 83 c4 10 add $0x10,%esp
2fd6: 89 45 e0 mov %eax,-0x20(%ebp)
if(c == (char*)0xffffffff){
2fd9: 83 7d e0 ff cmpl $0xffffffff,-0x20(%ebp)
2fdd: 75 1b jne 2ffa <sbrktest+0x1c2>
printf(stdout, "sbrk could not deallocate\n");
2fdf: a1 a4 5e 00 00 mov 0x5ea4,%eax
2fe4: 83 ec 08 sub $0x8,%esp
2fe7: 68 c6 54 00 00 push $0x54c6
2fec: 50 push %eax
2fed: e8 a8 0d 00 00 call 3d9a <printf>
2ff2: 83 c4 10 add $0x10,%esp
exit();
2ff5: e8 09 0c 00 00 call 3c03 <exit>
}
c = sbrk(0);
2ffa: 83 ec 0c sub $0xc,%esp
2ffd: 6a 00 push $0x0
2fff: e8 87 0c 00 00 call 3c8b <sbrk>
3004: 83 c4 10 add $0x10,%esp
3007: 89 45 e0 mov %eax,-0x20(%ebp)
if(c != a - 4096){
300a: 8b 45 f4 mov -0xc(%ebp),%eax
300d: 2d 00 10 00 00 sub $0x1000,%eax
3012: 3b 45 e0 cmp -0x20(%ebp),%eax
3015: 74 1e je 3035 <sbrktest+0x1fd>
printf(stdout, "sbrk deallocation produced wrong address, a %x c %x\n", a, c);
3017: a1 a4 5e 00 00 mov 0x5ea4,%eax
301c: ff 75 e0 pushl -0x20(%ebp)
301f: ff 75 f4 pushl -0xc(%ebp)
3022: 68 e4 54 00 00 push $0x54e4
3027: 50 push %eax
3028: e8 6d 0d 00 00 call 3d9a <printf>
302d: 83 c4 10 add $0x10,%esp
exit();
3030: e8 ce 0b 00 00 call 3c03 <exit>
}
// can one re-allocate that page?
a = sbrk(0);
3035: 83 ec 0c sub $0xc,%esp
3038: 6a 00 push $0x0
303a: e8 4c 0c 00 00 call 3c8b <sbrk>
303f: 83 c4 10 add $0x10,%esp
3042: 89 45 f4 mov %eax,-0xc(%ebp)
c = sbrk(4096);
3045: 83 ec 0c sub $0xc,%esp
3048: 68 00 10 00 00 push $0x1000
304d: e8 39 0c 00 00 call 3c8b <sbrk>
3052: 83 c4 10 add $0x10,%esp
3055: 89 45 e0 mov %eax,-0x20(%ebp)
if(c != a || sbrk(0) != a + 4096){
3058: 8b 45 e0 mov -0x20(%ebp),%eax
305b: 3b 45 f4 cmp -0xc(%ebp),%eax
305e: 75 1b jne 307b <sbrktest+0x243>
3060: 83 ec 0c sub $0xc,%esp
3063: 6a 00 push $0x0
3065: e8 21 0c 00 00 call 3c8b <sbrk>
306a: 83 c4 10 add $0x10,%esp
306d: 89 c2 mov %eax,%edx
306f: 8b 45 f4 mov -0xc(%ebp),%eax
3072: 05 00 10 00 00 add $0x1000,%eax
3077: 39 c2 cmp %eax,%edx
3079: 74 1e je 3099 <sbrktest+0x261>
printf(stdout, "sbrk re-allocation failed, a %x c %x\n", a, c);
307b: a1 a4 5e 00 00 mov 0x5ea4,%eax
3080: ff 75 e0 pushl -0x20(%ebp)
3083: ff 75 f4 pushl -0xc(%ebp)
3086: 68 1c 55 00 00 push $0x551c
308b: 50 push %eax
308c: e8 09 0d 00 00 call 3d9a <printf>
3091: 83 c4 10 add $0x10,%esp
exit();
3094: e8 6a 0b 00 00 call 3c03 <exit>
}
if(*lastaddr == 99){
3099: 8b 45 d4 mov -0x2c(%ebp),%eax
309c: 0f b6 00 movzbl (%eax),%eax
309f: 3c 63 cmp $0x63,%al
30a1: 75 1b jne 30be <sbrktest+0x286>
// should be zero
printf(stdout, "sbrk de-allocation didn't really deallocate\n");
30a3: a1 a4 5e 00 00 mov 0x5ea4,%eax
30a8: 83 ec 08 sub $0x8,%esp
30ab: 68 44 55 00 00 push $0x5544
30b0: 50 push %eax
30b1: e8 e4 0c 00 00 call 3d9a <printf>
30b6: 83 c4 10 add $0x10,%esp
exit();
30b9: e8 45 0b 00 00 call 3c03 <exit>
}
a = sbrk(0);
30be: 83 ec 0c sub $0xc,%esp
30c1: 6a 00 push $0x0
30c3: e8 c3 0b 00 00 call 3c8b <sbrk>
30c8: 83 c4 10 add $0x10,%esp
30cb: 89 45 f4 mov %eax,-0xc(%ebp)
c = sbrk(-(sbrk(0) - oldbrk));
30ce: 8b 5d ec mov -0x14(%ebp),%ebx
30d1: 83 ec 0c sub $0xc,%esp
30d4: 6a 00 push $0x0
30d6: e8 b0 0b 00 00 call 3c8b <sbrk>
30db: 83 c4 10 add $0x10,%esp
30de: 29 c3 sub %eax,%ebx
30e0: 89 d8 mov %ebx,%eax
30e2: 83 ec 0c sub $0xc,%esp
30e5: 50 push %eax
30e6: e8 a0 0b 00 00 call 3c8b <sbrk>
30eb: 83 c4 10 add $0x10,%esp
30ee: 89 45 e0 mov %eax,-0x20(%ebp)
if(c != a){
30f1: 8b 45 e0 mov -0x20(%ebp),%eax
30f4: 3b 45 f4 cmp -0xc(%ebp),%eax
30f7: 74 1e je 3117 <sbrktest+0x2df>
printf(stdout, "sbrk downsize failed, a %x c %x\n", a, c);
30f9: a1 a4 5e 00 00 mov 0x5ea4,%eax
30fe: ff 75 e0 pushl -0x20(%ebp)
3101: ff 75 f4 pushl -0xc(%ebp)
3104: 68 74 55 00 00 push $0x5574
3109: 50 push %eax
310a: e8 8b 0c 00 00 call 3d9a <printf>
310f: 83 c4 10 add $0x10,%esp
exit();
3112: e8 ec 0a 00 00 call 3c03 <exit>
}
// can we read the kernel's memory?
for(a = (char*)(KERNBASE); a < (char*) (KERNBASE+2000000); a += 50000){
3117: c7 45 f4 00 00 00 80 movl $0x80000000,-0xc(%ebp)
311e: eb 76 jmp 3196 <sbrktest+0x35e>
ppid = getpid();
3120: e8 5e 0b 00 00 call 3c83 <getpid>
3125: 89 45 d0 mov %eax,-0x30(%ebp)
pid = fork();
3128: e8 ce 0a 00 00 call 3bfb <fork>
312d: 89 45 e4 mov %eax,-0x1c(%ebp)
if(pid < 0){
3130: 83 7d e4 00 cmpl $0x0,-0x1c(%ebp)
3134: 79 1b jns 3151 <sbrktest+0x319>
printf(stdout, "fork failed\n");
3136: a1 a4 5e 00 00 mov 0x5ea4,%eax
313b: 83 ec 08 sub $0x8,%esp
313e: 68 3d 45 00 00 push $0x453d
3143: 50 push %eax
3144: e8 51 0c 00 00 call 3d9a <printf>
3149: 83 c4 10 add $0x10,%esp
exit();
314c: e8 b2 0a 00 00 call 3c03 <exit>
}
if(pid == 0){
3151: 83 7d e4 00 cmpl $0x0,-0x1c(%ebp)
3155: 75 33 jne 318a <sbrktest+0x352>
printf(stdout, "oops could read %x = %x\n", a, *a);
3157: 8b 45 f4 mov -0xc(%ebp),%eax
315a: 0f b6 00 movzbl (%eax),%eax
315d: 0f be d0 movsbl %al,%edx
3160: a1 a4 5e 00 00 mov 0x5ea4,%eax
3165: 52 push %edx
3166: ff 75 f4 pushl -0xc(%ebp)
3169: 68 95 55 00 00 push $0x5595
316e: 50 push %eax
316f: e8 26 0c 00 00 call 3d9a <printf>
3174: 83 c4 10 add $0x10,%esp
kill(ppid);
3177: 83 ec 0c sub $0xc,%esp
317a: ff 75 d0 pushl -0x30(%ebp)
317d: e8 b1 0a 00 00 call 3c33 <kill>
3182: 83 c4 10 add $0x10,%esp
exit();
3185: e8 79 0a 00 00 call 3c03 <exit>
}
wait();
318a: e8 7c 0a 00 00 call 3c0b <wait>
printf(stdout, "sbrk downsize failed, a %x c %x\n", a, c);
exit();
}
// can we read the kernel's memory?
for(a = (char*)(KERNBASE); a < (char*) (KERNBASE+2000000); a += 50000){
318f: 81 45 f4 50 c3 00 00 addl $0xc350,-0xc(%ebp)
3196: 81 7d f4 7f 84 1e 80 cmpl $0x801e847f,-0xc(%ebp)
319d: 76 81 jbe 3120 <sbrktest+0x2e8>
wait();
}
// if we run the system out of memory, does it clean up the last
// failed allocation?
if(pipe(fds) != 0){
319f: 83 ec 0c sub $0xc,%esp
31a2: 8d 45 c8 lea -0x38(%ebp),%eax
31a5: 50 push %eax
31a6: e8 68 0a 00 00 call 3c13 <pipe>
31ab: 83 c4 10 add $0x10,%esp
31ae: 85 c0 test %eax,%eax
31b0: 74 17 je 31c9 <sbrktest+0x391>
printf(1, "pipe() failed\n");
31b2: 83 ec 08 sub $0x8,%esp
31b5: 68 91 44 00 00 push $0x4491
31ba: 6a 01 push $0x1
31bc: e8 d9 0b 00 00 call 3d9a <printf>
31c1: 83 c4 10 add $0x10,%esp
exit();
31c4: e8 3a 0a 00 00 call 3c03 <exit>
}
for(i = 0; i < sizeof(pids)/sizeof(pids[0]); i++){
31c9: c7 45 f0 00 00 00 00 movl $0x0,-0x10(%ebp)
31d0: e9 88 00 00 00 jmp 325d <sbrktest+0x425>
if((pids[i] = fork()) == 0){
31d5: e8 21 0a 00 00 call 3bfb <fork>
31da: 89 c2 mov %eax,%edx
31dc: 8b 45 f0 mov -0x10(%ebp),%eax
31df: 89 54 85 a0 mov %edx,-0x60(%ebp,%eax,4)
31e3: 8b 45 f0 mov -0x10(%ebp),%eax
31e6: 8b 44 85 a0 mov -0x60(%ebp,%eax,4),%eax
31ea: 85 c0 test %eax,%eax
31ec: 75 4a jne 3238 <sbrktest+0x400>
// allocate a lot of memory
sbrk(BIG - (uint)sbrk(0));
31ee: 83 ec 0c sub $0xc,%esp
31f1: 6a 00 push $0x0
31f3: e8 93 0a 00 00 call 3c8b <sbrk>
31f8: 83 c4 10 add $0x10,%esp
31fb: ba 00 00 40 06 mov $0x6400000,%edx
3200: 29 c2 sub %eax,%edx
3202: 89 d0 mov %edx,%eax
3204: 83 ec 0c sub $0xc,%esp
3207: 50 push %eax
3208: e8 7e 0a 00 00 call 3c8b <sbrk>
320d: 83 c4 10 add $0x10,%esp
write(fds[1], "x", 1);
3210: 8b 45 cc mov -0x34(%ebp),%eax
3213: 83 ec 04 sub $0x4,%esp
3216: 6a 01 push $0x1
3218: 68 f6 44 00 00 push $0x44f6
321d: 50 push %eax
321e: e8 00 0a 00 00 call 3c23 <write>
3223: 83 c4 10 add $0x10,%esp
// sit around until killed
for(;;) sleep(1000);
3226: 83 ec 0c sub $0xc,%esp
3229: 68 e8 03 00 00 push $0x3e8
322e: e8 60 0a 00 00 call 3c93 <sleep>
3233: 83 c4 10 add $0x10,%esp
3236: eb ee jmp 3226 <sbrktest+0x3ee>
}
if(pids[i] != -1)
3238: 8b 45 f0 mov -0x10(%ebp),%eax
323b: 8b 44 85 a0 mov -0x60(%ebp,%eax,4),%eax
323f: 83 f8 ff cmp $0xffffffff,%eax
3242: 74 15 je 3259 <sbrktest+0x421>
read(fds[0], &scratch, 1);
3244: 8b 45 c8 mov -0x38(%ebp),%eax
3247: 83 ec 04 sub $0x4,%esp
324a: 6a 01 push $0x1
324c: 8d 55 9f lea -0x61(%ebp),%edx
324f: 52 push %edx
3250: 50 push %eax
3251: e8 c5 09 00 00 call 3c1b <read>
3256: 83 c4 10 add $0x10,%esp
// failed allocation?
if(pipe(fds) != 0){
printf(1, "pipe() failed\n");
exit();
}
for(i = 0; i < sizeof(pids)/sizeof(pids[0]); i++){
3259: 83 45 f0 01 addl $0x1,-0x10(%ebp)
325d: 8b 45 f0 mov -0x10(%ebp),%eax
3260: 83 f8 09 cmp $0x9,%eax
3263: 0f 86 6c ff ff ff jbe 31d5 <sbrktest+0x39d>
if(pids[i] != -1)
read(fds[0], &scratch, 1);
}
// if those failed allocations freed up the pages they did allocate,
// we'll be able to allocate here
c = sbrk(4096);
3269: 83 ec 0c sub $0xc,%esp
326c: 68 00 10 00 00 push $0x1000
3271: e8 15 0a 00 00 call 3c8b <sbrk>
3276: 83 c4 10 add $0x10,%esp
3279: 89 45 e0 mov %eax,-0x20(%ebp)
for(i = 0; i < sizeof(pids)/sizeof(pids[0]); i++){
327c: c7 45 f0 00 00 00 00 movl $0x0,-0x10(%ebp)
3283: eb 2b jmp 32b0 <sbrktest+0x478>
if(pids[i] == -1)
3285: 8b 45 f0 mov -0x10(%ebp),%eax
3288: 8b 44 85 a0 mov -0x60(%ebp,%eax,4),%eax
328c: 83 f8 ff cmp $0xffffffff,%eax
328f: 74 1a je 32ab <sbrktest+0x473>
continue;
kill(pids[i]);
3291: 8b 45 f0 mov -0x10(%ebp),%eax
3294: 8b 44 85 a0 mov -0x60(%ebp,%eax,4),%eax
3298: 83 ec 0c sub $0xc,%esp
329b: 50 push %eax
329c: e8 92 09 00 00 call 3c33 <kill>
32a1: 83 c4 10 add $0x10,%esp
wait();
32a4: e8 62 09 00 00 call 3c0b <wait>
32a9: eb 01 jmp 32ac <sbrktest+0x474>
// if those failed allocations freed up the pages they did allocate,
// we'll be able to allocate here
c = sbrk(4096);
for(i = 0; i < sizeof(pids)/sizeof(pids[0]); i++){
if(pids[i] == -1)
continue;
32ab: 90 nop
read(fds[0], &scratch, 1);
}
// if those failed allocations freed up the pages they did allocate,
// we'll be able to allocate here
c = sbrk(4096);
for(i = 0; i < sizeof(pids)/sizeof(pids[0]); i++){
32ac: 83 45 f0 01 addl $0x1,-0x10(%ebp)
32b0: 8b 45 f0 mov -0x10(%ebp),%eax
32b3: 83 f8 09 cmp $0x9,%eax
32b6: 76 cd jbe 3285 <sbrktest+0x44d>
if(pids[i] == -1)
continue;
kill(pids[i]);
wait();
}
if(c == (char*)0xffffffff){
32b8: 83 7d e0 ff cmpl $0xffffffff,-0x20(%ebp)
32bc: 75 1b jne 32d9 <sbrktest+0x4a1>
printf(stdout, "failed sbrk leaked memory\n");
32be: a1 a4 5e 00 00 mov 0x5ea4,%eax
32c3: 83 ec 08 sub $0x8,%esp
32c6: 68 ae 55 00 00 push $0x55ae
32cb: 50 push %eax
32cc: e8 c9 0a 00 00 call 3d9a <printf>
32d1: 83 c4 10 add $0x10,%esp
exit();
32d4: e8 2a 09 00 00 call 3c03 <exit>
}
if(sbrk(0) > oldbrk)
32d9: 83 ec 0c sub $0xc,%esp
32dc: 6a 00 push $0x0
32de: e8 a8 09 00 00 call 3c8b <sbrk>
32e3: 83 c4 10 add $0x10,%esp
32e6: 3b 45 ec cmp -0x14(%ebp),%eax
32e9: 76 20 jbe 330b <sbrktest+0x4d3>
sbrk(-(sbrk(0) - oldbrk));
32eb: 8b 5d ec mov -0x14(%ebp),%ebx
32ee: 83 ec 0c sub $0xc,%esp
32f1: 6a 00 push $0x0
32f3: e8 93 09 00 00 call 3c8b <sbrk>
32f8: 83 c4 10 add $0x10,%esp
32fb: 29 c3 sub %eax,%ebx
32fd: 89 d8 mov %ebx,%eax
32ff: 83 ec 0c sub $0xc,%esp
3302: 50 push %eax
3303: e8 83 09 00 00 call 3c8b <sbrk>
3308: 83 c4 10 add $0x10,%esp
printf(stdout, "sbrk test OK\n");
330b: a1 a4 5e 00 00 mov 0x5ea4,%eax
3310: 83 ec 08 sub $0x8,%esp
3313: 68 c9 55 00 00 push $0x55c9
3318: 50 push %eax
3319: e8 7c 0a 00 00 call 3d9a <printf>
331e: 83 c4 10 add $0x10,%esp
}
3321: 90 nop
3322: 8b 5d fc mov -0x4(%ebp),%ebx
3325: c9 leave
3326: c3 ret
00003327 <validateint>:
void
validateint(int *p)
{
3327: 55 push %ebp
3328: 89 e5 mov %esp,%ebp
332a: 53 push %ebx
332b: 83 ec 10 sub $0x10,%esp
int res;
asm("mov %%esp, %%ebx\n\t"
332e: b8 0d 00 00 00 mov $0xd,%eax
3333: 8b 55 08 mov 0x8(%ebp),%edx
3336: 89 d1 mov %edx,%ecx
3338: 89 e3 mov %esp,%ebx
333a: 89 cc mov %ecx,%esp
333c: cd 40 int $0x40
333e: 89 dc mov %ebx,%esp
3340: 89 45 f8 mov %eax,-0x8(%ebp)
"int %2\n\t"
"mov %%ebx, %%esp" :
"=a" (res) :
"a" (SYS_sleep), "n" (T_SYSCALL), "c" (p) :
"ebx");
}
3343: 90 nop
3344: 83 c4 10 add $0x10,%esp
3347: 5b pop %ebx
3348: 5d pop %ebp
3349: c3 ret
0000334a <validatetest>:
void
validatetest(void)
{
334a: 55 push %ebp
334b: 89 e5 mov %esp,%ebp
334d: 83 ec 18 sub $0x18,%esp
int hi, pid;
uint p;
printf(stdout, "validate test\n");
3350: a1 a4 5e 00 00 mov 0x5ea4,%eax
3355: 83 ec 08 sub $0x8,%esp
3358: 68 d7 55 00 00 push $0x55d7
335d: 50 push %eax
335e: e8 37 0a 00 00 call 3d9a <printf>
3363: 83 c4 10 add $0x10,%esp
hi = 1100*1024;
3366: c7 45 f0 00 30 11 00 movl $0x113000,-0x10(%ebp)
for(p = 0; p <= (uint)hi; p += 4096){
336d: c7 45 f4 00 00 00 00 movl $0x0,-0xc(%ebp)
3374: e9 8a 00 00 00 jmp 3403 <validatetest+0xb9>
if((pid = fork()) == 0){
3379: e8 7d 08 00 00 call 3bfb <fork>
337e: 89 45 ec mov %eax,-0x14(%ebp)
3381: 83 7d ec 00 cmpl $0x0,-0x14(%ebp)
3385: 75 14 jne 339b <validatetest+0x51>
// try to crash the kernel by passing in a badly placed integer
validateint((int*)p);
3387: 8b 45 f4 mov -0xc(%ebp),%eax
338a: 83 ec 0c sub $0xc,%esp
338d: 50 push %eax
338e: e8 94 ff ff ff call 3327 <validateint>
3393: 83 c4 10 add $0x10,%esp
exit();
3396: e8 68 08 00 00 call 3c03 <exit>
}
sleep(0);
339b: 83 ec 0c sub $0xc,%esp
339e: 6a 00 push $0x0
33a0: e8 ee 08 00 00 call 3c93 <sleep>
33a5: 83 c4 10 add $0x10,%esp
sleep(0);
33a8: 83 ec 0c sub $0xc,%esp
33ab: 6a 00 push $0x0
33ad: e8 e1 08 00 00 call 3c93 <sleep>
33b2: 83 c4 10 add $0x10,%esp
kill(pid);
33b5: 83 ec 0c sub $0xc,%esp
33b8: ff 75 ec pushl -0x14(%ebp)
33bb: e8 73 08 00 00 call 3c33 <kill>
33c0: 83 c4 10 add $0x10,%esp
wait();
33c3: e8 43 08 00 00 call 3c0b <wait>
// try to crash the kernel by passing in a bad string pointer
if(link("nosuchfile", (char*)p) != -1){
33c8: 8b 45 f4 mov -0xc(%ebp),%eax
33cb: 83 ec 08 sub $0x8,%esp
33ce: 50 push %eax
33cf: 68 e6 55 00 00 push $0x55e6
33d4: e8 8a 08 00 00 call 3c63 <link>
33d9: 83 c4 10 add $0x10,%esp
33dc: 83 f8 ff cmp $0xffffffff,%eax
33df: 74 1b je 33fc <validatetest+0xb2>
printf(stdout, "link should not succeed\n");
33e1: a1 a4 5e 00 00 mov 0x5ea4,%eax
33e6: 83 ec 08 sub $0x8,%esp
33e9: 68 f1 55 00 00 push $0x55f1
33ee: 50 push %eax
33ef: e8 a6 09 00 00 call 3d9a <printf>
33f4: 83 c4 10 add $0x10,%esp
exit();
33f7: e8 07 08 00 00 call 3c03 <exit>
uint p;
printf(stdout, "validate test\n");
hi = 1100*1024;
for(p = 0; p <= (uint)hi; p += 4096){
33fc: 81 45 f4 00 10 00 00 addl $0x1000,-0xc(%ebp)
3403: 8b 45 f0 mov -0x10(%ebp),%eax
3406: 39 45 f4 cmp %eax,-0xc(%ebp)
3409: 0f 86 6a ff ff ff jbe 3379 <validatetest+0x2f>
printf(stdout, "link should not succeed\n");
exit();
}
}
printf(stdout, "validate ok\n");
340f: a1 a4 5e 00 00 mov 0x5ea4,%eax
3414: 83 ec 08 sub $0x8,%esp
3417: 68 0a 56 00 00 push $0x560a
341c: 50 push %eax
341d: e8 78 09 00 00 call 3d9a <printf>
3422: 83 c4 10 add $0x10,%esp
}
3425: 90 nop
3426: c9 leave
3427: c3 ret
00003428 <bsstest>:
// does unintialized data start out zero?
char uninit[10000];
void
bsstest(void)
{
3428: 55 push %ebp
3429: 89 e5 mov %esp,%ebp
342b: 83 ec 18 sub $0x18,%esp
int i;
printf(stdout, "bss test\n");
342e: a1 a4 5e 00 00 mov 0x5ea4,%eax
3433: 83 ec 08 sub $0x8,%esp
3436: 68 17 56 00 00 push $0x5617
343b: 50 push %eax
343c: e8 59 09 00 00 call 3d9a <printf>
3441: 83 c4 10 add $0x10,%esp
for(i = 0; i < sizeof(uninit); i++){
3444: c7 45 f4 00 00 00 00 movl $0x0,-0xc(%ebp)
344b: eb 2e jmp 347b <bsstest+0x53>
if(uninit[i] != '\0'){
344d: 8b 45 f4 mov -0xc(%ebp),%eax
3450: 05 60 5f 00 00 add $0x5f60,%eax
3455: 0f b6 00 movzbl (%eax),%eax
3458: 84 c0 test %al,%al
345a: 74 1b je 3477 <bsstest+0x4f>
printf(stdout, "bss test failed\n");
345c: a1 a4 5e 00 00 mov 0x5ea4,%eax
3461: 83 ec 08 sub $0x8,%esp
3464: 68 21 56 00 00 push $0x5621
3469: 50 push %eax
346a: e8 2b 09 00 00 call 3d9a <printf>
346f: 83 c4 10 add $0x10,%esp
exit();
3472: e8 8c 07 00 00 call 3c03 <exit>
bsstest(void)
{
int i;
printf(stdout, "bss test\n");
for(i = 0; i < sizeof(uninit); i++){
3477: 83 45 f4 01 addl $0x1,-0xc(%ebp)
347b: 8b 45 f4 mov -0xc(%ebp),%eax
347e: 3d 0f 27 00 00 cmp $0x270f,%eax
3483: 76 c8 jbe 344d <bsstest+0x25>
if(uninit[i] != '\0'){
printf(stdout, "bss test failed\n");
exit();
}
}
printf(stdout, "bss test ok\n");
3485: a1 a4 5e 00 00 mov 0x5ea4,%eax
348a: 83 ec 08 sub $0x8,%esp
348d: 68 32 56 00 00 push $0x5632
3492: 50 push %eax
3493: e8 02 09 00 00 call 3d9a <printf>
3498: 83 c4 10 add $0x10,%esp
}
349b: 90 nop
349c: c9 leave
349d: c3 ret
0000349e <bigargtest>:
// does exec return an error if the arguments
// are larger than a page? or does it write
// below the stack and wreck the instructions/data?
void
bigargtest(void)
{
349e: 55 push %ebp
349f: 89 e5 mov %esp,%ebp
34a1: 83 ec 18 sub $0x18,%esp
int pid, fd;
unlink("bigarg-ok");
34a4: 83 ec 0c sub $0xc,%esp
34a7: 68 3f 56 00 00 push $0x563f
34ac: e8 a2 07 00 00 call 3c53 <unlink>
34b1: 83 c4 10 add $0x10,%esp
pid = fork();
34b4: e8 42 07 00 00 call 3bfb <fork>
34b9: 89 45 f0 mov %eax,-0x10(%ebp)
if(pid == 0){
34bc: 83 7d f0 00 cmpl $0x0,-0x10(%ebp)
34c0: 0f 85 97 00 00 00 jne 355d <bigargtest+0xbf>
static char *args[MAXARG];
int i;
for(i = 0; i < MAXARG-1; i++)
34c6: c7 45 f4 00 00 00 00 movl $0x0,-0xc(%ebp)
34cd: eb 12 jmp 34e1 <bigargtest+0x43>
args[i] = "bigargs test: failed\n ";
34cf: 8b 45 f4 mov -0xc(%ebp),%eax
34d2: c7 04 85 c0 5e 00 00 movl $0x564c,0x5ec0(,%eax,4)
34d9: 4c 56 00 00
unlink("bigarg-ok");
pid = fork();
if(pid == 0){
static char *args[MAXARG];
int i;
for(i = 0; i < MAXARG-1; i++)
34dd: 83 45 f4 01 addl $0x1,-0xc(%ebp)
34e1: 83 7d f4 1e cmpl $0x1e,-0xc(%ebp)
34e5: 7e e8 jle 34cf <bigargtest+0x31>
args[i] = "bigargs test: failed\n ";
args[MAXARG-1] = 0;
34e7: c7 05 3c 5f 00 00 00 movl $0x0,0x5f3c
34ee: 00 00 00
printf(stdout, "bigarg test\n");
34f1: a1 a4 5e 00 00 mov 0x5ea4,%eax
34f6: 83 ec 08 sub $0x8,%esp
34f9: 68 29 57 00 00 push $0x5729
34fe: 50 push %eax
34ff: e8 96 08 00 00 call 3d9a <printf>
3504: 83 c4 10 add $0x10,%esp
exec("echo", args);
3507: 83 ec 08 sub $0x8,%esp
350a: 68 c0 5e 00 00 push $0x5ec0
350f: 68 50 41 00 00 push $0x4150
3514: e8 22 07 00 00 call 3c3b <exec>
3519: 83 c4 10 add $0x10,%esp
printf(stdout, "bigarg test ok\n");
351c: a1 a4 5e 00 00 mov 0x5ea4,%eax
3521: 83 ec 08 sub $0x8,%esp
3524: 68 36 57 00 00 push $0x5736
3529: 50 push %eax
352a: e8 6b 08 00 00 call 3d9a <printf>
352f: 83 c4 10 add $0x10,%esp
fd = open("bigarg-ok", O_CREATE);
3532: 83 ec 08 sub $0x8,%esp
3535: 68 00 02 00 00 push $0x200
353a: 68 3f 56 00 00 push $0x563f
353f: e8 ff 06 00 00 call 3c43 <open>
3544: 83 c4 10 add $0x10,%esp
3547: 89 45 ec mov %eax,-0x14(%ebp)
close(fd);
354a: 83 ec 0c sub $0xc,%esp
354d: ff 75 ec pushl -0x14(%ebp)
3550: e8 d6 06 00 00 call 3c2b <close>
3555: 83 c4 10 add $0x10,%esp
exit();
3558: e8 a6 06 00 00 call 3c03 <exit>
} else if(pid < 0){
355d: 83 7d f0 00 cmpl $0x0,-0x10(%ebp)
3561: 79 1b jns 357e <bigargtest+0xe0>
printf(stdout, "bigargtest: fork failed\n");
3563: a1 a4 5e 00 00 mov 0x5ea4,%eax
3568: 83 ec 08 sub $0x8,%esp
356b: 68 46 57 00 00 push $0x5746
3570: 50 push %eax
3571: e8 24 08 00 00 call 3d9a <printf>
3576: 83 c4 10 add $0x10,%esp
exit();
3579: e8 85 06 00 00 call 3c03 <exit>
}
wait();
357e: e8 88 06 00 00 call 3c0b <wait>
fd = open("bigarg-ok", 0);
3583: 83 ec 08 sub $0x8,%esp
3586: 6a 00 push $0x0
3588: 68 3f 56 00 00 push $0x563f
358d: e8 b1 06 00 00 call 3c43 <open>
3592: 83 c4 10 add $0x10,%esp
3595: 89 45 ec mov %eax,-0x14(%ebp)
if(fd < 0){
3598: 83 7d ec 00 cmpl $0x0,-0x14(%ebp)
359c: 79 1b jns 35b9 <bigargtest+0x11b>
printf(stdout, "bigarg test failed!\n");
359e: a1 a4 5e 00 00 mov 0x5ea4,%eax
35a3: 83 ec 08 sub $0x8,%esp
35a6: 68 5f 57 00 00 push $0x575f
35ab: 50 push %eax
35ac: e8 e9 07 00 00 call 3d9a <printf>
35b1: 83 c4 10 add $0x10,%esp
exit();
35b4: e8 4a 06 00 00 call 3c03 <exit>
}
close(fd);
35b9: 83 ec 0c sub $0xc,%esp
35bc: ff 75 ec pushl -0x14(%ebp)
35bf: e8 67 06 00 00 call 3c2b <close>
35c4: 83 c4 10 add $0x10,%esp
unlink("bigarg-ok");
35c7: 83 ec 0c sub $0xc,%esp
35ca: 68 3f 56 00 00 push $0x563f
35cf: e8 7f 06 00 00 call 3c53 <unlink>
35d4: 83 c4 10 add $0x10,%esp
}
35d7: 90 nop
35d8: c9 leave
35d9: c3 ret
000035da <fsfull>:
// what happens when the file system runs out of blocks?
// answer: balloc panics, so this test is not useful.
void
fsfull()
{
35da: 55 push %ebp
35db: 89 e5 mov %esp,%ebp
35dd: 53 push %ebx
35de: 83 ec 64 sub $0x64,%esp
int nfiles;
int fsblocks = 0;
35e1: c7 45 f0 00 00 00 00 movl $0x0,-0x10(%ebp)
printf(1, "fsfull test\n");
35e8: 83 ec 08 sub $0x8,%esp
35eb: 68 74 57 00 00 push $0x5774
35f0: 6a 01 push $0x1
35f2: e8 a3 07 00 00 call 3d9a <printf>
35f7: 83 c4 10 add $0x10,%esp
for(nfiles = 0; ; nfiles++){
35fa: c7 45 f4 00 00 00 00 movl $0x0,-0xc(%ebp)
char name[64];
name[0] = 'f';
3601: c6 45 a4 66 movb $0x66,-0x5c(%ebp)
name[1] = '0' + nfiles / 1000;
3605: 8b 4d f4 mov -0xc(%ebp),%ecx
3608: ba d3 4d 62 10 mov $0x10624dd3,%edx
360d: 89 c8 mov %ecx,%eax
360f: f7 ea imul %edx
3611: c1 fa 06 sar $0x6,%edx
3614: 89 c8 mov %ecx,%eax
3616: c1 f8 1f sar $0x1f,%eax
3619: 29 c2 sub %eax,%edx
361b: 89 d0 mov %edx,%eax
361d: 83 c0 30 add $0x30,%eax
3620: 88 45 a5 mov %al,-0x5b(%ebp)
name[2] = '0' + (nfiles % 1000) / 100;
3623: 8b 5d f4 mov -0xc(%ebp),%ebx
3626: ba d3 4d 62 10 mov $0x10624dd3,%edx
362b: 89 d8 mov %ebx,%eax
362d: f7 ea imul %edx
362f: c1 fa 06 sar $0x6,%edx
3632: 89 d8 mov %ebx,%eax
3634: c1 f8 1f sar $0x1f,%eax
3637: 89 d1 mov %edx,%ecx
3639: 29 c1 sub %eax,%ecx
363b: 69 c1 e8 03 00 00 imul $0x3e8,%ecx,%eax
3641: 29 c3 sub %eax,%ebx
3643: 89 d9 mov %ebx,%ecx
3645: ba 1f 85 eb 51 mov $0x51eb851f,%edx
364a: 89 c8 mov %ecx,%eax
364c: f7 ea imul %edx
364e: c1 fa 05 sar $0x5,%edx
3651: 89 c8 mov %ecx,%eax
3653: c1 f8 1f sar $0x1f,%eax
3656: 29 c2 sub %eax,%edx
3658: 89 d0 mov %edx,%eax
365a: 83 c0 30 add $0x30,%eax
365d: 88 45 a6 mov %al,-0x5a(%ebp)
name[3] = '0' + (nfiles % 100) / 10;
3660: 8b 5d f4 mov -0xc(%ebp),%ebx
3663: ba 1f 85 eb 51 mov $0x51eb851f,%edx
3668: 89 d8 mov %ebx,%eax
366a: f7 ea imul %edx
366c: c1 fa 05 sar $0x5,%edx
366f: 89 d8 mov %ebx,%eax
3671: c1 f8 1f sar $0x1f,%eax
3674: 89 d1 mov %edx,%ecx
3676: 29 c1 sub %eax,%ecx
3678: 6b c1 64 imul $0x64,%ecx,%eax
367b: 29 c3 sub %eax,%ebx
367d: 89 d9 mov %ebx,%ecx
367f: ba 67 66 66 66 mov $0x66666667,%edx
3684: 89 c8 mov %ecx,%eax
3686: f7 ea imul %edx
3688: c1 fa 02 sar $0x2,%edx
368b: 89 c8 mov %ecx,%eax
368d: c1 f8 1f sar $0x1f,%eax
3690: 29 c2 sub %eax,%edx
3692: 89 d0 mov %edx,%eax
3694: 83 c0 30 add $0x30,%eax
3697: 88 45 a7 mov %al,-0x59(%ebp)
name[4] = '0' + (nfiles % 10);
369a: 8b 4d f4 mov -0xc(%ebp),%ecx
369d: ba 67 66 66 66 mov $0x66666667,%edx
36a2: 89 c8 mov %ecx,%eax
36a4: f7 ea imul %edx
36a6: c1 fa 02 sar $0x2,%edx
36a9: 89 c8 mov %ecx,%eax
36ab: c1 f8 1f sar $0x1f,%eax
36ae: 29 c2 sub %eax,%edx
36b0: 89 d0 mov %edx,%eax
36b2: c1 e0 02 shl $0x2,%eax
36b5: 01 d0 add %edx,%eax
36b7: 01 c0 add %eax,%eax
36b9: 29 c1 sub %eax,%ecx
36bb: 89 ca mov %ecx,%edx
36bd: 89 d0 mov %edx,%eax
36bf: 83 c0 30 add $0x30,%eax
36c2: 88 45 a8 mov %al,-0x58(%ebp)
name[5] = '\0';
36c5: c6 45 a9 00 movb $0x0,-0x57(%ebp)
printf(1, "writing %s\n", name);
36c9: 83 ec 04 sub $0x4,%esp
36cc: 8d 45 a4 lea -0x5c(%ebp),%eax
36cf: 50 push %eax
36d0: 68 81 57 00 00 push $0x5781
36d5: 6a 01 push $0x1
36d7: e8 be 06 00 00 call 3d9a <printf>
36dc: 83 c4 10 add $0x10,%esp
int fd = open(name, O_CREATE|O_RDWR);
36df: 83 ec 08 sub $0x8,%esp
36e2: 68 02 02 00 00 push $0x202
36e7: 8d 45 a4 lea -0x5c(%ebp),%eax
36ea: 50 push %eax
36eb: e8 53 05 00 00 call 3c43 <open>
36f0: 83 c4 10 add $0x10,%esp
36f3: 89 45 e8 mov %eax,-0x18(%ebp)
if(fd < 0){
36f6: 83 7d e8 00 cmpl $0x0,-0x18(%ebp)
36fa: 79 18 jns 3714 <fsfull+0x13a>
printf(1, "open %s failed\n", name);
36fc: 83 ec 04 sub $0x4,%esp
36ff: 8d 45 a4 lea -0x5c(%ebp),%eax
3702: 50 push %eax
3703: 68 8d 57 00 00 push $0x578d
3708: 6a 01 push $0x1
370a: e8 8b 06 00 00 call 3d9a <printf>
370f: 83 c4 10 add $0x10,%esp
break;
3712: eb 6b jmp 377f <fsfull+0x1a5>
}
int total = 0;
3714: c7 45 ec 00 00 00 00 movl $0x0,-0x14(%ebp)
while(1){
int cc = write(fd, buf, 512);
371b: 83 ec 04 sub $0x4,%esp
371e: 68 00 02 00 00 push $0x200
3723: 68 80 86 00 00 push $0x8680
3728: ff 75 e8 pushl -0x18(%ebp)
372b: e8 f3 04 00 00 call 3c23 <write>
3730: 83 c4 10 add $0x10,%esp
3733: 89 45 e4 mov %eax,-0x1c(%ebp)
if(cc < 512)
3736: 81 7d e4 ff 01 00 00 cmpl $0x1ff,-0x1c(%ebp)
373d: 7e 0c jle 374b <fsfull+0x171>
break;
total += cc;
373f: 8b 45 e4 mov -0x1c(%ebp),%eax
3742: 01 45 ec add %eax,-0x14(%ebp)
fsblocks++;
3745: 83 45 f0 01 addl $0x1,-0x10(%ebp)
}
3749: eb d0 jmp 371b <fsfull+0x141>
}
int total = 0;
while(1){
int cc = write(fd, buf, 512);
if(cc < 512)
break;
374b: 90 nop
total += cc;
fsblocks++;
}
printf(1, "wrote %d bytes\n", total);
374c: 83 ec 04 sub $0x4,%esp
374f: ff 75 ec pushl -0x14(%ebp)
3752: 68 9d 57 00 00 push $0x579d
3757: 6a 01 push $0x1
3759: e8 3c 06 00 00 call 3d9a <printf>
375e: 83 c4 10 add $0x10,%esp
close(fd);
3761: 83 ec 0c sub $0xc,%esp
3764: ff 75 e8 pushl -0x18(%ebp)
3767: e8 bf 04 00 00 call 3c2b <close>
376c: 83 c4 10 add $0x10,%esp
if(total == 0)
376f: 83 7d ec 00 cmpl $0x0,-0x14(%ebp)
3773: 74 09 je 377e <fsfull+0x1a4>
int nfiles;
int fsblocks = 0;
printf(1, "fsfull test\n");
for(nfiles = 0; ; nfiles++){
3775: 83 45 f4 01 addl $0x1,-0xc(%ebp)
}
printf(1, "wrote %d bytes\n", total);
close(fd);
if(total == 0)
break;
}
3779: e9 83 fe ff ff jmp 3601 <fsfull+0x27>
fsblocks++;
}
printf(1, "wrote %d bytes\n", total);
close(fd);
if(total == 0)
break;
377e: 90 nop
}
while(nfiles >= 0){
377f: e9 db 00 00 00 jmp 385f <fsfull+0x285>
char name[64];
name[0] = 'f';
3784: c6 45 a4 66 movb $0x66,-0x5c(%ebp)
name[1] = '0' + nfiles / 1000;
3788: 8b 4d f4 mov -0xc(%ebp),%ecx
378b: ba d3 4d 62 10 mov $0x10624dd3,%edx
3790: 89 c8 mov %ecx,%eax
3792: f7 ea imul %edx
3794: c1 fa 06 sar $0x6,%edx
3797: 89 c8 mov %ecx,%eax
3799: c1 f8 1f sar $0x1f,%eax
379c: 29 c2 sub %eax,%edx
379e: 89 d0 mov %edx,%eax
37a0: 83 c0 30 add $0x30,%eax
37a3: 88 45 a5 mov %al,-0x5b(%ebp)
name[2] = '0' + (nfiles % 1000) / 100;
37a6: 8b 5d f4 mov -0xc(%ebp),%ebx
37a9: ba d3 4d 62 10 mov $0x10624dd3,%edx
37ae: 89 d8 mov %ebx,%eax
37b0: f7 ea imul %edx
37b2: c1 fa 06 sar $0x6,%edx
37b5: 89 d8 mov %ebx,%eax
37b7: c1 f8 1f sar $0x1f,%eax
37ba: 89 d1 mov %edx,%ecx
37bc: 29 c1 sub %eax,%ecx
37be: 69 c1 e8 03 00 00 imul $0x3e8,%ecx,%eax
37c4: 29 c3 sub %eax,%ebx
37c6: 89 d9 mov %ebx,%ecx
37c8: ba 1f 85 eb 51 mov $0x51eb851f,%edx
37cd: 89 c8 mov %ecx,%eax
37cf: f7 ea imul %edx
37d1: c1 fa 05 sar $0x5,%edx
37d4: 89 c8 mov %ecx,%eax
37d6: c1 f8 1f sar $0x1f,%eax
37d9: 29 c2 sub %eax,%edx
37db: 89 d0 mov %edx,%eax
37dd: 83 c0 30 add $0x30,%eax
37e0: 88 45 a6 mov %al,-0x5a(%ebp)
name[3] = '0' + (nfiles % 100) / 10;
37e3: 8b 5d f4 mov -0xc(%ebp),%ebx
37e6: ba 1f 85 eb 51 mov $0x51eb851f,%edx
37eb: 89 d8 mov %ebx,%eax
37ed: f7 ea imul %edx
37ef: c1 fa 05 sar $0x5,%edx
37f2: 89 d8 mov %ebx,%eax
37f4: c1 f8 1f sar $0x1f,%eax
37f7: 89 d1 mov %edx,%ecx
37f9: 29 c1 sub %eax,%ecx
37fb: 6b c1 64 imul $0x64,%ecx,%eax
37fe: 29 c3 sub %eax,%ebx
3800: 89 d9 mov %ebx,%ecx
3802: ba 67 66 66 66 mov $0x66666667,%edx
3807: 89 c8 mov %ecx,%eax
3809: f7 ea imul %edx
380b: c1 fa 02 sar $0x2,%edx
380e: 89 c8 mov %ecx,%eax
3810: c1 f8 1f sar $0x1f,%eax
3813: 29 c2 sub %eax,%edx
3815: 89 d0 mov %edx,%eax
3817: 83 c0 30 add $0x30,%eax
381a: 88 45 a7 mov %al,-0x59(%ebp)
name[4] = '0' + (nfiles % 10);
381d: 8b 4d f4 mov -0xc(%ebp),%ecx
3820: ba 67 66 66 66 mov $0x66666667,%edx
3825: 89 c8 mov %ecx,%eax
3827: f7 ea imul %edx
3829: c1 fa 02 sar $0x2,%edx
382c: 89 c8 mov %ecx,%eax
382e: c1 f8 1f sar $0x1f,%eax
3831: 29 c2 sub %eax,%edx
3833: 89 d0 mov %edx,%eax
3835: c1 e0 02 shl $0x2,%eax
3838: 01 d0 add %edx,%eax
383a: 01 c0 add %eax,%eax
383c: 29 c1 sub %eax,%ecx
383e: 89 ca mov %ecx,%edx
3840: 89 d0 mov %edx,%eax
3842: 83 c0 30 add $0x30,%eax
3845: 88 45 a8 mov %al,-0x58(%ebp)
name[5] = '\0';
3848: c6 45 a9 00 movb $0x0,-0x57(%ebp)
unlink(name);
384c: 83 ec 0c sub $0xc,%esp
384f: 8d 45 a4 lea -0x5c(%ebp),%eax
3852: 50 push %eax
3853: e8 fb 03 00 00 call 3c53 <unlink>
3858: 83 c4 10 add $0x10,%esp
nfiles--;
385b: 83 6d f4 01 subl $0x1,-0xc(%ebp)
close(fd);
if(total == 0)
break;
}
while(nfiles >= 0){
385f: 83 7d f4 00 cmpl $0x0,-0xc(%ebp)
3863: 0f 89 1b ff ff ff jns 3784 <fsfull+0x1aa>
name[5] = '\0';
unlink(name);
nfiles--;
}
printf(1, "fsfull test finished\n");
3869: 83 ec 08 sub $0x8,%esp
386c: 68 ad 57 00 00 push $0x57ad
3871: 6a 01 push $0x1
3873: e8 22 05 00 00 call 3d9a <printf>
3878: 83 c4 10 add $0x10,%esp
}
387b: 90 nop
387c: 8b 5d fc mov -0x4(%ebp),%ebx
387f: c9 leave
3880: c3 ret
00003881 <rand>:
unsigned long randstate = 1;
unsigned int
rand()
{
3881: 55 push %ebp
3882: 89 e5 mov %esp,%ebp
randstate = randstate * 1664525 + 1013904223;
3884: a1 a8 5e 00 00 mov 0x5ea8,%eax
3889: 69 c0 0d 66 19 00 imul $0x19660d,%eax,%eax
388f: 05 5f f3 6e 3c add $0x3c6ef35f,%eax
3894: a3 a8 5e 00 00 mov %eax,0x5ea8
return randstate;
3899: a1 a8 5e 00 00 mov 0x5ea8,%eax
}
389e: 5d pop %ebp
389f: c3 ret
000038a0 <main>:
int
main(int argc, char *argv[])
{
38a0: 8d 4c 24 04 lea 0x4(%esp),%ecx
38a4: 83 e4 f0 and $0xfffffff0,%esp
38a7: ff 71 fc pushl -0x4(%ecx)
38aa: 55 push %ebp
38ab: 89 e5 mov %esp,%ebp
38ad: 51 push %ecx
38ae: 83 ec 04 sub $0x4,%esp
printf(1, "usertests starting\n");
38b1: 83 ec 08 sub $0x8,%esp
38b4: 68 c3 57 00 00 push $0x57c3
38b9: 6a 01 push $0x1
38bb: e8 da 04 00 00 call 3d9a <printf>
38c0: 83 c4 10 add $0x10,%esp
if(open("usertests.ran", 0) >= 0){
38c3: 83 ec 08 sub $0x8,%esp
38c6: 6a 00 push $0x0
38c8: 68 d7 57 00 00 push $0x57d7
38cd: e8 71 03 00 00 call 3c43 <open>
38d2: 83 c4 10 add $0x10,%esp
38d5: 85 c0 test %eax,%eax
38d7: 78 17 js 38f0 <main+0x50>
printf(1, "already ran user tests -- rebuild fs.img\n");
38d9: 83 ec 08 sub $0x8,%esp
38dc: 68 e8 57 00 00 push $0x57e8
38e1: 6a 01 push $0x1
38e3: e8 b2 04 00 00 call 3d9a <printf>
38e8: 83 c4 10 add $0x10,%esp
exit();
38eb: e8 13 03 00 00 call 3c03 <exit>
}
close(open("usertests.ran", O_CREATE));
38f0: 83 ec 08 sub $0x8,%esp
38f3: 68 00 02 00 00 push $0x200
38f8: 68 d7 57 00 00 push $0x57d7
38fd: e8 41 03 00 00 call 3c43 <open>
3902: 83 c4 10 add $0x10,%esp
3905: 83 ec 0c sub $0xc,%esp
3908: 50 push %eax
3909: e8 1d 03 00 00 call 3c2b <close>
390e: 83 c4 10 add $0x10,%esp
bigargtest();
3911: e8 88 fb ff ff call 349e <bigargtest>
bigwrite();
3916: e8 ea ea ff ff call 2405 <bigwrite>
bigargtest();
391b: e8 7e fb ff ff call 349e <bigargtest>
bsstest();
3920: e8 03 fb ff ff call 3428 <bsstest>
sbrktest();
3925: e8 0e f5 ff ff call 2e38 <sbrktest>
validatetest();
392a: e8 1b fa ff ff call 334a <validatetest>
opentest();
392f: e8 cc c6 ff ff call 0 <opentest>
writetest();
3934: e8 76 c7 ff ff call af <writetest>
writetest1();
3939: e8 81 c9 ff ff call 2bf <writetest1>
createtest();
393e: e8 78 cb ff ff call 4bb <createtest>
mem();
3943: e8 3e d1 ff ff call a86 <mem>
pipe1();
3948: e8 75 cd ff ff call 6c2 <pipe1>
preempt();
394d: e8 59 cf ff ff call 8ab <preempt>
exitwait();
3952: e8 b7 d0 ff ff call a0e <exitwait>
rmdot();
3957: e8 1b ef ff ff call 2877 <rmdot>
fourteen();
395c: e8 ba ed ff ff call 271b <fourteen>
bigfile();
3961: e8 9d eb ff ff call 2503 <bigfile>
subdir();
3966: e8 56 e3 ff ff call 1cc1 <subdir>
concreate();
396b: e8 f3 dc ff ff call 1663 <concreate>
linkunlink();
3970: e8 9e e0 ff ff call 1a13 <linkunlink>
linktest();
3975: e8 a7 da ff ff call 1421 <linktest>
unlinkread();
397a: e8 e0 d8 ff ff call 125f <unlinkread>
createdelete();
397f: e8 35 d6 ff ff call fb9 <createdelete>
twofiles();
3984: e8 d1 d3 ff ff call d5a <twofiles>
sharedfd();
3989: e8 e9 d1 ff ff call b77 <sharedfd>
dirfile();
398e: e8 69 f0 ff ff call 29fc <dirfile>
iref();
3993: e8 9c f2 ff ff call 2c34 <iref>
forktest();
3998: e8 d1 f3 ff ff call 2d6e <forktest>
bigdir(); // slow
399d: e8 aa e1 ff ff call 1b4c <bigdir>
exectest();
39a2: e8 c8 cc ff ff call 66f <exectest>
exit();
39a7: e8 57 02 00 00 call 3c03 <exit>
000039ac <stosb>:
"cc");
}
static inline void
stosb(void *addr, int data, int cnt)
{
39ac: 55 push %ebp
39ad: 89 e5 mov %esp,%ebp
39af: 57 push %edi
39b0: 53 push %ebx
asm volatile("cld; rep stosb" :
39b1: 8b 4d 08 mov 0x8(%ebp),%ecx
39b4: 8b 55 10 mov 0x10(%ebp),%edx
39b7: 8b 45 0c mov 0xc(%ebp),%eax
39ba: 89 cb mov %ecx,%ebx
39bc: 89 df mov %ebx,%edi
39be: 89 d1 mov %edx,%ecx
39c0: fc cld
39c1: f3 aa rep stos %al,%es:(%edi)
39c3: 89 ca mov %ecx,%edx
39c5: 89 fb mov %edi,%ebx
39c7: 89 5d 08 mov %ebx,0x8(%ebp)
39ca: 89 55 10 mov %edx,0x10(%ebp)
"=D" (addr), "=c" (cnt) :
"0" (addr), "1" (cnt), "a" (data) :
"memory", "cc");
}
39cd: 90 nop
39ce: 5b pop %ebx
39cf: 5f pop %edi
39d0: 5d pop %ebp
39d1: c3 ret
000039d2 <strcpy>:
#include "user.h"
#include "x86.h"
char*
strcpy(char *s, char *t)
{
39d2: 55 push %ebp
39d3: 89 e5 mov %esp,%ebp
39d5: 83 ec 10 sub $0x10,%esp
char *os;
os = s;
39d8: 8b 45 08 mov 0x8(%ebp),%eax
39db: 89 45 fc mov %eax,-0x4(%ebp)
while((*s++ = *t++) != 0)
39de: 90 nop
39df: 8b 45 08 mov 0x8(%ebp),%eax
39e2: 8d 50 01 lea 0x1(%eax),%edx
39e5: 89 55 08 mov %edx,0x8(%ebp)
39e8: 8b 55 0c mov 0xc(%ebp),%edx
39eb: 8d 4a 01 lea 0x1(%edx),%ecx
39ee: 89 4d 0c mov %ecx,0xc(%ebp)
39f1: 0f b6 12 movzbl (%edx),%edx
39f4: 88 10 mov %dl,(%eax)
39f6: 0f b6 00 movzbl (%eax),%eax
39f9: 84 c0 test %al,%al
39fb: 75 e2 jne 39df <strcpy+0xd>
;
return os;
39fd: 8b 45 fc mov -0x4(%ebp),%eax
}
3a00: c9 leave
3a01: c3 ret
00003a02 <strcmp>:
int
strcmp(const char *p, const char *q)
{
3a02: 55 push %ebp
3a03: 89 e5 mov %esp,%ebp
while(*p && *p == *q)
3a05: eb 08 jmp 3a0f <strcmp+0xd>
p++, q++;
3a07: 83 45 08 01 addl $0x1,0x8(%ebp)
3a0b: 83 45 0c 01 addl $0x1,0xc(%ebp)
}
int
strcmp(const char *p, const char *q)
{
while(*p && *p == *q)
3a0f: 8b 45 08 mov 0x8(%ebp),%eax
3a12: 0f b6 00 movzbl (%eax),%eax
3a15: 84 c0 test %al,%al
3a17: 74 10 je 3a29 <strcmp+0x27>
3a19: 8b 45 08 mov 0x8(%ebp),%eax
3a1c: 0f b6 10 movzbl (%eax),%edx
3a1f: 8b 45 0c mov 0xc(%ebp),%eax
3a22: 0f b6 00 movzbl (%eax),%eax
3a25: 38 c2 cmp %al,%dl
3a27: 74 de je 3a07 <strcmp+0x5>
p++, q++;
return (uchar)*p - (uchar)*q;
3a29: 8b 45 08 mov 0x8(%ebp),%eax
3a2c: 0f b6 00 movzbl (%eax),%eax
3a2f: 0f b6 d0 movzbl %al,%edx
3a32: 8b 45 0c mov 0xc(%ebp),%eax
3a35: 0f b6 00 movzbl (%eax),%eax
3a38: 0f b6 c0 movzbl %al,%eax
3a3b: 29 c2 sub %eax,%edx
3a3d: 89 d0 mov %edx,%eax
}
3a3f: 5d pop %ebp
3a40: c3 ret
00003a41 <strlen>:
uint
strlen(char *s)
{
3a41: 55 push %ebp
3a42: 89 e5 mov %esp,%ebp
3a44: 83 ec 10 sub $0x10,%esp
int n;
for(n = 0; s[n]; n++)
3a47: c7 45 fc 00 00 00 00 movl $0x0,-0x4(%ebp)
3a4e: eb 04 jmp 3a54 <strlen+0x13>
3a50: 83 45 fc 01 addl $0x1,-0x4(%ebp)
3a54: 8b 55 fc mov -0x4(%ebp),%edx
3a57: 8b 45 08 mov 0x8(%ebp),%eax
3a5a: 01 d0 add %edx,%eax
3a5c: 0f b6 00 movzbl (%eax),%eax
3a5f: 84 c0 test %al,%al
3a61: 75 ed jne 3a50 <strlen+0xf>
;
return n;
3a63: 8b 45 fc mov -0x4(%ebp),%eax
}
3a66: c9 leave
3a67: c3 ret
00003a68 <memset>:
void*
memset(void *dst, int c, uint n)
{
3a68: 55 push %ebp
3a69: 89 e5 mov %esp,%ebp
stosb(dst, c, n);
3a6b: 8b 45 10 mov 0x10(%ebp),%eax
3a6e: 50 push %eax
3a6f: ff 75 0c pushl 0xc(%ebp)
3a72: ff 75 08 pushl 0x8(%ebp)
3a75: e8 32 ff ff ff call 39ac <stosb>
3a7a: 83 c4 0c add $0xc,%esp
return dst;
3a7d: 8b 45 08 mov 0x8(%ebp),%eax
}
3a80: c9 leave
3a81: c3 ret
00003a82 <strchr>:
char*
strchr(const char *s, char c)
{
3a82: 55 push %ebp
3a83: 89 e5 mov %esp,%ebp
3a85: 83 ec 04 sub $0x4,%esp
3a88: 8b 45 0c mov 0xc(%ebp),%eax
3a8b: 88 45 fc mov %al,-0x4(%ebp)
for(; *s; s++)
3a8e: eb 14 jmp 3aa4 <strchr+0x22>
if(*s == c)
3a90: 8b 45 08 mov 0x8(%ebp),%eax
3a93: 0f b6 00 movzbl (%eax),%eax
3a96: 3a 45 fc cmp -0x4(%ebp),%al
3a99: 75 05 jne 3aa0 <strchr+0x1e>
return (char*)s;
3a9b: 8b 45 08 mov 0x8(%ebp),%eax
3a9e: eb 13 jmp 3ab3 <strchr+0x31>
}
char*
strchr(const char *s, char c)
{
for(; *s; s++)
3aa0: 83 45 08 01 addl $0x1,0x8(%ebp)
3aa4: 8b 45 08 mov 0x8(%ebp),%eax
3aa7: 0f b6 00 movzbl (%eax),%eax
3aaa: 84 c0 test %al,%al
3aac: 75 e2 jne 3a90 <strchr+0xe>
if(*s == c)
return (char*)s;
return 0;
3aae: b8 00 00 00 00 mov $0x0,%eax
}
3ab3: c9 leave
3ab4: c3 ret
00003ab5 <gets>:
char*
gets(char *buf, int max)
{
3ab5: 55 push %ebp
3ab6: 89 e5 mov %esp,%ebp
3ab8: 83 ec 18 sub $0x18,%esp
int i, cc;
char c;
for(i=0; i+1 < max; ){
3abb: c7 45 f4 00 00 00 00 movl $0x0,-0xc(%ebp)
3ac2: eb 42 jmp 3b06 <gets+0x51>
cc = read(0, &c, 1);
3ac4: 83 ec 04 sub $0x4,%esp
3ac7: 6a 01 push $0x1
3ac9: 8d 45 ef lea -0x11(%ebp),%eax
3acc: 50 push %eax
3acd: 6a 00 push $0x0
3acf: e8 47 01 00 00 call 3c1b <read>
3ad4: 83 c4 10 add $0x10,%esp
3ad7: 89 45 f0 mov %eax,-0x10(%ebp)
if(cc < 1)
3ada: 83 7d f0 00 cmpl $0x0,-0x10(%ebp)
3ade: 7e 33 jle 3b13 <gets+0x5e>
break;
buf[i++] = c;
3ae0: 8b 45 f4 mov -0xc(%ebp),%eax
3ae3: 8d 50 01 lea 0x1(%eax),%edx
3ae6: 89 55 f4 mov %edx,-0xc(%ebp)
3ae9: 89 c2 mov %eax,%edx
3aeb: 8b 45 08 mov 0x8(%ebp),%eax
3aee: 01 c2 add %eax,%edx
3af0: 0f b6 45 ef movzbl -0x11(%ebp),%eax
3af4: 88 02 mov %al,(%edx)
if(c == '\n' || c == '\r')
3af6: 0f b6 45 ef movzbl -0x11(%ebp),%eax
3afa: 3c 0a cmp $0xa,%al
3afc: 74 16 je 3b14 <gets+0x5f>
3afe: 0f b6 45 ef movzbl -0x11(%ebp),%eax
3b02: 3c 0d cmp $0xd,%al
3b04: 74 0e je 3b14 <gets+0x5f>
gets(char *buf, int max)
{
int i, cc;
char c;
for(i=0; i+1 < max; ){
3b06: 8b 45 f4 mov -0xc(%ebp),%eax
3b09: 83 c0 01 add $0x1,%eax
3b0c: 3b 45 0c cmp 0xc(%ebp),%eax
3b0f: 7c b3 jl 3ac4 <gets+0xf>
3b11: eb 01 jmp 3b14 <gets+0x5f>
cc = read(0, &c, 1);
if(cc < 1)
break;
3b13: 90 nop
buf[i++] = c;
if(c == '\n' || c == '\r')
break;
}
buf[i] = '\0';
3b14: 8b 55 f4 mov -0xc(%ebp),%edx
3b17: 8b 45 08 mov 0x8(%ebp),%eax
3b1a: 01 d0 add %edx,%eax
3b1c: c6 00 00 movb $0x0,(%eax)
return buf;
3b1f: 8b 45 08 mov 0x8(%ebp),%eax
}
3b22: c9 leave
3b23: c3 ret
00003b24 <stat>:
int
stat(char *n, struct stat *st)
{
3b24: 55 push %ebp
3b25: 89 e5 mov %esp,%ebp
3b27: 83 ec 18 sub $0x18,%esp
int fd;
int r;
fd = open(n, O_RDONLY);
3b2a: 83 ec 08 sub $0x8,%esp
3b2d: 6a 00 push $0x0
3b2f: ff 75 08 pushl 0x8(%ebp)
3b32: e8 0c 01 00 00 call 3c43 <open>
3b37: 83 c4 10 add $0x10,%esp
3b3a: 89 45 f4 mov %eax,-0xc(%ebp)
if(fd < 0)
3b3d: 83 7d f4 00 cmpl $0x0,-0xc(%ebp)
3b41: 79 07 jns 3b4a <stat+0x26>
return -1;
3b43: b8 ff ff ff ff mov $0xffffffff,%eax
3b48: eb 25 jmp 3b6f <stat+0x4b>
r = fstat(fd, st);
3b4a: 83 ec 08 sub $0x8,%esp
3b4d: ff 75 0c pushl 0xc(%ebp)
3b50: ff 75 f4 pushl -0xc(%ebp)
3b53: e8 03 01 00 00 call 3c5b <fstat>
3b58: 83 c4 10 add $0x10,%esp
3b5b: 89 45 f0 mov %eax,-0x10(%ebp)
close(fd);
3b5e: 83 ec 0c sub $0xc,%esp
3b61: ff 75 f4 pushl -0xc(%ebp)
3b64: e8 c2 00 00 00 call 3c2b <close>
3b69: 83 c4 10 add $0x10,%esp
return r;
3b6c: 8b 45 f0 mov -0x10(%ebp),%eax
}
3b6f: c9 leave
3b70: c3 ret
00003b71 <atoi>:
int
atoi(const char *s)
{
3b71: 55 push %ebp
3b72: 89 e5 mov %esp,%ebp
3b74: 83 ec 10 sub $0x10,%esp
int n;
n = 0;
3b77: c7 45 fc 00 00 00 00 movl $0x0,-0x4(%ebp)
while('0' <= *s && *s <= '9')
3b7e: eb 25 jmp 3ba5 <atoi+0x34>
n = n*10 + *s++ - '0';
3b80: 8b 55 fc mov -0x4(%ebp),%edx
3b83: 89 d0 mov %edx,%eax
3b85: c1 e0 02 shl $0x2,%eax
3b88: 01 d0 add %edx,%eax
3b8a: 01 c0 add %eax,%eax
3b8c: 89 c1 mov %eax,%ecx
3b8e: 8b 45 08 mov 0x8(%ebp),%eax
3b91: 8d 50 01 lea 0x1(%eax),%edx
3b94: 89 55 08 mov %edx,0x8(%ebp)
3b97: 0f b6 00 movzbl (%eax),%eax
3b9a: 0f be c0 movsbl %al,%eax
3b9d: 01 c8 add %ecx,%eax
3b9f: 83 e8 30 sub $0x30,%eax
3ba2: 89 45 fc mov %eax,-0x4(%ebp)
atoi(const char *s)
{
int n;
n = 0;
while('0' <= *s && *s <= '9')
3ba5: 8b 45 08 mov 0x8(%ebp),%eax
3ba8: 0f b6 00 movzbl (%eax),%eax
3bab: 3c 2f cmp $0x2f,%al
3bad: 7e 0a jle 3bb9 <atoi+0x48>
3baf: 8b 45 08 mov 0x8(%ebp),%eax
3bb2: 0f b6 00 movzbl (%eax),%eax
3bb5: 3c 39 cmp $0x39,%al
3bb7: 7e c7 jle 3b80 <atoi+0xf>
n = n*10 + *s++ - '0';
return n;
3bb9: 8b 45 fc mov -0x4(%ebp),%eax
}
3bbc: c9 leave
3bbd: c3 ret
00003bbe <memmove>:
void*
memmove(void *vdst, void *vsrc, int n)
{
3bbe: 55 push %ebp
3bbf: 89 e5 mov %esp,%ebp
3bc1: 83 ec 10 sub $0x10,%esp
char *dst, *src;
dst = vdst;
3bc4: 8b 45 08 mov 0x8(%ebp),%eax
3bc7: 89 45 fc mov %eax,-0x4(%ebp)
src = vsrc;
3bca: 8b 45 0c mov 0xc(%ebp),%eax
3bcd: 89 45 f8 mov %eax,-0x8(%ebp)
while(n-- > 0)
3bd0: eb 17 jmp 3be9 <memmove+0x2b>
*dst++ = *src++;
3bd2: 8b 45 fc mov -0x4(%ebp),%eax
3bd5: 8d 50 01 lea 0x1(%eax),%edx
3bd8: 89 55 fc mov %edx,-0x4(%ebp)
3bdb: 8b 55 f8 mov -0x8(%ebp),%edx
3bde: 8d 4a 01 lea 0x1(%edx),%ecx
3be1: 89 4d f8 mov %ecx,-0x8(%ebp)
3be4: 0f b6 12 movzbl (%edx),%edx
3be7: 88 10 mov %dl,(%eax)
{
char *dst, *src;
dst = vdst;
src = vsrc;
while(n-- > 0)
3be9: 8b 45 10 mov 0x10(%ebp),%eax
3bec: 8d 50 ff lea -0x1(%eax),%edx
3bef: 89 55 10 mov %edx,0x10(%ebp)
3bf2: 85 c0 test %eax,%eax
3bf4: 7f dc jg 3bd2 <memmove+0x14>
*dst++ = *src++;
return vdst;
3bf6: 8b 45 08 mov 0x8(%ebp),%eax
}
3bf9: c9 leave
3bfa: c3 ret
00003bfb <fork>:
name: \
movl $SYS_ ## name, %eax; \
int $T_SYSCALL; \
ret
SYSCALL(fork)
3bfb: b8 01 00 00 00 mov $0x1,%eax
3c00: cd 40 int $0x40
3c02: c3 ret
00003c03 <exit>:
SYSCALL(exit)
3c03: b8 02 00 00 00 mov $0x2,%eax
3c08: cd 40 int $0x40
3c0a: c3 ret
00003c0b <wait>:
SYSCALL(wait)
3c0b: b8 03 00 00 00 mov $0x3,%eax
3c10: cd 40 int $0x40
3c12: c3 ret
00003c13 <pipe>:
SYSCALL(pipe)
3c13: b8 04 00 00 00 mov $0x4,%eax
3c18: cd 40 int $0x40
3c1a: c3 ret
00003c1b <read>:
SYSCALL(read)
3c1b: b8 05 00 00 00 mov $0x5,%eax
3c20: cd 40 int $0x40
3c22: c3 ret
00003c23 <write>:
SYSCALL(write)
3c23: b8 10 00 00 00 mov $0x10,%eax
3c28: cd 40 int $0x40
3c2a: c3 ret
00003c2b <close>:
SYSCALL(close)
3c2b: b8 15 00 00 00 mov $0x15,%eax
3c30: cd 40 int $0x40
3c32: c3 ret
00003c33 <kill>:
SYSCALL(kill)
3c33: b8 06 00 00 00 mov $0x6,%eax
3c38: cd 40 int $0x40
3c3a: c3 ret
00003c3b <exec>:
SYSCALL(exec)
3c3b: b8 07 00 00 00 mov $0x7,%eax
3c40: cd 40 int $0x40
3c42: c3 ret
00003c43 <open>:
SYSCALL(open)
3c43: b8 0f 00 00 00 mov $0xf,%eax
3c48: cd 40 int $0x40
3c4a: c3 ret
00003c4b <mknod>:
SYSCALL(mknod)
3c4b: b8 11 00 00 00 mov $0x11,%eax
3c50: cd 40 int $0x40
3c52: c3 ret
00003c53 <unlink>:
SYSCALL(unlink)
3c53: b8 12 00 00 00 mov $0x12,%eax
3c58: cd 40 int $0x40
3c5a: c3 ret
00003c5b <fstat>:
SYSCALL(fstat)
3c5b: b8 08 00 00 00 mov $0x8,%eax
3c60: cd 40 int $0x40
3c62: c3 ret
00003c63 <link>:
SYSCALL(link)
3c63: b8 13 00 00 00 mov $0x13,%eax
3c68: cd 40 int $0x40
3c6a: c3 ret
00003c6b <mkdir>:
SYSCALL(mkdir)
3c6b: b8 14 00 00 00 mov $0x14,%eax
3c70: cd 40 int $0x40
3c72: c3 ret
00003c73 <chdir>:
SYSCALL(chdir)
3c73: b8 09 00 00 00 mov $0x9,%eax
3c78: cd 40 int $0x40
3c7a: c3 ret
00003c7b <dup>:
SYSCALL(dup)
3c7b: b8 0a 00 00 00 mov $0xa,%eax
3c80: cd 40 int $0x40
3c82: c3 ret
00003c83 <getpid>:
SYSCALL(getpid)
3c83: b8 0b 00 00 00 mov $0xb,%eax
3c88: cd 40 int $0x40
3c8a: c3 ret
00003c8b <sbrk>:
SYSCALL(sbrk)
3c8b: b8 0c 00 00 00 mov $0xc,%eax
3c90: cd 40 int $0x40
3c92: c3 ret
00003c93 <sleep>:
SYSCALL(sleep)
3c93: b8 0d 00 00 00 mov $0xd,%eax
3c98: cd 40 int $0x40
3c9a: c3 ret
00003c9b <uptime>:
SYSCALL(uptime)
3c9b: b8 0e 00 00 00 mov $0xe,%eax
3ca0: cd 40 int $0x40
3ca2: c3 ret
00003ca3 <getCuPos>:
SYSCALL(getCuPos)
3ca3: b8 16 00 00 00 mov $0x16,%eax
3ca8: cd 40 int $0x40
3caa: c3 ret
00003cab <setCuPos>:
SYSCALL(setCuPos)
3cab: b8 17 00 00 00 mov $0x17,%eax
3cb0: cd 40 int $0x40
3cb2: c3 ret
00003cb3 <getSnapshot>:
SYSCALL(getSnapshot)
3cb3: b8 18 00 00 00 mov $0x18,%eax
3cb8: cd 40 int $0x40
3cba: c3 ret
00003cbb <clearScreen>:
3cbb: b8 19 00 00 00 mov $0x19,%eax
3cc0: cd 40 int $0x40
3cc2: c3 ret
00003cc3 <putc>:
#include "stat.h"
#include "user.h"
static void
putc(int fd, char c)
{
3cc3: 55 push %ebp
3cc4: 89 e5 mov %esp,%ebp
3cc6: 83 ec 18 sub $0x18,%esp
3cc9: 8b 45 0c mov 0xc(%ebp),%eax
3ccc: 88 45 f4 mov %al,-0xc(%ebp)
write(fd, &c, 1);
3ccf: 83 ec 04 sub $0x4,%esp
3cd2: 6a 01 push $0x1
3cd4: 8d 45 f4 lea -0xc(%ebp),%eax
3cd7: 50 push %eax
3cd8: ff 75 08 pushl 0x8(%ebp)
3cdb: e8 43 ff ff ff call 3c23 <write>
3ce0: 83 c4 10 add $0x10,%esp
}
3ce3: 90 nop
3ce4: c9 leave
3ce5: c3 ret
00003ce6 <printint>:
static void
printint(int fd, int xx, int base, int sgn)
{
3ce6: 55 push %ebp
3ce7: 89 e5 mov %esp,%ebp
3ce9: 53 push %ebx
3cea: 83 ec 24 sub $0x24,%esp
static char digits[] = "0123456789ABCDEF";
char buf[16];
int i, neg;
uint x;
neg = 0;
3ced: c7 45 f0 00 00 00 00 movl $0x0,-0x10(%ebp)
if(sgn && xx < 0){
3cf4: 83 7d 14 00 cmpl $0x0,0x14(%ebp)
3cf8: 74 17 je 3d11 <printint+0x2b>
3cfa: 83 7d 0c 00 cmpl $0x0,0xc(%ebp)
3cfe: 79 11 jns 3d11 <printint+0x2b>
neg = 1;
3d00: c7 45 f0 01 00 00 00 movl $0x1,-0x10(%ebp)
x = -xx;
3d07: 8b 45 0c mov 0xc(%ebp),%eax
3d0a: f7 d8 neg %eax
3d0c: 89 45 ec mov %eax,-0x14(%ebp)
3d0f: eb 06 jmp 3d17 <printint+0x31>
} else {
x = xx;
3d11: 8b 45 0c mov 0xc(%ebp),%eax
3d14: 89 45 ec mov %eax,-0x14(%ebp)
}
i = 0;
3d17: c7 45 f4 00 00 00 00 movl $0x0,-0xc(%ebp)
do{
buf[i++] = digits[x % base];
3d1e: 8b 4d f4 mov -0xc(%ebp),%ecx
3d21: 8d 41 01 lea 0x1(%ecx),%eax
3d24: 89 45 f4 mov %eax,-0xc(%ebp)
3d27: 8b 5d 10 mov 0x10(%ebp),%ebx
3d2a: 8b 45 ec mov -0x14(%ebp),%eax
3d2d: ba 00 00 00 00 mov $0x0,%edx
3d32: f7 f3 div %ebx
3d34: 89 d0 mov %edx,%eax
3d36: 0f b6 80 ac 5e 00 00 movzbl 0x5eac(%eax),%eax
3d3d: 88 44 0d dc mov %al,-0x24(%ebp,%ecx,1)
}while((x /= base) != 0);
3d41: 8b 5d 10 mov 0x10(%ebp),%ebx
3d44: 8b 45 ec mov -0x14(%ebp),%eax
3d47: ba 00 00 00 00 mov $0x0,%edx
3d4c: f7 f3 div %ebx
3d4e: 89 45 ec mov %eax,-0x14(%ebp)
3d51: 83 7d ec 00 cmpl $0x0,-0x14(%ebp)
3d55: 75 c7 jne 3d1e <printint+0x38>
if(neg)
3d57: 83 7d f0 00 cmpl $0x0,-0x10(%ebp)
3d5b: 74 2d je 3d8a <printint+0xa4>
buf[i++] = '-';
3d5d: 8b 45 f4 mov -0xc(%ebp),%eax
3d60: 8d 50 01 lea 0x1(%eax),%edx
3d63: 89 55 f4 mov %edx,-0xc(%ebp)
3d66: c6 44 05 dc 2d movb $0x2d,-0x24(%ebp,%eax,1)
while(--i >= 0)
3d6b: eb 1d jmp 3d8a <printint+0xa4>
putc(fd, buf[i]);
3d6d: 8d 55 dc lea -0x24(%ebp),%edx
3d70: 8b 45 f4 mov -0xc(%ebp),%eax
3d73: 01 d0 add %edx,%eax
3d75: 0f b6 00 movzbl (%eax),%eax
3d78: 0f be c0 movsbl %al,%eax
3d7b: 83 ec 08 sub $0x8,%esp
3d7e: 50 push %eax
3d7f: ff 75 08 pushl 0x8(%ebp)
3d82: e8 3c ff ff ff call 3cc3 <putc>
3d87: 83 c4 10 add $0x10,%esp
buf[i++] = digits[x % base];
}while((x /= base) != 0);
if(neg)
buf[i++] = '-';
while(--i >= 0)
3d8a: 83 6d f4 01 subl $0x1,-0xc(%ebp)
3d8e: 83 7d f4 00 cmpl $0x0,-0xc(%ebp)
3d92: 79 d9 jns 3d6d <printint+0x87>
putc(fd, buf[i]);
}
3d94: 90 nop
3d95: 8b 5d fc mov -0x4(%ebp),%ebx
3d98: c9 leave
3d99: c3 ret
00003d9a <printf>:
// Print to the given fd. Only understands %d, %x, %p, %s.
void
printf(int fd, char *fmt, ...)
{
3d9a: 55 push %ebp
3d9b: 89 e5 mov %esp,%ebp
3d9d: 83 ec 28 sub $0x28,%esp
char *s;
int c, i, state;
uint *ap;
state = 0;
3da0: c7 45 ec 00 00 00 00 movl $0x0,-0x14(%ebp)
ap = (uint*)(void*)&fmt + 1;
3da7: 8d 45 0c lea 0xc(%ebp),%eax
3daa: 83 c0 04 add $0x4,%eax
3dad: 89 45 e8 mov %eax,-0x18(%ebp)
for(i = 0; fmt[i]; i++){
3db0: c7 45 f0 00 00 00 00 movl $0x0,-0x10(%ebp)
3db7: e9 59 01 00 00 jmp 3f15 <printf+0x17b>
c = fmt[i] & 0xff;
3dbc: 8b 55 0c mov 0xc(%ebp),%edx
3dbf: 8b 45 f0 mov -0x10(%ebp),%eax
3dc2: 01 d0 add %edx,%eax
3dc4: 0f b6 00 movzbl (%eax),%eax
3dc7: 0f be c0 movsbl %al,%eax
3dca: 25 ff 00 00 00 and $0xff,%eax
3dcf: 89 45 e4 mov %eax,-0x1c(%ebp)
if(state == 0){
3dd2: 83 7d ec 00 cmpl $0x0,-0x14(%ebp)
3dd6: 75 2c jne 3e04 <printf+0x6a>
if(c == '%'){
3dd8: 83 7d e4 25 cmpl $0x25,-0x1c(%ebp)
3ddc: 75 0c jne 3dea <printf+0x50>
state = '%';
3dde: c7 45 ec 25 00 00 00 movl $0x25,-0x14(%ebp)
3de5: e9 27 01 00 00 jmp 3f11 <printf+0x177>
} else {
putc(fd, c);
3dea: 8b 45 e4 mov -0x1c(%ebp),%eax
3ded: 0f be c0 movsbl %al,%eax
3df0: 83 ec 08 sub $0x8,%esp
3df3: 50 push %eax
3df4: ff 75 08 pushl 0x8(%ebp)
3df7: e8 c7 fe ff ff call 3cc3 <putc>
3dfc: 83 c4 10 add $0x10,%esp
3dff: e9 0d 01 00 00 jmp 3f11 <printf+0x177>
}
} else if(state == '%'){
3e04: 83 7d ec 25 cmpl $0x25,-0x14(%ebp)
3e08: 0f 85 03 01 00 00 jne 3f11 <printf+0x177>
if(c == 'd'){
3e0e: 83 7d e4 64 cmpl $0x64,-0x1c(%ebp)
3e12: 75 1e jne 3e32 <printf+0x98>
printint(fd, *ap, 10, 1);
3e14: 8b 45 e8 mov -0x18(%ebp),%eax
3e17: 8b 00 mov (%eax),%eax
3e19: 6a 01 push $0x1
3e1b: 6a 0a push $0xa
3e1d: 50 push %eax
3e1e: ff 75 08 pushl 0x8(%ebp)
3e21: e8 c0 fe ff ff call 3ce6 <printint>
3e26: 83 c4 10 add $0x10,%esp
ap++;
3e29: 83 45 e8 04 addl $0x4,-0x18(%ebp)
3e2d: e9 d8 00 00 00 jmp 3f0a <printf+0x170>
} else if(c == 'x' || c == 'p'){
3e32: 83 7d e4 78 cmpl $0x78,-0x1c(%ebp)
3e36: 74 06 je 3e3e <printf+0xa4>
3e38: 83 7d e4 70 cmpl $0x70,-0x1c(%ebp)
3e3c: 75 1e jne 3e5c <printf+0xc2>
printint(fd, *ap, 16, 0);
3e3e: 8b 45 e8 mov -0x18(%ebp),%eax
3e41: 8b 00 mov (%eax),%eax
3e43: 6a 00 push $0x0
3e45: 6a 10 push $0x10
3e47: 50 push %eax
3e48: ff 75 08 pushl 0x8(%ebp)
3e4b: e8 96 fe ff ff call 3ce6 <printint>
3e50: 83 c4 10 add $0x10,%esp
ap++;
3e53: 83 45 e8 04 addl $0x4,-0x18(%ebp)
3e57: e9 ae 00 00 00 jmp 3f0a <printf+0x170>
} else if(c == 's'){
3e5c: 83 7d e4 73 cmpl $0x73,-0x1c(%ebp)
3e60: 75 43 jne 3ea5 <printf+0x10b>
s = (char*)*ap;
3e62: 8b 45 e8 mov -0x18(%ebp),%eax
3e65: 8b 00 mov (%eax),%eax
3e67: 89 45 f4 mov %eax,-0xc(%ebp)
ap++;
3e6a: 83 45 e8 04 addl $0x4,-0x18(%ebp)
if(s == 0)
3e6e: 83 7d f4 00 cmpl $0x0,-0xc(%ebp)
3e72: 75 25 jne 3e99 <printf+0xff>
s = "(null)";
3e74: c7 45 f4 12 58 00 00 movl $0x5812,-0xc(%ebp)
while(*s != 0){
3e7b: eb 1c jmp 3e99 <printf+0xff>
putc(fd, *s);
3e7d: 8b 45 f4 mov -0xc(%ebp),%eax
3e80: 0f b6 00 movzbl (%eax),%eax
3e83: 0f be c0 movsbl %al,%eax
3e86: 83 ec 08 sub $0x8,%esp
3e89: 50 push %eax
3e8a: ff 75 08 pushl 0x8(%ebp)
3e8d: e8 31 fe ff ff call 3cc3 <putc>
3e92: 83 c4 10 add $0x10,%esp
s++;
3e95: 83 45 f4 01 addl $0x1,-0xc(%ebp)
} else if(c == 's'){
s = (char*)*ap;
ap++;
if(s == 0)
s = "(null)";
while(*s != 0){
3e99: 8b 45 f4 mov -0xc(%ebp),%eax
3e9c: 0f b6 00 movzbl (%eax),%eax
3e9f: 84 c0 test %al,%al
3ea1: 75 da jne 3e7d <printf+0xe3>
3ea3: eb 65 jmp 3f0a <printf+0x170>
putc(fd, *s);
s++;
}
} else if(c == 'c'){
3ea5: 83 7d e4 63 cmpl $0x63,-0x1c(%ebp)
3ea9: 75 1d jne 3ec8 <printf+0x12e>
putc(fd, *ap);
3eab: 8b 45 e8 mov -0x18(%ebp),%eax
3eae: 8b 00 mov (%eax),%eax
3eb0: 0f be c0 movsbl %al,%eax
3eb3: 83 ec 08 sub $0x8,%esp
3eb6: 50 push %eax
3eb7: ff 75 08 pushl 0x8(%ebp)
3eba: e8 04 fe ff ff call 3cc3 <putc>
3ebf: 83 c4 10 add $0x10,%esp
ap++;
3ec2: 83 45 e8 04 addl $0x4,-0x18(%ebp)
3ec6: eb 42 jmp 3f0a <printf+0x170>
} else if(c == '%'){
3ec8: 83 7d e4 25 cmpl $0x25,-0x1c(%ebp)
3ecc: 75 17 jne 3ee5 <printf+0x14b>
putc(fd, c);
3ece: 8b 45 e4 mov -0x1c(%ebp),%eax
3ed1: 0f be c0 movsbl %al,%eax
3ed4: 83 ec 08 sub $0x8,%esp
3ed7: 50 push %eax
3ed8: ff 75 08 pushl 0x8(%ebp)
3edb: e8 e3 fd ff ff call 3cc3 <putc>
3ee0: 83 c4 10 add $0x10,%esp
3ee3: eb 25 jmp 3f0a <printf+0x170>
} else {
// Unknown % sequence. Print it to draw attention.
putc(fd, '%');
3ee5: 83 ec 08 sub $0x8,%esp
3ee8: 6a 25 push $0x25
3eea: ff 75 08 pushl 0x8(%ebp)
3eed: e8 d1 fd ff ff call 3cc3 <putc>
3ef2: 83 c4 10 add $0x10,%esp
putc(fd, c);
3ef5: 8b 45 e4 mov -0x1c(%ebp),%eax
3ef8: 0f be c0 movsbl %al,%eax
3efb: 83 ec 08 sub $0x8,%esp
3efe: 50 push %eax
3eff: ff 75 08 pushl 0x8(%ebp)
3f02: e8 bc fd ff ff call 3cc3 <putc>
3f07: 83 c4 10 add $0x10,%esp
}
state = 0;
3f0a: c7 45 ec 00 00 00 00 movl $0x0,-0x14(%ebp)
int c, i, state;
uint *ap;
state = 0;
ap = (uint*)(void*)&fmt + 1;
for(i = 0; fmt[i]; i++){
3f11: 83 45 f0 01 addl $0x1,-0x10(%ebp)
3f15: 8b 55 0c mov 0xc(%ebp),%edx
3f18: 8b 45 f0 mov -0x10(%ebp),%eax
3f1b: 01 d0 add %edx,%eax
3f1d: 0f b6 00 movzbl (%eax),%eax
3f20: 84 c0 test %al,%al
3f22: 0f 85 94 fe ff ff jne 3dbc <printf+0x22>
putc(fd, c);
}
state = 0;
}
}
}
3f28: 90 nop
3f29: c9 leave
3f2a: c3 ret
00003f2b <free>:
static Header base;
static Header *freep;
void
free(void *ap)
{
3f2b: 55 push %ebp
3f2c: 89 e5 mov %esp,%ebp
3f2e: 83 ec 10 sub $0x10,%esp
Header *bp, *p;
bp = (Header*)ap - 1;
3f31: 8b 45 08 mov 0x8(%ebp),%eax
3f34: 83 e8 08 sub $0x8,%eax
3f37: 89 45 f8 mov %eax,-0x8(%ebp)
for(p = freep; !(bp > p && bp < p->s.ptr); p = p->s.ptr)
3f3a: a1 48 5f 00 00 mov 0x5f48,%eax
3f3f: 89 45 fc mov %eax,-0x4(%ebp)
3f42: eb 24 jmp 3f68 <free+0x3d>
if(p >= p->s.ptr && (bp > p || bp < p->s.ptr))
3f44: 8b 45 fc mov -0x4(%ebp),%eax
3f47: 8b 00 mov (%eax),%eax
3f49: 3b 45 fc cmp -0x4(%ebp),%eax
3f4c: 77 12 ja 3f60 <free+0x35>
3f4e: 8b 45 f8 mov -0x8(%ebp),%eax
3f51: 3b 45 fc cmp -0x4(%ebp),%eax
3f54: 77 24 ja 3f7a <free+0x4f>
3f56: 8b 45 fc mov -0x4(%ebp),%eax
3f59: 8b 00 mov (%eax),%eax
3f5b: 3b 45 f8 cmp -0x8(%ebp),%eax
3f5e: 77 1a ja 3f7a <free+0x4f>
free(void *ap)
{
Header *bp, *p;
bp = (Header*)ap - 1;
for(p = freep; !(bp > p && bp < p->s.ptr); p = p->s.ptr)
3f60: 8b 45 fc mov -0x4(%ebp),%eax
3f63: 8b 00 mov (%eax),%eax
3f65: 89 45 fc mov %eax,-0x4(%ebp)
3f68: 8b 45 f8 mov -0x8(%ebp),%eax
3f6b: 3b 45 fc cmp -0x4(%ebp),%eax
3f6e: 76 d4 jbe 3f44 <free+0x19>
3f70: 8b 45 fc mov -0x4(%ebp),%eax
3f73: 8b 00 mov (%eax),%eax
3f75: 3b 45 f8 cmp -0x8(%ebp),%eax
3f78: 76 ca jbe 3f44 <free+0x19>
if(p >= p->s.ptr && (bp > p || bp < p->s.ptr))
break;
if(bp + bp->s.size == p->s.ptr){
3f7a: 8b 45 f8 mov -0x8(%ebp),%eax
3f7d: 8b 40 04 mov 0x4(%eax),%eax
3f80: 8d 14 c5 00 00 00 00 lea 0x0(,%eax,8),%edx
3f87: 8b 45 f8 mov -0x8(%ebp),%eax
3f8a: 01 c2 add %eax,%edx
3f8c: 8b 45 fc mov -0x4(%ebp),%eax
3f8f: 8b 00 mov (%eax),%eax
3f91: 39 c2 cmp %eax,%edx
3f93: 75 24 jne 3fb9 <free+0x8e>
bp->s.size += p->s.ptr->s.size;
3f95: 8b 45 f8 mov -0x8(%ebp),%eax
3f98: 8b 50 04 mov 0x4(%eax),%edx
3f9b: 8b 45 fc mov -0x4(%ebp),%eax
3f9e: 8b 00 mov (%eax),%eax
3fa0: 8b 40 04 mov 0x4(%eax),%eax
3fa3: 01 c2 add %eax,%edx
3fa5: 8b 45 f8 mov -0x8(%ebp),%eax
3fa8: 89 50 04 mov %edx,0x4(%eax)
bp->s.ptr = p->s.ptr->s.ptr;
3fab: 8b 45 fc mov -0x4(%ebp),%eax
3fae: 8b 00 mov (%eax),%eax
3fb0: 8b 10 mov (%eax),%edx
3fb2: 8b 45 f8 mov -0x8(%ebp),%eax
3fb5: 89 10 mov %edx,(%eax)
3fb7: eb 0a jmp 3fc3 <free+0x98>
} else
bp->s.ptr = p->s.ptr;
3fb9: 8b 45 fc mov -0x4(%ebp),%eax
3fbc: 8b 10 mov (%eax),%edx
3fbe: 8b 45 f8 mov -0x8(%ebp),%eax
3fc1: 89 10 mov %edx,(%eax)
if(p + p->s.size == bp){
3fc3: 8b 45 fc mov -0x4(%ebp),%eax
3fc6: 8b 40 04 mov 0x4(%eax),%eax
3fc9: 8d 14 c5 00 00 00 00 lea 0x0(,%eax,8),%edx
3fd0: 8b 45 fc mov -0x4(%ebp),%eax
3fd3: 01 d0 add %edx,%eax
3fd5: 3b 45 f8 cmp -0x8(%ebp),%eax
3fd8: 75 20 jne 3ffa <free+0xcf>
p->s.size += bp->s.size;
3fda: 8b 45 fc mov -0x4(%ebp),%eax
3fdd: 8b 50 04 mov 0x4(%eax),%edx
3fe0: 8b 45 f8 mov -0x8(%ebp),%eax
3fe3: 8b 40 04 mov 0x4(%eax),%eax
3fe6: 01 c2 add %eax,%edx
3fe8: 8b 45 fc mov -0x4(%ebp),%eax
3feb: 89 50 04 mov %edx,0x4(%eax)
p->s.ptr = bp->s.ptr;
3fee: 8b 45 f8 mov -0x8(%ebp),%eax
3ff1: 8b 10 mov (%eax),%edx
3ff3: 8b 45 fc mov -0x4(%ebp),%eax
3ff6: 89 10 mov %edx,(%eax)
3ff8: eb 08 jmp 4002 <free+0xd7>
} else
p->s.ptr = bp;
3ffa: 8b 45 fc mov -0x4(%ebp),%eax
3ffd: 8b 55 f8 mov -0x8(%ebp),%edx
4000: 89 10 mov %edx,(%eax)
freep = p;
4002: 8b 45 fc mov -0x4(%ebp),%eax
4005: a3 48 5f 00 00 mov %eax,0x5f48
}
400a: 90 nop
400b: c9 leave
400c: c3 ret
0000400d <morecore>:
static Header*
morecore(uint nu)
{
400d: 55 push %ebp
400e: 89 e5 mov %esp,%ebp
4010: 83 ec 18 sub $0x18,%esp
char *p;
Header *hp;
if(nu < 4096)
4013: 81 7d 08 ff 0f 00 00 cmpl $0xfff,0x8(%ebp)
401a: 77 07 ja 4023 <morecore+0x16>
nu = 4096;
401c: c7 45 08 00 10 00 00 movl $0x1000,0x8(%ebp)
p = sbrk(nu * sizeof(Header));
4023: 8b 45 08 mov 0x8(%ebp),%eax
4026: c1 e0 03 shl $0x3,%eax
4029: 83 ec 0c sub $0xc,%esp
402c: 50 push %eax
402d: e8 59 fc ff ff call 3c8b <sbrk>
4032: 83 c4 10 add $0x10,%esp
4035: 89 45 f4 mov %eax,-0xc(%ebp)
if(p == (char*)-1)
4038: 83 7d f4 ff cmpl $0xffffffff,-0xc(%ebp)
403c: 75 07 jne 4045 <morecore+0x38>
return 0;
403e: b8 00 00 00 00 mov $0x0,%eax
4043: eb 26 jmp 406b <morecore+0x5e>
hp = (Header*)p;
4045: 8b 45 f4 mov -0xc(%ebp),%eax
4048: 89 45 f0 mov %eax,-0x10(%ebp)
hp->s.size = nu;
404b: 8b 45 f0 mov -0x10(%ebp),%eax
404e: 8b 55 08 mov 0x8(%ebp),%edx
4051: 89 50 04 mov %edx,0x4(%eax)
free((void*)(hp + 1));
4054: 8b 45 f0 mov -0x10(%ebp),%eax
4057: 83 c0 08 add $0x8,%eax
405a: 83 ec 0c sub $0xc,%esp
405d: 50 push %eax
405e: e8 c8 fe ff ff call 3f2b <free>
4063: 83 c4 10 add $0x10,%esp
return freep;
4066: a1 48 5f 00 00 mov 0x5f48,%eax
}
406b: c9 leave
406c: c3 ret
0000406d <malloc>:
void*
malloc(uint nbytes)
{
406d: 55 push %ebp
406e: 89 e5 mov %esp,%ebp
4070: 83 ec 18 sub $0x18,%esp
Header *p, *prevp;
uint nunits;
nunits = (nbytes + sizeof(Header) - 1)/sizeof(Header) + 1;
4073: 8b 45 08 mov 0x8(%ebp),%eax
4076: 83 c0 07 add $0x7,%eax
4079: c1 e8 03 shr $0x3,%eax
407c: 83 c0 01 add $0x1,%eax
407f: 89 45 ec mov %eax,-0x14(%ebp)
if((prevp = freep) == 0){
4082: a1 48 5f 00 00 mov 0x5f48,%eax
4087: 89 45 f0 mov %eax,-0x10(%ebp)
408a: 83 7d f0 00 cmpl $0x0,-0x10(%ebp)
408e: 75 23 jne 40b3 <malloc+0x46>
base.s.ptr = freep = prevp = &base;
4090: c7 45 f0 40 5f 00 00 movl $0x5f40,-0x10(%ebp)
4097: 8b 45 f0 mov -0x10(%ebp),%eax
409a: a3 48 5f 00 00 mov %eax,0x5f48
409f: a1 48 5f 00 00 mov 0x5f48,%eax
40a4: a3 40 5f 00 00 mov %eax,0x5f40
base.s.size = 0;
40a9: c7 05 44 5f 00 00 00 movl $0x0,0x5f44
40b0: 00 00 00
}
for(p = prevp->s.ptr; ; prevp = p, p = p->s.ptr){
40b3: 8b 45 f0 mov -0x10(%ebp),%eax
40b6: 8b 00 mov (%eax),%eax
40b8: 89 45 f4 mov %eax,-0xc(%ebp)
if(p->s.size >= nunits){
40bb: 8b 45 f4 mov -0xc(%ebp),%eax
40be: 8b 40 04 mov 0x4(%eax),%eax
40c1: 3b 45 ec cmp -0x14(%ebp),%eax
40c4: 72 4d jb 4113 <malloc+0xa6>
if(p->s.size == nunits)
40c6: 8b 45 f4 mov -0xc(%ebp),%eax
40c9: 8b 40 04 mov 0x4(%eax),%eax
40cc: 3b 45 ec cmp -0x14(%ebp),%eax
40cf: 75 0c jne 40dd <malloc+0x70>
prevp->s.ptr = p->s.ptr;
40d1: 8b 45 f4 mov -0xc(%ebp),%eax
40d4: 8b 10 mov (%eax),%edx
40d6: 8b 45 f0 mov -0x10(%ebp),%eax
40d9: 89 10 mov %edx,(%eax)
40db: eb 26 jmp 4103 <malloc+0x96>
else {
p->s.size -= nunits;
40dd: 8b 45 f4 mov -0xc(%ebp),%eax
40e0: 8b 40 04 mov 0x4(%eax),%eax
40e3: 2b 45 ec sub -0x14(%ebp),%eax
40e6: 89 c2 mov %eax,%edx
40e8: 8b 45 f4 mov -0xc(%ebp),%eax
40eb: 89 50 04 mov %edx,0x4(%eax)
p += p->s.size;
40ee: 8b 45 f4 mov -0xc(%ebp),%eax
40f1: 8b 40 04 mov 0x4(%eax),%eax
40f4: c1 e0 03 shl $0x3,%eax
40f7: 01 45 f4 add %eax,-0xc(%ebp)
p->s.size = nunits;
40fa: 8b 45 f4 mov -0xc(%ebp),%eax
40fd: 8b 55 ec mov -0x14(%ebp),%edx
4100: 89 50 04 mov %edx,0x4(%eax)
}
freep = prevp;
4103: 8b 45 f0 mov -0x10(%ebp),%eax
4106: a3 48 5f 00 00 mov %eax,0x5f48
return (void*)(p + 1);
410b: 8b 45 f4 mov -0xc(%ebp),%eax
410e: 83 c0 08 add $0x8,%eax
4111: eb 3b jmp 414e <malloc+0xe1>
}
if(p == freep)
4113: a1 48 5f 00 00 mov 0x5f48,%eax
4118: 39 45 f4 cmp %eax,-0xc(%ebp)
411b: 75 1e jne 413b <malloc+0xce>
if((p = morecore(nunits)) == 0)
411d: 83 ec 0c sub $0xc,%esp
4120: ff 75 ec pushl -0x14(%ebp)
4123: e8 e5 fe ff ff call 400d <morecore>
4128: 83 c4 10 add $0x10,%esp
412b: 89 45 f4 mov %eax,-0xc(%ebp)
412e: 83 7d f4 00 cmpl $0x0,-0xc(%ebp)
4132: 75 07 jne 413b <malloc+0xce>
return 0;
4134: b8 00 00 00 00 mov $0x0,%eax
4139: eb 13 jmp 414e <malloc+0xe1>
nunits = (nbytes + sizeof(Header) - 1)/sizeof(Header) + 1;
if((prevp = freep) == 0){
base.s.ptr = freep = prevp = &base;
base.s.size = 0;
}
for(p = prevp->s.ptr; ; prevp = p, p = p->s.ptr){
413b: 8b 45 f4 mov -0xc(%ebp),%eax
413e: 89 45 f0 mov %eax,-0x10(%ebp)
4141: 8b 45 f4 mov -0xc(%ebp),%eax
4144: 8b 00 mov (%eax),%eax
4146: 89 45 f4 mov %eax,-0xc(%ebp)
return (void*)(p + 1);
}
if(p == freep)
if((p = morecore(nunits)) == 0)
return 0;
}
4149: e9 6d ff ff ff jmp 40bb <malloc+0x4e>
}
414e: c9 leave
414f: c3 ret
|
/*++
Copyright (c) 2015 Microsoft Corporation
Module Name:
nlqsat.cpp
Abstract:
Quantifier Satisfiability Solver for nlsat
Author:
Nikolaj Bjorner (nbjorner) 2015-10-17
Revision History:
--*/
#include "util/uint_set.h"
#include "util/scoped_ptr_vector.h"
#include "ast/expr2var.h"
#include "ast/ast_util.h"
#include "ast/rewriter/expr_safe_replace.h"
#include "ast/ast_pp.h"
#include "ast/for_each_expr.h"
#include "ast/rewriter/rewriter.h"
#include "ast/rewriter/th_rewriter.h"
#include "ast/rewriter/rewriter_def.h"
#include "ast/rewriter/quant_hoist.h"
#include "qe/nlqsat.h"
#include "qe/qsat.h"
#include "nlsat/nlsat_solver.h"
#include "nlsat/nlsat_explain.h"
#include "nlsat/nlsat_assignment.h"
#include "nlsat/tactic/goal2nlsat.h"
#include "tactic/core/tseitin_cnf_tactic.h"
namespace qe {
enum qsat_mode_t {
qsat_t,
elim_t
};
class nlqsat : public tactic {
typedef unsigned_vector assumption_vector;
typedef nlsat::scoped_literal_vector clause;
struct stats {
unsigned m_num_rounds;
stats() { reset(); }
void reset() { memset(this, 0, sizeof(*this)); }
};
struct solver_state {
ast_manager& m;
params_ref m_params;
nlsat::solver m_solver;
nlsat::literal m_is_true;
nlsat::assignment m_rmodel;
svector<lbool> m_bmodel;
nlsat::assignment m_rmodel0;
svector<lbool> m_bmodel0;
bool m_valid_model;
vector<nlsat::var_vector> m_bound_rvars;
vector<svector<nlsat::bool_var> > m_bound_bvars;
scoped_ptr_vector<nlsat::scoped_literal_vector> m_preds;
svector<max_level> m_rvar2level;
u_map<max_level> m_bvar2level;
expr2var m_a2b, m_t2x;
u_map<expr*> m_b2a, m_x2t;
nlsat::literal_vector m_assumptions;
nlsat::literal_vector m_asms;
nlsat::literal_vector m_cached_asms;
unsigned_vector m_cached_asms_lim;
u_map<expr*> m_asm2fml;
solver_state(ast_manager& m, params_ref const& p):
m(m),
m_params(p),
m_solver(m.limit(), p, true),
m_rmodel(m_solver.am()),
m_rmodel0(m_solver.am()),
m_valid_model(false),
m_a2b(m),
m_t2x(m)
{}
~solver_state() {
reset();
}
void g2s(goal const& g) {
goal2nlsat gs;
gs(g, m_params, m_solver, m_a2b, m_t2x);
}
void init_expr2var(vector<app_ref_vector> const& qvars) {
for (app_ref_vector const& qvs : qvars) {
init_expr2var(qvs);
}
}
void init_expr2var(app_ref_vector const& qvars) {
for (app* v : qvars) {
if (m.is_bool(v)) {
nlsat::bool_var b = m_solver.mk_bool_var();
m_solver.inc_ref(b);
m_a2b.insert(v, b);
}
else {
// TODO: assert it is of type Real.
m_t2x.insert(v, m_solver.mk_var(false));
}
}
}
void init_var2expr() {
for (auto const& kv : m_t2x) {
m_x2t.insert(kv.m_value, kv.m_key);
}
for (auto const& kv : m_a2b) {
m_b2a.insert(kv.m_value, kv.m_key);
}
}
void save_model(bool is_exists) {
svector<nlsat::bool_var> bvars;
for (auto const& kv : m_bvar2level) {
bvars.push_back(kv.m_key);
}
m_solver.get_rvalues(m_rmodel);
m_solver.get_bvalues(bvars, m_bmodel);
m_valid_model = true;
if (is_exists) {
m_rmodel0.copy(m_rmodel);
m_bmodel0.reset();
m_bmodel0.append(m_bmodel);
}
}
void unsave_model() {
SASSERT(m_valid_model);
m_solver.set_rvalues(m_rmodel);
m_solver.set_bvalues(m_bmodel);
}
void clear_model() {
m_valid_model = false;
m_rmodel.reset();
m_bmodel.reset();
m_solver.set_rvalues(m_rmodel);
}
void add_assumption_literal(clause& clause, expr* fml) {
nlsat::bool_var b = m_solver.mk_bool_var();
clause.push_back(nlsat::literal(b, true));
m_assumptions.push_back(nlsat::literal(b, false));
m_solver.inc_ref(b);
m_asm2fml.insert(b, fml);
m_bvar2level.insert(b, max_level());
}
expr_ref clause2fml(nlsat::scoped_literal_vector const& clause) {
expr_ref_vector fmls(m);
expr_ref fml(m);
expr* t;
nlsat2goal n2g(m);
for (nlsat::literal l : clause) {
if (m_asm2fml.find(l.var(), t)) {
fml = t;
if (l.sign()) {
fml = push_not(fml);
}
SASSERT(l.sign());
fmls.push_back(fml);
}
else {
fmls.push_back(n2g(m_solver, m_b2a, m_x2t, l));
}
}
fml = mk_or(fmls);
return fml;
}
void add_literal(nlsat::literal_vector& lits, nlsat::literal l) {
lbool r = m_solver.value(l);
switch (r) {
case l_true:
lits.push_back(l);
break;
case l_false:
lits.push_back(~l);
break;
default:
lits.push_back(l);
break;
}
}
void display(std::ostream& out) {
out << "level " << level() << "\n";
display_preds(out);
display_assumptions(out);
m_solver.display(out << "solver:\n");
}
void display_assumptions(std::ostream& out) {
m_solver.display(out << "assumptions: ", m_asms.size(), m_asms.c_ptr());
out << "\n";
}
void display_preds(std::ostream& out) {
for (unsigned i = 0; i < m_preds.size(); ++i) {
m_solver.display(out << i << ": ", m_preds[i]->size(), m_preds[i]->c_ptr());
out << "\n";
}
}
unsigned level() const {
return m_cached_asms_lim.size();
}
void reset() {
m_asms.reset();
m_cached_asms.reset();
m_cached_asms_lim.reset();
m_is_true = nlsat::null_literal;
m_rmodel.reset();
m_valid_model = false;
m_bound_rvars.reset();
m_bound_bvars.reset();
m_preds.reset();
for (auto const& kv : m_bvar2level) {
m_solver.dec_ref(kv.m_key);
}
m_rvar2level.reset();
m_bvar2level.reset();
m_t2x.reset();
m_a2b.reset();
m_b2a.reset();
m_x2t.reset();
m_assumptions.reset();
m_asm2fml.reset();
}
};
ast_manager& m;
solver_state s;
qsat_mode_t m_mode;
params_ref m_params;
tactic_ref m_nftactic;
stats m_stats;
statistics m_st;
obj_hashtable<expr> m_free_vars;
expr_ref_vector m_answer;
expr_safe_replace m_answer_simplify;
expr_ref_vector m_trail;
expr_ref_vector m_mbps;
ref<generic_model_converter> m_div_mc;
lbool check_sat() {
while (true) {
++m_stats.m_num_rounds;
check_cancel();
init_assumptions();
lbool res = s.m_solver.check(s.m_asms);
TRACE("qe", s.display(tout << res << "\n"); );
switch (res) {
case l_true:
s.save_model(is_exists(level()));
push();
break;
case l_false:
if (0 == level()) return l_false;
if (1 == level() && m_mode == qsat_t) return l_true;
project();
break;
case l_undef:
return res;
}
}
return l_undef;
}
void init_assumptions() {
unsigned lvl = level();
s.m_asms.reset();
s.m_asms.push_back(is_exists()?s.m_is_true:~s.m_is_true);
s.m_asms.append(s.m_assumptions);
TRACE("qe", tout << "model valid: " << s.m_valid_model << " level: " << lvl << " ";
s.display_assumptions(tout);
s.m_solver.display(tout););
if (!s.m_valid_model) {
s.m_asms.append(s.m_cached_asms);
return;
}
s.unsave_model();
if (lvl == 0) {
SASSERT(s.m_cached_asms.empty());
return;
}
if (lvl <= s.m_preds.size()) {
for (unsigned j = 0; j < s.m_preds[lvl - 1]->size(); ++j) {
s.add_literal(s.m_cached_asms, (*s.m_preds[lvl - 1])[j]);
}
}
s.m_asms.append(s.m_cached_asms);
for (unsigned i = lvl + 1; i < s.m_preds.size(); i += 2) {
for (unsigned j = 0; j < s.m_preds[i]->size(); ++j) {
nlsat::literal l = (*s.m_preds[i])[j];
max_level lv = s.m_bvar2level.find(l.var());
bool use =
(lv.m_fa == i && (lv.m_ex == UINT_MAX || lv.m_ex < lvl)) ||
(lv.m_ex == i && (lv.m_fa == UINT_MAX || lv.m_fa < lvl));
if (use) {
s.add_literal(s.m_asms, l);
}
}
}
TRACE("qe", s.display(tout);
tout << "assumptions\n";
for (nlsat::literal a : s.m_asms) {
s.m_solver.display(tout, a) << "\n";
});
s.save_model(is_exists(level()));
}
template<class S, class T>
void insert_set(S& set, T const& vec) {
for (auto const& v : vec) {
set.insert(v);
}
}
void mbp(unsigned level, nlsat::scoped_literal_vector& result) {
nlsat::var_vector vars;
uint_set fvars;
extract_vars(level, vars, fvars);
mbp(vars, fvars, result);
}
void extract_vars(unsigned level, nlsat::var_vector& vars, uint_set& fvars) {
for (unsigned i = 0; i < s.m_bound_rvars.size(); ++i) {
if (i < level) {
insert_set(fvars, s.m_bound_bvars[i]);
}
else {
vars.append(s.m_bound_rvars[i]);
}
}
}
void display_project(std::ostream& out, nlsat::var v, nlsat::scoped_literal_vector const& r1, nlsat::scoped_literal_vector const& r2) {
for (auto const& kv : s.m_x2t) {
out << "(declare-const x" << kv.m_key << " Real)\n";
}
s.m_solver.display(out << "(assert (not (exists ((", v) << " Real)) \n";
s.m_solver.display_smt2(out << "(and ", r1.size(), r1.c_ptr()) << "))))\n";
s.m_solver.display_smt2(out << "(assert (and ", r2.size(), r2.c_ptr()); out << "))\n";
out << "(check-sat)\n(reset)\n";
}
void mbp(nlsat::var_vector const& vars, uint_set const& fvars, clause& result) {
//
// Also project auxiliary variables from clausification.
//
s.unsave_model();
nlsat::explain& ex = s.m_solver.get_explain();
nlsat::scoped_literal_vector new_result(s.m_solver);
result.reset();
// project quantified Boolean variables.
for (nlsat::literal lit : s.m_asms) {
if (!s.m_b2a.contains(lit.var()) || fvars.contains(lit.var())) {
result.push_back(lit);
}
}
TRACE("qe", s.m_solver.display(tout, result.size(), result.c_ptr()); tout << "\n";);
// project quantified real variables.
// They are sorted by size, so we project the largest variables first to avoid
// renaming variables.
//std::cout << "***** NEW PASS *****\n";
for (unsigned i = vars.size(); i-- > 0;) {
new_result.reset();
ex.project(vars[i], result.size(), result.c_ptr(), new_result);
TRACE("qe", display_project(tout, vars[i], result, new_result););
TRACE("qe", display_project(std::cout, vars[i], result, new_result););
result.swap(new_result);
}
expr_ref fml = s.clause2fml(result);
std::cout << "fml from nlqsat::mbp : " << fml << "\n";
m_mbps.push_back(fml);
negate_clause(result);
}
void negate_clause(clause& result) {
for (unsigned i = 0; i < result.size(); ++i) {
result.set(i, ~result[i]);
}
}
unsigned level() const {
return s.level();
}
void enforce_parity(clause& cl) {
cl.push_back(is_exists()?~s.m_is_true:s.m_is_true);
}
void add_clause(clause& cl) {
if (cl.empty()) {
cl.push_back(~s.m_solver.mk_true());
}
SASSERT(!cl.empty());
nlsat::literal_vector lits(cl.size(), cl.c_ptr());
s.m_solver.mk_clause(lits.size(), lits.c_ptr());
}
max_level get_level(clause const& cl) {
return get_level(cl.size(), cl.c_ptr());
}
max_level get_level(unsigned n, nlsat::literal const* ls) {
max_level level;
for (unsigned i = 0; i < n; ++i) {
level.merge(get_level(ls[i]));
}
return level;
}
max_level get_level(nlsat::literal l) {
max_level level;
if (s.m_bvar2level.find(l.var(), level)) {
return level;
}
nlsat::var_vector vs;
s.m_solver.vars(l, vs);
TRACE("qe", s.m_solver.display(tout << vs << " ", l) << "\n";);
for (unsigned v : vs) {
level.merge(s.m_rvar2level.get(v, max_level()));
}
if (level == max_level())
throw default_exception("level not in NRA");
set_level(l.var(), level);
return level;
}
void set_level(nlsat::bool_var v, max_level const& level) {
unsigned k = level.max();
while (s.m_preds.size() <= k) {
s.m_preds.push_back(alloc(nlsat::scoped_literal_vector, s.m_solver));
}
nlsat::literal l(v, false);
s.m_preds[k]->push_back(l);
s.m_solver.inc_ref(v);
s.m_bvar2level.insert(v, level);
TRACE("qe", s.m_solver.display(tout, l); tout << ": " << level << "\n";);
}
void project() {
TRACE("qe", s.display_assumptions(tout););
if (!s.m_valid_model) {
pop(1);
return;
}
if (m_mode == elim_t) {
project_qe();
return;
}
SASSERT(level() >= 2);
unsigned num_scopes;
clause cl(s.m_solver);
mbp(level()-1, cl);
max_level clevel = get_level(cl);
enforce_parity(cl);
add_clause(cl);
if (clevel.max() == UINT_MAX) {
num_scopes = 2*(level()/2);
}
else {
SASSERT(clevel.max() + 2 <= level());
num_scopes = level() - clevel.max();
SASSERT(num_scopes >= 2);
}
TRACE("qe", tout << "backtrack: " << num_scopes << "\n";);
pop(num_scopes);
}
void project_qe() {
SASSERT(level() >= 1 && m_mode == elim_t && s.m_valid_model);
clause cl(s.m_solver);
mbp(std::max(1u, level()-1), cl);
expr_ref fml = s.clause2fml(cl);
TRACE("qe", tout << level() << ": " << fml << "\n";);
max_level clevel = get_level(cl);
if (level() == 1 || clevel.max() == 0) {
add_assumption_literal(cl, fml);
}
else {
enforce_parity(cl);
}
add_clause(cl);
if (level() == 1) { // is_forall() && clevel.max() == 0
add_to_answer(fml);
}
if (level() == 1) {
pop(1);
}
else {
pop(2);
}
}
void add_to_answer(expr_ref& fml) {
m_answer_simplify(fml);
expr* e;
if (m.is_not(fml, e)) {
m_answer_simplify.insert(e, m.mk_false());
}
else {
m_answer_simplify.insert(fml, m.mk_true());
}
m_answer.push_back(fml);
}
void add_assumption_literal(clause& clause, expr* fml) {
s.add_assumption_literal(clause, fml);
m_trail.push_back(fml);
}
bool is_exists() const { return is_exists(level()); }
bool is_forall() const { return is_forall(level()); }
bool is_exists(unsigned level) const { return (level % 2) == 0; }
bool is_forall(unsigned level) const { return is_exists(level+1); }
void check_cancel() {
}
struct div {
expr_ref num, den;
app_ref name;
div(ast_manager& m, expr* n, expr* d, app* nm):
num(n, m), den(d, m), name(nm, m) {}
};
class div_rewriter_cfg : public default_rewriter_cfg {
ast_manager& m;
arith_util a;
expr_ref m_zero;
vector<div> m_divs;
public:
div_rewriter_cfg(nlqsat& s): m(s.m), a(s.m), m_zero(a.mk_real(0), m) {}
~div_rewriter_cfg() {}
br_status reduce_app(func_decl* f, unsigned sz, expr* const* args, expr_ref& result, proof_ref& pr) {
rational r(1);
if (is_decl_of(f, a.get_family_id(), OP_DIV) &&
sz == 2 && (!a.is_numeral(args[1], r) || r.is_zero()) &&
is_ground(args[0]) && is_ground(args[1])) {
result = m.mk_fresh_const("div", a.mk_real());
m_divs.push_back(div(m, args[0], args[1], to_app(result)));
return BR_DONE;
}
return BR_FAILED;
}
vector<div> const& divs() const { return m_divs; }
};
//template class rewriter_tpl<div_rewriter_cfg>;
class div_rewriter_star : public rewriter_tpl<div_rewriter_cfg> {
div_rewriter_cfg m_cfg;
public:
div_rewriter_star(nlqsat& s):
rewriter_tpl<div_rewriter_cfg>(s.m, false, m_cfg),
m_cfg(s)
{}
vector<div> const& divs() const { return m_cfg.divs(); }
};
class is_pure_proc {
nlqsat& s;
arith_util a;
bool m_has_divs;
public:
is_pure_proc(nlqsat& s): s(s), a(s.m), m_has_divs(false) {}
void operator()(::var * n) {
if (!a.is_real(n) && !s.m.is_bool(n)) {
throw tactic_exception("not NRA");
}
}
void operator()(app * n) {
if (n->get_family_id() == s.m.get_basic_family_id()) {
return;
}
if (is_uninterp_const(n) && (a.is_real(n) || s.m.is_bool(n))) {
return;
}
if (a.is_mul(n) || a.is_add(n) || a.is_sub(n) || a.is_uminus(n) || a.is_numeral(n) ||
a.is_le(n) || a.is_ge(n) || a.is_lt(n) || a.is_gt(n)) {
return;
}
expr* n1, *n2;
rational r;
if (a.is_div(n, n1, n2) && a.is_numeral(n2, r) && !r.is_zero()) {
return;
}
if (a.is_power(n, n1, n2) && a.is_numeral(n2, r) && r.is_unsigned() && r.is_pos()) {
return;
}
if (a.is_div(n) && s.m_mode == qsat_t && is_ground(n)) {
m_has_divs = true;
return;
}
TRACE("qe", tout << "not NRA: " << mk_pp(n, s.m) << "\n";);
throw tactic_exception("not NRA");
}
void operator()(quantifier * n) {}
bool has_divs() const { return m_has_divs; }
};
/*
Ackermanize division
For each p/q:
q != 0 => div_pq*q = p
For each p/q, p'/q'
p = p', q = q' => div_pq = div_pq'
*/
void ackermanize_div(expr_ref& fml, expr_ref_vector& paxioms) {
is_pure_proc is_pure(*this);
{
expr_fast_mark1 visited;
quick_for_each_expr(is_pure, visited, fml);
}
if (is_pure.has_divs()) {
arith_util arith(m);
proof_ref pr(m);
div_rewriter_star rw(*this);
rw(fml, fml, pr);
vector<div> const& divs = rw.divs();
m_div_mc = alloc(generic_model_converter, m, "purify");
for (unsigned i = 0; i < divs.size(); ++i) {
expr_ref den_is0(m.mk_eq(divs[i].den, arith.mk_real(0)), m);
paxioms.push_back(m.mk_or(den_is0, m.mk_eq(divs[i].num, arith.mk_mul(divs[i].den, divs[i].name))));
for (unsigned j = i + 1; j < divs.size(); ++j) {
paxioms.push_back(m.mk_or(m.mk_not(m.mk_eq(divs[i].den, divs[j].den)),
m.mk_not(m.mk_eq(divs[i].num, divs[j].num)),
m.mk_eq(divs[i].name, divs[j].name)));
}
}
expr_ref body(arith.mk_real(0), m);
expr_ref v0(m.mk_var(0, arith.mk_real()), m);
expr_ref v1(m.mk_var(1, arith.mk_real()), m);
for (auto const& p : divs) {
body = m.mk_ite(m.mk_and(m.mk_eq(v0, p.num), m.mk_eq(v1, p.den)), p.name, body);
}
m_div_mc->add(arith.mk_div0(), body);
}
}
void reset() override {
s.reset();
m_st.reset();
s.m_solver.collect_statistics(m_st);
m_free_vars.reset();
m_answer.reset();
m_answer_simplify.reset();
m_trail.reset();
}
void push() {
s.m_cached_asms_lim.push_back(s.m_cached_asms.size());
}
void pop(unsigned num_scopes) {
s.clear_model();
unsigned new_level = level() - num_scopes;
s.m_cached_asms.shrink(s.m_cached_asms_lim[new_level]);
s.m_cached_asms_lim.shrink(new_level);
}
// expr -> nlsat::solver
bool hoist(expr_ref& fml) {
expr_ref_vector paxioms(m);
ackermanize_div(fml, paxioms);
quantifier_hoister hoist(m);
vector<app_ref_vector> qvars;
app_ref_vector vars(m);
bool is_forall = false;
pred_abs abs(m);
expr_ref fml_a(m.mk_and(fml, mk_and(paxioms)), m);
abs.get_free_vars(fml_a, vars);
insert_set(m_free_vars, vars);
qvars.push_back(vars);
vars.reset();
if (m_mode == elim_t) {
is_forall = true;
hoist.pull_quantifier(is_forall, fml, vars);
qvars.push_back(vars);
}
else {
hoist.pull_quantifier(is_forall, fml, vars);
qvars.back().append(vars);
}
do {
is_forall = !is_forall;
vars.reset();
hoist.pull_quantifier(is_forall, fml, vars);
qvars.push_back(vars);
}
while (!vars.empty());
SASSERT(qvars.size() >= 2);
SASSERT(qvars.back().empty());
s.init_expr2var(qvars);
expr_ref is_true(m), fml1(m), fml2(m);
is_true = m.mk_fresh_const("is_true", m.mk_bool_sort());
fml = m.mk_iff(is_true, fml);
goal_ref g = alloc(goal, m);
g->assert_expr(fml);
for (expr* f : paxioms) {
g->assert_expr(f);
}
expr_dependency_ref core(m);
goal_ref_buffer result;
(*m_nftactic)(g, result);
SASSERT(result.size() == 1);
TRACE("qe", result[0]->display(tout););
s.g2s(*result[0]);
// insert variables and their levels.
for (unsigned i = 0; i < qvars.size(); ++i) {
s.m_bound_bvars.push_back(svector<nlsat::bool_var>());
s.m_bound_rvars.push_back(nlsat::var_vector());
max_level lvl;
if (is_exists(i)) lvl.m_ex = i; else lvl.m_fa = i;
for (app* v : qvars[i]) {
if (s.m_a2b.is_var(v)) {
SASSERT(m.is_bool(v));
nlsat::bool_var b = s.m_a2b.to_var(v);
TRACE("qe", tout << mk_pp(v, m) << " |-> b" << b << "\n";);
s.m_bound_bvars.back().push_back(b);
set_level(b, lvl);
}
else if (s.m_t2x.is_var(v)) {
nlsat::var w = s.m_t2x.to_var(v);
TRACE("qe", tout << mk_pp(v, m) << " |-> x" << w << "\n";);
s.m_bound_rvars.back().push_back(w);
s.m_rvar2level.setx(w, lvl, max_level());
}
else {
TRACE("qe", tout << mk_pp(v, m) << " not found\n";);
}
}
}
s.init_var2expr();
s.m_is_true = nlsat::literal(s.m_a2b.to_var(is_true), false);
// insert literals from arithmetical sub-formulas
nlsat::atom_vector const& atoms = s.m_solver.get_atoms();
TRACE("qe", s.m_solver.display(tout););
for (unsigned i = 0; i < atoms.size(); ++i) {
if (atoms[i]) {
get_level(nlsat::literal(i, false));
}
}
TRACE("qe", tout << fml << "\n";);
return true;
}
// Return false if nlsat assigned noninteger value to an integer variable.
// [copied from nlsat_tactic.cpp]
bool mk_model(model_converter_ref & mc) {
bool ok = true;
model_ref md = alloc(model, m);
arith_util util(m);
for (auto const& kv : s.m_t2x) {
nlsat::var x = kv.m_value;
expr * t = kv.m_key;
if (!is_uninterp_const(t) || !m_free_vars.contains(t))
continue;
expr * v;
try {
v = util.mk_numeral(s.m_solver.am(), s.m_rmodel0.value(x), util.is_int(t));
}
catch (z3_error & ex) {
throw ex;
}
catch (z3_exception &) {
v = util.mk_to_int(util.mk_numeral(s.m_solver.am(), s.m_rmodel0.value(x), false));
ok = false;
}
md->register_decl(to_app(t)->get_decl(), v);
}
for (auto const& kv : s.m_a2b) {
expr * a = kv.m_key;
nlsat::bool_var b = kv.m_value;
if (a == nullptr || !is_uninterp_const(a) || b == s.m_is_true.var() || !m_free_vars.contains(a))
continue;
lbool val = s.m_bmodel0.get(b, l_undef);
if (val == l_undef)
continue; // don't care
md->register_decl(to_app(a)->get_decl(), val == l_true ? m.mk_true() : m.mk_false());
}
mc = model2model_converter(md.get());
return ok;
}
public:
nlqsat(ast_manager& m, qsat_mode_t mode, params_ref const& p):
m(m),
s(m, p),
m_mode(mode),
m_params(p),
m_nftactic(nullptr),
m_answer(m),
m_answer_simplify(m),
m_trail(m),
m_mbps(m),
m_div_mc(nullptr) {
s.m_solver.get_explain().set_signed_project(true);
m_nftactic = mk_tseitin_cnf_tactic(m);
}
~nlqsat() override {
}
// Daniel added this
expr_ref clause2fml(nlsat::scoped_literal_vector const& clause) {
return s.clause2fml(clause);
}
expr_ref_vector get_mbps() { return m_mbps; }
void updt_params(params_ref const & p) override {
params_ref p2(p);
p2.set_bool("factor", false);
s.m_solver.updt_params(p2);
}
void collect_param_descrs(param_descrs & r) override {
}
void operator()(/* in */ goal_ref const & in,
/* out */ goal_ref_buffer & result) override {
tactic_report report("nlqsat-tactic", *in);
std::cout << "In operator() of nlqsat\n";
in->display(std::cout);
ptr_vector<expr> fmls;
expr_ref fml(m);
in->get_formulas(fmls);
fml = mk_and(m, fmls.size(), fmls.c_ptr());
if (m_mode == elim_t) {
fml = m.mk_not(fml);
}
reset();
TRACE("qe", tout << fml << "\n";);
if (!hoist(fml)) {
std::cout << "hoist returned false. Returning\n";
result.push_back(in.get());
return;
}
std::cout << "hoist returned true. Moving on\n";
TRACE("qe", tout << "ex: " << fml << "\n";);
lbool is_sat = check_sat();
switch (is_sat) {
case l_false:
std::cout << "is_sat returned false\n";
in->reset();
in->inc_depth();
if (m_mode == elim_t) {
fml = mk_and(m_answer);
}
else {
fml = m.mk_false();
}
in->assert_expr(fml);
result.push_back(in.get());
break;
case l_true:
std::cout << "is_sat returned true\n";
SASSERT(m_mode == qsat_t);
in->reset();
in->inc_depth();
result.push_back(in.get());
if (in->models_enabled()) {
model_converter_ref mc;
VERIFY(mk_model(mc));
mc = concat(m_div_mc.get(), mc.get());
in->add(mc.get());
#if 0
model_ref mdl;
model_converter2model(m, mc.get(), mdl);
for (expr* f : fmls) {
if (is_ground(f))
std::cout << mk_pp(f, m) << " |-> " << (*mdl)(f) << "\n";
}
break;
ptr_vector<expr> todo;
todo.append(fmls.size(), fmls.c_ptr());
ast_mark visited;
while (!todo.empty()) {
expr* e = todo.back();
todo.pop_back();
if (visited.is_marked(e)) continue;
visited.mark(e, true);
if (is_ground(e)) {
std::cout << mk_pp(e, m) << " |-> " << (*mdl)(e) << "\n";
}
if (is_app(e)) {
for (expr* arg : *to_app(e)) todo.push_back(arg);
}
else if (is_quantifier(e)) {
todo.push_back(to_quantifier(e)->get_expr());
}
}
#endif
}
break;
case l_undef:
std::cout << "is_sat returned undef\n";
result.push_back(in.get());
throw tactic_exception("search failed");
}
}
void collect_statistics(statistics & st) const override {
st.copy(m_st);
st.update("qsat num rounds", m_stats.m_num_rounds);
}
void reset_statistics() override {
m_stats.reset();
s.m_solver.reset_statistics();
}
void cleanup() override {
reset();
}
void set_logic(symbol const & l) override {
}
void set_progress_callback(progress_callback * callback) override {
}
tactic * translate(ast_manager & m) override {
return alloc(nlqsat, m, m_mode, m_params);
}
};
};
tactic * mk_nlqsat_tactic(ast_manager & m, params_ref const& p) {
return alloc(qe::nlqsat, m, qe::qsat_t, p);
}
tactic * mk_nlqe_tactic(ast_manager & m, params_ref const& p) {
return alloc(qe::nlqsat, m, qe::elim_t, p);
}
|
COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
Copyright (c) GeoWorks 1992 -- All Rights Reserved
PROJECT: PC GEOS
MODULE: Video Drivers
FILE: vgaPalette.asm
AUTHOR: Jim DeFrisco, Oct 15, 1992
ROUTINES:
Name Description
---- -----------
REVISION HISTORY:
Name Date Description
---- ---- -----------
Jim 10/15/92 Initial revision
DESCRIPTION:
Palette stuff
$Id: vgaPalette.asm,v 1.1 97/04/18 11:41:58 newdeal Exp $
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@
COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
SetDevicePalette
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
SYNOPSIS: Set the hardware palette
CALLED BY: VidSetPalette
PASS: currentPalette setup
RETURN: nothing
DESTROYED: nothing
PSEUDO CODE/STRATEGY:
KNOWN BUGS/SIDE EFFECTS/IDEAS:
REVISION HISTORY:
Name Date Description
---- ---- -----------
jim 10/15/92 Initial version
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@
SetDevicePalette proc near
uses ax, bx, cx, dx, ds
.enter
jmp noPalette
mov ah, 010h
mov al, 13h
mov bl, 0
mov bh, 1
int 10h
mov ah, 010h
mov al, 13h
mov bl, 1
mov bh, 0
int 10h
clr cx
mov bx, offset currentPalette
segmov ds, cs, ax
setPaletteLoop:
mov dx, 03c8h
mov al, cl
out dx, al
mov dx, 03c9h
mov al, cs:[bx+0]
shr al, 1
shr al, 1
and al, 63
out dx, al
mov al, cs:[bx+1]
shr al, 1
shr al, 1
and al, 63
out dx, al
mov al, cs:[bx+2]
shr al, 1
shr al, 1
and al, 63
out dx, al
add bx, 3
inc cx
cmp cx, 16
jne setPaletteLoop
noPalette:
.leave
ret
SetDevicePalette endp
COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
FixColorRGB
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
SYNOPSIS: Translate a 24-bit RGB value to a valid 6-bit VGA palette
entry
CALLED BY: INTERNAL
PASS: al - red component
bl - green component
bh - blue component
RETURN: al - fixed red component
bl - fixed green component
bh - fixed blue component
DESTROYED: nothing
PSEUDO CODE/STRATEGY:
map the full range of 0-ff into 3f values evenly distributed
between 0 and ff.
new component=(old AND 0xfc) OR (old >> 6)
KNOWN BUGS/SIDE EFFECTS/IDEAS:
none
REVISION HISTORY:
Name Date Description
---- ---- -----------
Jim 07/89 Initial version
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@
FixColorRGB proc near
uses cx
.enter
; fix red component
mov cl, al ; save red component
clr ch
shl cx, 1 ; get two high bits into ch
shl cx, 1
and al, 0xfc ; clear out low two bits
or al, ch ; set two bits as approp.
; fix green component
mov cl, bl ; do green component
clr ch
shl cx, 1 ; get two high bits into ch
shl cx, 1
and bl, 0xfc ; clear out low two bits
or bl, ch ; set two bits as approp.
; fix blue component
mov cl, bh ; do green component
clr ch
shl cx, 1 ; get two high bits into ch
shl cx, 1
and bh, 0xfc ; clear out low two bits
or bh, ch ; set two bits as approp.
.leave
ret
FixColorRGB endp
|
; A202023: Triangle T(n,k), read by rows, given by (1, 0, 1, 0, 0, 0, 0, 0, 0, 0, ...) DELTA (0, 1, -1, 0, 0, 0, 0, 0, 0, 0, ...) where DELTA is the operator defined in A084938.
; 1,1,0,1,1,0,1,3,0,0,1,6,1,0,0,1,10,5,0,0,0,1,15,15,1,0,0,0,1,21,35,7,0,0,0,0,1,28,70,28,1,0,0,0,0,1,36,126,84,9,0,0,0,0,0,1,45,210,210,45,1,0,0,0,0,0
lpb $0
add $1,1
sub $0,$1
lpe
mul $0,2
bin $1,$0
|
TITLE DOS_DUP - Internal SFT DUP (for network SFTs)
NAME DOS_DUP
;
; Microsoft Confidential
; Copyright (C) Microsoft Corporation 1991
; All Rights Reserved.
;
;** Low level DUP routine for use by EXEC when creating a new process. Exports
; the DUP to the server machine and increments the SFT ref count
;
; DOS_DUP
;
; Modification history:
;
; Created: ARR 30 March 1983
.xlist
.xcref
include version.inc
include dosseg.inc
INCLUDE DOSSYM.INC
INCLUDE DEVSYM.INC
include sf.inc
.cref
.list
i_need THISSFT,DWORD
DOSCODE SEGMENT
ASSUME SS:DOSDATA,CS:DOSCODE
allow_getdseg
BREAK <DOS_DUP -- DUP SFT across network>
;---------------------------------------------------------------------------
;
; Procedure Name : DOS_DUP
;
; Inputs:
; [THISSFT] set to the SFT for the file being DUPed
; (a non net SFT is OK, in this case the ref
; count is simply incremented)
; Function:
; Signal to the devices that alogical open is occurring
; Returns:
; ES:DI point to SFT
; Carry clear
; SFT ref_count is incremented
; Registers modified: None.
; NOTE:
; This routine is called from $CREATE_PROCESS_DATA_BLOCK at DOSINIT
; time with SS NOT DOSGROUP. There will be no Network handles at
; that time.
procedure DOS_DUP,NEAR
ASSUME SS:NOTHING
getdseg <es> ; es -> dosdata
LES DI,ThisSFT
assume es:nothing
Entry Dos_Dup_Direct
Assert ISSFT,<ES,DI>,"DOSDup"
invoke IsSFTNet
JNZ DO_INC
invoke DEV_OPEN_SFT
DO_INC:
Assert ISSFT,<ES,DI>,"DOSDup/DoInc"
INC ES:[DI.sf_ref_count] ; Clears carry (if this ever wraps
; we're in big trouble anyway)
return
EndProc DOS_DUP
DOSCODE ENDS
END
|
include io.h
cr equ 10
lf equ 13
.model small
.Stack 200h
.Data
newline db cr, lf, 0
number_prompt1 db cr, lf, 'Enter Number one :', 0
number_prompt2 db cr, lf, 'Enter Number two :', 0
number_prompt3 db cr, lf, 'Enter Number three :', 0
number_one db 10 dup(?)
number_two db 10 dup(?)
number_three db 10 dup(?)
result db 10 dup(?)
sum dw 0
sum_prompt db 'The Sum is :', 0
.Code
main proc
mov ax, @Data
mov ds, ax
;-----------------------------------------------------------
clrscr
output number_prompt1
inputs number_one, 4
atoi number_one
add sum,ax
output number_prompt2
inputs number_two, 4
atoi number_two
add sum,ax
output number_prompt3
inputs number_three, 4
atoi number_three
add sum,ax
itoa result,sum
output newline
output sum_prompt
output result
;-----------------------------------------------------------
mov ax,4c00h
int 21h
main endp
end main
|
; A229853: 384*n + 1.
; 1,385,769,1153,1537,1921,2305,2689,3073,3457,3841,4225,4609,4993,5377,5761,6145,6529,6913,7297,7681,8065,8449,8833,9217,9601,9985,10369,10753,11137,11521,11905,12289,12673,13057,13441,13825,14209,14593,14977,15361,15745,16129,16513,16897,17281,17665,18049,18433,18817,19201,19585,19969,20353,20737,21121,21505,21889,22273,22657,23041,23425,23809,24193,24577,24961,25345,25729,26113,26497,26881,27265,27649,28033,28417,28801,29185,29569,29953,30337,30721,31105,31489,31873,32257,32641,33025,33409,33793,34177,34561,34945,35329,35713,36097,36481,36865,37249,37633,38017,38401,38785,39169,39553,39937,40321,40705,41089,41473,41857,42241,42625,43009,43393,43777,44161,44545,44929,45313,45697,46081,46465,46849,47233,47617,48001,48385,48769,49153,49537,49921,50305,50689,51073,51457,51841,52225,52609,52993,53377,53761,54145,54529,54913,55297,55681,56065,56449,56833,57217,57601,57985,58369,58753,59137,59521,59905,60289,60673,61057,61441,61825,62209,62593,62977,63361,63745,64129,64513,64897,65281,65665,66049,66433,66817,67201,67585,67969,68353,68737,69121,69505,69889,70273,70657,71041,71425,71809,72193,72577,72961,73345,73729,74113,74497,74881,75265,75649,76033,76417,76801,77185,77569,77953,78337,78721,79105,79489,79873,80257,80641,81025,81409,81793,82177,82561,82945,83329,83713,84097,84481,84865,85249,85633,86017,86401,86785,87169,87553,87937,88321,88705,89089,89473,89857,90241,90625,91009,91393,91777,92161,92545,92929,93313,93697,94081,94465,94849,95233,95617
mov $1,$0
mul $1,384
add $1,1
|
.global s_prepare_buffers
s_prepare_buffers:
push %r10
push %r15
push %r9
push %rax
push %rcx
push %rdi
push %rdx
push %rsi
lea addresses_normal_ht+0x1c702, %rsi
lea addresses_WT_ht+0x1df02, %rdi
cmp %r10, %r10
mov $24, %rcx
rep movsw
nop
nop
nop
nop
nop
add $27642, %r15
lea addresses_D_ht+0x5602, %rsi
lea addresses_WC_ht+0x6702, %rdi
nop
xor $32631, %r9
mov $123, %rcx
rep movsw
nop
nop
nop
nop
xor %r15, %r15
lea addresses_UC_ht+0x15e02, %r9
nop
nop
nop
and $63656, %rax
mov $0x6162636465666768, %r10
movq %r10, %xmm2
vmovups %ymm2, (%r9)
nop
sub %r15, %r15
lea addresses_UC_ht+0x15902, %r15
nop
nop
cmp %rsi, %rsi
and $0xffffffffffffffc0, %r15
vmovaps (%r15), %ymm4
vextracti128 $0, %ymm4, %xmm4
vpextrq $0, %xmm4, %rdi
nop
add $7554, %rax
lea addresses_WT_ht+0x154c2, %rsi
lea addresses_WT_ht+0x6702, %rdi
clflush (%rdi)
and %rdx, %rdx
mov $67, %rcx
rep movsl
add %rdi, %rdi
lea addresses_A_ht+0x10702, %r9
nop
nop
nop
nop
nop
add %r10, %r10
mov $0x6162636465666768, %r15
movq %r15, %xmm2
vmovups %ymm2, (%r9)
nop
sub $33854, %r15
lea addresses_UC_ht+0x18682, %rdx
nop
nop
nop
nop
and $41538, %r10
vmovups (%rdx), %ymm7
vextracti128 $0, %ymm7, %xmm7
vpextrq $0, %xmm7, %rcx
nop
nop
nop
xor $62528, %r15
lea addresses_WT_ht+0xbb2a, %rcx
nop
add $28950, %r10
movb (%rcx), %r15b
nop
nop
xor %rax, %rax
lea addresses_UC_ht+0x9902, %r9
nop
nop
nop
nop
xor $26843, %rsi
movb (%r9), %r10b
nop
nop
and %r10, %r10
pop %rsi
pop %rdx
pop %rdi
pop %rcx
pop %rax
pop %r9
pop %r15
pop %r10
ret
.global s_faulty_load
s_faulty_load:
push %r11
push %r12
push %r13
push %r14
push %r8
push %rbx
push %rsi
// Store
mov $0x674249000000052a, %rsi
nop
dec %r11
mov $0x5152535455565758, %rbx
movq %rbx, %xmm0
movups %xmm0, (%rsi)
nop
nop
cmp %r14, %r14
// Store
lea addresses_WT+0x1a4f8, %rsi
nop
nop
xor $31980, %r13
movw $0x5152, (%rsi)
nop
nop
nop
and $17662, %r13
// Load
lea addresses_WT+0x8802, %rbx
dec %r11
mov (%rbx), %si
nop
nop
nop
nop
sub $46031, %r12
// Faulty Load
lea addresses_US+0x7f02, %r12
nop
nop
nop
nop
add %rbx, %rbx
vmovups (%r12), %ymm1
vextracti128 $1, %ymm1, %xmm1
vpextrq $0, %xmm1, %r11
lea oracles, %r13
and $0xff, %r11
shlq $12, %r11
mov (%r13,%r11,1), %r11
pop %rsi
pop %rbx
pop %r8
pop %r14
pop %r13
pop %r12
pop %r11
ret
/*
<gen_faulty_load>
[REF]
{'OP': 'LOAD', 'src': {'type': 'addresses_US', 'AVXalign': False, 'congruent': 0, 'size': 16, 'same': True, 'NT': False}}
{'OP': 'STOR', 'dst': {'type': 'addresses_NC', 'AVXalign': False, 'congruent': 2, 'size': 16, 'same': False, 'NT': False}}
{'OP': 'STOR', 'dst': {'type': 'addresses_WT', 'AVXalign': False, 'congruent': 1, 'size': 2, 'same': False, 'NT': False}}
{'OP': 'LOAD', 'src': {'type': 'addresses_WT', 'AVXalign': False, 'congruent': 7, 'size': 2, 'same': False, 'NT': False}}
[Faulty Load]
{'OP': 'LOAD', 'src': {'type': 'addresses_US', 'AVXalign': False, 'congruent': 0, 'size': 32, 'same': True, 'NT': False}}
<gen_prepare_buffer>
{'OP': 'REPM', 'src': {'type': 'addresses_normal_ht', 'congruent': 10, 'same': True}, 'dst': {'type': 'addresses_WT_ht', 'congruent': 11, 'same': False}}
{'OP': 'REPM', 'src': {'type': 'addresses_D_ht', 'congruent': 7, 'same': False}, 'dst': {'type': 'addresses_WC_ht', 'congruent': 10, 'same': False}}
{'OP': 'STOR', 'dst': {'type': 'addresses_UC_ht', 'AVXalign': False, 'congruent': 8, 'size': 32, 'same': False, 'NT': False}}
{'OP': 'LOAD', 'src': {'type': 'addresses_UC_ht', 'AVXalign': True, 'congruent': 7, 'size': 32, 'same': False, 'NT': False}}
{'OP': 'REPM', 'src': {'type': 'addresses_WT_ht', 'congruent': 6, 'same': True}, 'dst': {'type': 'addresses_WT_ht', 'congruent': 8, 'same': False}}
{'OP': 'STOR', 'dst': {'type': 'addresses_A_ht', 'AVXalign': False, 'congruent': 11, 'size': 32, 'same': False, 'NT': False}}
{'OP': 'LOAD', 'src': {'type': 'addresses_UC_ht', 'AVXalign': False, 'congruent': 6, 'size': 32, 'same': True, 'NT': False}}
{'OP': 'LOAD', 'src': {'type': 'addresses_WT_ht', 'AVXalign': False, 'congruent': 2, 'size': 1, 'same': True, 'NT': False}}
{'OP': 'LOAD', 'src': {'type': 'addresses_UC_ht', 'AVXalign': False, 'congruent': 8, 'size': 1, 'same': False, 'NT': False}}
{'00': 21829}
00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
*/
|
#include "pch.h"
#include "Direct3D9.h"
#include "VertexBufferImpl.h"
#include <Kore/Graphics4/Graphics.h>
#include <Kore/SystemMicrosoft.h>
using namespace Kore;
Graphics4::VertexBuffer* VertexBufferImpl::_current = nullptr;
VertexBufferImpl::VertexBufferImpl(int count, int instanceDataStepRate) : myCount(count), instanceDataStepRate(instanceDataStepRate) {}
Graphics4::VertexBuffer::VertexBuffer(int count, const VertexStructure& structure, Usage usage, int instanceDataStepRate) : VertexBufferImpl(count, instanceDataStepRate) {
DWORD usageFlags = D3DUSAGE_WRITEONLY;
if (usage == Kore::Graphics4::DynamicUsage){
usageFlags = D3DUSAGE_DYNAMIC | D3DUSAGE_WRITEONLY;
}
myStride = 0;
for (int i = 0; i < structure.size; ++i) {
switch (structure.elements[i].data) {
case Float1VertexData:
myStride += 4 * 1;
break;
case Float2VertexData:
myStride += 4 * 2;
break;
case Float3VertexData:
myStride += 4 * 3;
break;
case Float4VertexData:
myStride += 4 * 4;
break;
case ColorVertexData:
myStride += 4;
break;
case Float4x4VertexData:
myStride += 4 * 4 * 4;
break;
}
}
Microsoft::affirm(device->CreateVertexBuffer(stride() * count, usageFlags, 0, D3DPOOL_DEFAULT, &vb, 0));
}
Graphics4::VertexBuffer::~VertexBuffer() {
vb->Release();
}
float* Graphics4::VertexBuffer::lock() {
return lock(0, count());
}
float* Graphics4::VertexBuffer::lock(int start, int count) {
float* vertices;
unset();
Microsoft::affirm(vb->Lock(start, count * stride(), (void**)&vertices, D3DLOCK_DISCARD));
return vertices;
}
void Graphics4::VertexBuffer::unlock() {
Microsoft::affirm(vb->Unlock());
}
int Graphics4::VertexBuffer::_set(int offset) {
_offset = offset;
if (instanceDataStepRate == 0) {
_current = this;
}
else {
Microsoft::affirm(device->SetStreamSourceFreq(offset, (D3DSTREAMSOURCE_INSTANCEDATA | instanceDataStepRate)));
}
Microsoft::affirm(device->SetStreamSource(offset, vb, 0, stride()));
return 0;
}
void VertexBufferImpl::unset() {
if (_current == (Graphics4::VertexBuffer*)this) {
Microsoft::affirm(device->SetStreamSource(0, nullptr, 0, 0));
_current = nullptr;
}
}
int Graphics4::VertexBuffer::count() {
return myCount;
}
int Graphics4::VertexBuffer::stride() {
return myStride;
}
|
;
; Grundy Newbrain Specific libraries
;
; Stefano Bodrato - 29/05/2007
;
;
; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
;
; close an open file
;
; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
;
; int close(int handle);
;
; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
;
;
; $Id: close.asm,v 1.4 2016/06/19 20:26:58 dom Exp $
;
SECTION code_clib
PUBLIC close
PUBLIC _close
EXTERN nbhandl
EXTERN nb_close
.close
._close
pop bc
pop hl
push hl
push bc
push hl
call nb_close
pop hl
ld de,100 ; we use stream numbers startimg from 100
add hl,de
ld de,nbhandl
xor a
add hl,de
ld (hl),a ; free flag for handle
ld hl,0
ret
|
#include "label.h"
Label::Label(QWidget *parent) :
QLabel(parent)
{
}
|
#include "xml/parser.hh"
#include <base/compiler.hh>
#include <fs/file.hh>
#include <iostream>
#include <stack>
#include <xml/expat.hh>
#include <xml/handlers.hh>
#include "dirs.hh"
namespace xml {
env::command vars_from(env::command&& xml_command) {
env::command result{};
result.tool = std::move(xml_command.tool);
result.args.reserve(xml_command.args.size());
for (auto& arg : xml_command.args) {
if (std::holds_alternative<std::string>(arg))
result.args.push_back(std::get<std::string>(arg));
else if (std::holds_alternative<var>(arg))
result.args.push_back(std::get<var>(arg));
else {
auto& name = std::get<named_var>(arg).value;
#define CASE(NAME) \
if (name == #NAME##sv) { \
result.args.push_back(var::NAME); \
} else
VAR(CASE)
result.args.push_back(named_var{std::move(name)});
#undef CASE
}
}
return result;
}
commands vars_from(commands&& xml_commands) {
commands result{};
result.reserve(xml_commands.size());
for (auto& command : xml_commands)
result.push_back(vars_from(std::move(command)));
return result;
}
std::optional<rule_type> rule_from(std::string_view name) {
#define CASE(NAME) \
if (name == #NAME##sv) return rule_type::NAME;
RULE(CASE)
#undef CASE
return std::nullopt;
}
std::optional<std::map<rule_type, commands>> rules_from(
std::map<std::string, commands>&& rules) {
std::optional<std::map<rule_type, commands>> result{
std::map<rule_type, commands>{}};
auto& res = *result;
for (auto& [key, value] : rules) {
auto const type = rule_from(key);
if (!type) {
std::cerr << "error: unknown rule: " << key << '\n';
result = std::nullopt;
return result;
}
res[*type] = vars_from(std::move(value));
}
static constexpr rule_type rule_ids[] = {
#define NAME(X) rule_type::X,
RULE(NAME)
#undef NAME
};
for (auto const rule : rule_ids) {
auto it = res.lower_bound(rule);
if (it == res.end() || it->first != rule) {
std::cerr << "warning: rule for ";
#define CASE(NAME) \
case rule_type::NAME: \
std::cerr << #NAME; \
break;
switch (rule) {
RULE(CASE)
default:
std::cerr << "?[" << int(rule) << ']';
};
#undef CASE
std::cerr << " missing\n";
res.insert(it, {rule, commands{}});
}
}
return result;
}
class parser : public xml::ExpatBase<parser> {
std::stack<std::unique_ptr<handler_interface>> handlers_{};
int ignore_depth_{0};
xml_config config_{};
public:
parser() { handlers_.push(std::make_unique<document_handler>()); }
static bool load(std::filesystem::path const& filename,
compiler_factory_config& output) {
auto file = fs::fopen(filename);
if (!file) return false;
xml::parser ldr{};
if (!ldr.create()) return false;
ldr.enableElementHandler();
ldr.enableCdataSectionHandler();
ldr.enableCharacterDataHandler();
ldr.config_.out = &output;
char buffer[8196];
while (auto const byte_count = file.load(buffer, sizeof(buffer))) {
ldr.parse(buffer, static_cast<int>(byte_count), false);
}
ldr.parse(buffer, 0, true);
if (output.ident.compat != u8"gcc"sv) return false;
auto rules = xml::rules_from(std::move(ldr.config_.str_rules));
if (!rules) return false;
output.rules = std::move(*rules);
return true;
}
void onStartElement(char const* name, char const** attrs) {
if (!ignore_depth_) {
auto const tag =
std::u8string_view{reinterpret_cast<char8_t const*>(name)};
auto current = handlers_.top().get();
auto next = current->onChild(tag);
if (next) {
next->onElement(config_, attrs);
handlers_.push(std::move(next));
return;
}
}
std::cerr << '[' << ignore_depth_ << "] >>> " << name;
for (auto attr = attrs; *attr; attr += 2) {
std::cerr << ' ' << attr[0] << "=\"" << attr[1] << '"';
}
std::cerr << '\n';
++ignore_depth_;
}
void onEndElement(char const* name) {
if (ignore_depth_) {
--ignore_depth_;
std::cerr << '[' << ignore_depth_ << "] <<< " << name << '\n';
return;
}
auto current = std::move(handlers_.top());
handlers_.pop();
current->onStop(config_);
}
void onCharacterData(char const* data, int length) {
if (ignore_depth_) return;
auto current = handlers_.top().get();
current->onCharacter(
std::u8string_view{reinterpret_cast<char8_t const*>(data),
static_cast<size_t>(length)});
}
};
bool parse(std::filesystem::path const& filename,
compiler_factory_config& output) {
return parser::load(filename, output);
}
} // namespace xml
|
// Copyright (c) 2010 Satoshi Nakamoto
// Copyright (c) 2009-2012 The Bitcoin developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include <boost/assign/list_of.hpp>
#include "wallet.h"
#include "walletdb.h"
#include "bitcoinrpc.h"
#include "init.h"
#include "base58.h"
using namespace std;
using namespace boost;
using namespace boost::assign;
using namespace json_spirit;
int64 nWalletUnlockTime;
static CCriticalSection cs_nWalletUnlockTime;
std::string HelpRequiringPassphrase()
{
return pwalletMain->IsCrypted()
? "\nrequires wallet passphrase to be set with walletpassphrase first"
: "";
}
void EnsureWalletIsUnlocked()
{
if (pwalletMain->IsLocked())
throw JSONRPCError(RPC_WALLET_UNLOCK_NEEDED, "Error: Please enter the wallet passphrase with walletpassphrase first.");
}
void WalletTxToJSON(const CWalletTx& wtx, Object& entry)
{
int confirms = wtx.GetDepthInMainChain();
entry.push_back(Pair("confirmations", confirms));
if (wtx.IsCoinBase())
entry.push_back(Pair("generated", true));
if (confirms)
{
entry.push_back(Pair("blockhash", wtx.hashBlock.GetHex()));
entry.push_back(Pair("blockindex", wtx.nIndex));
entry.push_back(Pair("blocktime", (boost::int64_t)(mapBlockIndex[wtx.hashBlock]->nTime)));
}
entry.push_back(Pair("txid", wtx.GetHash().GetHex()));
entry.push_back(Pair("time", (boost::int64_t)wtx.GetTxTime()));
entry.push_back(Pair("timereceived", (boost::int64_t)wtx.nTimeReceived));
BOOST_FOREACH(const PAIRTYPE(string,string)& item, wtx.mapValue)
entry.push_back(Pair(item.first, item.second));
}
string AccountFromValue(const Value& value)
{
string strAccount = value.get_str();
if (strAccount == "*")
throw JSONRPCError(RPC_WALLET_INVALID_ACCOUNT_NAME, "Invalid account name");
return strAccount;
}
Value getinfo(const Array& params, bool fHelp)
{
if (fHelp || params.size() != 0)
throw runtime_error(
"getinfo\n"
"Returns an object containing various state info.");
proxyType proxy;
GetProxy(NET_IPV4, proxy);
Object obj;
obj.push_back(Pair("version", (int)CLIENT_VERSION));
obj.push_back(Pair("protocolversion",(int)PROTOCOL_VERSION));
obj.push_back(Pair("walletversion", pwalletMain->GetVersion()));
obj.push_back(Pair("balance", ValueFromAmount(pwalletMain->GetBalance())));
obj.push_back(Pair("blocks", (int)nBestHeight));
obj.push_back(Pair("timeoffset", (boost::int64_t)GetTimeOffset()));
obj.push_back(Pair("connections", (int)vNodes.size()));
obj.push_back(Pair("proxy", (proxy.first.IsValid() ? proxy.first.ToStringIPPort() : string())));
obj.push_back(Pair("difficulty", (double)GetDifficulty()));
obj.push_back(Pair("testnet", fTestNet));
obj.push_back(Pair("keypoololdest", (boost::int64_t)pwalletMain->GetOldestKeyPoolTime()));
obj.push_back(Pair("keypoolsize", pwalletMain->GetKeyPoolSize()));
obj.push_back(Pair("paytxfee", ValueFromAmount(nTransactionFee)));
obj.push_back(Pair("mininput", ValueFromAmount(nMinimumInputValue)));
if (pwalletMain->IsCrypted())
obj.push_back(Pair("unlocked_until", (boost::int64_t)nWalletUnlockTime / 1000));
obj.push_back(Pair("errors", GetWarnings("statusbar")));
return obj;
}
Value getnewaddress(const Array& params, bool fHelp)
{
if (fHelp || params.size() > 1)
throw runtime_error(
"getnewaddress [account]\n"
"Returns a new ElliteCoin address for receiving payments. "
"If [account] is specified (recommended), it is added to the address book "
"so payments received with the address will be credited to [account].");
// Parse the account first so we don't generate a key if there's an error
string strAccount;
if (params.size() > 0)
strAccount = AccountFromValue(params[0]);
if (!pwalletMain->IsLocked())
pwalletMain->TopUpKeyPool();
// Generate a new key that is added to wallet
CPubKey newKey;
if (!pwalletMain->GetKeyFromPool(newKey, false))
throw JSONRPCError(RPC_WALLET_KEYPOOL_RAN_OUT, "Error: Keypool ran out, please call keypoolrefill first");
CKeyID keyID = newKey.GetID();
pwalletMain->SetAddressBookName(keyID, strAccount);
return CBitcoinAddress(keyID).ToString();
}
CBitcoinAddress GetAccountAddress(string strAccount, bool bForceNew=false)
{
CWalletDB walletdb(pwalletMain->strWalletFile);
CAccount account;
walletdb.ReadAccount(strAccount, account);
bool bKeyUsed = false;
// Check if the current key has been used
if (account.vchPubKey.IsValid())
{
CScript scriptPubKey;
scriptPubKey.SetDestination(account.vchPubKey.GetID());
for (map<uint256, CWalletTx>::iterator it = pwalletMain->mapWallet.begin();
it != pwalletMain->mapWallet.end() && account.vchPubKey.IsValid();
++it)
{
const CWalletTx& wtx = (*it).second;
BOOST_FOREACH(const CTxOut& txout, wtx.vout)
if (txout.scriptPubKey == scriptPubKey)
bKeyUsed = true;
}
}
// Generate a new key
if (!account.vchPubKey.IsValid() || bForceNew || bKeyUsed)
{
if (!pwalletMain->GetKeyFromPool(account.vchPubKey, false))
throw JSONRPCError(RPC_WALLET_KEYPOOL_RAN_OUT, "Error: Keypool ran out, please call keypoolrefill first");
pwalletMain->SetAddressBookName(account.vchPubKey.GetID(), strAccount);
walletdb.WriteAccount(strAccount, account);
}
return CBitcoinAddress(account.vchPubKey.GetID());
}
Value getaccountaddress(const Array& params, bool fHelp)
{
if (fHelp || params.size() != 1)
throw runtime_error(
"getaccountaddress <account>\n"
"Returns the current ElliteCoin address for receiving payments to this account.");
// Parse the account first so we don't generate a key if there's an error
string strAccount = AccountFromValue(params[0]);
Value ret;
ret = GetAccountAddress(strAccount).ToString();
return ret;
}
Value setaccount(const Array& params, bool fHelp)
{
if (fHelp || params.size() < 1 || params.size() > 2)
throw runtime_error(
"setaccount <ellitecoinaddress> <account>\n"
"Sets the account associated with the given address.");
CBitcoinAddress address(params[0].get_str());
if (!address.IsValid())
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid ElliteCoin address");
string strAccount;
if (params.size() > 1)
strAccount = AccountFromValue(params[1]);
// Detect when changing the account of an address that is the 'unused current key' of another account:
if (pwalletMain->mapAddressBook.count(address.Get()))
{
string strOldAccount = pwalletMain->mapAddressBook[address.Get()];
if (address == GetAccountAddress(strOldAccount))
GetAccountAddress(strOldAccount, true);
}
pwalletMain->SetAddressBookName(address.Get(), strAccount);
return Value::null;
}
Value getaccount(const Array& params, bool fHelp)
{
if (fHelp || params.size() != 1)
throw runtime_error(
"getaccount <ellitecoinaddress>\n"
"Returns the account associated with the given address.");
CBitcoinAddress address(params[0].get_str());
if (!address.IsValid())
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid ElliteCoin address");
string strAccount;
map<CTxDestination, string>::iterator mi = pwalletMain->mapAddressBook.find(address.Get());
if (mi != pwalletMain->mapAddressBook.end() && !(*mi).second.empty())
strAccount = (*mi).second;
return strAccount;
}
Value getaddressesbyaccount(const Array& params, bool fHelp)
{
if (fHelp || params.size() != 1)
throw runtime_error(
"getaddressesbyaccount <account>\n"
"Returns the list of addresses for the given account.");
string strAccount = AccountFromValue(params[0]);
// Find all addresses that have the given account
Array ret;
BOOST_FOREACH(const PAIRTYPE(CBitcoinAddress, string)& item, pwalletMain->mapAddressBook)
{
const CBitcoinAddress& address = item.first;
const string& strName = item.second;
if (strName == strAccount)
ret.push_back(address.ToString());
}
return ret;
}
Value setmininput(const Array& params, bool fHelp)
{
if (fHelp || params.size() < 1 || params.size() > 1)
throw runtime_error(
"setmininput <amount>\n"
"<amount> is a real and is rounded to the nearest 0.00000001");
// Amount
int64 nAmount = 0;
if (params[0].get_real() != 0.0)
nAmount = AmountFromValue(params[0]); // rejects 0.0 amounts
nMinimumInputValue = nAmount;
return true;
}
Value sendtoaddress(const Array& params, bool fHelp)
{
if (fHelp || params.size() < 2 || params.size() > 4)
throw runtime_error(
"sendtoaddress <ellitecoinaddress> <amount> [comment] [comment-to]\n"
"<amount> is a real and is rounded to the nearest 0.00000001"
+ HelpRequiringPassphrase());
CBitcoinAddress address(params[0].get_str());
if (!address.IsValid())
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid ElliteCoin address");
// Amount
int64 nAmount = AmountFromValue(params[1]);
// Wallet comments
CWalletTx wtx;
if (params.size() > 2 && params[2].type() != null_type && !params[2].get_str().empty())
wtx.mapValue["comment"] = params[2].get_str();
if (params.size() > 3 && params[3].type() != null_type && !params[3].get_str().empty())
wtx.mapValue["to"] = params[3].get_str();
if (pwalletMain->IsLocked())
throw JSONRPCError(RPC_WALLET_UNLOCK_NEEDED, "Error: Please enter the wallet passphrase with walletpassphrase first.");
string strError = pwalletMain->SendMoneyToDestination(address.Get(), nAmount, wtx);
if (strError != "")
throw JSONRPCError(RPC_WALLET_ERROR, strError);
return wtx.GetHash().GetHex();
}
Value listaddressgroupings(const Array& params, bool fHelp)
{
if (fHelp)
throw runtime_error(
"listaddressgroupings\n"
"Lists groups of addresses which have had their common ownership\n"
"made public by common use as inputs or as the resulting change\n"
"in past transactions");
Array jsonGroupings;
map<CTxDestination, int64> balances = pwalletMain->GetAddressBalances();
BOOST_FOREACH(set<CTxDestination> grouping, pwalletMain->GetAddressGroupings())
{
Array jsonGrouping;
BOOST_FOREACH(CTxDestination address, grouping)
{
Array addressInfo;
addressInfo.push_back(CBitcoinAddress(address).ToString());
addressInfo.push_back(ValueFromAmount(balances[address]));
{
LOCK(pwalletMain->cs_wallet);
if (pwalletMain->mapAddressBook.find(CBitcoinAddress(address).Get()) != pwalletMain->mapAddressBook.end())
addressInfo.push_back(pwalletMain->mapAddressBook.find(CBitcoinAddress(address).Get())->second);
}
jsonGrouping.push_back(addressInfo);
}
jsonGroupings.push_back(jsonGrouping);
}
return jsonGroupings;
}
Value signmessage(const Array& params, bool fHelp)
{
if (fHelp || params.size() != 2)
throw runtime_error(
"signmessage <ellitecoinaddress> <message>\n"
"Sign a message with the private key of an address");
EnsureWalletIsUnlocked();
string strAddress = params[0].get_str();
string strMessage = params[1].get_str();
CBitcoinAddress addr(strAddress);
if (!addr.IsValid())
throw JSONRPCError(RPC_TYPE_ERROR, "Invalid address");
CKeyID keyID;
if (!addr.GetKeyID(keyID))
throw JSONRPCError(RPC_TYPE_ERROR, "Address does not refer to key");
CKey key;
if (!pwalletMain->GetKey(keyID, key))
throw JSONRPCError(RPC_WALLET_ERROR, "Private key not available");
CHashWriter ss(SER_GETHASH, 0);
ss << strMessageMagic;
ss << strMessage;
vector<unsigned char> vchSig;
if (!key.SignCompact(ss.GetHash(), vchSig))
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Sign failed");
return EncodeBase64(&vchSig[0], vchSig.size());
}
Value verifymessage(const Array& params, bool fHelp)
{
if (fHelp || params.size() != 3)
throw runtime_error(
"verifymessage <ellitecoinaddress> <signature> <message>\n"
"Verify a signed message");
string strAddress = params[0].get_str();
string strSign = params[1].get_str();
string strMessage = params[2].get_str();
CBitcoinAddress addr(strAddress);
if (!addr.IsValid())
throw JSONRPCError(RPC_TYPE_ERROR, "Invalid address");
CKeyID keyID;
if (!addr.GetKeyID(keyID))
throw JSONRPCError(RPC_TYPE_ERROR, "Address does not refer to key");
bool fInvalid = false;
vector<unsigned char> vchSig = DecodeBase64(strSign.c_str(), &fInvalid);
if (fInvalid)
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Malformed base64 encoding");
CHashWriter ss(SER_GETHASH, 0);
ss << strMessageMagic;
ss << strMessage;
CPubKey pubkey;
if (!pubkey.RecoverCompact(ss.GetHash(), vchSig))
return false;
return (pubkey.GetID() == keyID);
}
Value getreceivedbyaddress(const Array& params, bool fHelp)
{
if (fHelp || params.size() < 1 || params.size() > 2)
throw runtime_error(
"getreceivedbyaddress <ellitecoinaddress> [minconf=1]\n"
"Returns the total amount received by <ellitecoinaddress> in transactions with at least [minconf] confirmations.");
// Bitcoin address
CBitcoinAddress address = CBitcoinAddress(params[0].get_str());
CScript scriptPubKey;
if (!address.IsValid())
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid ElliteCoin address");
scriptPubKey.SetDestination(address.Get());
if (!IsMine(*pwalletMain,scriptPubKey))
return (double)0.0;
// Minimum confirmations
int nMinDepth = 1;
if (params.size() > 1)
nMinDepth = params[1].get_int();
// Tally
int64 nAmount = 0;
for (map<uint256, CWalletTx>::iterator it = pwalletMain->mapWallet.begin(); it != pwalletMain->mapWallet.end(); ++it)
{
const CWalletTx& wtx = (*it).second;
if (wtx.IsCoinBase() || !wtx.IsFinal())
continue;
BOOST_FOREACH(const CTxOut& txout, wtx.vout)
if (txout.scriptPubKey == scriptPubKey)
if (wtx.GetDepthInMainChain() >= nMinDepth)
nAmount += txout.nValue;
}
return ValueFromAmount(nAmount);
}
void GetAccountAddresses(string strAccount, set<CTxDestination>& setAddress)
{
BOOST_FOREACH(const PAIRTYPE(CTxDestination, string)& item, pwalletMain->mapAddressBook)
{
const CTxDestination& address = item.first;
const string& strName = item.second;
if (strName == strAccount)
setAddress.insert(address);
}
}
Value getreceivedbyaccount(const Array& params, bool fHelp)
{
if (fHelp || params.size() < 1 || params.size() > 2)
throw runtime_error(
"getreceivedbyaccount <account> [minconf=1]\n"
"Returns the total amount received by addresses with <account> in transactions with at least [minconf] confirmations.");
// Minimum confirmations
int nMinDepth = 1;
if (params.size() > 1)
nMinDepth = params[1].get_int();
// Get the set of pub keys assigned to account
string strAccount = AccountFromValue(params[0]);
set<CTxDestination> setAddress;
GetAccountAddresses(strAccount, setAddress);
// Tally
int64 nAmount = 0;
for (map<uint256, CWalletTx>::iterator it = pwalletMain->mapWallet.begin(); it != pwalletMain->mapWallet.end(); ++it)
{
const CWalletTx& wtx = (*it).second;
if (wtx.IsCoinBase() || !wtx.IsFinal())
continue;
BOOST_FOREACH(const CTxOut& txout, wtx.vout)
{
CTxDestination address;
if (ExtractDestination(txout.scriptPubKey, address) && IsMine(*pwalletMain, address) && setAddress.count(address))
if (wtx.GetDepthInMainChain() >= nMinDepth)
nAmount += txout.nValue;
}
}
return (double)nAmount / (double)COIN;
}
int64 GetAccountBalance(CWalletDB& walletdb, const string& strAccount, int nMinDepth)
{
int64 nBalance = 0;
// Tally wallet transactions
for (map<uint256, CWalletTx>::iterator it = pwalletMain->mapWallet.begin(); it != pwalletMain->mapWallet.end(); ++it)
{
const CWalletTx& wtx = (*it).second;
if (!wtx.IsFinal())
continue;
int64 nReceived, nSent, nFee;
wtx.GetAccountAmounts(strAccount, nReceived, nSent, nFee);
if (nReceived != 0 && wtx.GetDepthInMainChain() >= nMinDepth)
nBalance += nReceived;
nBalance -= nSent + nFee;
}
// Tally internal accounting entries
nBalance += walletdb.GetAccountCreditDebit(strAccount);
return nBalance;
}
int64 GetAccountBalance(const string& strAccount, int nMinDepth)
{
CWalletDB walletdb(pwalletMain->strWalletFile);
return GetAccountBalance(walletdb, strAccount, nMinDepth);
}
Value getbalance(const Array& params, bool fHelp)
{
if (fHelp || params.size() > 2)
throw runtime_error(
"getbalance [account] [minconf=1]\n"
"If [account] is not specified, returns the server's total available balance.\n"
"If [account] is specified, returns the balance in the account.");
if (params.size() == 0)
return ValueFromAmount(pwalletMain->GetBalance());
int nMinDepth = 1;
if (params.size() > 1)
nMinDepth = params[1].get_int();
if (params[0].get_str() == "*") {
// Calculate total balance a different way from GetBalance()
// (GetBalance() sums up all unspent TxOuts)
// getbalance and getbalance '*' 0 should return the same number
int64 nBalance = 0;
for (map<uint256, CWalletTx>::iterator it = pwalletMain->mapWallet.begin(); it != pwalletMain->mapWallet.end(); ++it)
{
const CWalletTx& wtx = (*it).second;
if (!wtx.IsConfirmed())
continue;
int64 allFee;
string strSentAccount;
list<pair<CTxDestination, int64> > listReceived;
list<pair<CTxDestination, int64> > listSent;
wtx.GetAmounts(listReceived, listSent, allFee, strSentAccount);
if (wtx.GetDepthInMainChain() >= nMinDepth)
{
BOOST_FOREACH(const PAIRTYPE(CTxDestination,int64)& r, listReceived)
nBalance += r.second;
}
BOOST_FOREACH(const PAIRTYPE(CTxDestination,int64)& r, listSent)
nBalance -= r.second;
nBalance -= allFee;
}
return ValueFromAmount(nBalance);
}
string strAccount = AccountFromValue(params[0]);
int64 nBalance = GetAccountBalance(strAccount, nMinDepth);
return ValueFromAmount(nBalance);
}
Value movecmd(const Array& params, bool fHelp)
{
if (fHelp || params.size() < 3 || params.size() > 5)
throw runtime_error(
"move <fromaccount> <toaccount> <amount> [minconf=1] [comment]\n"
"Move from one account in your wallet to another.");
string strFrom = AccountFromValue(params[0]);
string strTo = AccountFromValue(params[1]);
int64 nAmount = AmountFromValue(params[2]);
if (params.size() > 3)
// unused parameter, used to be nMinDepth, keep type-checking it though
(void)params[3].get_int();
string strComment;
if (params.size() > 4)
strComment = params[4].get_str();
CWalletDB walletdb(pwalletMain->strWalletFile);
if (!walletdb.TxnBegin())
throw JSONRPCError(RPC_DATABASE_ERROR, "database error");
int64 nNow = GetAdjustedTime();
// Debit
CAccountingEntry debit;
debit.nOrderPos = pwalletMain->IncOrderPosNext(&walletdb);
debit.strAccount = strFrom;
debit.nCreditDebit = -nAmount;
debit.nTime = nNow;
debit.strOtherAccount = strTo;
debit.strComment = strComment;
walletdb.WriteAccountingEntry(debit);
// Credit
CAccountingEntry credit;
credit.nOrderPos = pwalletMain->IncOrderPosNext(&walletdb);
credit.strAccount = strTo;
credit.nCreditDebit = nAmount;
credit.nTime = nNow;
credit.strOtherAccount = strFrom;
credit.strComment = strComment;
walletdb.WriteAccountingEntry(credit);
if (!walletdb.TxnCommit())
throw JSONRPCError(RPC_DATABASE_ERROR, "database error");
return true;
}
Value sendfrom(const Array& params, bool fHelp)
{
if (fHelp || params.size() < 3 || params.size() > 6)
throw runtime_error(
"sendfrom <fromaccount> <toellitecoinaddress> <amount> [minconf=1] [comment] [comment-to]\n"
"<amount> is a real and is rounded to the nearest 0.00000001"
+ HelpRequiringPassphrase());
string strAccount = AccountFromValue(params[0]);
CBitcoinAddress address(params[1].get_str());
if (!address.IsValid())
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid ElliteCoin address");
int64 nAmount = AmountFromValue(params[2]);
int nMinDepth = 1;
if (params.size() > 3)
nMinDepth = params[3].get_int();
CWalletTx wtx;
wtx.strFromAccount = strAccount;
if (params.size() > 4 && params[4].type() != null_type && !params[4].get_str().empty())
wtx.mapValue["comment"] = params[4].get_str();
if (params.size() > 5 && params[5].type() != null_type && !params[5].get_str().empty())
wtx.mapValue["to"] = params[5].get_str();
EnsureWalletIsUnlocked();
// Check funds
int64 nBalance = GetAccountBalance(strAccount, nMinDepth);
if (nAmount > nBalance)
throw JSONRPCError(RPC_WALLET_INSUFFICIENT_FUNDS, "Account has insufficient funds");
// Send
string strError = pwalletMain->SendMoneyToDestination(address.Get(), nAmount, wtx);
if (strError != "")
throw JSONRPCError(RPC_WALLET_ERROR, strError);
return wtx.GetHash().GetHex();
}
Value sendmany(const Array& params, bool fHelp)
{
if (fHelp || params.size() < 2 || params.size() > 4)
throw runtime_error(
"sendmany <fromaccount> {address:amount,...} [minconf=1] [comment]\n"
"amounts are double-precision floating point numbers"
+ HelpRequiringPassphrase());
string strAccount = AccountFromValue(params[0]);
Object sendTo = params[1].get_obj();
int nMinDepth = 1;
if (params.size() > 2)
nMinDepth = params[2].get_int();
CWalletTx wtx;
wtx.strFromAccount = strAccount;
if (params.size() > 3 && params[3].type() != null_type && !params[3].get_str().empty())
wtx.mapValue["comment"] = params[3].get_str();
set<CBitcoinAddress> setAddress;
vector<pair<CScript, int64> > vecSend;
int64 totalAmount = 0;
BOOST_FOREACH(const Pair& s, sendTo)
{
CBitcoinAddress address(s.name_);
if (!address.IsValid())
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, string("Invalid ElliteCoin address: ")+s.name_);
if (setAddress.count(address))
throw JSONRPCError(RPC_INVALID_PARAMETER, string("Invalid parameter, duplicated address: ")+s.name_);
setAddress.insert(address);
CScript scriptPubKey;
scriptPubKey.SetDestination(address.Get());
int64 nAmount = AmountFromValue(s.value_);
totalAmount += nAmount;
vecSend.push_back(make_pair(scriptPubKey, nAmount));
}
EnsureWalletIsUnlocked();
// Check funds
int64 nBalance = GetAccountBalance(strAccount, nMinDepth);
if (totalAmount > nBalance)
throw JSONRPCError(RPC_WALLET_INSUFFICIENT_FUNDS, "Account has insufficient funds");
// Send
CReserveKey keyChange(pwalletMain);
int64 nFeeRequired = 0;
string strFailReason;
bool fCreated = pwalletMain->CreateTransaction(vecSend, wtx, keyChange, nFeeRequired, strFailReason);
if (!fCreated)
throw JSONRPCError(RPC_WALLET_INSUFFICIENT_FUNDS, strFailReason);
if (!pwalletMain->CommitTransaction(wtx, keyChange))
throw JSONRPCError(RPC_WALLET_ERROR, "Transaction commit failed");
return wtx.GetHash().GetHex();
}
//
// Used by addmultisigaddress / createmultisig:
//
static CScript _createmultisig(const Array& params)
{
int nRequired = params[0].get_int();
const Array& keys = params[1].get_array();
// Gather public keys
if (nRequired < 1)
throw runtime_error("a multisignature address must require at least one key to redeem");
if ((int)keys.size() < nRequired)
throw runtime_error(
strprintf("not enough keys supplied "
"(got %"PRIszu" keys, but need at least %d to redeem)", keys.size(), nRequired));
std::vector<CPubKey> pubkeys;
pubkeys.resize(keys.size());
for (unsigned int i = 0; i < keys.size(); i++)
{
const std::string& ks = keys[i].get_str();
// Case 1: ElliteCoin address and we have full public key:
CBitcoinAddress address(ks);
if (address.IsValid())
{
CKeyID keyID;
if (!address.GetKeyID(keyID))
throw runtime_error(
strprintf("%s does not refer to a key",ks.c_str()));
CPubKey vchPubKey;
if (!pwalletMain->GetPubKey(keyID, vchPubKey))
throw runtime_error(
strprintf("no full public key for address %s",ks.c_str()));
if (!vchPubKey.IsFullyValid())
throw runtime_error(" Invalid public key: "+ks);
pubkeys[i] = vchPubKey;
}
// Case 2: hex public key
else if (IsHex(ks))
{
CPubKey vchPubKey(ParseHex(ks));
if (!vchPubKey.IsFullyValid())
throw runtime_error(" Invalid public key: "+ks);
pubkeys[i] = vchPubKey;
}
else
{
throw runtime_error(" Invalid public key: "+ks);
}
}
CScript result;
result.SetMultisig(nRequired, pubkeys);
return result;
}
Value addmultisigaddress(const Array& params, bool fHelp)
{
if (fHelp || params.size() < 2 || params.size() > 3)
{
string msg = "addmultisigaddress <nrequired> <'[\"key\",\"key\"]'> [account]\n"
"Add a nrequired-to-sign multisignature address to the wallet\"\n"
"each key is a ElliteCoin address or hex-encoded public key\n"
"If [account] is specified, assign address to [account].";
throw runtime_error(msg);
}
string strAccount;
if (params.size() > 2)
strAccount = AccountFromValue(params[2]);
// Construct using pay-to-script-hash:
CScript inner = _createmultisig(params);
CScriptID innerID = inner.GetID();
pwalletMain->AddCScript(inner);
pwalletMain->SetAddressBookName(innerID, strAccount);
return CBitcoinAddress(innerID).ToString();
}
Value createmultisig(const Array& params, bool fHelp)
{
if (fHelp || params.size() < 2 || params.size() > 2)
{
string msg = "createmultisig <nrequired> <'[\"key\",\"key\"]'>\n"
"Creates a multi-signature address and returns a json object\n"
"with keys:\n"
"address : ellitecoin address\n"
"redeemScript : hex-encoded redemption script";
throw runtime_error(msg);
}
// Construct using pay-to-script-hash:
CScript inner = _createmultisig(params);
CScriptID innerID = inner.GetID();
CBitcoinAddress address(innerID);
Object result;
result.push_back(Pair("address", address.ToString()));
result.push_back(Pair("redeemScript", HexStr(inner.begin(), inner.end())));
return result;
}
struct tallyitem
{
int64 nAmount;
int nConf;
vector<uint256> txids;
tallyitem()
{
nAmount = 0;
nConf = std::numeric_limits<int>::max();
}
};
Value ListReceived(const Array& params, bool fByAccounts)
{
// Minimum confirmations
int nMinDepth = 1;
if (params.size() > 0)
nMinDepth = params[0].get_int();
// Whether to include empty accounts
bool fIncludeEmpty = false;
if (params.size() > 1)
fIncludeEmpty = params[1].get_bool();
// Tally
map<CBitcoinAddress, tallyitem> mapTally;
for (map<uint256, CWalletTx>::iterator it = pwalletMain->mapWallet.begin(); it != pwalletMain->mapWallet.end(); ++it)
{
const CWalletTx& wtx = (*it).second;
if (wtx.IsCoinBase() || !wtx.IsFinal())
continue;
int nDepth = wtx.GetDepthInMainChain();
if (nDepth < nMinDepth)
continue;
BOOST_FOREACH(const CTxOut& txout, wtx.vout)
{
CTxDestination address;
if (!ExtractDestination(txout.scriptPubKey, address) || !IsMine(*pwalletMain, address))
continue;
tallyitem& item = mapTally[address];
item.nAmount += txout.nValue;
item.nConf = min(item.nConf, nDepth);
item.txids.push_back(wtx.GetHash());
}
}
// Reply
Array ret;
map<string, tallyitem> mapAccountTally;
BOOST_FOREACH(const PAIRTYPE(CBitcoinAddress, string)& item, pwalletMain->mapAddressBook)
{
const CBitcoinAddress& address = item.first;
const string& strAccount = item.second;
map<CBitcoinAddress, tallyitem>::iterator it = mapTally.find(address);
if (it == mapTally.end() && !fIncludeEmpty)
continue;
int64 nAmount = 0;
int nConf = std::numeric_limits<int>::max();
if (it != mapTally.end())
{
nAmount = (*it).second.nAmount;
nConf = (*it).second.nConf;
}
if (fByAccounts)
{
tallyitem& item = mapAccountTally[strAccount];
item.nAmount += nAmount;
item.nConf = min(item.nConf, nConf);
}
else
{
Object obj;
obj.push_back(Pair("address", address.ToString()));
obj.push_back(Pair("account", strAccount));
obj.push_back(Pair("amount", ValueFromAmount(nAmount)));
obj.push_back(Pair("confirmations", (nConf == std::numeric_limits<int>::max() ? 0 : nConf)));
Array transactions;
if (it != mapTally.end())
{
BOOST_FOREACH(const uint256& item, (*it).second.txids)
{
transactions.push_back(item.GetHex());
}
}
obj.push_back(Pair("txids", transactions));
ret.push_back(obj);
}
}
if (fByAccounts)
{
for (map<string, tallyitem>::iterator it = mapAccountTally.begin(); it != mapAccountTally.end(); ++it)
{
int64 nAmount = (*it).second.nAmount;
int nConf = (*it).second.nConf;
Object obj;
obj.push_back(Pair("account", (*it).first));
obj.push_back(Pair("amount", ValueFromAmount(nAmount)));
obj.push_back(Pair("confirmations", (nConf == std::numeric_limits<int>::max() ? 0 : nConf)));
ret.push_back(obj);
}
}
return ret;
}
Value listreceivedbyaddress(const Array& params, bool fHelp)
{
if (fHelp || params.size() > 2)
throw runtime_error(
"listreceivedbyaddress [minconf=1] [includeempty=false]\n"
"[minconf] is the minimum number of confirmations before payments are included.\n"
"[includeempty] whether to include addresses that haven't received any payments.\n"
"Returns an array of objects containing:\n"
" \"address\" : receiving address\n"
" \"account\" : the account of the receiving address\n"
" \"amount\" : total amount received by the address\n"
" \"confirmations\" : number of confirmations of the most recent transaction included\n"
" \"txids\" : list of transactions with outputs to the address\n");
return ListReceived(params, false);
}
Value listreceivedbyaccount(const Array& params, bool fHelp)
{
if (fHelp || params.size() > 2)
throw runtime_error(
"listreceivedbyaccount [minconf=1] [includeempty=false]\n"
"[minconf] is the minimum number of confirmations before payments are included.\n"
"[includeempty] whether to include accounts that haven't received any payments.\n"
"Returns an array of objects containing:\n"
" \"account\" : the account of the receiving addresses\n"
" \"amount\" : total amount received by addresses with this account\n"
" \"confirmations\" : number of confirmations of the most recent transaction included");
return ListReceived(params, true);
}
void ListTransactions(const CWalletTx& wtx, const string& strAccount, int nMinDepth, bool fLong, Array& ret)
{
int64 nFee;
string strSentAccount;
list<pair<CTxDestination, int64> > listReceived;
list<pair<CTxDestination, int64> > listSent;
wtx.GetAmounts(listReceived, listSent, nFee, strSentAccount);
bool fAllAccounts = (strAccount == string("*"));
// Sent
if ((!listSent.empty() || nFee != 0) && (fAllAccounts || strAccount == strSentAccount))
{
BOOST_FOREACH(const PAIRTYPE(CTxDestination, int64)& s, listSent)
{
Object entry;
entry.push_back(Pair("account", strSentAccount));
entry.push_back(Pair("address", CBitcoinAddress(s.first).ToString()));
entry.push_back(Pair("category", "send"));
entry.push_back(Pair("amount", ValueFromAmount(-s.second)));
entry.push_back(Pair("fee", ValueFromAmount(-nFee)));
if (fLong)
WalletTxToJSON(wtx, entry);
ret.push_back(entry);
}
}
// Received
if (listReceived.size() > 0 && wtx.GetDepthInMainChain() >= nMinDepth)
{
BOOST_FOREACH(const PAIRTYPE(CTxDestination, int64)& r, listReceived)
{
string account;
if (pwalletMain->mapAddressBook.count(r.first))
account = pwalletMain->mapAddressBook[r.first];
if (fAllAccounts || (account == strAccount))
{
Object entry;
entry.push_back(Pair("account", account));
entry.push_back(Pair("address", CBitcoinAddress(r.first).ToString()));
if (wtx.IsCoinBase())
{
if (wtx.GetDepthInMainChain() < 1)
entry.push_back(Pair("category", "orphan"));
else if (wtx.GetBlocksToMaturity() > 0)
entry.push_back(Pair("category", "immature"));
else
entry.push_back(Pair("category", "generate"));
}
else
entry.push_back(Pair("category", "receive"));
entry.push_back(Pair("amount", ValueFromAmount(r.second)));
if (fLong)
WalletTxToJSON(wtx, entry);
ret.push_back(entry);
}
}
}
}
void AcentryToJSON(const CAccountingEntry& acentry, const string& strAccount, Array& ret)
{
bool fAllAccounts = (strAccount == string("*"));
if (fAllAccounts || acentry.strAccount == strAccount)
{
Object entry;
entry.push_back(Pair("account", acentry.strAccount));
entry.push_back(Pair("category", "move"));
entry.push_back(Pair("time", (boost::int64_t)acentry.nTime));
entry.push_back(Pair("amount", ValueFromAmount(acentry.nCreditDebit)));
entry.push_back(Pair("otheraccount", acentry.strOtherAccount));
entry.push_back(Pair("comment", acentry.strComment));
ret.push_back(entry);
}
}
Value listtransactions(const Array& params, bool fHelp)
{
if (fHelp || params.size() > 3)
throw runtime_error(
"listtransactions [account] [count=10] [from=0]\n"
"Returns up to [count] most recent transactions skipping the first [from] transactions for account [account].");
string strAccount = "*";
if (params.size() > 0)
strAccount = params[0].get_str();
int nCount = 10;
if (params.size() > 1)
nCount = params[1].get_int();
int nFrom = 0;
if (params.size() > 2)
nFrom = params[2].get_int();
if (nCount < 0)
throw JSONRPCError(RPC_INVALID_PARAMETER, "Negative count");
if (nFrom < 0)
throw JSONRPCError(RPC_INVALID_PARAMETER, "Negative from");
Array ret;
std::list<CAccountingEntry> acentries;
CWallet::TxItems txOrdered = pwalletMain->OrderedTxItems(acentries, strAccount);
// iterate backwards until we have nCount items to return:
for (CWallet::TxItems::reverse_iterator it = txOrdered.rbegin(); it != txOrdered.rend(); ++it)
{
CWalletTx *const pwtx = (*it).second.first;
if (pwtx != 0)
ListTransactions(*pwtx, strAccount, 0, true, ret);
CAccountingEntry *const pacentry = (*it).second.second;
if (pacentry != 0)
AcentryToJSON(*pacentry, strAccount, ret);
if ((int)ret.size() >= (nCount+nFrom)) break;
}
// ret is newest to oldest
if (nFrom > (int)ret.size())
nFrom = ret.size();
if ((nFrom + nCount) > (int)ret.size())
nCount = ret.size() - nFrom;
Array::iterator first = ret.begin();
std::advance(first, nFrom);
Array::iterator last = ret.begin();
std::advance(last, nFrom+nCount);
if (last != ret.end()) ret.erase(last, ret.end());
if (first != ret.begin()) ret.erase(ret.begin(), first);
std::reverse(ret.begin(), ret.end()); // Return oldest to newest
return ret;
}
Value listaccounts(const Array& params, bool fHelp)
{
if (fHelp || params.size() > 1)
throw runtime_error(
"listaccounts [minconf=1]\n"
"Returns Object that has account names as keys, account balances as values.");
int nMinDepth = 1;
if (params.size() > 0)
nMinDepth = params[0].get_int();
map<string, int64> mapAccountBalances;
BOOST_FOREACH(const PAIRTYPE(CTxDestination, string)& entry, pwalletMain->mapAddressBook) {
if (IsMine(*pwalletMain, entry.first)) // This address belongs to me
mapAccountBalances[entry.second] = 0;
}
for (map<uint256, CWalletTx>::iterator it = pwalletMain->mapWallet.begin(); it != pwalletMain->mapWallet.end(); ++it)
{
const CWalletTx& wtx = (*it).second;
int64 nFee;
string strSentAccount;
list<pair<CTxDestination, int64> > listReceived;
list<pair<CTxDestination, int64> > listSent;
wtx.GetAmounts(listReceived, listSent, nFee, strSentAccount);
mapAccountBalances[strSentAccount] -= nFee;
BOOST_FOREACH(const PAIRTYPE(CTxDestination, int64)& s, listSent)
mapAccountBalances[strSentAccount] -= s.second;
if (wtx.GetDepthInMainChain() >= nMinDepth)
{
BOOST_FOREACH(const PAIRTYPE(CTxDestination, int64)& r, listReceived)
if (pwalletMain->mapAddressBook.count(r.first))
mapAccountBalances[pwalletMain->mapAddressBook[r.first]] += r.second;
else
mapAccountBalances[""] += r.second;
}
}
list<CAccountingEntry> acentries;
CWalletDB(pwalletMain->strWalletFile).ListAccountCreditDebit("*", acentries);
BOOST_FOREACH(const CAccountingEntry& entry, acentries)
mapAccountBalances[entry.strAccount] += entry.nCreditDebit;
Object ret;
BOOST_FOREACH(const PAIRTYPE(string, int64)& accountBalance, mapAccountBalances) {
ret.push_back(Pair(accountBalance.first, ValueFromAmount(accountBalance.second)));
}
return ret;
}
Value listsinceblock(const Array& params, bool fHelp)
{
if (fHelp)
throw runtime_error(
"listsinceblock [blockhash] [target-confirmations]\n"
"Get all transactions in blocks since block [blockhash], or all transactions if omitted");
CBlockIndex *pindex = NULL;
int target_confirms = 1;
if (params.size() > 0)
{
uint256 blockId = 0;
blockId.SetHex(params[0].get_str());
pindex = CBlockLocator(blockId).GetBlockIndex();
}
if (params.size() > 1)
{
target_confirms = params[1].get_int();
if (target_confirms < 1)
throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter");
}
int depth = pindex ? (1 + nBestHeight - pindex->nHeight) : -1;
Array transactions;
for (map<uint256, CWalletTx>::iterator it = pwalletMain->mapWallet.begin(); it != pwalletMain->mapWallet.end(); it++)
{
CWalletTx tx = (*it).second;
if (depth == -1 || tx.GetDepthInMainChain() < depth)
ListTransactions(tx, "*", 0, true, transactions);
}
uint256 lastblock;
if (target_confirms == 1)
{
lastblock = hashBestChain;
}
else
{
int target_height = pindexBest->nHeight + 1 - target_confirms;
CBlockIndex *block;
for (block = pindexBest;
block && block->nHeight > target_height;
block = block->pprev) { }
lastblock = block ? block->GetBlockHash() : 0;
}
Object ret;
ret.push_back(Pair("transactions", transactions));
ret.push_back(Pair("lastblock", lastblock.GetHex()));
return ret;
}
Value gettransaction(const Array& params, bool fHelp)
{
if (fHelp || params.size() != 1)
throw runtime_error(
"gettransaction <txid>\n"
"Get detailed information about in-wallet transaction <txid>");
uint256 hash;
hash.SetHex(params[0].get_str());
Object entry;
if (!pwalletMain->mapWallet.count(hash))
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid or non-wallet transaction id");
const CWalletTx& wtx = pwalletMain->mapWallet[hash];
int64 nCredit = wtx.GetCredit();
int64 nDebit = wtx.GetDebit();
int64 nNet = nCredit - nDebit;
int64 nFee = (wtx.IsFromMe() ? wtx.GetValueOut() - nDebit : 0);
entry.push_back(Pair("amount", ValueFromAmount(nNet - nFee)));
if (wtx.IsFromMe())
entry.push_back(Pair("fee", ValueFromAmount(nFee)));
WalletTxToJSON(wtx, entry);
Array details;
ListTransactions(wtx, "*", 0, false, details);
entry.push_back(Pair("details", details));
return entry;
}
Value backupwallet(const Array& params, bool fHelp)
{
if (fHelp || params.size() != 1)
throw runtime_error(
"backupwallet <destination>\n"
"Safely copies wallet.dat to destination, which can be a directory or a path with filename.");
string strDest = params[0].get_str();
if (!BackupWallet(*pwalletMain, strDest))
throw JSONRPCError(RPC_WALLET_ERROR, "Error: Wallet backup failed!");
return Value::null;
}
Value keypoolrefill(const Array& params, bool fHelp)
{
if (fHelp || params.size() > 0)
throw runtime_error(
"keypoolrefill\n"
"Fills the keypool."
+ HelpRequiringPassphrase());
EnsureWalletIsUnlocked();
pwalletMain->TopUpKeyPool();
if (pwalletMain->GetKeyPoolSize() < GetArg("-keypool", 100))
throw JSONRPCError(RPC_WALLET_ERROR, "Error refreshing keypool.");
return Value::null;
}
void ThreadTopUpKeyPool(void* parg)
{
// Make this thread recognisable as the key-topping-up thread
RenameThread("bitcoin-key-top");
pwalletMain->TopUpKeyPool();
}
void ThreadCleanWalletPassphrase(void* parg)
{
// Make this thread recognisable as the wallet relocking thread
RenameThread("bitcoin-lock-wa");
int64 nMyWakeTime = GetTimeMillis() + *((int64*)parg) * 1000;
ENTER_CRITICAL_SECTION(cs_nWalletUnlockTime);
if (nWalletUnlockTime == 0)
{
nWalletUnlockTime = nMyWakeTime;
do
{
if (nWalletUnlockTime==0)
break;
int64 nToSleep = nWalletUnlockTime - GetTimeMillis();
if (nToSleep <= 0)
break;
LEAVE_CRITICAL_SECTION(cs_nWalletUnlockTime);
MilliSleep(nToSleep);
ENTER_CRITICAL_SECTION(cs_nWalletUnlockTime);
} while(1);
if (nWalletUnlockTime)
{
nWalletUnlockTime = 0;
pwalletMain->Lock();
}
}
else
{
if (nWalletUnlockTime < nMyWakeTime)
nWalletUnlockTime = nMyWakeTime;
}
LEAVE_CRITICAL_SECTION(cs_nWalletUnlockTime);
delete (int64*)parg;
}
Value walletpassphrase(const Array& params, bool fHelp)
{
if (pwalletMain->IsCrypted() && (fHelp || params.size() != 2))
throw runtime_error(
"walletpassphrase <passphrase> <timeout>\n"
"Stores the wallet decryption key in memory for <timeout> seconds.");
if (fHelp)
return true;
if (!pwalletMain->IsCrypted())
throw JSONRPCError(RPC_WALLET_WRONG_ENC_STATE, "Error: running with an unencrypted wallet, but walletpassphrase was called.");
if (!pwalletMain->IsLocked())
throw JSONRPCError(RPC_WALLET_ALREADY_UNLOCKED, "Error: Wallet is already unlocked.");
// Note that the walletpassphrase is stored in params[0] which is not mlock()ed
SecureString strWalletPass;
strWalletPass.reserve(100);
// TODO: get rid of this .c_str() by implementing SecureString::operator=(std::string)
// Alternately, find a way to make params[0] mlock()'d to begin with.
strWalletPass = params[0].get_str().c_str();
if (strWalletPass.length() > 0)
{
if (!pwalletMain->Unlock(strWalletPass))
throw JSONRPCError(RPC_WALLET_PASSPHRASE_INCORRECT, "Error: The wallet passphrase entered was incorrect.");
}
else
throw runtime_error(
"walletpassphrase <passphrase> <timeout>\n"
"Stores the wallet decryption key in memory for <timeout> seconds.");
NewThread(ThreadTopUpKeyPool, NULL);
int64* pnSleepTime = new int64(params[1].get_int64());
NewThread(ThreadCleanWalletPassphrase, pnSleepTime);
return Value::null;
}
Value walletpassphrasechange(const Array& params, bool fHelp)
{
if (pwalletMain->IsCrypted() && (fHelp || params.size() != 2))
throw runtime_error(
"walletpassphrasechange <oldpassphrase> <newpassphrase>\n"
"Changes the wallet passphrase from <oldpassphrase> to <newpassphrase>.");
if (fHelp)
return true;
if (!pwalletMain->IsCrypted())
throw JSONRPCError(RPC_WALLET_WRONG_ENC_STATE, "Error: running with an unencrypted wallet, but walletpassphrasechange was called.");
// TODO: get rid of these .c_str() calls by implementing SecureString::operator=(std::string)
// Alternately, find a way to make params[0] mlock()'d to begin with.
SecureString strOldWalletPass;
strOldWalletPass.reserve(100);
strOldWalletPass = params[0].get_str().c_str();
SecureString strNewWalletPass;
strNewWalletPass.reserve(100);
strNewWalletPass = params[1].get_str().c_str();
if (strOldWalletPass.length() < 1 || strNewWalletPass.length() < 1)
throw runtime_error(
"walletpassphrasechange <oldpassphrase> <newpassphrase>\n"
"Changes the wallet passphrase from <oldpassphrase> to <newpassphrase>.");
if (!pwalletMain->ChangeWalletPassphrase(strOldWalletPass, strNewWalletPass))
throw JSONRPCError(RPC_WALLET_PASSPHRASE_INCORRECT, "Error: The wallet passphrase entered was incorrect.");
return Value::null;
}
Value walletlock(const Array& params, bool fHelp)
{
if (pwalletMain->IsCrypted() && (fHelp || params.size() != 0))
throw runtime_error(
"walletlock\n"
"Removes the wallet encryption key from memory, locking the wallet.\n"
"After calling this method, you will need to call walletpassphrase again\n"
"before being able to call any methods which require the wallet to be unlocked.");
if (fHelp)
return true;
if (!pwalletMain->IsCrypted())
throw JSONRPCError(RPC_WALLET_WRONG_ENC_STATE, "Error: running with an unencrypted wallet, but walletlock was called.");
{
LOCK(cs_nWalletUnlockTime);
pwalletMain->Lock();
nWalletUnlockTime = 0;
}
return Value::null;
}
Value encryptwallet(const Array& params, bool fHelp)
{
if (!pwalletMain->IsCrypted() && (fHelp || params.size() != 1))
throw runtime_error(
"encryptwallet <passphrase>\n"
"Encrypts the wallet with <passphrase>.");
if (fHelp)
return true;
if (pwalletMain->IsCrypted())
throw JSONRPCError(RPC_WALLET_WRONG_ENC_STATE, "Error: running with an encrypted wallet, but encryptwallet was called.");
// TODO: get rid of this .c_str() by implementing SecureString::operator=(std::string)
// Alternately, find a way to make params[0] mlock()'d to begin with.
SecureString strWalletPass;
strWalletPass.reserve(100);
strWalletPass = params[0].get_str().c_str();
if (strWalletPass.length() < 1)
throw runtime_error(
"encryptwallet <passphrase>\n"
"Encrypts the wallet with <passphrase>.");
if (!pwalletMain->EncryptWallet(strWalletPass))
throw JSONRPCError(RPC_WALLET_ENCRYPTION_FAILED, "Error: Failed to encrypt the wallet.");
// BDB seems to have a bad habit of writing old data into
// slack space in .dat files; that is bad if the old data is
// unencrypted private keys. So:
StartShutdown();
return "wallet encrypted; ElliteCoin server stopping, restart to run with encrypted wallet. The keypool has been flushed, you need to make a new backup.";
}
class DescribeAddressVisitor : public boost::static_visitor<Object>
{
public:
Object operator()(const CNoDestination &dest) const { return Object(); }
Object operator()(const CKeyID &keyID) const {
Object obj;
CPubKey vchPubKey;
pwalletMain->GetPubKey(keyID, vchPubKey);
obj.push_back(Pair("isscript", false));
obj.push_back(Pair("pubkey", HexStr(vchPubKey)));
obj.push_back(Pair("iscompressed", vchPubKey.IsCompressed()));
return obj;
}
Object operator()(const CScriptID &scriptID) const {
Object obj;
obj.push_back(Pair("isscript", true));
CScript subscript;
pwalletMain->GetCScript(scriptID, subscript);
std::vector<CTxDestination> addresses;
txnouttype whichType;
int nRequired;
ExtractDestinations(subscript, whichType, addresses, nRequired);
obj.push_back(Pair("script", GetTxnOutputType(whichType)));
Array a;
BOOST_FOREACH(const CTxDestination& addr, addresses)
a.push_back(CBitcoinAddress(addr).ToString());
obj.push_back(Pair("addresses", a));
if (whichType == TX_MULTISIG)
obj.push_back(Pair("sigsrequired", nRequired));
return obj;
}
};
Value validateaddress(const Array& params, bool fHelp)
{
if (fHelp || params.size() != 1)
throw runtime_error(
"validateaddress <ellitecoinaddress>\n"
"Return information about <ellitecoinaddress>.");
CBitcoinAddress address(params[0].get_str());
bool isValid = address.IsValid();
Object ret;
ret.push_back(Pair("isvalid", isValid));
if (isValid)
{
CTxDestination dest = address.Get();
string currentAddress = address.ToString();
ret.push_back(Pair("address", currentAddress));
bool fMine = IsMine(*pwalletMain, dest);
ret.push_back(Pair("ismine", fMine));
if (fMine) {
Object detail = boost::apply_visitor(DescribeAddressVisitor(), dest);
ret.insert(ret.end(), detail.begin(), detail.end());
}
if (pwalletMain->mapAddressBook.count(dest))
ret.push_back(Pair("account", pwalletMain->mapAddressBook[dest]));
}
return ret;
}
Value lockunspent(const Array& params, bool fHelp)
{
if (fHelp || params.size() < 1 || params.size() > 2)
throw runtime_error(
"lockunspent unlock? [array-of-Objects]\n"
"Updates list of temporarily unspendable outputs.");
if (params.size() == 1)
RPCTypeCheck(params, list_of(bool_type));
else
RPCTypeCheck(params, list_of(bool_type)(array_type));
bool fUnlock = params[0].get_bool();
if (params.size() == 1) {
if (fUnlock)
pwalletMain->UnlockAllCoins();
return true;
}
Array outputs = params[1].get_array();
BOOST_FOREACH(Value& output, outputs)
{
if (output.type() != obj_type)
throw JSONRPCError(-8, "Invalid parameter, expected object");
const Object& o = output.get_obj();
RPCTypeCheck(o, map_list_of("txid", str_type)("vout", int_type));
string txid = find_value(o, "txid").get_str();
if (!IsHex(txid))
throw JSONRPCError(-8, "Invalid parameter, expected hex txid");
int nOutput = find_value(o, "vout").get_int();
if (nOutput < 0)
throw JSONRPCError(-8, "Invalid parameter, vout must be positive");
COutPoint outpt(uint256(txid), nOutput);
if (fUnlock)
pwalletMain->UnlockCoin(outpt);
else
pwalletMain->LockCoin(outpt);
}
return true;
}
Value listlockunspent(const Array& params, bool fHelp)
{
if (fHelp || params.size() > 0)
throw runtime_error(
"listlockunspent\n"
"Returns list of temporarily unspendable outputs.");
vector<COutPoint> vOutpts;
pwalletMain->ListLockedCoins(vOutpts);
Array ret;
BOOST_FOREACH(COutPoint &outpt, vOutpts) {
Object o;
o.push_back(Pair("txid", outpt.hash.GetHex()));
o.push_back(Pair("vout", (int)outpt.n));
ret.push_back(o);
}
return ret;
}
|
; A189673: Fixed point of the morphism 0->010, 1->110.
; 0,1,0,1,1,0,0,1,0,1,1,0,1,1,0,0,1,0,0,1,0,1,1,0,0,1,0,1,1,0,1,1,0,0,1,0,1,1,0,1,1,0,0,1,0,0,1,0,1,1,0,0,1,0,0,1,0,1,1,0,0,1,0,1,1,0,1,1,0,0,1,0,0,1,0,1,1,0,0,1,0,1,1,0,1,1,0,0,1,0,1,1,0,1,1,0,0,1,0,0,1,0,1,1,0,0,1,0,1,1,0,1,1,0,0,1,0,1,1,0,1,1,0,0,1,0,0,1,0,1,1,0,0,1,0,0,1,0,1,1,0,0,1,0,1,1,0,1,1,0,0,1,0,0,1,0,1,1,0,0,1,0,0,1,0,1,1,0,0,1,0,1,1,0,1,1,0,0,1,0,0,1,0,1,1,0,0,1,0,1,1,0,1,1,0,0,1,0,1,1,0,1,1,0,0,1,0,0,1,0,1,1,0,0,1,0,0,1,0,1,1,0,0,1,0,1,1,0,1,1,0,0,1,0,0,1,0,1,1,0,0,1,0,1,1,0,1,1,0,0
mul $0,48
mov $3,$0
sub $3,3
lpb $0,1
mov $1,$3
mov $3,$0
mov $0,$1
mov $1,7
div $3,3
lpe
sub $0,3
gcd $0,2
lpb $0,1
sub $0,1
mul $0,14
mov $1,$2
lpe
div $1,7
|
;/*
; FreeRTOS V9.0.0rc2 - Copyright (C) 2016 Real Time Engineers Ltd.
; All rights reserved
;
;
; ***************************************************************************
; * *
; * FreeRTOS tutorial books are available in pdf and paperback. *
; * Complete, revised, and edited pdf reference manuals are also *
; * available. *
; * *
; * Purchasing FreeRTOS documentation will not only help you, by *
; * ensuring you get running as quickly as possible and with an *
; * in-depth knowledge of how to use FreeRTOS, it will also help *
; * the FreeRTOS project to continue with its mission of providing *
; * professional grade, cross platform, de facto standard solutions *
; * for microcontrollers - completely free of charge! *
; * *
; * >>> See http://www.FreeRTOS.org/Documentation for details. <<< *
; * *
; * Thank you for using FreeRTOS, and thank you for your support! *
; * *
; ***************************************************************************
;
;
; This file is part of the FreeRTOS distribution.
;
; FreeRTOS is free software; you can redistribute it and/or modify it under
; the terms of the GNU General Public License (version 2) as published by the
; Free Software Foundation AND MODIFIED BY the FreeRTOS exception.
; >>>NOTE<<< The modification to the GPL is included to allow you to
; distribute a combined work that includes FreeRTOS without being obliged to
; provide the source code for proprietary components outside of the FreeRTOS
; kernel. FreeRTOS 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 and the FreeRTOS license exception along with FreeRTOS; if not it
; can be viewed here: http://www.freertos.org/a00114.html and also obtained
; by writing to Richard Barry, contact details for whom are available on the
; FreeRTOS WEB site.
;
; 1 tab == 4 spaces!
;
; http://www.FreeRTOS.org - Documentation, latest information, license and
; contact details.
;
; http://www.SafeRTOS.com - A version that is certified for use in safety
; critical systems.
;
; http://www.OpenRTOS.com - Commercial support, development, porting,
; licensing and training services.
;*/
.text
.arm
.ref vTaskSwitchContext
.ref xTaskIncrementTick
.ref ulTaskHasFPUContext
.ref pxCurrentTCB
;/*-----------------------------------------------------------*/
;
; Save Task Context
;
portSAVE_CONTEXT .macro
DSB
; Push R0 as we are going to use it
STMDB SP!, {R0}
; Set R0 to point to the task stack pointer.
STMDB SP,{SP}^
SUB SP, SP, #4
LDMIA SP!,{R0}
; Push the return address onto the stack.
STMDB R0!, {LR}
; Now LR has been saved, it can be used instead of R0.
MOV LR, R0
; Pop R0 so it can be saved onto the task stack.
LDMIA SP!, {R0}
; Push all the system mode registers onto the task stack.
STMDB LR,{R0-LR}^
SUB LR, LR, #60
; Push the SPSR onto the task stack.
MRS R0, SPSR
STMDB LR!, {R0}
.if (__TI_VFP_SUPPORT__)
;Determine if the task maintains an FPU context.
LDR R0, ulFPUContextConst
LDR R0, [R0]
; Test the flag
CMP R0, #0
; If the task is not using a floating point context then skip the
; saving of the FPU registers.
BEQ $+16
FSTMDBD LR!, {D0-D15}
FMRX R1, FPSCR
STMFD LR!, {R1}
; Save the flag
STMDB LR!, {R0}
.endif
; Store the new top of stack for the task.
LDR R0, pxCurrentTCBConst
LDR R0, [R0]
STR LR, [R0]
.endm
;/*-----------------------------------------------------------*/
;
; Restore Task Context
;
portRESTORE_CONTEXT .macro
LDR R0, pxCurrentTCBConst
LDR R0, [R0]
LDR LR, [R0]
.if (__TI_VFP_SUPPORT__)
; The floating point context flag is the first thing on the stack.
LDR R0, ulFPUContextConst
LDMFD LR!, {R1}
STR R1, [R0]
; Test the flag
CMP R1, #0
; If the task is not using a floating point context then skip the
; VFP register loads.
BEQ $+16
; Restore the floating point context.
LDMFD LR!, {R0}
FLDMIAD LR!, {D0-D15}
FMXR FPSCR, R0
.endif
; Get the SPSR from the stack.
LDMFD LR!, {R0}
MSR SPSR_CSXF, R0
; Restore all system mode registers for the task.
LDMFD LR, {R0-R14}^
; Restore the return address.
LDR LR, [LR, #+60]
; And return - correcting the offset in the LR to obtain the
; correct address.
SUBS PC, LR, #4
.endm
;/*-----------------------------------------------------------*/
; Start the first task by restoring its context.
.def vPortStartFirstTask
vPortStartFirstTask:
portRESTORE_CONTEXT
;/*-----------------------------------------------------------*/
; Yield to another task.
.def vPortYieldProcessor
vPortYieldProcessor:
; Within an IRQ ISR the link register has an offset from the true return
; address. SWI doesn't do this. Add the offset manually so the ISR
; return code can be used.
ADD LR, LR, #4
; First save the context of the current task.
portSAVE_CONTEXT
; Select the next task to execute. */
BL vTaskSwitchContext
; Restore the context of the task selected to execute.
portRESTORE_CONTEXT
;/*-----------------------------------------------------------*/
; Yield to another task from within the FreeRTOS API
.def vPortYeildWithinAPI
vPortYeildWithinAPI:
; Save the context of the current task.
portSAVE_CONTEXT
; Clear SSI flag.
MOVW R0, #0xFFF4
MOVT R0, #0xFFFF
LDR R0, [R0]
; Select the next task to execute. */
BL vTaskSwitchContext
; Restore the context of the task selected to execute.
portRESTORE_CONTEXT
;/*-----------------------------------------------------------*/
; Preemptive Tick
.def vPortPreemptiveTick
vPortPreemptiveTick:
; Save the context of the current task.
portSAVE_CONTEXT
; Clear interrupt flag
MOVW R0, #0xFC88
MOVT R0, #0xFFFF
MOV R1, #1
STR R1, [R0]
; Increment the tick count, making any adjustments to the blocked lists
; that may be necessary.
BL xTaskIncrementTick
; Select the next task to execute.
CMP R0, #0
BLNE vTaskSwitchContext
; Restore the context of the task selected to execute.
portRESTORE_CONTEXT
;-------------------------------------------------------------------------------
.if (__TI_VFP_SUPPORT__)
.def vPortInitialiseFPSCR
vPortInitialiseFPSCR:
MOV R0, #0
FMXR FPSCR, R0
BX LR
.endif ;__TI_VFP_SUPPORT__
pxCurrentTCBConst .word pxCurrentTCB
ulFPUContextConst .word ulTaskHasFPUContext
;-------------------------------------------------------------------------------
|
//===--- SILLayout.cpp - Defines SIL-level aggregate layouts --------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
//
// This file defines classes that describe the physical layout of nominal
// types in SIL, including structs, classes, and boxes. This is distinct from
// the AST-level layout for several reasons:
// - It avoids redundant work lowering the layout of aggregates from the AST.
// - It allows optimizations to manipulate the layout of aggregates without
// requiring changes to the AST. For instance, optimizations can eliminate
// dead fields from instances or turn invariant fields into global variables.
// - It allows for SIL-only aggregates to exist, such as boxes.
// - It improves the robustness of code in the face of resilience. A resilient
// type can be modeled in SIL as not having a layout at all, preventing the
// inappropriate use of fragile projection and injection operations on the
// type.
//
//===----------------------------------------------------------------------===//
#include "swift/AST/ASTContext.h"
#include "swift/AST/SILLayout.h"
#include "swift/AST/GenericSignature.h"
#include "swift/AST/Types.h"
#include "swift/Basic/Range.h"
using namespace swift;
static bool anyMutable(ArrayRef<SILField> Fields) {
for (auto &field : Fields) {
if (field.isMutable())
return true;
}
return false;
}
#ifndef NDEBUG
/// Verify that the types of fields are valid within a given generic signature.
static void verifyFields(CanGenericSignature Sig, ArrayRef<SILField> Fields) {
for (auto &field : Fields) {
auto ty = field.getLoweredType();
// Layouts should never refer to archetypes, since they represent an
// abstract generic type layout.
assert(!ty->hasArchetype()
&& "SILLayout field cannot have an archetype type");
assert(!ty->hasTypeVariable()
&& "SILLayout cannot contain constraint system type variables");
assert(!ty->hasHole() &&
"SILLayout cannot contain constraint system type holes");
if (!ty->hasTypeParameter())
continue;
field.getLoweredType().findIf([Sig](Type t) -> bool {
if (auto gpt = t->getAs<GenericTypeParamType>()) {
// Check that the generic param exists in the generic signature.
assert(Sig && "generic param in nongeneric layout?");
assert(std::find(Sig.getGenericParams().begin(),
Sig.getGenericParams().end(),
gpt->getCanonicalType()) != Sig.getGenericParams().end()
&& "generic param not declared in generic signature?!");
}
return false;
});
}
}
#endif
SILLayout::SILLayout(CanGenericSignature Sig,
ArrayRef<SILField> Fields)
: GenericSigAndFlags(Sig, getFlagsValue(anyMutable(Fields))),
NumFields(Fields.size())
{
#ifndef NDEBUG
verifyFields(Sig, Fields);
#endif
auto FieldsMem = getTrailingObjects<SILField>();
for (unsigned i : indices(Fields)) {
new (FieldsMem + i) SILField(Fields[i]);
}
}
void SILLayout::Profile(llvm::FoldingSetNodeID &id,
CanGenericSignature Generics,
ArrayRef<SILField> Fields) {
id.AddPointer(Generics.getPointer());
for (auto &field : Fields) {
id.AddPointer(field.getLoweredType().getPointer());
id.AddBoolean(field.isMutable());
}
}
|
//===--- CodeCompletion.cpp - Code completion implementation --------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
#include "swift/IDE/CodeCompletion.h"
#include "CodeCompletionResultBuilder.h"
#include "swift/AST/ASTPrinter.h"
#include "swift/AST/ASTWalker.h"
#include "swift/AST/Comment.h"
#include "swift/AST/Initializer.h"
#include "swift/AST/GenericSignature.h"
#include "swift/AST/LazyResolver.h"
#include "swift/AST/NameLookup.h"
#include "swift/AST/ParameterList.h"
#include "swift/AST/ProtocolConformance.h"
#include "swift/AST/SubstitutionMap.h"
#include "swift/AST/USRGeneration.h"
#include "swift/Basic/Defer.h"
#include "swift/Basic/LLVM.h"
#include "swift/ClangImporter/ClangImporter.h"
#include "swift/ClangImporter/ClangModule.h"
#include "swift/IDE/CodeCompletionCache.h"
#include "swift/IDE/Utils.h"
#include "swift/Parse/CodeCompletionCallbacks.h"
#include "swift/Sema/IDETypeChecking.h"
#include "swift/Subsystems.h"
#include "clang/AST/ASTContext.h"
#include "clang/AST/Attr.h"
#include "clang/AST/Comment.h"
#include "clang/AST/CommentVisitor.h"
#include "clang/AST/Decl.h"
#include "clang/Basic/Module.h"
#include "clang/Index/USRGeneration.h"
#include "llvm/ADT/SmallString.h"
#include "llvm/ADT/StringRef.h"
#include "llvm/Support/Compiler.h"
#include "llvm/Support/raw_ostream.h"
#include "llvm/Support/SaveAndRestore.h"
#include <algorithm>
#include <string>
using namespace swift;
using namespace ide;
using CommandWordsPairs = std::vector<std::pair<StringRef, StringRef>>;
enum CodeCompletionCommandKind {
none,
keyword,
recommended,
recommendedover,
mutatingvariant,
nonmutatingvariant,
};
CodeCompletionCommandKind getCommandKind(StringRef Command) {
#define CHECK_CASE(KIND) \
if (Command == #KIND) \
return CodeCompletionCommandKind::KIND;
CHECK_CASE(keyword);
CHECK_CASE(recommended);
CHECK_CASE(recommendedover);
CHECK_CASE(mutatingvariant);
CHECK_CASE(nonmutatingvariant);
#undef CHECK_CASE
return CodeCompletionCommandKind::none;
}
StringRef getCommandName(CodeCompletionCommandKind Kind) {
#define CHECK_CASE(KIND) \
if (CodeCompletionCommandKind::KIND == Kind) { \
static std::string Name(#KIND); \
return Name; \
}
CHECK_CASE(keyword)
CHECK_CASE(recommended)
CHECK_CASE(recommendedover)
CHECK_CASE(mutatingvariant);
CHECK_CASE(nonmutatingvariant);
#undef CHECK_CASE
llvm_unreachable("Cannot handle this Kind.");
}
bool containsInterestedWords(StringRef Content, StringRef Splitter,
bool AllowWhitespace) {
do {
Content = Content.split(Splitter).second;
Content = AllowWhitespace ? Content.trim() : Content;
#define CHECK_CASE(KIND) \
if (Content.startswith(#KIND)) \
return true;
CHECK_CASE(keyword)
CHECK_CASE(recommended)
CHECK_CASE(recommendedover)
CHECK_CASE(mutatingvariant);
CHECK_CASE(nonmutatingvariant);
#undef CHECK_CASE
} while (!Content.empty());
return false;
}
void splitTextByComma(StringRef Text, std::vector<StringRef>& Subs) {
do {
auto Pair = Text.split(',');
auto Key = Pair.first.trim();
if (!Key.empty())
Subs.push_back(Key);
Text = Pair.second;
} while (!Text.empty());
}
namespace clang {
namespace comments {
class WordPairsArrangedViewer {
ArrayRef<std::pair<StringRef, StringRef>> Content;
std::vector<StringRef> ViewedText;
std::vector<StringRef> Words;
StringRef Key;
bool isKeyViewed(StringRef K) {
return std::find(ViewedText.begin(), ViewedText.end(), K) != ViewedText.end();
}
public:
WordPairsArrangedViewer(ArrayRef<std::pair<StringRef, StringRef>> Content):
Content(Content) {}
bool hasNext() {
Words.clear();
bool Found = false;
for (auto P : Content) {
if (!Found && !isKeyViewed(P.first)) {
Key = P.first;
Found = true;
}
if (Found && P.first == Key)
Words.push_back(P.second);
}
return Found;
}
std::pair<StringRef, ArrayRef<StringRef>> next() {
bool HasNext = hasNext();
(void) HasNext;
assert(HasNext && "Have no more data.");
ViewedText.push_back(Key);
return std::make_pair(Key, llvm::makeArrayRef(Words));
}
};
class ClangCommentExtractor : public ConstCommentVisitor<ClangCommentExtractor> {
CommandWordsPairs &Words;
const CommandTraits &Traits;
std::vector<const Comment *> Parents;
void visitChildren(const Comment* C) {
Parents.push_back(C);
for (auto It = C->child_begin(); It != C->child_end(); ++ It)
visit(*It);
Parents.pop_back();
}
public:
ClangCommentExtractor(CommandWordsPairs &Words,
const CommandTraits &Traits) : Words(Words),
Traits(Traits) {}
#define CHILD_VISIT(NAME) \
void visit##NAME(const NAME *C) {\
visitChildren(C);\
}
CHILD_VISIT(FullComment)
CHILD_VISIT(ParagraphComment)
#undef CHILD_VISIT
void visitInlineCommandComment(const InlineCommandComment *C) {
auto Command = C->getCommandName(Traits);
auto CommandKind = getCommandKind(Command);
if (CommandKind == CodeCompletionCommandKind::none)
return;
auto &Parent = Parents.back();
for (auto CIT = std::find(Parent->child_begin(), Parent->child_end(), C) + 1;
CIT != Parent->child_end(); CIT++) {
if (auto TC = dyn_cast<TextComment>(*CIT)) {
auto Text = TC->getText();
std::vector<StringRef> Subs;
splitTextByComma(Text, Subs);
auto Kind = getCommandName(CommandKind);
for (auto S : Subs)
Words.push_back(std::make_pair(Kind, S));
} else
break;
}
}
};
void getClangDocKeyword(ClangImporter &Importer, const Decl *D,
CommandWordsPairs &Words) {
ClangCommentExtractor Extractor(Words, Importer.getClangASTContext().
getCommentCommandTraits());
if (auto RC = Importer.getClangASTContext().getRawCommentForAnyRedecl(D)) {
auto RT = RC->getRawText(Importer.getClangASTContext().getSourceManager());
if (containsInterestedWords(RT, "@", /*AllowWhitespace*/false)) {
FullComment* Comment = Importer.getClangASTContext().
getLocalCommentForDeclUncached(D);
Extractor.visit(Comment);
}
}
}
} // end namespace comments
} // end namespace clang
namespace swift {
namespace markup {
class SwiftDocWordExtractor : public MarkupASTWalker {
CommandWordsPairs &Pairs;
CodeCompletionCommandKind Kind;
public:
SwiftDocWordExtractor(CommandWordsPairs &Pairs) :
Pairs(Pairs), Kind(CodeCompletionCommandKind::none) {}
void visitKeywordField(const KeywordField *Field) override {
Kind = CodeCompletionCommandKind::keyword;
}
void visitRecommendedField(const RecommendedField *Field) override {
Kind = CodeCompletionCommandKind::recommended;
}
void visitRecommendedoverField(const RecommendedoverField *Field) override {
Kind = CodeCompletionCommandKind::recommendedover;
}
void visitMutatingvariantField(const MutatingvariantField *Field) override {
Kind = CodeCompletionCommandKind::mutatingvariant;
}
void visitNonmutatingvariantField(const NonmutatingvariantField *Field) override {
Kind = CodeCompletionCommandKind::nonmutatingvariant;
}
void visitText(const Text *Text) override {
if (Kind == CodeCompletionCommandKind::none)
return;
StringRef CommandName = getCommandName(Kind);
std::vector<StringRef> Subs;
splitTextByComma(Text->str(), Subs);
for (auto S : Subs)
Pairs.push_back(std::make_pair(CommandName, S));
}
};
void getSwiftDocKeyword(const Decl* D, CommandWordsPairs &Words) {
auto Interested = false;
for (auto C : D->getRawComment().Comments) {
if (containsInterestedWords(C.RawText, "-", /*AllowWhitespace*/true)) {
Interested = true;
break;
}
}
if (!Interested)
return;
static swift::markup::MarkupContext MC;
auto DC = getSingleDocComment(MC, D);
if (!DC.hasValue())
return;
SwiftDocWordExtractor Extractor(Words);
for (auto Part : DC.getValue()->getBodyNodes()) {
switch (Part->getKind()) {
case ASTNodeKind::KeywordField:
case ASTNodeKind::RecommendedField:
case ASTNodeKind::RecommendedoverField:
case ASTNodeKind::MutatingvariantField:
case ASTNodeKind::NonmutatingvariantField:
Extractor.walk(Part);
break;
default:
break;
}
}
}
} // end namespace markup
} // end namespace swift
static bool shouldHideDeclFromCompletionResults(const ValueDecl *D) {
// Hide private stdlib declarations.
if (D->isPrivateStdlibDecl(/*treatNonBuiltinProtocolsAsPublic*/false) ||
// ShowInInterfaceAttr is for decls to show in interface as exception but
// they are not intended to be used directly.
D->getAttrs().hasAttribute<ShowInInterfaceAttr>())
return true;
if (AvailableAttr::isUnavailable(D))
return true;
if (auto *ClangD = D->getClangDecl()) {
if (ClangD->hasAttr<clang::SwiftPrivateAttr>())
return true;
}
// Hide editor placeholders.
if (D->getBaseName().isEditorPlaceholder())
return true;
if (!D->isUserAccessible())
return true;
return false;
}
using DeclFilter = std::function<bool(ValueDecl *, DeclVisibilityKind)>;
static bool DefaultFilter(ValueDecl* VD, DeclVisibilityKind Kind) {
return true;
}
static bool KeyPathFilter(ValueDecl* decl, DeclVisibilityKind) {
return isa<TypeDecl>(decl) ||
(isa<VarDecl>(decl) && decl->getDeclContext()->isTypeContext());
}
static bool SwiftKeyPathFilter(ValueDecl* decl, DeclVisibilityKind) {
switch(decl->getKind()){
case DeclKind::Var:
case DeclKind::Subscript:
return true;
default:
return false;
}
}
std::string swift::ide::removeCodeCompletionTokens(
StringRef Input, StringRef TokenName, unsigned *CompletionOffset) {
assert(TokenName.size() >= 1);
*CompletionOffset = ~0U;
std::string CleanFile;
CleanFile.reserve(Input.size());
const std::string Token = std::string("#^") + TokenName.str() + "^#";
for (const char *Ptr = Input.begin(), *End = Input.end();
Ptr != End; ++Ptr) {
const char C = *Ptr;
if (C == '#' && Ptr <= End - Token.size() &&
StringRef(Ptr, Token.size()) == Token) {
Ptr += Token.size() - 1;
*CompletionOffset = CleanFile.size();
CleanFile += '\0';
continue;
}
if (C == '#' && Ptr <= End - 2 && Ptr[1] == '^') {
do {
Ptr++;
} while (Ptr < End && *Ptr != '#');
if (Ptr == End)
break;
continue;
}
CleanFile += C;
}
return CleanFile;
}
namespace {
class StmtFinder : public ASTWalker {
SourceManager &SM;
SourceLoc Loc;
StmtKind Kind;
Stmt *Found = nullptr;
public:
StmtFinder(SourceManager &SM, SourceLoc Loc, StmtKind Kind)
: SM(SM), Loc(Loc), Kind(Kind) {}
std::pair<bool, Stmt *> walkToStmtPre(Stmt *S) override {
return { SM.rangeContainsTokenLoc(S->getSourceRange(), Loc), S };
}
Stmt *walkToStmtPost(Stmt *S) override {
if (S->getKind() == Kind) {
Found = S;
return nullptr;
}
return S;
}
Stmt *getFoundStmt() const {
return Found;
}
};
} // end anonymous namespace
static Stmt *findNearestStmt(const AbstractFunctionDecl *AFD, SourceLoc Loc,
StmtKind Kind) {
auto &SM = AFD->getASTContext().SourceMgr;
assert(SM.rangeContainsTokenLoc(AFD->getSourceRange(), Loc));
StmtFinder Finder(SM, Loc, Kind);
// FIXME(thread-safety): the walker is mutating the AST.
const_cast<AbstractFunctionDecl *>(AFD)->walk(Finder);
return Finder.getFoundStmt();
}
/// Prepare the given expression for type-checking again, prinicipally by
/// erasing any ErrorType types on the given expression, allowing later
/// type-checking to make progress.
///
/// FIXME: this is fundamentally a workaround for the fact that we may end up
/// typechecking parts of an expression more than once - first for checking
/// the context, and later for checking more-specific things like unresolved
/// members. We should restructure code-completion type-checking so that we
/// never typecheck more than once (or find a more principled way to do it).
static void prepareForRetypechecking(Expr *E) {
assert(E);
struct Eraser : public ASTWalker {
std::pair<bool, Expr *> walkToExprPre(Expr *expr) override {
if (expr && expr->getType() && expr->getType()->hasError())
expr->setType(Type());
if (auto *ACE = dyn_cast_or_null<AutoClosureExpr>(expr)) {
return { true, ACE->getSingleExpressionBody() };
}
return { true, expr };
}
bool walkToTypeLocPre(TypeLoc &TL) override {
if (TL.getType() && TL.getType()->hasError())
TL.setType(Type(), /*was validated*/false);
return true;
}
std::pair<bool, Pattern*> walkToPatternPre(Pattern *P) override {
if (P && P->hasType() && P->getType()->hasError()) {
P->setType(Type());
}
return { true, P };
}
std::pair<bool, Stmt *> walkToStmtPre(Stmt *S) override {
return { false, S };
}
};
E->walk(Eraser());
}
CodeCompletionString::CodeCompletionString(ArrayRef<Chunk> Chunks) {
std::uninitialized_copy(Chunks.begin(), Chunks.end(),
getTrailingObjects<Chunk>());
NumChunks = Chunks.size();
}
CodeCompletionString *CodeCompletionString::create(llvm::BumpPtrAllocator &Allocator,
ArrayRef<Chunk> Chunks) {
void *CCSMem = Allocator.Allocate(totalSizeToAlloc<Chunk>(Chunks.size()),
alignof(CodeCompletionString));
return new (CCSMem) CodeCompletionString(Chunks);
}
void CodeCompletionString::print(raw_ostream &OS) const {
unsigned PrevNestingLevel = 0;
for (auto C : getChunks()) {
bool AnnotatedTextChunk = false;
if (C.getNestingLevel() < PrevNestingLevel) {
OS << "#}";
}
switch (C.getKind()) {
using ChunkKind = Chunk::ChunkKind;
case ChunkKind::AccessControlKeyword:
case ChunkKind::DeclAttrKeyword:
case ChunkKind::DeclAttrParamKeyword:
case ChunkKind::OverrideKeyword:
case ChunkKind::ThrowsKeyword:
case ChunkKind::RethrowsKeyword:
case ChunkKind::DeclIntroducer:
case ChunkKind::Text:
case ChunkKind::LeftParen:
case ChunkKind::RightParen:
case ChunkKind::LeftBracket:
case ChunkKind::RightBracket:
case ChunkKind::LeftAngle:
case ChunkKind::RightAngle:
case ChunkKind::Dot:
case ChunkKind::Ellipsis:
case ChunkKind::Comma:
case ChunkKind::ExclamationMark:
case ChunkKind::QuestionMark:
case ChunkKind::Ampersand:
case ChunkKind::Equal:
case ChunkKind::Whitespace:
AnnotatedTextChunk = C.isAnnotation();
LLVM_FALLTHROUGH;
case ChunkKind::CallParameterName:
case ChunkKind::CallParameterInternalName:
case ChunkKind::CallParameterColon:
case ChunkKind::DeclAttrParamColon:
case ChunkKind::CallParameterType:
case ChunkKind::CallParameterClosureType:
case ChunkKind::GenericParameterName:
if (AnnotatedTextChunk)
OS << "['";
else if (C.getKind() == ChunkKind::CallParameterInternalName)
OS << "(";
else if (C.getKind() == ChunkKind::CallParameterClosureType)
OS << "##";
for (char Ch : C.getText()) {
if (Ch == '\n')
OS << "\\n";
else
OS << Ch;
}
if (AnnotatedTextChunk)
OS << "']";
else if (C.getKind() == ChunkKind::CallParameterInternalName)
OS << ")";
break;
case ChunkKind::OptionalBegin:
case ChunkKind::CallParameterBegin:
case ChunkKind::GenericParameterBegin:
OS << "{#";
break;
case ChunkKind::DynamicLookupMethodCallTail:
case ChunkKind::OptionalMethodCallTail:
OS << C.getText();
break;
case ChunkKind::TypeAnnotation:
OS << "[#";
OS << C.getText();
OS << "#]";
break;
case ChunkKind::BraceStmtWithCursor:
OS << " {|}";
break;
}
PrevNestingLevel = C.getNestingLevel();
}
while (PrevNestingLevel > 0) {
OS << "#}";
PrevNestingLevel--;
}
}
void CodeCompletionString::dump() const {
print(llvm::errs());
}
CodeCompletionDeclKind
CodeCompletionResult::getCodeCompletionDeclKind(const Decl *D) {
switch (D->getKind()) {
case DeclKind::Import:
case DeclKind::Extension:
case DeclKind::PatternBinding:
case DeclKind::EnumCase:
case DeclKind::TopLevelCode:
case DeclKind::IfConfig:
case DeclKind::PoundDiagnostic:
case DeclKind::MissingMember:
llvm_unreachable("not expecting such a declaration result");
case DeclKind::Module:
return CodeCompletionDeclKind::Module;
case DeclKind::TypeAlias:
return CodeCompletionDeclKind::TypeAlias;
case DeclKind::AssociatedType:
return CodeCompletionDeclKind::AssociatedType;
case DeclKind::GenericTypeParam:
return CodeCompletionDeclKind::GenericTypeParam;
case DeclKind::Enum:
return CodeCompletionDeclKind::Enum;
case DeclKind::Struct:
return CodeCompletionDeclKind::Struct;
case DeclKind::Class:
return CodeCompletionDeclKind::Class;
case DeclKind::Protocol:
return CodeCompletionDeclKind::Protocol;
case DeclKind::Var:
case DeclKind::Param: {
auto DC = D->getDeclContext();
if (DC->isTypeContext()) {
if (cast<VarDecl>(D)->isStatic())
return CodeCompletionDeclKind::StaticVar;
else
return CodeCompletionDeclKind::InstanceVar;
}
if (DC->isLocalContext())
return CodeCompletionDeclKind::LocalVar;
return CodeCompletionDeclKind::GlobalVar;
}
case DeclKind::Constructor:
return CodeCompletionDeclKind::Constructor;
case DeclKind::Destructor:
return CodeCompletionDeclKind::Destructor;
case DeclKind::Accessor:
case DeclKind::Func: {
auto DC = D->getDeclContext();
auto FD = cast<FuncDecl>(D);
if (DC->isTypeContext()) {
if (FD->isStatic())
return CodeCompletionDeclKind::StaticMethod;
return CodeCompletionDeclKind::InstanceMethod;
}
if (FD->isOperator()) {
if (auto op = FD->getOperatorDecl()) {
switch (op->getKind()) {
case DeclKind::PrefixOperator:
return CodeCompletionDeclKind::PrefixOperatorFunction;
case DeclKind::PostfixOperator:
return CodeCompletionDeclKind::PostfixOperatorFunction;
case DeclKind::InfixOperator:
return CodeCompletionDeclKind::InfixOperatorFunction;
default:
llvm_unreachable("unexpected operator kind");
}
} else {
return CodeCompletionDeclKind::InfixOperatorFunction;
}
}
return CodeCompletionDeclKind::FreeFunction;
}
case DeclKind::InfixOperator:
return CodeCompletionDeclKind::InfixOperatorFunction;
case DeclKind::PrefixOperator:
return CodeCompletionDeclKind::PrefixOperatorFunction;
case DeclKind::PostfixOperator:
return CodeCompletionDeclKind::PostfixOperatorFunction;
case DeclKind::PrecedenceGroup:
return CodeCompletionDeclKind::PrecedenceGroup;
case DeclKind::EnumElement:
return CodeCompletionDeclKind::EnumElement;
case DeclKind::Subscript:
return CodeCompletionDeclKind::Subscript;
}
llvm_unreachable("invalid DeclKind");
}
void CodeCompletionResult::print(raw_ostream &OS) const {
llvm::SmallString<64> Prefix;
switch (getKind()) {
case ResultKind::Declaration:
Prefix.append("Decl");
switch (getAssociatedDeclKind()) {
case CodeCompletionDeclKind::Class:
Prefix.append("[Class]");
break;
case CodeCompletionDeclKind::Struct:
Prefix.append("[Struct]");
break;
case CodeCompletionDeclKind::Enum:
Prefix.append("[Enum]");
break;
case CodeCompletionDeclKind::EnumElement:
Prefix.append("[EnumElement]");
break;
case CodeCompletionDeclKind::Protocol:
Prefix.append("[Protocol]");
break;
case CodeCompletionDeclKind::TypeAlias:
Prefix.append("[TypeAlias]");
break;
case CodeCompletionDeclKind::AssociatedType:
Prefix.append("[AssociatedType]");
break;
case CodeCompletionDeclKind::GenericTypeParam:
Prefix.append("[GenericTypeParam]");
break;
case CodeCompletionDeclKind::Constructor:
Prefix.append("[Constructor]");
break;
case CodeCompletionDeclKind::Destructor:
Prefix.append("[Destructor]");
break;
case CodeCompletionDeclKind::Subscript:
Prefix.append("[Subscript]");
break;
case CodeCompletionDeclKind::StaticMethod:
Prefix.append("[StaticMethod]");
break;
case CodeCompletionDeclKind::InstanceMethod:
Prefix.append("[InstanceMethod]");
break;
case CodeCompletionDeclKind::PrefixOperatorFunction:
Prefix.append("[PrefixOperatorFunction]");
break;
case CodeCompletionDeclKind::PostfixOperatorFunction:
Prefix.append("[PostfixOperatorFunction]");
break;
case CodeCompletionDeclKind::InfixOperatorFunction:
Prefix.append("[InfixOperatorFunction]");
break;
case CodeCompletionDeclKind::FreeFunction:
Prefix.append("[FreeFunction]");
break;
case CodeCompletionDeclKind::StaticVar:
Prefix.append("[StaticVar]");
break;
case CodeCompletionDeclKind::InstanceVar:
Prefix.append("[InstanceVar]");
break;
case CodeCompletionDeclKind::LocalVar:
Prefix.append("[LocalVar]");
break;
case CodeCompletionDeclKind::GlobalVar:
Prefix.append("[GlobalVar]");
break;
case CodeCompletionDeclKind::Module:
Prefix.append("[Module]");
break;
case CodeCompletionDeclKind::PrecedenceGroup:
Prefix.append("[PrecedenceGroup]");
break;
}
break;
case ResultKind::Keyword:
Prefix.append("Keyword");
switch (getKeywordKind()) {
case CodeCompletionKeywordKind::None:
break;
#define KEYWORD(X) case CodeCompletionKeywordKind::kw_##X: \
Prefix.append("[" #X "]"); \
break;
#define POUND_KEYWORD(X) case CodeCompletionKeywordKind::pound_##X: \
Prefix.append("[#" #X "]"); \
break;
#include "swift/Syntax/TokenKinds.def"
}
break;
case ResultKind::Pattern:
Prefix.append("Pattern");
break;
case ResultKind::Literal:
Prefix.append("Literal");
switch (getLiteralKind()) {
case CodeCompletionLiteralKind::ArrayLiteral:
Prefix.append("[Array]");
break;
case CodeCompletionLiteralKind::BooleanLiteral:
Prefix.append("[Boolean]");
break;
case CodeCompletionLiteralKind::ColorLiteral:
Prefix.append("[_Color]");
break;
case CodeCompletionLiteralKind::ImageLiteral:
Prefix.append("[_Image]");
break;
case CodeCompletionLiteralKind::DictionaryLiteral:
Prefix.append("[Dictionary]");
break;
case CodeCompletionLiteralKind::IntegerLiteral:
Prefix.append("[Integer]");
break;
case CodeCompletionLiteralKind::NilLiteral:
Prefix.append("[Nil]");
break;
case CodeCompletionLiteralKind::StringLiteral:
Prefix.append("[String]");
break;
case CodeCompletionLiteralKind::Tuple:
Prefix.append("[Tuple]");
break;
}
break;
case ResultKind::BuiltinOperator:
Prefix.append("BuiltinOperator");
break;
}
Prefix.append("/");
switch (getSemanticContext()) {
case SemanticContextKind::None:
Prefix.append("None");
break;
case SemanticContextKind::ExpressionSpecific:
Prefix.append("ExprSpecific");
break;
case SemanticContextKind::Local:
Prefix.append("Local");
break;
case SemanticContextKind::CurrentNominal:
Prefix.append("CurrNominal");
break;
case SemanticContextKind::Super:
Prefix.append("Super");
break;
case SemanticContextKind::OutsideNominal:
Prefix.append("OutNominal");
break;
case SemanticContextKind::CurrentModule:
Prefix.append("CurrModule");
break;
case SemanticContextKind::OtherModule:
Prefix.append("OtherModule");
if (!ModuleName.empty())
Prefix.append((Twine("[") + ModuleName + "]").str());
break;
}
if (NotRecommended)
Prefix.append("/NotRecommended");
if (NumBytesToErase != 0) {
Prefix.append("/Erase[");
Prefix.append(Twine(NumBytesToErase).str());
Prefix.append("]");
}
switch (TypeDistance) {
case ExpectedTypeRelation::Invalid:
Prefix.append("/TypeRelation[Invalid]");
break;
case ExpectedTypeRelation::Identical:
Prefix.append("/TypeRelation[Identical]");
break;
case ExpectedTypeRelation::Convertible:
Prefix.append("/TypeRelation[Convertible]");
break;
case ExpectedTypeRelation::Unrelated:
break;
}
for (clang::comments::WordPairsArrangedViewer Viewer(DocWords);
Viewer.hasNext();) {
auto Pair = Viewer.next();
Prefix.append("/");
Prefix.append(Pair.first);
Prefix.append("[");
StringRef Sep = ", ";
for (auto KW : Pair.second) {
Prefix.append(KW);
Prefix.append(Sep);
}
for (unsigned I = 0, N = Sep.size(); I < N; ++I)
Prefix.pop_back();
Prefix.append("]");
}
Prefix.append(": ");
while (Prefix.size() < 36) {
Prefix.append(" ");
}
OS << Prefix;
CompletionString->print(OS);
}
void CodeCompletionResult::dump() const {
print(llvm::errs());
}
static StringRef copyString(llvm::BumpPtrAllocator &Allocator,
StringRef Str) {
char *Mem = Allocator.Allocate<char>(Str.size());
std::copy(Str.begin(), Str.end(), Mem);
return StringRef(Mem, Str.size());
}
static ArrayRef<StringRef> copyStringArray(llvm::BumpPtrAllocator &Allocator,
ArrayRef<StringRef> Arr) {
StringRef *Buff = Allocator.Allocate<StringRef>(Arr.size());
std::copy(Arr.begin(), Arr.end(), Buff);
return llvm::makeArrayRef(Buff, Arr.size());
}
static ArrayRef<std::pair<StringRef, StringRef>> copyStringPairArray(
llvm::BumpPtrAllocator &Allocator,
ArrayRef<std::pair<StringRef, StringRef>> Arr) {
std::pair<StringRef, StringRef> *Buff = Allocator.Allocate<std::pair<StringRef,
StringRef>>(Arr.size());
std::copy(Arr.begin(), Arr.end(), Buff);
return llvm::makeArrayRef(Buff, Arr.size());
}
void CodeCompletionResultBuilder::addChunkWithText(
CodeCompletionString::Chunk::ChunkKind Kind, StringRef Text) {
addChunkWithTextNoCopy(Kind, copyString(*Sink.Allocator, Text));
}
void CodeCompletionResultBuilder::setAssociatedDecl(const Decl *D) {
assert(Kind == CodeCompletionResult::ResultKind::Declaration);
AssociatedDecl = D;
if (auto *ClangD = D->getClangDecl())
CurrentModule = ClangD->getImportedOwningModule();
// FIXME: macros
// FIXME: imported header module
if (!CurrentModule)
CurrentModule = D->getModuleContext();
if (D->getAttrs().getDeprecated(D->getASTContext()))
setNotRecommended(CodeCompletionResult::Deprecated);
}
StringRef CodeCompletionContext::copyString(StringRef Str) {
return ::copyString(*CurrentResults.Allocator, Str);
}
bool shouldCopyAssociatedUSRForDecl(const ValueDecl *VD) {
// Avoid trying to generate a USR for some declaration types.
if (isa<AbstractTypeParamDecl>(VD) && !isa<AssociatedTypeDecl>(VD))
return false;
if (isa<ParamDecl>(VD))
return false;
if (isa<ModuleDecl>(VD))
return false;
if (VD->hasClangNode() && !VD->getClangDecl())
return false;
return true;
}
template <typename FnTy>
static void walkValueDeclAndOverriddenDecls(const Decl *D, const FnTy &Fn) {
if (auto *VD = dyn_cast<ValueDecl>(D)) {
Fn(VD);
walkOverriddenDecls(VD, Fn);
}
}
ArrayRef<StringRef> copyAssociatedUSRs(llvm::BumpPtrAllocator &Allocator,
const Decl *D) {
llvm::SmallVector<StringRef, 4> USRs;
walkValueDeclAndOverriddenDecls(D, [&](llvm::PointerUnion<const ValueDecl*,
const clang::NamedDecl*> OD) {
llvm::SmallString<128> SS;
bool Ignored = true;
if (auto *OVD = OD.dyn_cast<const ValueDecl*>()) {
if (shouldCopyAssociatedUSRForDecl(OVD)) {
llvm::raw_svector_ostream OS(SS);
Ignored = printDeclUSR(OVD, OS);
}
} else if (auto *OND = OD.dyn_cast<const clang::NamedDecl*>()) {
Ignored = clang::index::generateUSRForDecl(OND, SS);
}
if (!Ignored)
USRs.push_back(copyString(Allocator, SS));
});
if (!USRs.empty())
return copyStringArray(Allocator, USRs);
return ArrayRef<StringRef>();
}
static CodeCompletionResult::ExpectedTypeRelation calculateTypeRelation(
Type Ty,
Type ExpectedTy,
DeclContext *DC) {
if (Ty.isNull() || ExpectedTy.isNull() ||
Ty->is<ErrorType>() ||
ExpectedTy->is<ErrorType>())
return CodeCompletionResult::ExpectedTypeRelation::Unrelated;
if (Ty->isEqual(ExpectedTy))
return CodeCompletionResult::ExpectedTypeRelation::Identical;
if (isConvertibleTo(Ty, ExpectedTy, *DC))
return CodeCompletionResult::ExpectedTypeRelation::Convertible;
if (auto FT = Ty->getAs<AnyFunctionType>()) {
if (FT->getResult()->isVoid())
return CodeCompletionResult::ExpectedTypeRelation::Invalid;
}
return CodeCompletionResult::ExpectedTypeRelation::Unrelated;
}
static CodeCompletionResult::ExpectedTypeRelation
calculateTypeRelationForDecl(const Decl *D, Type ExpectedType,
bool IsImplicitlyCurriedInstanceMethod,
bool UseFuncResultType = true) {
auto VD = dyn_cast<ValueDecl>(D);
auto DC = D->getDeclContext();
if (!VD)
return CodeCompletionResult::ExpectedTypeRelation::Unrelated;
if (auto FD = dyn_cast<AbstractFunctionDecl>(VD)) {
auto funcType = FD->getInterfaceType()->getAs<AnyFunctionType>();
if (DC->isTypeContext() && funcType && funcType->is<AnyFunctionType>() &&
!IsImplicitlyCurriedInstanceMethod)
funcType = funcType->getResult()->getAs<AnyFunctionType>();
if (funcType) {
auto relation = calculateTypeRelation(funcType, ExpectedType, DC);
if (UseFuncResultType)
relation =
std::max(relation, calculateTypeRelation(funcType->getResult(),
ExpectedType, DC));
return relation;
}
}
if (auto NTD = dyn_cast<NominalTypeDecl>(VD)) {
return std::max(
calculateTypeRelation(NTD->getInterfaceType(), ExpectedType, DC),
calculateTypeRelation(NTD->getDeclaredInterfaceType(), ExpectedType, DC));
}
return calculateTypeRelation(VD->getInterfaceType(), ExpectedType, DC);
}
static CodeCompletionResult::ExpectedTypeRelation
calculateMaxTypeRelationForDecl(
const Decl *D,
ArrayRef<Type> ExpectedTypes,
bool IsImplicitlyCurriedInstanceMethod = false) {
auto Result = CodeCompletionResult::ExpectedTypeRelation::Unrelated;
for (auto Type : ExpectedTypes) {
Result = std::max(Result, calculateTypeRelationForDecl(
D, Type, IsImplicitlyCurriedInstanceMethod));
}
return Result;
}
CodeCompletionOperatorKind
CodeCompletionResult::getCodeCompletionOperatorKind(StringRef name) {
using CCOK = CodeCompletionOperatorKind;
using OpPair = std::pair<StringRef, CCOK>;
// This list must be kept in alphabetical order.
static OpPair ops[] = {
std::make_pair("!", CCOK::Bang),
std::make_pair("!=", CCOK::NotEq),
std::make_pair("!==", CCOK::NotEqEq),
std::make_pair("%", CCOK::Modulo),
std::make_pair("%=", CCOK::ModuloEq),
std::make_pair("&", CCOK::Amp),
std::make_pair("&&", CCOK::AmpAmp),
std::make_pair("&*", CCOK::AmpStar),
std::make_pair("&+", CCOK::AmpPlus),
std::make_pair("&-", CCOK::AmpMinus),
std::make_pair("&=", CCOK::AmpEq),
std::make_pair("(", CCOK::LParen),
std::make_pair("*", CCOK::Star),
std::make_pair("*=", CCOK::StarEq),
std::make_pair("+", CCOK::Plus),
std::make_pair("+=", CCOK::PlusEq),
std::make_pair("-", CCOK::Minus),
std::make_pair("-=", CCOK::MinusEq),
std::make_pair(".", CCOK::Dot),
std::make_pair("...", CCOK::DotDotDot),
std::make_pair("..<", CCOK::DotDotLess),
std::make_pair("/", CCOK::Slash),
std::make_pair("/=", CCOK::SlashEq),
std::make_pair("<", CCOK::Less),
std::make_pair("<<", CCOK::LessLess),
std::make_pair("<<=", CCOK::LessLessEq),
std::make_pair("<=", CCOK::LessEq),
std::make_pair("=", CCOK::Eq),
std::make_pair("==", CCOK::EqEq),
std::make_pair("===", CCOK::EqEqEq),
std::make_pair(">", CCOK::Greater),
std::make_pair(">=", CCOK::GreaterEq),
std::make_pair(">>", CCOK::GreaterGreater),
std::make_pair(">>=", CCOK::GreaterGreaterEq),
std::make_pair("?.", CCOK::QuestionDot),
std::make_pair("^", CCOK::Caret),
std::make_pair("^=", CCOK::CaretEq),
std::make_pair("|", CCOK::Pipe),
std::make_pair("|=", CCOK::PipeEq),
std::make_pair("||", CCOK::PipePipe),
std::make_pair("~=", CCOK::TildeEq),
};
static auto opsSize = sizeof(ops) / sizeof(ops[0]);
auto I = std::lower_bound(
ops, &ops[opsSize], std::make_pair(name, CCOK::None),
[](const OpPair &a, const OpPair &b) { return a.first < b.first; });
if (I == &ops[opsSize] || I->first != name)
return CCOK::Unknown;
return I->second;
}
static StringRef getOperatorName(CodeCompletionString *str) {
return str->getFirstTextChunk(/*includeLeadingPunctuation=*/true);
}
CodeCompletionOperatorKind
CodeCompletionResult::getCodeCompletionOperatorKind(CodeCompletionString *str) {
return getCodeCompletionOperatorKind(getOperatorName(str));
}
CodeCompletionResult *CodeCompletionResultBuilder::takeResult() {
auto *CCS = CodeCompletionString::create(*Sink.Allocator, Chunks);
switch (Kind) {
case CodeCompletionResult::ResultKind::Declaration: {
StringRef BriefComment;
auto MaybeClangNode = AssociatedDecl->getClangNode();
if (MaybeClangNode) {
if (auto *D = MaybeClangNode.getAsDecl()) {
const auto &ClangContext = D->getASTContext();
if (const clang::RawComment *RC =
ClangContext.getRawCommentForAnyRedecl(D))
BriefComment = RC->getBriefText(ClangContext);
}
} else {
BriefComment = AssociatedDecl->getBriefComment();
}
StringRef ModuleName;
if (CurrentModule) {
if (Sink.LastModule.first == CurrentModule.getOpaqueValue()) {
ModuleName = Sink.LastModule.second;
} else {
if (auto *C = CurrentModule.dyn_cast<const clang::Module *>()) {
ModuleName = copyString(*Sink.Allocator, C->getFullModuleName());
} else {
ModuleName = copyString(
*Sink.Allocator,
CurrentModule.get<const swift::ModuleDecl *>()->getName().str());
}
Sink.LastModule.first = CurrentModule.getOpaqueValue();
Sink.LastModule.second = ModuleName;
}
}
auto typeRelation = ExpectedTypeRelation;
if (typeRelation == CodeCompletionResult::Unrelated)
typeRelation =
calculateMaxTypeRelationForDecl(AssociatedDecl, ExpectedDeclTypes);
if (typeRelation == CodeCompletionResult::Invalid) {
IsNotRecommended = true;
NotRecReason = CodeCompletionResult::NotRecommendedReason::TypeMismatch;
}
return new (*Sink.Allocator) CodeCompletionResult(
SemanticContext, NumBytesToErase, CCS, AssociatedDecl, ModuleName,
/*NotRecommended=*/IsNotRecommended, NotRecReason,
copyString(*Sink.Allocator, BriefComment),
copyAssociatedUSRs(*Sink.Allocator, AssociatedDecl),
copyStringPairArray(*Sink.Allocator, CommentWords), typeRelation);
}
case CodeCompletionResult::ResultKind::Keyword:
return new (*Sink.Allocator)
CodeCompletionResult(KeywordKind, SemanticContext, NumBytesToErase,
CCS, ExpectedTypeRelation);
case CodeCompletionResult::ResultKind::BuiltinOperator:
case CodeCompletionResult::ResultKind::Pattern:
return new (*Sink.Allocator) CodeCompletionResult(
Kind, SemanticContext, NumBytesToErase, CCS, ExpectedTypeRelation);
case CodeCompletionResult::ResultKind::Literal:
assert(LiteralKind.hasValue());
return new (*Sink.Allocator)
CodeCompletionResult(*LiteralKind, SemanticContext, NumBytesToErase,
CCS, ExpectedTypeRelation);
}
llvm_unreachable("Unhandled CodeCompletionResult in switch.");
}
void CodeCompletionResultBuilder::finishResult() {
if (!Cancelled)
Sink.Results.push_back(takeResult());
}
MutableArrayRef<CodeCompletionResult *> CodeCompletionContext::takeResults() {
// Copy pointers to the results.
const size_t Count = CurrentResults.Results.size();
CodeCompletionResult **Results =
CurrentResults.Allocator->Allocate<CodeCompletionResult *>(Count);
std::copy(CurrentResults.Results.begin(), CurrentResults.Results.end(),
Results);
CurrentResults.Results.clear();
return MutableArrayRef<CodeCompletionResult *>(Results, Count);
}
Optional<unsigned> CodeCompletionString::getFirstTextChunkIndex(
bool includeLeadingPunctuation) const {
for (auto i : indices(getChunks())) {
auto &C = getChunks()[i];
switch (C.getKind()) {
using ChunkKind = Chunk::ChunkKind;
case ChunkKind::Text:
case ChunkKind::CallParameterName:
case ChunkKind::CallParameterInternalName:
case ChunkKind::GenericParameterName:
case ChunkKind::LeftParen:
case ChunkKind::LeftBracket:
case ChunkKind::Equal:
case ChunkKind::DeclAttrParamKeyword:
case ChunkKind::DeclAttrKeyword:
return i;
case ChunkKind::Dot:
case ChunkKind::ExclamationMark:
case ChunkKind::QuestionMark:
if (includeLeadingPunctuation)
return i;
continue;
case ChunkKind::RightParen:
case ChunkKind::RightBracket:
case ChunkKind::LeftAngle:
case ChunkKind::RightAngle:
case ChunkKind::Ellipsis:
case ChunkKind::Comma:
case ChunkKind::Ampersand:
case ChunkKind::Whitespace:
case ChunkKind::AccessControlKeyword:
case ChunkKind::OverrideKeyword:
case ChunkKind::ThrowsKeyword:
case ChunkKind::RethrowsKeyword:
case ChunkKind::DeclIntroducer:
case ChunkKind::CallParameterColon:
case ChunkKind::DeclAttrParamColon:
case ChunkKind::CallParameterType:
case ChunkKind::CallParameterClosureType:
case ChunkKind::OptionalBegin:
case ChunkKind::CallParameterBegin:
case ChunkKind::GenericParameterBegin:
case ChunkKind::DynamicLookupMethodCallTail:
case ChunkKind::OptionalMethodCallTail:
case ChunkKind::TypeAnnotation:
continue;
case ChunkKind::BraceStmtWithCursor:
llvm_unreachable("should have already extracted the text");
}
}
return None;
}
StringRef
CodeCompletionString::getFirstTextChunk(bool includeLeadingPunctuation) const {
Optional<unsigned> Idx = getFirstTextChunkIndex(includeLeadingPunctuation);
if (Idx.hasValue())
return getChunks()[*Idx].getText();
return StringRef();
}
void CodeCompletionString::getName(raw_ostream &OS) const {
auto FirstTextChunk = getFirstTextChunkIndex();
int TextSize = 0;
if (FirstTextChunk.hasValue()) {
for (auto C : getChunks().slice(*FirstTextChunk)) {
using ChunkKind = Chunk::ChunkKind;
bool shouldPrint = !C.isAnnotation();
switch (C.getKind()) {
case ChunkKind::TypeAnnotation:
case ChunkKind::CallParameterClosureType:
case ChunkKind::DeclAttrParamColon:
continue;
case ChunkKind::ThrowsKeyword:
case ChunkKind::RethrowsKeyword:
shouldPrint = true; // Even when they're annotations.
break;
default:
break;
}
if (C.hasText() && shouldPrint) {
TextSize += C.getText().size();
OS << C.getText();
}
}
}
assert((TextSize > 0) &&
"code completion string should have non-empty name!");
}
void CodeCompletionContext::sortCompletionResults(
MutableArrayRef<CodeCompletionResult *> Results) {
struct ResultAndName {
CodeCompletionResult *result;
std::string name;
};
// Caching the name of each field is important to avoid unnecessary calls to
// CodeCompletionString::getName().
std::vector<ResultAndName> nameCache(Results.size());
for (unsigned i = 0, n = Results.size(); i < n; ++i) {
auto *result = Results[i];
nameCache[i].result = result;
llvm::raw_string_ostream OS(nameCache[i].name);
result->getCompletionString()->getName(OS);
OS.flush();
}
// Sort nameCache, and then transform Results to return the pointers in order.
std::sort(nameCache.begin(), nameCache.end(),
[](const ResultAndName &LHS, const ResultAndName &RHS) {
int Result = StringRef(LHS.name).compare_lower(RHS.name);
// If the case insensitive comparison is equal, then secondary sort order
// should be case sensitive.
if (Result == 0)
Result = LHS.name.compare(RHS.name);
return Result < 0;
});
std::transform(nameCache.begin(), nameCache.end(), Results.begin(),
[](const ResultAndName &entry) { return entry.result; });
}
namespace {
class CodeCompletionCallbacksImpl : public CodeCompletionCallbacks {
CodeCompletionContext &CompletionContext;
std::vector<RequestedCachedModule> RequestedModules;
CodeCompletionConsumer &Consumer;
CodeCompletionExpr *CodeCompleteTokenExpr = nullptr;
AssignExpr *AssignmentExpr;
CallExpr *FuncCallExpr;
UnresolvedMemberExpr *UnresolvedExpr;
bool UnresolvedExprInReturn;
std::vector<std::string> TokensBeforeUnresolvedExpr;
CompletionKind Kind = CompletionKind::None;
Expr *ParsedExpr = nullptr;
SourceLoc DotLoc;
TypeLoc ParsedTypeLoc;
DeclContext *CurDeclContext = nullptr;
DeclAttrKind AttrKind;
int AttrParamIndex;
bool IsInSil;
bool HasSpace = false;
bool ShouldCompleteCallPatternAfterParen = true;
bool PreferFunctionReferencesToCalls = false;
Optional<DeclKind> AttTargetDK;
SmallVector<StringRef, 3> ParsedKeywords;
std::vector<std::pair<std::string, bool>> SubModuleNameVisibilityPairs;
StmtKind ParentStmtKind;
void addSuperKeyword(CodeCompletionResultSink &Sink) {
auto *DC = CurDeclContext->getInnermostTypeContext();
if (!DC)
return;
auto *CD = DC->getAsClassOrClassExtensionContext();
if (CD == nullptr)
return;
Type ST = CD->getSuperclass();
if (ST.isNull() || ST->is<ErrorType>())
return;
CodeCompletionResultBuilder Builder(Sink,
CodeCompletionResult::ResultKind::Keyword,
SemanticContextKind::CurrentNominal,
{});
Builder.setKeywordKind(CodeCompletionKeywordKind::kw_super);
Builder.addTextChunk("super");
Builder.addTypeAnnotation(ST.getString());
}
/// \brief Set to true when we have delivered code completion results
/// to the \c Consumer.
bool DeliveredResults = false;
bool typecheckContext(DeclContext *DC) {
// Nothing to type check in module context.
if (DC->isModuleScopeContext())
return true;
// Type check the parent context.
if (!typecheckContext(DC->getParent()))
return false;
// Type-check this context.
switch (DC->getContextKind()) {
case DeclContextKind::AbstractClosureExpr:
case DeclContextKind::Initializer:
case DeclContextKind::Module:
case DeclContextKind::SerializedLocal:
// Nothing to do for these.
return true;
case DeclContextKind::AbstractFunctionDecl:
return typeCheckAbstractFunctionBodyUntil(
cast<AbstractFunctionDecl>(DC),
P.Context.SourceMgr.getCodeCompletionLoc());
case DeclContextKind::ExtensionDecl:
return typeCheckCompletionDecl(cast<ExtensionDecl>(DC));
case DeclContextKind::GenericTypeDecl:
return typeCheckCompletionDecl(cast<GenericTypeDecl>(DC));
case DeclContextKind::FileUnit:
llvm_unreachable("module scope context handled above");
case DeclContextKind::SubscriptDecl:
// FIXME: what do we need to check here?
return true;
case DeclContextKind::TopLevelCodeDecl:
return typeCheckTopLevelCodeDecl(cast<TopLevelCodeDecl>(DC));
}
llvm_unreachable("Unhandled DeclContextKind in switch.");
}
Optional<std::pair<Type, ConcreteDeclRef>> typeCheckParsedExpr() {
assert(ParsedExpr && "should have an expression");
// Figure out the kind of type-check we'll be performing.
auto CheckKind = CompletionTypeCheckKind::Normal;
if (Kind == CompletionKind::KeyPathExpr ||
Kind == CompletionKind::KeyPathExprDot)
CheckKind = CompletionTypeCheckKind::KeyPath;
// If we've already successfully type-checked the expression for some
// reason, just return the type.
// FIXME: if it's ErrorType but we've already typechecked we shouldn't
// typecheck again. rdar://21466394
if (CheckKind == CompletionTypeCheckKind::Normal &&
ParsedExpr->getType() && !ParsedExpr->getType()->is<ErrorType>())
return std::make_pair(ParsedExpr->getType(),
ParsedExpr->getReferencedDecl());
prepareForRetypechecking(ParsedExpr);
ConcreteDeclRef ReferencedDecl = nullptr;
Expr *ModifiedExpr = ParsedExpr;
if (auto T = getTypeOfCompletionContextExpr(P.Context, CurDeclContext,
CheckKind, ModifiedExpr,
ReferencedDecl)) {
// FIXME: even though we don't apply the solution, the type checker may
// modify the original expression. We should understand what effect that
// may have on code completion.
ParsedExpr = ModifiedExpr;
return std::make_pair(*T, ReferencedDecl);
}
return None;
}
/// \returns true on success, false on failure.
bool typecheckParsedType() {
assert(ParsedTypeLoc.getTypeRepr() && "should have a TypeRepr");
return !performTypeLocChecking(P.Context, ParsedTypeLoc,
CurDeclContext, false);
}
public:
CodeCompletionCallbacksImpl(Parser &P,
CodeCompletionContext &CompletionContext,
CodeCompletionConsumer &Consumer)
: CodeCompletionCallbacks(P), CompletionContext(CompletionContext),
Consumer(Consumer) {
}
void completeExpr() override;
void completeDotExpr(Expr *E, SourceLoc DotLoc) override;
void completeStmtOrExpr() override;
void completePostfixExprBeginning(CodeCompletionExpr *E) override;
void completeForEachSequenceBeginning(CodeCompletionExpr *E) override;
void completePostfixExpr(Expr *E, bool hasSpace) override;
void completePostfixExprParen(Expr *E, Expr *CodeCompletionE) override;
void completeExprSuper(SuperRefExpr *SRE) override;
void completeExprSuperDot(SuperRefExpr *SRE) override;
void completeExprKeyPath(KeyPathExpr *KPE, bool HasDot) override;
void completeTypeSimpleBeginning() override;
void completeTypeIdentifierWithDot(IdentTypeRepr *ITR) override;
void completeTypeIdentifierWithoutDot(IdentTypeRepr *ITR) override;
void completeCaseStmtBeginning() override;
void completeCaseStmtDotPrefix() override;
void completeDeclAttrKeyword(Decl *D, bool Sil, bool Param) override;
void completeDeclAttrParam(DeclAttrKind DK, int Index) override;
void completeNominalMemberBeginning(
SmallVectorImpl<StringRef> &Keywords) override;
void completePoundAvailablePlatform() override;
void completeImportDecl(std::vector<std::pair<Identifier, SourceLoc>> &Path) override;
void completeUnresolvedMember(UnresolvedMemberExpr *E,
ArrayRef<StringRef> Identifiers,
bool HasReturn) override;
void completeAssignmentRHS(AssignExpr *E) override;
void completeCallArg(CallExpr *E) override;
void completeReturnStmt(CodeCompletionExpr *E) override;
void completeAfterPound(CodeCompletionExpr *E, StmtKind ParentKind) override;
void completeGenericParams(TypeLoc TL) override;
void addKeywords(CodeCompletionResultSink &Sink, bool MaybeFuncBody);
void doneParsing() override;
void deliverCompletionResults();
};
} // end anonymous namespace
void CodeCompletionCallbacksImpl::completeExpr() {
if (DeliveredResults)
return;
Parser::ParserPositionRAII RestorePosition(P);
P.restoreParserPosition(ExprBeginPosition);
// FIXME: implement fallback code completion.
deliverCompletionResults();
}
namespace {
static bool isTopLevelContext(const DeclContext *DC) {
for (; DC && DC->isLocalContext(); DC = DC->getParent()) {
switch (DC->getContextKind()) {
case DeclContextKind::TopLevelCodeDecl:
return true;
case DeclContextKind::AbstractFunctionDecl:
case DeclContextKind::SubscriptDecl:
return false;
default:
continue;
}
}
return false;
}
static Type getReturnTypeFromContext(const DeclContext *DC) {
if (auto FD = dyn_cast<AbstractFunctionDecl>(DC)) {
if (FD->hasInterfaceType()) {
if (auto FT = FD->getInterfaceType()->getAs<FunctionType>()) {
return FT->getResult();
}
}
} else if (auto CE = dyn_cast<AbstractClosureExpr>(DC)) {
if (CE->getType()) {
return CE->getResultType();
}
}
return Type();
}
static KnownProtocolKind
protocolForLiteralKind(CodeCompletionLiteralKind kind) {
switch (kind) {
case CodeCompletionLiteralKind::ArrayLiteral:
return KnownProtocolKind::ExpressibleByArrayLiteral;
case CodeCompletionLiteralKind::BooleanLiteral:
return KnownProtocolKind::ExpressibleByBooleanLiteral;
case CodeCompletionLiteralKind::ColorLiteral:
return KnownProtocolKind::ExpressibleByColorLiteral;
case CodeCompletionLiteralKind::ImageLiteral:
return KnownProtocolKind::ExpressibleByImageLiteral;
case CodeCompletionLiteralKind::DictionaryLiteral:
return KnownProtocolKind::ExpressibleByDictionaryLiteral;
case CodeCompletionLiteralKind::IntegerLiteral:
return KnownProtocolKind::ExpressibleByIntegerLiteral;
case CodeCompletionLiteralKind::NilLiteral:
return KnownProtocolKind::ExpressibleByNilLiteral;
case CodeCompletionLiteralKind::StringLiteral:
return KnownProtocolKind::ExpressibleByUnicodeScalarLiteral;
case CodeCompletionLiteralKind::Tuple:
llvm_unreachable("no such protocol kind");
}
llvm_unreachable("Unhandled CodeCompletionLiteralKind in switch.");
}
/// Whether funcType has a single argument (not including defaulted arguments)
/// that is of type () -> ().
static bool hasTrivialTrailingClosure(const FuncDecl *FD,
AnyFunctionType *funcType) {
SmallVector<bool, 4> defaultMap;
computeDefaultMap(funcType->getInput(), FD,
/*level*/ FD->isInstanceMember() ? 1 : 0, defaultMap);
bool OneArg = defaultMap.size() == 1;
if (defaultMap.size() > 1) {
auto NonDefault = std::count(defaultMap.begin(), defaultMap.end() - 1, false);
OneArg = (NonDefault == 0);
}
if (OneArg) {
auto param = funcType->getParams().back();
if (!param.isAutoClosure()) {
if (auto Fn = param.getType()->getAs<AnyFunctionType>()) {
return Fn->getInput()->isVoid() && Fn->getResult()->isVoid();
}
}
}
return false;
}
/// Build completions by doing visible decl lookup from a context.
class CompletionLookup final : public swift::VisibleDeclConsumer {
CodeCompletionResultSink &Sink;
ASTContext &Ctx;
OwnedResolver TypeResolver;
const DeclContext *CurrDeclContext;
ClangImporter *Importer;
CodeCompletionContext *CompletionContext;
enum class LookupKind {
ValueExpr,
ValueInDeclContext,
EnumElement,
Type,
TypeInDeclContext,
ImportFromModule
};
LookupKind Kind;
/// Type of the user-provided expression for LookupKind::ValueExpr
/// completions.
Type ExprType;
/// Whether the expr is of statically inferred metatype.
bool IsStaticMetatype;
/// User-provided base type for LookupKind::Type completions.
Type BaseType;
/// Expected types of the code completion expression.
std::vector<Type> ExpectedTypes;
bool HaveDot = false;
bool IsUnwrappedOptional = false;
SourceLoc DotLoc;
bool NeedLeadingDot = false;
bool NeedOptionalUnwrap = false;
unsigned NumBytesToEraseForOptionalUnwrap = 0;
bool HaveLParen = false;
bool IsSuperRefExpr = false;
bool IsSelfRefExpr = false;
bool IsKeyPathExpr = false;
bool IsSwiftKeyPathExpr = false;
bool IsDynamicLookup = false;
bool PreferFunctionReferencesToCalls = false;
bool HaveLeadingSpace = false;
bool IncludeInstanceMembers = false;
/// \brief True if we are code completing inside a static method.
bool InsideStaticMethod = false;
/// \brief Innermost method that the code completion point is in.
const AbstractFunctionDecl *CurrentMethod = nullptr;
Optional<SemanticContextKind> ForcedSemanticContext = None;
bool IsUnresolvedMember = false;
public:
bool FoundFunctionCalls = false;
bool FoundFunctionsWithoutFirstKeyword = false;
private:
void foundFunction(const AbstractFunctionDecl *AFD) {
FoundFunctionCalls = true;
DeclName Name = AFD->getFullName();
auto ArgNames = Name.getArgumentNames();
if (ArgNames.empty())
return;
if (ArgNames[0].empty())
FoundFunctionsWithoutFirstKeyword = true;
}
void foundFunction(const AnyFunctionType *AFT) {
FoundFunctionCalls = true;
Type In = AFT->getInput();
if (!In)
return;
if (In->hasParenSugar()) {
FoundFunctionsWithoutFirstKeyword = true;
return;
}
TupleType *InTuple = In->getAs<TupleType>();
if (!InTuple)
return;
auto Elements = InTuple->getElements();
if (Elements.empty())
return;
if (!Elements[0].hasName())
FoundFunctionsWithoutFirstKeyword = true;
}
void setClangDeclKeywords(const ValueDecl *VD, CommandWordsPairs &Pairs,
CodeCompletionResultBuilder &Builder) {
if (auto *CD = VD->getClangDecl()) {
clang::comments::getClangDocKeyword(*Importer, CD, Pairs);
} else {
swift::markup::getSwiftDocKeyword(VD, Pairs);
}
Builder.addDeclDocCommentWords(llvm::makeArrayRef(Pairs));
}
bool shouldUseFunctionReference(AbstractFunctionDecl *D) {
if (PreferFunctionReferencesToCalls)
return true;
bool isImplicitlyCurriedIM = isImplicitlyCurriedInstanceMethod(D);
for (auto expectedType : ExpectedTypes) {
if (expectedType &&
expectedType->lookThroughAllOptionalTypes()
->is<AnyFunctionType>() &&
calculateTypeRelationForDecl(D, expectedType, isImplicitlyCurriedIM,
/*UseFuncResultType=*/false) >=
CodeCompletionResult::ExpectedTypeRelation::Convertible) {
return true;
}
}
return false;
}
public:
struct RequestedResultsTy {
const ModuleDecl *TheModule;
bool OnlyTypes;
bool NeedLeadingDot;
static RequestedResultsTy fromModule(const ModuleDecl *TheModule) {
return { TheModule, false, false };
}
RequestedResultsTy onlyTypes() const {
return { TheModule, true, NeedLeadingDot };
}
RequestedResultsTy needLeadingDot(bool NeedDot) const {
return { TheModule, OnlyTypes, NeedDot };
}
static RequestedResultsTy toplevelResults() {
return { nullptr, false, false };
}
};
Optional<RequestedResultsTy> RequestedCachedResults;
public:
CompletionLookup(CodeCompletionResultSink &Sink,
ASTContext &Ctx,
const DeclContext *CurrDeclContext,
CodeCompletionContext *CompletionContext = nullptr)
: Sink(Sink), Ctx(Ctx),
TypeResolver(createLazyResolver(Ctx)), CurrDeclContext(CurrDeclContext),
Importer(static_cast<ClangImporter *>(CurrDeclContext->getASTContext().
getClangModuleLoader())),
CompletionContext(CompletionContext) {
// Determine if we are doing code completion inside a static method.
if (CurrDeclContext) {
CurrentMethod = CurrDeclContext->getInnermostMethodContext();
if (auto *FD = dyn_cast_or_null<FuncDecl>(CurrentMethod))
InsideStaticMethod = FD->isStatic();
}
}
void discardTypeResolver() {
TypeResolver.reset();
}
void setHaveDot(SourceLoc DotLoc) {
HaveDot = true;
this->DotLoc = DotLoc;
}
void setIsUnwrappedOptional(bool value) {
IsUnwrappedOptional = value;
}
void setIsStaticMetatype(bool value) {
IsStaticMetatype = value;
}
void setExpectedTypes(ArrayRef<Type> Types) {
ExpectedTypes.reserve(Types.size());
for (auto T : Types)
if (T)
ExpectedTypes.push_back(T);
}
bool hasExpectedTypes() const { return !ExpectedTypes.empty(); }
bool needDot() const {
return NeedLeadingDot;
}
void setHaveLParen(bool Value) {
HaveLParen = Value;
}
void setIsSuperRefExpr() {
IsSuperRefExpr = true;
}
void setIsSelfRefExpr(bool value) { IsSelfRefExpr = value; }
void setIsKeyPathExpr() {
IsKeyPathExpr = true;
}
void setIsSwiftKeyPathExpr() {
IsSwiftKeyPathExpr = true;
}
void setIsDynamicLookup() {
IsDynamicLookup = true;
}
void setPreferFunctionReferencesToCalls() {
PreferFunctionReferencesToCalls = true;
}
void setHaveLeadingSpace(bool value) { HaveLeadingSpace = value; }
void includeInstanceMembers() {
IncludeInstanceMembers = true;
}
void addSubModuleNames(std::vector<std::pair<std::string, bool>>
&SubModuleNameVisibilityPairs) {
for (auto &Pair : SubModuleNameVisibilityPairs) {
CodeCompletionResultBuilder Builder(Sink,
CodeCompletionResult::ResultKind::
Declaration,
SemanticContextKind::OtherModule,
ExpectedTypes);
auto MD = ModuleDecl::create(Ctx.getIdentifier(Pair.first), Ctx);
Builder.setAssociatedDecl(MD);
Builder.addTextChunk(MD->getNameStr());
Builder.addTypeAnnotation("Module");
if (Pair.second)
Builder.setNotRecommended(CodeCompletionResult::NotRecommendedReason::
Redundant);
}
}
void collectImportedModules(llvm::StringSet<> &ImportedModules) {
SmallVector<ModuleDecl::ImportedModule, 16> Imported;
SmallVector<ModuleDecl::ImportedModule, 16> FurtherImported;
CurrDeclContext->getParentSourceFile()->getImportedModules(Imported,
ModuleDecl::ImportFilter::All);
while (!Imported.empty()) {
ModuleDecl *MD = Imported.back().second;
Imported.pop_back();
if (!ImportedModules.insert(MD->getNameStr()).second)
continue;
FurtherImported.clear();
MD->getImportedModules(FurtherImported, ModuleDecl::ImportFilter::Public);
Imported.append(FurtherImported.begin(), FurtherImported.end());
for (auto SubMod : FurtherImported) {
Imported.push_back(SubMod);
}
}
}
void addImportModuleNames() {
// FIXME: Add user-defined swift modules
SmallVector<StringRef, 20> ModuleNames;
// Collect clang module names.
{
SmallVector<clang::Module*, 20> ClangModules;
Ctx.getVisibleTopLevelClangModules(ClangModules);
for (auto *M : ClangModules) {
if (!M->isAvailable())
continue;
if (M->getTopLevelModuleName().startswith("_"))
continue;
if (M->getTopLevelModuleName() == Ctx.SwiftShimsModuleName.str())
continue;
ModuleNames.push_back(M->getTopLevelModuleName());
}
}
std::sort(ModuleNames.begin(), ModuleNames.end(),
[](StringRef LHS, StringRef RHS) {
return LHS.compare_lower(RHS) < 0;
});
llvm::StringSet<> ImportedModules;
collectImportedModules(ImportedModules);
for (auto ModuleName : ModuleNames) {
auto MD = ModuleDecl::create(Ctx.getIdentifier(ModuleName), Ctx);
CodeCompletionResultBuilder Builder(
Sink,
CodeCompletionResult::ResultKind::Declaration,
SemanticContextKind::OtherModule,
ExpectedTypes);
Builder.setAssociatedDecl(MD);
Builder.addTextChunk(MD->getNameStr());
Builder.addTypeAnnotation("Module");
// Imported modules are not recommended.
if (ImportedModules.count(MD->getNameStr()) != 0)
Builder.setNotRecommended(
CodeCompletionResult::NotRecommendedReason::Redundant);
}
}
SemanticContextKind getSemanticContext(const Decl *D,
DeclVisibilityKind Reason) {
if (ForcedSemanticContext)
return *ForcedSemanticContext;
if (IsUnresolvedMember) {
if (isa<EnumElementDecl>(D)) {
return SemanticContextKind::ExpressionSpecific;
}
}
switch (Reason) {
case DeclVisibilityKind::LocalVariable:
case DeclVisibilityKind::FunctionParameter:
case DeclVisibilityKind::GenericParameter:
return SemanticContextKind::Local;
case DeclVisibilityKind::MemberOfCurrentNominal:
if (IsSuperRefExpr &&
CurrentMethod && CurrentMethod->getOverriddenDecl() == D)
return SemanticContextKind::ExpressionSpecific;
return SemanticContextKind::CurrentNominal;
case DeclVisibilityKind::MemberOfProtocolImplementedByCurrentNominal:
case DeclVisibilityKind::MemberOfSuper:
return SemanticContextKind::Super;
case DeclVisibilityKind::MemberOfOutsideNominal:
return SemanticContextKind::OutsideNominal;
case DeclVisibilityKind::VisibleAtTopLevel:
if (CurrDeclContext &&
D->getModuleContext() == CurrDeclContext->getParentModule()) {
// Treat global variables from the same source file as local when
// completing at top-level.
if (isa<VarDecl>(D) && isTopLevelContext(CurrDeclContext) &&
D->getDeclContext()->getParentSourceFile() ==
CurrDeclContext->getParentSourceFile()) {
return SemanticContextKind::Local;
} else {
return SemanticContextKind::CurrentModule;
}
} else {
return SemanticContextKind::OtherModule;
}
case DeclVisibilityKind::DynamicLookup:
// AnyObject results can come from different modules, including the
// current module, but we always assign them the OtherModule semantic
// context. These declarations are uniqued by signature, so it is
// totally random (determined by the hash function) which of the
// equivalent declarations (across multiple modules) we will get.
return SemanticContextKind::OtherModule;
}
llvm_unreachable("unhandled kind");
}
void addLeadingDot(CodeCompletionResultBuilder &Builder) {
if (NeedOptionalUnwrap) {
Builder.setNumBytesToErase(NumBytesToEraseForOptionalUnwrap);
Builder.addQuestionMark();
Builder.addLeadingDot();
return;
}
if (needDot())
Builder.addLeadingDot();
}
void addTypeAnnotation(CodeCompletionResultBuilder &Builder, Type T) {
T = T->getReferenceStorageReferent();
if (T->isVoid())
Builder.addTypeAnnotation("Void");
else
Builder.addTypeAnnotation(T.getString());
}
void addTypeAnnotationForImplicitlyUnwrappedOptional(
CodeCompletionResultBuilder &Builder, Type T,
bool dynamicOrOptional = false) {
std::string suffix;
// FIXME: This retains previous behavior, but in reality the type of dynamic
// lookups is IUO, not Optional as it is for the @optional attribute.
if (dynamicOrOptional) {
T = T->getOptionalObjectType();
suffix = "!?";
} else {
suffix = "!";
}
Type ObjectType = T->getReferenceStorageReferent()->getOptionalObjectType();
if (ObjectType->isVoid())
Builder.addTypeAnnotation("Void" + suffix);
else
Builder.addTypeAnnotation(ObjectType.getStringAsComponent() + suffix);
}
/// For printing in code completion results, replace archetypes with
/// protocol compositions.
///
/// FIXME: Perhaps this should be an option in PrintOptions instead.
Type eraseArchetypes(ModuleDecl *M, Type type, GenericSignature *genericSig) {
auto buildProtocolComposition = [&](ArrayRef<ProtocolDecl *> protos) -> Type {
SmallVector<Type, 2> types;
for (auto proto : protos)
types.push_back(proto->getDeclaredInterfaceType());
return ProtocolCompositionType::get(M->getASTContext(), types,
/*HasExplicitAnyObject=*/false);
};
if (auto *genericFuncType = type->getAs<GenericFunctionType>()) {
return GenericFunctionType::get(genericSig,
eraseArchetypes(M, genericFuncType->getInput(), genericSig),
eraseArchetypes(M, genericFuncType->getResult(), genericSig),
genericFuncType->getExtInfo());
}
return type.transform([&](Type t) -> Type {
// FIXME: Code completion should only deal with one or the other,
// and not both.
if (auto *archetypeType = t->getAs<ArchetypeType>()) {
auto protos = archetypeType->getConformsTo();
if (!protos.empty())
return buildProtocolComposition(protos);
}
if (t->isTypeParameter()) {
auto protos = genericSig->getConformsTo(t);
if (!protos.empty())
return buildProtocolComposition(protos);
}
return t;
});
}
Type getTypeOfMember(const ValueDecl *VD, Optional<Type> ExprType = None) {
if (!ExprType)
ExprType = this->ExprType;
auto *M = CurrDeclContext->getParentModule();
auto *GenericSig = VD->getInnermostDeclContext()
->getGenericSignatureOfContext();
Type T = VD->getInterfaceType();
if (*ExprType) {
Type ContextTy = VD->getDeclContext()->getDeclaredInterfaceType();
if (ContextTy) {
// Look through lvalue types and metatypes
Type MaybeNominalType = (*ExprType)->getRValueType();
if (auto Metatype = MaybeNominalType->getAs<MetatypeType>())
MaybeNominalType = Metatype->getInstanceType();
if (auto SelfType = MaybeNominalType->getAs<DynamicSelfType>())
MaybeNominalType = SelfType->getSelfType();
// For optional protocol requirements and dynamic dispatch,
// strip off optionality from the base type, but only if
// we're not actually completing a member of Optional.
if (!ContextTy->getOptionalObjectType() &&
MaybeNominalType->getOptionalObjectType())
MaybeNominalType = MaybeNominalType->getOptionalObjectType();
// For dynamic lookup don't substitute in the base type.
if (MaybeNominalType->isAnyObject())
return T;
// FIXME: Sometimes ExprType is the type of the member here,
// and not the type of the base. That is inconsistent and
// should be cleaned up.
if (!MaybeNominalType->mayHaveMembers())
return T;
// For everything else, substitute in the base type.
auto Subs = MaybeNominalType->getMemberSubstitutionMap(M, VD);
// Pass in DesugarMemberTypes so that we see the actual
// concrete type witnesses instead of type alias types.
T = T.subst(Subs,
(SubstFlags::DesugarMemberTypes |
SubstFlags::UseErrorType));
}
}
return eraseArchetypes(M, T, GenericSig);
}
Type getAssociatedTypeType(const AssociatedTypeDecl *ATD) {
Type BaseTy = BaseType;
if (!BaseTy)
BaseTy = ExprType;
if (!BaseTy && CurrDeclContext)
BaseTy = CurrDeclContext->getInnermostTypeContext()
->getDeclaredTypeInContext();
if (BaseTy) {
BaseTy = BaseTy->getRValueInstanceType();
if (auto NTD = BaseTy->getAnyNominal()) {
auto *Module = NTD->getParentModule();
auto Conformance = Module->lookupConformance(
BaseTy, ATD->getProtocol());
if (Conformance && Conformance->isConcrete()) {
return Conformance->getConcrete()
->getTypeWitness(const_cast<AssociatedTypeDecl *>(ATD),
TypeResolver.get());
}
}
}
return Type();
}
void addVarDeclRef(const VarDecl *VD, DeclVisibilityKind Reason) {
if (!VD->hasName() ||
(VD->hasAccess() && !VD->isAccessibleFrom(CurrDeclContext)) ||
shouldHideDeclFromCompletionResults(VD))
return;
StringRef Name = VD->getName().get();
assert(!Name.empty() && "name should not be empty");
CommandWordsPairs Pairs;
CodeCompletionResultBuilder Builder(
Sink,
CodeCompletionResult::ResultKind::Declaration,
getSemanticContext(VD, Reason), ExpectedTypes);
Builder.setAssociatedDecl(VD);
addLeadingDot(Builder);
Builder.addTextChunk(Name);
setClangDeclKeywords(VD, Pairs, Builder);
// Add a type annotation.
Type VarType = getTypeOfMember(VD);
if (VD->getName() == Ctx.Id_self) {
// Strip inout from 'self'. It is useful to show inout for function
// parameters. But for 'self' it is just noise.
VarType = VarType->getInOutObjectType();
}
auto DynamicOrOptional =
IsDynamicLookup || VD->getAttrs().hasAttribute<OptionalAttr>();
if (DynamicOrOptional) {
// Values of properties that were found on a AnyObject have
// Optional<T> type. Same applies to optional members.
VarType = OptionalType::get(VarType);
}
if (VD->getAttrs().hasAttribute<ImplicitlyUnwrappedOptionalAttr>())
addTypeAnnotationForImplicitlyUnwrappedOptional(Builder, VarType,
DynamicOrOptional);
else
addTypeAnnotation(Builder, VarType);
}
void addParameters(CodeCompletionResultBuilder &Builder,
const ParameterList *params) {
bool NeedComma = false;
for (auto ¶m : *params) {
if (NeedComma)
Builder.addComma();
NeedComma = true;
Type type = param->getInterfaceType();
if (param->isVariadic())
type = ParamDecl::getVarargBaseTy(type);
auto isIUO =
param->getAttrs().hasAttribute<ImplicitlyUnwrappedOptionalAttr>();
Builder.addCallParameter(param->getArgumentName(), type,
param->isVariadic(), /*Outermost*/ true,
param->isInOut(), isIUO);
}
}
void addPatternFromTypeImpl(CodeCompletionResultBuilder &Builder, Type T,
Identifier Label, bool IsTopLevel, bool IsVarArg) {
if (auto *TT = T->getAs<TupleType>()) {
if (!Label.empty()) {
Builder.addTextChunk(Label.str());
Builder.addTextChunk(": ");
}
if (!IsTopLevel || !HaveLParen)
Builder.addLeftParen();
else
Builder.addAnnotatedLeftParen();
bool NeedComma = false;
for (auto TupleElt : TT->getElements()) {
if (NeedComma)
Builder.addComma();
Type EltT = TupleElt.isVararg() ? TupleElt.getVarargBaseTy()
: TupleElt.getType();
addPatternFromTypeImpl(Builder, EltT, TupleElt.getName(), false,
TupleElt.isVararg());
NeedComma = true;
}
Builder.addRightParen();
return;
}
if (auto *PT = dyn_cast<ParenType>(T.getPointer())) {
if (IsTopLevel && !HaveLParen)
Builder.addLeftParen();
else if (IsTopLevel)
Builder.addAnnotatedLeftParen();
Builder.addCallParameter(Identifier(), PT->getUnderlyingType(),
/*IsVarArg*/ false, IsTopLevel,
PT->getParameterFlags().isInOut(),
/*isIUO*/ false);
if (IsTopLevel)
Builder.addRightParen();
return;
}
if (IsTopLevel && !HaveLParen)
Builder.addLeftParen();
else if (IsTopLevel)
Builder.addAnnotatedLeftParen();
Builder.addCallParameter(Label, T, IsVarArg, IsTopLevel, /*isInOut*/ false,
/*isIUO*/ false);
if (IsTopLevel)
Builder.addRightParen();
}
void addPatternFromType(CodeCompletionResultBuilder &Builder, Type T) {
addPatternFromTypeImpl(Builder, T, Identifier(), true, /*isVarArg*/false);
}
static bool hasInterestingDefaultValues(const AbstractFunctionDecl *func) {
if (!func) return false;
bool isMemberOfType = func->getDeclContext()->isTypeContext();
for (auto param : *func->getParameterList(isMemberOfType ? 1 : 0)) {
switch (param->getDefaultArgumentKind()) {
case DefaultArgumentKind::Normal:
case DefaultArgumentKind::Inherited: // FIXME: include this?
return true;
default:
break;
}
}
return false;
}
// Returns true if any content was added to Builder.
bool addParamPatternFromFunction(CodeCompletionResultBuilder &Builder,
const AnyFunctionType *AFT,
const AbstractFunctionDecl *AFD,
bool includeDefaultArgs = true) {
const ParameterList *BodyParams = nullptr;
if (AFD) {
BodyParams = AFD->getParameterList(AFD->getImplicitSelfDecl() ? 1 : 0);
// FIXME: Hack because we don't know which parameter list we're
// actually working with.
unsigned expectedNumParams;
if (auto *TT = dyn_cast<TupleType>(AFT->getInput().getPointer()))
expectedNumParams = TT->getNumElements();
else
expectedNumParams = 1;
if (expectedNumParams != BodyParams->size()) {
// Adjust to the "self" list if that is present, otherwise give up.
if (expectedNumParams == 1 && AFD->getImplicitSelfDecl())
BodyParams = AFD->getParameterList(0);
else
BodyParams = nullptr;
}
}
bool modifiedBuilder = false;
// Determine whether we should skip this argument because it is defaulted.
auto shouldSkipArg = [&](unsigned i) -> bool {
if (!BodyParams || i >= BodyParams->size())
return false;
switch (BodyParams->get(i)->getDefaultArgumentKind()) {
case DefaultArgumentKind::None:
return false;
case DefaultArgumentKind::Normal:
case DefaultArgumentKind::Inherited:
case DefaultArgumentKind::NilLiteral:
case DefaultArgumentKind::EmptyArray:
case DefaultArgumentKind::EmptyDictionary:
return !includeDefaultArgs;
case DefaultArgumentKind::File:
case DefaultArgumentKind::Line:
case DefaultArgumentKind::Column:
case DefaultArgumentKind::Function:
case DefaultArgumentKind::DSOHandle:
// Skip parameters that are defaulted to source location or other
// caller context information. Users typically don't want to specify
// these parameters.
return true;
}
llvm_unreachable("Unhandled DefaultArgumentKind in switch.");
};
// Do not desugar AFT->getInput(), as we want to treat (_: (a,b)) distinctly
// from (a,b) for code-completion.
if (auto *TT = dyn_cast<TupleType>(AFT->getInput().getPointer())) {
bool NeedComma = false;
// Iterate over the tuple type fields, corresponding to each parameter.
for (unsigned i = 0, e = TT->getNumElements(); i != e; ++i) {
// If we should skip this argument, do so.
if (shouldSkipArg(i)) continue;
const auto &TupleElt = TT->getElement(i);
auto ParamType = TupleElt.isVararg() ? TupleElt.getVarargBaseTy()
: TupleElt.getType();
auto Name = TupleElt.getName();
if (NeedComma)
Builder.addComma();
if (BodyParams) {
auto *PD = BodyParams->get(i);
// If we have a local name for the parameter, pass in that as well.
auto argName = PD->getArgumentName();
auto bodyName = PD->getName();
auto isIUO =
PD->getAttrs().hasAttribute<ImplicitlyUnwrappedOptionalAttr>();
Builder.addCallParameter(argName, bodyName, ParamType,
TupleElt.isVararg(), true,
TupleElt.isInOut(), isIUO);
} else {
Builder.addCallParameter(Name, ParamType, TupleElt.isVararg(),
/*TopLevel*/ true, TupleElt.isInOut(),
/*isIUO*/ false);
}
modifiedBuilder = true;
NeedComma = true;
}
} else if (!shouldSkipArg(0)) {
// If it's not a tuple, it could be a unary function.
Type T = AFT->getInput();
bool isInOut = false;
if (auto *PT = dyn_cast<ParenType>(T.getPointer())) {
// Only unwrap the paren sugar, if it exists.
T = PT->getUnderlyingType();
isInOut = PT->getParameterFlags().isInOut();
}
modifiedBuilder = true;
if (BodyParams) {
auto *PD = BodyParams->get(0);
auto argName = PD->getArgumentName();
auto bodyName = PD->getName();
auto isIUO =
PD->getAttrs().hasAttribute<ImplicitlyUnwrappedOptionalAttr>();
Builder.addCallParameter(argName, bodyName, T,
/*IsVarArg*/ false, /*Toplevel*/ true, isInOut,
isIUO);
} else
Builder.addCallParameter(Identifier(), T, /*IsVarArg*/ false,
/*TopLevel*/ true, isInOut,
/*isIUO*/ false);
}
return modifiedBuilder;
}
static void addThrows(CodeCompletionResultBuilder &Builder,
const AnyFunctionType *AFT,
const AbstractFunctionDecl *AFD) {
if (AFD && AFD->getAttrs().hasAttribute<RethrowsAttr>())
Builder.addAnnotatedRethrows();
else if (AFT->throws())
Builder.addAnnotatedThrows();
}
void addPoundAvailable(StmtKind ParentKind) {
if (ParentKind != StmtKind::If && ParentKind != StmtKind::Guard)
return;
CodeCompletionResultBuilder Builder(Sink, CodeCompletionResult::ResultKind::Keyword,
SemanticContextKind::ExpressionSpecific, ExpectedTypes);
Builder.addTextChunk("available");
Builder.addLeftParen();
Builder.addSimpleTypedParameter("Platform", /*IsVarArg=*/true);
Builder.addComma();
Builder.addTextChunk("*");
Builder.addRightParen();
}
void addPoundSelector(bool needPound) {
// #selector is only available when the Objective-C runtime is.
if (!Ctx.LangOpts.EnableObjCInterop) return;
CodeCompletionResultBuilder Builder(
Sink,
CodeCompletionResult::ResultKind::Keyword,
SemanticContextKind::ExpressionSpecific,
ExpectedTypes);
if (needPound)
Builder.addTextChunk("#selector");
else
Builder.addTextChunk("selector");
Builder.addLeftParen();
Builder.addSimpleTypedParameter("@objc method", /*IsVarArg=*/false);
Builder.addRightParen();
}
void addPoundKeyPath(bool needPound) {
// #keyPath is only available when the Objective-C runtime is.
if (!Ctx.LangOpts.EnableObjCInterop) return;
// After #, this is a very likely result. When just in a String context,
// it's not.
auto semanticContext = needPound ? SemanticContextKind::None
: SemanticContextKind::ExpressionSpecific;
CodeCompletionResultBuilder Builder(
Sink,
CodeCompletionResult::ResultKind::Keyword,
semanticContext, ExpectedTypes);
if (needPound)
Builder.addTextChunk("#keyPath");
else
Builder.addTextChunk("keyPath");
Builder.addLeftParen();
Builder.addSimpleTypedParameter("@objc property sequence",
/*IsVarArg=*/false);
Builder.addRightParen();
}
void addFunctionCallPattern(const AnyFunctionType *AFT,
const AbstractFunctionDecl *AFD = nullptr) {
if (AFD)
foundFunction(AFD);
else
foundFunction(AFT);
// Add the pattern, possibly including any default arguments.
auto addPattern = [&](bool includeDefaultArgs = true) {
// FIXME: to get the corect semantic context we need to know how lookup
// would have found the declaration AFD. For now, just choose a reasonable
// default, it's most likely to be CurrentModule or CurrentNominal.
CodeCompletionResultBuilder Builder(
Sink, CodeCompletionResult::ResultKind::Pattern,
SemanticContextKind::CurrentModule, ExpectedTypes);
if (!HaveLParen)
Builder.addLeftParen();
else
Builder.addAnnotatedLeftParen();
bool anyParam = addParamPatternFromFunction(Builder, AFT, AFD, includeDefaultArgs);
if (HaveLParen && !anyParam) {
// Empty result, don't add it.
Builder.cancel();
return;
}
// The rparen matches the lparen here so that we insert both or neither.
if (!HaveLParen)
Builder.addRightParen();
else
Builder.addAnnotatedRightParen();
addThrows(Builder, AFT, AFD);
if (AFD &&
AFD->getAttrs().hasAttribute<ImplicitlyUnwrappedOptionalAttr>())
addTypeAnnotationForImplicitlyUnwrappedOptional(Builder,
AFT->getResult());
else
addTypeAnnotation(Builder, AFT->getResult());
};
if (hasInterestingDefaultValues(AFD))
addPattern(/*includeDefaultArgs*/ false);
addPattern();
}
bool isImplicitlyCurriedInstanceMethod(const AbstractFunctionDecl *FD) {
switch (Kind) {
case LookupKind::ValueExpr:
return ExprType->is<AnyMetatypeType>() && !FD->isStatic();
case LookupKind::ValueInDeclContext:
if (InsideStaticMethod &&
FD->getDeclContext() == CurrentMethod->getDeclContext() &&
!FD->isStatic())
return true;
if (auto Init = dyn_cast<Initializer>(CurrDeclContext))
return FD->getDeclContext() == Init->getParent() && !FD->isStatic();
return false;
case LookupKind::EnumElement:
case LookupKind::Type:
case LookupKind::TypeInDeclContext:
llvm_unreachable("cannot have a method call while doing a "
"type completion");
case LookupKind::ImportFromModule:
return false;
}
llvm_unreachable("Unhandled LookupKind in switch.");
}
void addMethodCall(const FuncDecl *FD, DeclVisibilityKind Reason) {
if (FD->getName().empty())
return;
foundFunction(FD);
bool IsImplicitlyCurriedInstanceMethod =
isImplicitlyCurriedInstanceMethod(FD);
StringRef Name = FD->getName().get();
assert(!Name.empty() && "name should not be empty");
unsigned FirstIndex = 0;
if (!IsImplicitlyCurriedInstanceMethod && FD->getImplicitSelfDecl())
FirstIndex = 1;
Type FunctionType = getTypeOfMember(FD);
assert(FunctionType);
if (FirstIndex != 0 && FunctionType->is<AnyFunctionType>())
FunctionType = FunctionType->castTo<AnyFunctionType>()->getResult();
bool trivialTrailingClosure = false;
if (!IsImplicitlyCurriedInstanceMethod &&
FunctionType->is<AnyFunctionType>()) {
trivialTrailingClosure = hasTrivialTrailingClosure(
FD, FunctionType->castTo<AnyFunctionType>());
}
// Add the method, possibly including any default arguments.
auto addMethodImpl = [&](bool includeDefaultArgs = true,
bool trivialTrailingClosure = false) {
CommandWordsPairs Pairs;
CodeCompletionResultBuilder Builder(
Sink, CodeCompletionResult::ResultKind::Declaration,
getSemanticContext(FD, Reason), ExpectedTypes);
setClangDeclKeywords(FD, Pairs, Builder);
Builder.setAssociatedDecl(FD);
addLeadingDot(Builder);
Builder.addTextChunk(Name);
if (IsDynamicLookup)
Builder.addDynamicLookupMethodCallTail();
else if (FD->getAttrs().hasAttribute<OptionalAttr>())
Builder.addOptionalMethodCallTail();
llvm::SmallString<32> TypeStr;
if (!FunctionType->is<AnyFunctionType>()) {
llvm::raw_svector_ostream OS(TypeStr);
FunctionType.print(OS);
Builder.addTypeAnnotation(OS.str());
return;
}
Type FirstInputType = FunctionType->castTo<AnyFunctionType>()->getInput();
if (IsImplicitlyCurriedInstanceMethod) {
bool isInOut = false;
if (auto PT = dyn_cast<ParenType>(FirstInputType.getPointer())) {
FirstInputType = PT->getUnderlyingType();
isInOut = PT->getParameterFlags().isInOut();
}
Builder.addLeftParen();
Builder.addCallParameter(Ctx.Id_self, FirstInputType,
/*IsVarArg*/ false, /*TopLevel*/ true, isInOut,
/*isIUO*/ false);
Builder.addRightParen();
} else if (trivialTrailingClosure) {
Builder.addBraceStmtWithCursor(" { code }");
} else {
Builder.addLeftParen();
auto AFT = FunctionType->castTo<AnyFunctionType>();
addParamPatternFromFunction(Builder, AFT, FD, includeDefaultArgs);
Builder.addRightParen();
addThrows(Builder, AFT, FD);
}
Type ResultType = FunctionType->castTo<AnyFunctionType>()->getResult();
// Build type annotation.
{
llvm::raw_svector_ostream OS(TypeStr);
for (unsigned i = FirstIndex + 1, e = FD->getParameterLists().size();
i != e; ++i) {
ResultType->castTo<AnyFunctionType>()->getInput()->print(OS);
ResultType = ResultType->castTo<AnyFunctionType>()->getResult();
OS << " -> ";
}
// What's left is the result type.
if (ResultType->isVoid()) {
OS << "Void";
} else if (!IsImplicitlyCurriedInstanceMethod
&& FD->getAttrs().hasAttribute<ImplicitlyUnwrappedOptionalAttr>()) {
// As we did with parameters in addParamPatternFromFunction,
// for regular methods we'll print '!' after implicitly
// unwrapped optional results.
auto ObjectType = ResultType->getOptionalObjectType();
OS << ObjectType->getStringAsComponent();
OS << "!";
} else {
ResultType.print(OS);
}
}
Builder.addTypeAnnotation(TypeStr);
};
if (FunctionType->is<AnyFunctionType>() &&
hasInterestingDefaultValues(FD)) {
addMethodImpl(/*includeDefaultArgs*/ false);
}
if (trivialTrailingClosure) {
addMethodImpl(/*includeDefaultArgs=*/false,
/*trivialTrailingClosure=*/true);
}
addMethodImpl();
}
void addConstructorCall(const ConstructorDecl *CD, DeclVisibilityKind Reason,
Optional<Type> BaseType, Optional<Type> Result,
bool IsOnMetatype = true,
Identifier addName = Identifier()) {
foundFunction(CD);
Type MemberType = getTypeOfMember(CD, BaseType);
AnyFunctionType *ConstructorType = nullptr;
if (auto MemberFuncType = MemberType->getAs<AnyFunctionType>())
ConstructorType = MemberFuncType->getResult()
->castTo<AnyFunctionType>();
bool needInit = false;
if (!IsOnMetatype) {
assert(addName.empty());
assert(isa<ConstructorDecl>(CurrDeclContext) &&
"can call super.init only inside a constructor");
needInit = true;
} else if (addName.empty() && HaveDot &&
Reason == DeclVisibilityKind::MemberOfCurrentNominal) {
// This case is querying the init function as member
needInit = true;
}
// If we won't be able to provide a result, bail out.
if (MemberType->hasError() && addName.empty() && !needInit)
return;
// Add the constructor, possibly including any default arguments.
auto addConstructorImpl = [&](bool includeDefaultArgs = true) {
CommandWordsPairs Pairs;
CodeCompletionResultBuilder Builder(
Sink, CodeCompletionResult::ResultKind::Declaration,
getSemanticContext(CD, Reason), ExpectedTypes);
setClangDeclKeywords(CD, Pairs, Builder);
Builder.setAssociatedDecl(CD);
if (needInit) {
assert(addName.empty());
addLeadingDot(Builder);
Builder.addTextChunk("init");
} else if (!addName.empty()) {
Builder.addTextChunk(addName.str());
} else {
assert(!MemberType->hasError() && "will insert empty result");
}
if (!ConstructorType) {
addTypeAnnotation(Builder, MemberType);
return;
}
assert(ConstructorType);
if (!HaveLParen)
Builder.addLeftParen();
else
Builder.addAnnotatedLeftParen();
bool anyParam = addParamPatternFromFunction(Builder, ConstructorType, CD,
includeDefaultArgs);
if (HaveLParen && !anyParam) {
// Empty result, don't add it.
Builder.cancel();
return;
}
// The rparen matches the lparen here so that we insert both or neither.
if (!HaveLParen)
Builder.addRightParen();
else
Builder.addAnnotatedRightParen();
addThrows(Builder, ConstructorType, CD);
if (CD->getAttrs().hasAttribute<ImplicitlyUnwrappedOptionalAttr>()) {
addTypeAnnotationForImplicitlyUnwrappedOptional(
Builder, Result.hasValue() ? Result.getValue()
: ConstructorType->getResult());
} else {
addTypeAnnotation(Builder, Result.hasValue()
? Result.getValue()
: ConstructorType->getResult());
}
};
if (ConstructorType && hasInterestingDefaultValues(CD))
addConstructorImpl(/*includeDefaultArgs*/ false);
addConstructorImpl();
}
void addConstructorCallsForType(Type type, Identifier name,
DeclVisibilityKind Reason) {
if (!Ctx.LangOpts.CodeCompleteInitsInPostfixExpr)
return;
assert(CurrDeclContext);
SmallVector<ValueDecl *, 16> initializers;
if (CurrDeclContext->lookupQualified(type, DeclBaseName::createConstructor(),
NL_QualifiedDefault,
TypeResolver.get(), initializers)) {
for (auto *init : initializers) {
if (shouldHideDeclFromCompletionResults(init))
continue;
addConstructorCall(cast<ConstructorDecl>(init), Reason, type, None,
/*IsOnMetatype=*/true, name);
}
}
}
bool shouldAddSubscriptCall() {
if (IsSwiftKeyPathExpr)
return true;
return !HaveDot;
}
void addSubscriptCall(const SubscriptDecl *SD, DeclVisibilityKind Reason) {
assert(shouldAddSubscriptCall() && "cannot add a subscript after a dot");
CommandWordsPairs Pairs;
CodeCompletionResultBuilder Builder(
Sink,
CodeCompletionResult::ResultKind::Declaration,
getSemanticContext(SD, Reason), ExpectedTypes);
Builder.setAssociatedDecl(SD);
setClangDeclKeywords(SD, Pairs, Builder);
Builder.addLeftBracket();
addParameters(Builder, SD->getIndices());
Builder.addRightBracket();
// Add a type annotation.
Type T = SD->getElementInterfaceType();
if (IsDynamicLookup) {
// Values of properties that were found on a AnyObject have
// Optional<T> type.
T = OptionalType::get(T);
}
addTypeAnnotation(Builder, T);
}
void addNominalTypeRef(const NominalTypeDecl *NTD,
DeclVisibilityKind Reason) {
CommandWordsPairs Pairs;
CodeCompletionResultBuilder Builder(
Sink,
CodeCompletionResult::ResultKind::Declaration,
getSemanticContext(NTD, Reason), ExpectedTypes);
Builder.setAssociatedDecl(NTD);
setClangDeclKeywords(NTD, Pairs, Builder);
addLeadingDot(Builder);
Builder.addTextChunk(NTD->getName().str());
addTypeAnnotation(Builder, NTD->getDeclaredType());
}
void addTypeAliasRef(const TypeAliasDecl *TAD, DeclVisibilityKind Reason) {
CommandWordsPairs Pairs;
CodeCompletionResultBuilder Builder(
Sink,
CodeCompletionResult::ResultKind::Declaration,
getSemanticContext(TAD, Reason), ExpectedTypes);
Builder.setAssociatedDecl(TAD);
setClangDeclKeywords(TAD, Pairs, Builder);
addLeadingDot(Builder);
Builder.addTextChunk(TAD->getName().str());
if (TAD->hasInterfaceType()) {
auto underlyingType = TAD->getUnderlyingTypeLoc().getType();
if (underlyingType->hasError()) {
Type parentType;
if (auto nominal =
TAD->getDeclContext()
->getAsNominalTypeOrNominalTypeExtensionContext()) {
parentType = nominal->getDeclaredInterfaceType();
}
addTypeAnnotation(
Builder,
NameAliasType::get(const_cast<TypeAliasDecl *>(TAD),
parentType, SubstitutionMap(),
underlyingType));
} else {
addTypeAnnotation(Builder, underlyingType);
}
}
}
void addGenericTypeParamRef(const GenericTypeParamDecl *GP,
DeclVisibilityKind Reason) {
CommandWordsPairs Pairs;
CodeCompletionResultBuilder Builder(
Sink,
CodeCompletionResult::ResultKind::Declaration,
getSemanticContext(GP, Reason), ExpectedTypes);
setClangDeclKeywords(GP, Pairs, Builder);
Builder.setAssociatedDecl(GP);
addLeadingDot(Builder);
Builder.addTextChunk(GP->getName().str());
addTypeAnnotation(Builder, GP->getDeclaredInterfaceType());
}
void addAssociatedTypeRef(const AssociatedTypeDecl *AT,
DeclVisibilityKind Reason) {
CommandWordsPairs Pairs;
CodeCompletionResultBuilder Builder(
Sink,
CodeCompletionResult::ResultKind::Declaration,
getSemanticContext(AT, Reason), ExpectedTypes);
setClangDeclKeywords(AT, Pairs, Builder);
Builder.setAssociatedDecl(AT);
addLeadingDot(Builder);
Builder.addTextChunk(AT->getName().str());
if (Type T = getAssociatedTypeType(AT))
addTypeAnnotation(Builder, T);
}
void addEnumElementRef(const EnumElementDecl *EED,
DeclVisibilityKind Reason,
bool HasTypeContext) {
if (!EED->hasName() ||
(EED->hasAccess() && !EED->isAccessibleFrom(CurrDeclContext)) ||
shouldHideDeclFromCompletionResults(EED))
return;
CommandWordsPairs Pairs;
CodeCompletionResultBuilder Builder(
Sink,
CodeCompletionResult::ResultKind::Declaration,
HasTypeContext ? SemanticContextKind::ExpressionSpecific
: getSemanticContext(EED, Reason), ExpectedTypes);
Builder.setAssociatedDecl(EED);
setClangDeclKeywords(EED, Pairs, Builder);
addLeadingDot(Builder);
Builder.addTextChunk(EED->getName().str());
if (auto *params = EED->getParameterList()) {
Builder.addLeftParen();
addParameters(Builder, params);
Builder.addRightParen();
}
// Enum element is of function type such as EnumName.type -> Int ->
// EnumName; however we should show Int -> EnumName as the type
Type EnumType;
if (EED->hasInterfaceType()) {
EnumType = EED->getInterfaceType();
if (auto FuncType = EnumType->getAs<AnyFunctionType>()) {
EnumType = FuncType->getResult();
}
}
if (EnumType)
addTypeAnnotation(Builder, EnumType);
}
void addKeyword(StringRef Name, Type TypeAnnotation,
SemanticContextKind SK = SemanticContextKind::None) {
CodeCompletionResultBuilder Builder(
Sink,
CodeCompletionResult::ResultKind::Keyword, SK, ExpectedTypes);
addLeadingDot(Builder);
Builder.addTextChunk(Name);
if (!TypeAnnotation.isNull())
addTypeAnnotation(Builder, TypeAnnotation);
}
void addKeyword(StringRef Name, StringRef TypeAnnotation) {
CodeCompletionResultBuilder Builder(
Sink,
CodeCompletionResult::ResultKind::Keyword,
SemanticContextKind::None, ExpectedTypes);
addLeadingDot(Builder);
Builder.addTextChunk(Name);
if (!TypeAnnotation.empty())
Builder.addTypeAnnotation(TypeAnnotation);
}
void addDeclAttrParamKeyword(StringRef Name, StringRef Annotation,
bool NeedSpecify) {
CodeCompletionResultBuilder Builder(
Sink,
CodeCompletionResult::ResultKind::Keyword,
SemanticContextKind::None, ExpectedTypes);
Builder.addDeclAttrParamKeyword(Name, Annotation, NeedSpecify);
}
void addDeclAttrKeyword(StringRef Name, StringRef Annotation) {
CodeCompletionResultBuilder Builder(
Sink,
CodeCompletionResult::ResultKind::Keyword,
SemanticContextKind::None, ExpectedTypes);
Builder.addDeclAttrKeyword(Name, Annotation);
}
/// Add the compound function name for the given function.
void addCompoundFunctionName(AbstractFunctionDecl *AFD,
DeclVisibilityKind Reason) {
CommandWordsPairs Pairs;
CodeCompletionResultBuilder Builder(
Sink, CodeCompletionResult::ResultKind::Declaration,
getSemanticContext(AFD, Reason), ExpectedTypes);
setClangDeclKeywords(AFD, Pairs, Builder);
Builder.setAssociatedDecl(AFD);
// Base name
addLeadingDot(Builder);
Builder.addTextChunk(AFD->getBaseName().userFacingName());
// Add the argument labels.
auto ArgLabels = AFD->getFullName().getArgumentNames();
if (!ArgLabels.empty()) {
if (!HaveLParen)
Builder.addLeftParen();
else
Builder.addAnnotatedLeftParen();
for (auto ArgLabel : ArgLabels) {
if (ArgLabel.empty())
Builder.addTextChunk("_");
else
Builder.addTextChunk(ArgLabel.str());
Builder.addTextChunk(":");
}
Builder.addRightParen();
}
}
// Implement swift::VisibleDeclConsumer.
void foundDecl(ValueDecl *D, DeclVisibilityKind Reason) override {
if (shouldHideDeclFromCompletionResults(D))
return;
if (IsKeyPathExpr && !KeyPathFilter(D, Reason))
return;
if (IsSwiftKeyPathExpr && !SwiftKeyPathFilter(D, Reason))
return;
if (!D->hasInterfaceType())
TypeResolver->resolveDeclSignature(D);
else if (isa<TypeAliasDecl>(D)) {
// A TypeAliasDecl might have type set, but not the underlying type.
TypeResolver->resolveDeclSignature(D);
}
switch (Kind) {
case LookupKind::ValueExpr:
if (auto *CD = dyn_cast<ConstructorDecl>(D)) {
// Do we want compound function names here?
if (shouldUseFunctionReference(CD)) {
addCompoundFunctionName(CD, Reason);
return;
}
if (auto MT = ExprType->getRValueType()->getAs<AnyMetatypeType>()) {
if (HaveDot) {
Type Ty;
for (Ty = MT; Ty && Ty->is<AnyMetatypeType>();
Ty = Ty->getAs<AnyMetatypeType>()->getInstanceType());
assert(Ty && "Cannot find instance type.");
// Add init() as member of the metatype.
if (Reason == DeclVisibilityKind::MemberOfCurrentNominal) {
if (IsStaticMetatype || CD->isRequired() ||
!Ty->is<ClassType>())
addConstructorCall(CD, Reason, None, None);
}
return;
}
}
if (auto MT = ExprType->getAs<AnyMetatypeType>()) {
if (HaveDot)
return;
// If instance type is type alias, showing users that the constructed
// type is the typealias instead of the underlying type of the alias.
Optional<Type> Result = None;
if (auto AT = MT->getInstanceType()) {
if (!CD->getInterfaceType()->is<ErrorType>() &&
(isa<NameAliasType>(AT.getPointer()) &&
AT->getDesugaredType() ==
CD->getResultInterfaceType().getPointer()))
Result = AT;
}
addConstructorCall(CD, Reason, None, Result);
}
if (IsSuperRefExpr || IsSelfRefExpr) {
if (!isa<ConstructorDecl>(CurrDeclContext))
return;
addConstructorCall(CD, Reason, None, None, /*IsOnMetatype=*/false);
}
return;
}
if (HaveLParen)
return;
if (auto *VD = dyn_cast<VarDecl>(D)) {
addVarDeclRef(VD, Reason);
return;
}
if (auto *FD = dyn_cast<FuncDecl>(D)) {
// We cannot call operators with a postfix parenthesis syntax.
if (FD->isBinaryOperator() || FD->isUnaryOperator())
return;
// We cannot call accessors. We use VarDecls and SubscriptDecls to
// produce completions that refer to getters and setters.
if (isa<AccessorDecl>(FD))
return;
// Do we want compound function names here?
if (shouldUseFunctionReference(FD)) {
addCompoundFunctionName(FD, Reason);
return;
}
addMethodCall(FD, Reason);
return;
}
if (auto *NTD = dyn_cast<NominalTypeDecl>(D)) {
addNominalTypeRef(NTD, Reason);
addConstructorCallsForType(NTD->getDeclaredInterfaceType(),
NTD->getName(), Reason);
return;
}
if (auto *TAD = dyn_cast<TypeAliasDecl>(D)) {
addTypeAliasRef(TAD, Reason);
auto type = TAD->mapTypeIntoContext(TAD->getUnderlyingTypeLoc().getType());
if (type->mayHaveMembers())
addConstructorCallsForType(type, TAD->getName(), Reason);
return;
}
if (auto *GP = dyn_cast<GenericTypeParamDecl>(D)) {
addGenericTypeParamRef(GP, Reason);
for (auto *protocol : GP->getConformingProtocols())
addConstructorCallsForType(protocol->getDeclaredInterfaceType(),
GP->getName(), Reason);
return;
}
if (auto *AT = dyn_cast<AssociatedTypeDecl>(D)) {
addAssociatedTypeRef(AT, Reason);
return;
}
if (auto *EED = dyn_cast<EnumElementDecl>(D)) {
addEnumElementRef(EED, Reason, /*HasTypeContext=*/false);
}
// Swift key path allows .[0]
if (shouldAddSubscriptCall()) {
if (auto *SD = dyn_cast<SubscriptDecl>(D)) {
if (ExprType->is<AnyMetatypeType>())
return;
addSubscriptCall(SD, Reason);
}
}
return;
case LookupKind::ValueInDeclContext:
case LookupKind::ImportFromModule:
if (auto *VD = dyn_cast<VarDecl>(D)) {
addVarDeclRef(VD, Reason);
return;
}
if (auto *FD = dyn_cast<FuncDecl>(D)) {
// We cannot call operators with a postfix parenthesis syntax.
if (FD->isBinaryOperator() || FD->isUnaryOperator())
return;
// We cannot call accessors. We use VarDecls and SubscriptDecls to
// produce completions that refer to getters and setters.
if (isa<AccessorDecl>(FD))
return;
// Do we want compound function names here?
if (shouldUseFunctionReference(FD)) {
addCompoundFunctionName(FD, Reason);
return;
}
addMethodCall(FD, Reason);
return;
}
if (auto *NTD = dyn_cast<NominalTypeDecl>(D)) {
addNominalTypeRef(NTD, Reason);
addConstructorCallsForType(NTD->getDeclaredInterfaceType(),
NTD->getName(), Reason);
return;
}
if (auto *TAD = dyn_cast<TypeAliasDecl>(D)) {
addTypeAliasRef(TAD, Reason);
auto type = TAD->mapTypeIntoContext(TAD->getDeclaredInterfaceType());
if (type->mayHaveMembers())
addConstructorCallsForType(type, TAD->getName(), Reason);
return;
}
if (auto *GP = dyn_cast<GenericTypeParamDecl>(D)) {
addGenericTypeParamRef(GP, Reason);
for (auto *protocol : GP->getConformingProtocols())
addConstructorCallsForType(protocol->getDeclaredInterfaceType(),
GP->getName(), Reason);
return;
}
if (auto *AT = dyn_cast<AssociatedTypeDecl>(D)) {
addAssociatedTypeRef(AT, Reason);
return;
}
return;
case LookupKind::EnumElement:
handleEnumElement(D, Reason);
return;
case LookupKind::Type:
case LookupKind::TypeInDeclContext:
if (auto *NTD = dyn_cast<NominalTypeDecl>(D)) {
addNominalTypeRef(NTD, Reason);
return;
}
if (auto *TAD = dyn_cast<TypeAliasDecl>(D)) {
addTypeAliasRef(TAD, Reason);
return;
}
if (auto *GP = dyn_cast<GenericTypeParamDecl>(D)) {
addGenericTypeParamRef(GP, Reason);
return;
}
if (auto *AT = dyn_cast<AssociatedTypeDecl>(D)) {
addAssociatedTypeRef(AT, Reason);
return;
}
return;
}
}
bool handleEnumElement(ValueDecl *D, DeclVisibilityKind Reason) {
if (!D->hasInterfaceType())
TypeResolver->resolveDeclSignature(D);
if (auto *EED = dyn_cast<EnumElementDecl>(D)) {
addEnumElementRef(EED, Reason, /*HasTypeContext=*/true);
return true;
} else if (auto *ED = dyn_cast<EnumDecl>(D)) {
llvm::DenseSet<EnumElementDecl *> Elements;
ED->getAllElements(Elements);
for (auto *Ele : Elements) {
if (!Ele->hasInterfaceType())
TypeResolver->resolveDeclSignature(Ele);
addEnumElementRef(Ele, Reason, /*HasTypeContext=*/true);
}
return true;
}
return false;
}
bool tryTupleExprCompletions(Type ExprType) {
auto *TT = ExprType->getAs<TupleType>();
if (!TT)
return false;
unsigned Index = 0;
for (auto TupleElt : TT->getElements()) {
CodeCompletionResultBuilder Builder(
Sink,
CodeCompletionResult::ResultKind::Pattern,
SemanticContextKind::CurrentNominal, ExpectedTypes);
addLeadingDot(Builder);
if (TupleElt.hasName()) {
Builder.addTextChunk(TupleElt.getName().str());
} else {
llvm::SmallString<4> IndexStr;
{
llvm::raw_svector_ostream OS(IndexStr);
OS << Index;
}
Builder.addTextChunk(IndexStr.str());
}
addTypeAnnotation(Builder, TupleElt.getType());
Index++;
}
return true;
}
bool tryFunctionCallCompletions(Type ExprType, const ValueDecl *VD) {
ExprType = ExprType->getRValueType();
if (auto AFT = ExprType->getAs<AnyFunctionType>()) {
if (auto *AFD = dyn_cast_or_null<AbstractFunctionDecl>(VD)) {
addFunctionCallPattern(AFT, AFD);
} else {
addFunctionCallPattern(AFT);
}
return true;
}
return false;
}
bool tryModuleCompletions(Type ExprType) {
if (auto MT = ExprType->getAs<ModuleType>()) {
ModuleDecl *M = MT->getModule();
if (CurrDeclContext->getParentModule() != M) {
// Only use the cache if it is not the current module.
RequestedCachedResults = RequestedResultsTy::fromModule(M)
.needLeadingDot(needDot());
return true;
}
}
return false;
}
/// If the given ExprType is optional, this adds completions for the unwrapped
/// type.
///
/// \return true if the given type was Optional .
bool tryUnwrappedCompletions(Type ExprType, bool isIUO) {
// FIXME: consider types convertible to T?.
ExprType = ExprType->getRValueType();
// FIXME: We don't always pass down whether a type is from an
// unforced IUO.
if (isIUO) {
if (Type Unwrapped = ExprType->getOptionalObjectType()) {
lookupVisibleMemberDecls(*this, Unwrapped, CurrDeclContext,
TypeResolver.get(), IncludeInstanceMembers);
return true;
}
assert(IsUnwrappedOptional && "IUOs should be optional if not bound/forced");
return false;
}
if (Type Unwrapped = ExprType->getOptionalObjectType()) {
llvm::SaveAndRestore<bool> ChangeNeedOptionalUnwrap(NeedOptionalUnwrap,
true);
if (DotLoc.isValid()) {
NumBytesToEraseForOptionalUnwrap = Ctx.SourceMgr.getByteDistance(
DotLoc, Ctx.SourceMgr.getCodeCompletionLoc());
} else {
NumBytesToEraseForOptionalUnwrap = 0;
}
if (NumBytesToEraseForOptionalUnwrap <=
CodeCompletionResult::MaxNumBytesToErase) {
if (!tryTupleExprCompletions(Unwrapped)) {
lookupVisibleMemberDecls(*this, Unwrapped, CurrDeclContext,
TypeResolver.get(),
IncludeInstanceMembers);
}
}
return true;
}
return false;
}
void getValueExprCompletions(Type ExprType, ValueDecl *VD = nullptr) {
Kind = LookupKind::ValueExpr;
NeedLeadingDot = !HaveDot;
// This is horrible
ExprType = ExprType->getRValueType();
this->ExprType = ExprType;
if (ExprType->hasTypeParameter()) {
DeclContext *DC;
if (VD) {
DC = VD->getInnermostDeclContext();
this->ExprType = DC->mapTypeIntoContext(ExprType);
} else if (auto NTD = ExprType->getRValueInstanceType()->getAnyNominal()) {
DC = NTD;
this->ExprType = DC->mapTypeIntoContext(ExprType);
}
}
// Handle special cases
bool isIUO = VD && VD->getAttrs()
.hasAttribute<ImplicitlyUnwrappedOptionalAttr>();
if (tryFunctionCallCompletions(ExprType, VD))
return;
if (tryModuleCompletions(ExprType))
return;
if (tryTupleExprCompletions(ExprType))
return;
// Don't check/return so we still add the members of Optional itself below
tryUnwrappedCompletions(ExprType, isIUO);
lookupVisibleMemberDecls(*this, ExprType, CurrDeclContext,
TypeResolver.get(), IncludeInstanceMembers);
}
template <typename T>
void collectOperatorsFromMap(SourceFile::OperatorMap<T> &map,
bool includePrivate,
std::vector<OperatorDecl *> &results) {
for (auto &pair : map) {
if (pair.second.getPointer() &&
(pair.second.getInt() || includePrivate)) {
results.push_back(pair.second.getPointer());
}
}
}
void collectOperatorsFrom(SourceFile *SF,
std::vector<OperatorDecl *> &results) {
bool includePrivate = CurrDeclContext->getParentSourceFile() == SF;
collectOperatorsFromMap(SF->PrefixOperators, includePrivate, results);
collectOperatorsFromMap(SF->PostfixOperators, includePrivate, results);
collectOperatorsFromMap(SF->InfixOperators, includePrivate, results);
}
void collectOperatorsFrom(LoadedFile *F,
std::vector<OperatorDecl *> &results) {
SmallVector<Decl *, 64> topLevelDecls;
F->getTopLevelDecls(topLevelDecls);
for (auto D : topLevelDecls) {
if (auto op = dyn_cast<OperatorDecl>(D))
results.push_back(op);
}
}
std::vector<OperatorDecl *> collectOperators() {
std::vector<OperatorDecl *> results;
assert(CurrDeclContext);
CurrDeclContext->getParentSourceFile()->forAllVisibleModules(
[&](ModuleDecl::ImportedModule import) {
for (auto fileUnit : import.second->getFiles()) {
switch (fileUnit->getKind()) {
case FileUnitKind::Builtin:
case FileUnitKind::Derived:
case FileUnitKind::ClangModule:
continue;
case FileUnitKind::Source:
collectOperatorsFrom(cast<SourceFile>(fileUnit), results);
break;
case FileUnitKind::SerializedAST:
collectOperatorsFrom(cast<LoadedFile>(fileUnit), results);
break;
}
}
});
return results;
}
void addPostfixBang(Type resultType) {
CodeCompletionResultBuilder builder(
Sink, CodeCompletionResult::ResultKind::BuiltinOperator,
SemanticContextKind::None, {});
// FIXME: we can't use the exclamation mark chunk kind, or it isn't
// included in the completion name.
builder.addTextChunk("!");
assert(resultType);
addTypeAnnotation(builder, resultType);
}
void addPostfixOperatorCompletion(OperatorDecl *op, Type resultType) {
// FIXME: we should get the semantic context of the function, not the
// operator decl.
auto semanticContext =
getSemanticContext(op, DeclVisibilityKind::VisibleAtTopLevel);
CodeCompletionResultBuilder builder(
Sink, CodeCompletionResult::ResultKind::Declaration, semanticContext,
{});
// FIXME: handle variable amounts of space.
if (HaveLeadingSpace)
builder.setNumBytesToErase(1);
builder.setAssociatedDecl(op);
builder.addTextChunk(op->getName().str());
assert(resultType);
addTypeAnnotation(builder, resultType);
}
void tryPostfixOperator(Expr *expr, PostfixOperatorDecl *op) {
if (!expr->getType())
return;
// We allocate these expressions on the stack because we know they can't
// escape and there isn't a better way to allocate scratch Expr nodes.
UnresolvedDeclRefExpr UDRE(op->getName(), DeclRefKind::PostfixOperator,
DeclNameLoc(expr->getSourceRange().End));
PostfixUnaryExpr opExpr(&UDRE, expr);
Expr *tempExpr = &opExpr;
ConcreteDeclRef referencedDecl;
if (auto T = getTypeOfCompletionContextExpr(
CurrDeclContext->getASTContext(),
const_cast<DeclContext *>(CurrDeclContext),
CompletionTypeCheckKind::Normal,
tempExpr,
referencedDecl))
addPostfixOperatorCompletion(op, *T);
}
void addAssignmentOperator(Type RHSType, Type resultType) {
CodeCompletionResultBuilder builder(
Sink, CodeCompletionResult::ResultKind::BuiltinOperator,
SemanticContextKind::None, {});
if (HaveLeadingSpace)
builder.addAnnotatedWhitespace(" ");
else
builder.addWhitespace(" ");
builder.addEqual();
builder.addWhitespace(" ");
assert(RHSType && resultType);
builder.addCallParameter(Identifier(), Identifier(), RHSType,
/*IsVarArg*/ false, /*TopLevel*/ true,
/*IsInOut*/ false, /*isIUO*/ false);
addTypeAnnotation(builder, resultType);
}
void addInfixOperatorCompletion(OperatorDecl *op, Type resultType,
Type RHSType) {
// FIXME: we should get the semantic context of the function, not the
// operator decl.
auto semanticContext =
getSemanticContext(op, DeclVisibilityKind::VisibleAtTopLevel);
CodeCompletionResultBuilder builder(
Sink, CodeCompletionResult::ResultKind::Declaration, semanticContext,
{});
builder.setAssociatedDecl(op);
if (HaveLeadingSpace)
builder.addAnnotatedWhitespace(" ");
else
builder.addWhitespace(" ");
builder.addTextChunk(op->getName().str());
builder.addWhitespace(" ");
if (RHSType)
builder.addCallParameter(Identifier(), Identifier(), RHSType, false, true,
/*IsInOut*/ false, /*isIUO*/ false);
if (resultType)
addTypeAnnotation(builder, resultType);
}
void tryInfixOperatorCompletion(InfixOperatorDecl *op, SequenceExpr *SE) {
if (op->getName().str() == "~>")
return;
MutableArrayRef<Expr *> sequence = SE->getElements();
assert(sequence.size() >= 3 && !sequence.back() &&
!sequence.drop_back(1).back() && "sequence not cleaned up");
assert((sequence.size() & 1) && "sequence expr ending with operator");
// FIXME: these checks should apply to the LHS of the operator, not the
// immediately left expression. Move under the type-checking.
Expr *LHS = sequence.drop_back(2).back();
if (LHS->getType() && (LHS->getType()->is<MetatypeType>() ||
LHS->getType()->is<AnyFunctionType>()))
return;
// We allocate these expressions on the stack because we know they can't
// escape and there isn't a better way to allocate scratch Expr nodes.
UnresolvedDeclRefExpr UDRE(op->getName(), DeclRefKind::BinaryOperator,
DeclNameLoc(LHS->getEndLoc()));
sequence.drop_back(1).back() = &UDRE;
CodeCompletionExpr CCE(LHS->getSourceRange());
sequence.back() = &CCE;
SWIFT_DEFER {
// Reset sequence.
SE->setElement(SE->getNumElements() - 1, nullptr);
SE->setElement(SE->getNumElements() - 2, nullptr);
prepareForRetypechecking(SE);
// Reset any references to operators in types, so they are properly
// handled as operators by sequence folding.
//
// FIXME: Would be better to have some kind of 'OperatorRefExpr'?
for (auto &element : sequence.drop_back(2)) {
if (auto operatorRef = element->getMemberOperatorRef()) {
operatorRef->setType(nullptr);
element = operatorRef;
}
}
};
Expr *expr = SE;
if (!typeCheckCompletionSequence(const_cast<DeclContext *>(CurrDeclContext),
expr)) {
if (!LHS->getType()->getRValueType()->getOptionalObjectType()) {
// Don't complete optional operators on non-optional types.
// FIXME: can we get the type-checker to disallow these for us?
if (op->getName().str() == "??")
return;
if (auto NT = CCE.getType()->getNominalOrBoundGenericNominal()) {
if (NT->getName() ==
CurrDeclContext->getASTContext().Id_OptionalNilComparisonType)
return;
}
}
// If the right-hand side and result type are both type parameters, we're
// not providing a useful completion.
if (expr->getType()->isTypeParameter() &&
CCE.getType()->isTypeParameter())
return;
addInfixOperatorCompletion(op, expr->getType(), CCE.getType());
}
}
void flattenBinaryExpr(BinaryExpr *expr, SmallVectorImpl<Expr *> &sequence) {
auto LHS = expr->getArg()->getElement(0);
if (auto binexpr = dyn_cast<BinaryExpr>(LHS))
flattenBinaryExpr(binexpr, sequence);
else
sequence.push_back(LHS);
sequence.push_back(expr->getFn());
auto RHS = expr->getArg()->getElement(1);
if (auto binexpr = dyn_cast<BinaryExpr>(RHS))
flattenBinaryExpr(binexpr, sequence);
else
sequence.push_back(RHS);
}
void typeCheckLeadingSequence(SmallVectorImpl<Expr *> &sequence) {
Expr *expr =
SequenceExpr::create(CurrDeclContext->getASTContext(), sequence);
prepareForRetypechecking(expr);
// Take advantage of the fact the type-checker leaves the types on the AST.
if (!typeCheckExpression(const_cast<DeclContext *>(CurrDeclContext),
expr)) {
if (auto binexpr = dyn_cast<BinaryExpr>(expr)) {
// Rebuild the sequence from the type-checked version.
sequence.clear();
flattenBinaryExpr(binexpr, sequence);
return;
}
}
// Fall back to just using the immediate LHS.
auto LHS = sequence.back();
sequence.clear();
sequence.push_back(LHS);
}
void getOperatorCompletions(Expr *LHS, ArrayRef<Expr *> leadingSequence) {
std::vector<OperatorDecl *> operators = collectOperators();
// FIXME: this always chooses the first operator with the given name.
llvm::DenseSet<Identifier> seenPostfixOperators;
llvm::DenseSet<Identifier> seenInfixOperators;
SmallVector<Expr *, 3> sequence(leadingSequence.begin(),
leadingSequence.end());
sequence.push_back(LHS);
assert((sequence.size() & 1) && "sequence expr ending with operator");
if (sequence.size() > 1)
typeCheckLeadingSequence(sequence);
// Create a single sequence expression, which we will modify for each
// operator, filling in the operator and dummy right-hand side.
sequence.push_back(nullptr); // operator
sequence.push_back(nullptr); // RHS
auto *SE = SequenceExpr::create(CurrDeclContext->getASTContext(), sequence);
prepareForRetypechecking(SE);
for (auto op : operators) {
switch (op->getKind()) {
case DeclKind::PrefixOperator:
// Don't insert prefix operators in postfix position.
// FIXME: where should these get completed?
break;
case DeclKind::PostfixOperator:
if (seenPostfixOperators.insert(op->getName()).second)
tryPostfixOperator(LHS, cast<PostfixOperatorDecl>(op));
break;
case DeclKind::InfixOperator:
if (seenInfixOperators.insert(op->getName()).second)
tryInfixOperatorCompletion(cast<InfixOperatorDecl>(op), SE);
break;
default:
llvm_unreachable("unexpected operator kind");
}
}
if (leadingSequence.empty() && LHS->getType() &&
LHS->getType()->hasLValueType()) {
addAssignmentOperator(LHS->getType()->getRValueType(),
CurrDeclContext->getASTContext().TheEmptyTupleType);
}
// FIXME: unify this with the ?.member completions.
if (auto T = LHS->getType())
if (auto ValueT = T->getRValueType()->getOptionalObjectType())
addPostfixBang(ValueT);
}
void addValueLiteralCompletions() {
auto &context = CurrDeclContext->getASTContext();
auto *module = CurrDeclContext->getParentModule();
auto addFromProto = [&](
CodeCompletionLiteralKind kind, StringRef defaultTypeName,
llvm::function_ref<void(CodeCompletionResultBuilder &)> consumer,
bool isKeyword = false) {
CodeCompletionResultBuilder builder(Sink, CodeCompletionResult::Literal,
SemanticContextKind::None, {});
builder.setLiteralKind(kind);
consumer(builder);
// Check for matching ExpectedTypes.
auto *P = context.getProtocol(protocolForLiteralKind(kind));
bool foundConformance = false;
for (auto T : ExpectedTypes) {
if (!T)
continue;
auto typeRelation = CodeCompletionResult::Identical;
// Convert through optional types unless we're looking for a protocol
// that Optional itself conforms to.
if (kind != CodeCompletionLiteralKind::NilLiteral) {
if (auto optionalObjT = T->getOptionalObjectType()) {
T = optionalObjT;
typeRelation = CodeCompletionResult::Convertible;
}
}
// Check for conformance to the literal protocol.
if (auto *NTD = T->getAnyNominal()) {
SmallVector<ProtocolConformance *, 2> conformances;
if (NTD->lookupConformance(module, P, conformances)) {
foundConformance = true;
addTypeAnnotation(builder, T);
builder.setExpectedTypeRelation(typeRelation);
}
}
}
// Fallback to showing the default type.
if (!foundConformance && !defaultTypeName.empty())
builder.addTypeAnnotation(defaultTypeName);
};
// FIXME: the pedantically correct way is to resolve Swift.*LiteralType.
using LK = CodeCompletionLiteralKind;
using Builder = CodeCompletionResultBuilder;
// Add literal completions that conform to specific protocols.
addFromProto(LK::IntegerLiteral, "Int", [](Builder &builder) {
builder.addTextChunk("0");
});
addFromProto(LK::BooleanLiteral, "Bool", [](Builder &builder) {
builder.addTextChunk("true");
}, /*isKeyword=*/true);
addFromProto(LK::BooleanLiteral, "Bool", [](Builder &builder) {
builder.addTextChunk("false");
}, /*isKeyword=*/true);
addFromProto(LK::NilLiteral, "", [](Builder &builder) {
builder.addTextChunk("nil");
}, /*isKeyword=*/true);
addFromProto(LK::StringLiteral, "String", [&](Builder &builder) {
builder.addTextChunk("\"");
builder.addSimpleNamedParameter("abc");
builder.addTextChunk("\"");
});
addFromProto(LK::ArrayLiteral, "Array", [&](Builder &builder) {
builder.addLeftBracket();
builder.addSimpleNamedParameter("values");
builder.addRightBracket();
});
addFromProto(LK::DictionaryLiteral, "Dictionary", [&](Builder &builder) {
builder.addLeftBracket();
builder.addSimpleNamedParameter("key");
builder.addTextChunk(": ");
builder.addSimpleNamedParameter("value");
builder.addRightBracket();
});
auto floatType = context.getFloatDecl()->getDeclaredType();
addFromProto(LK::ColorLiteral, "", [&](Builder &builder) {
builder.addTextChunk("#colorLiteral");
builder.addLeftParen();
builder.addCallParameter(context.getIdentifier("red"), floatType, false,
true, /*IsInOut*/ false,
/*isIUO*/ false);
builder.addComma();
builder.addCallParameter(context.getIdentifier("green"), floatType, false,
true, /*IsInOut*/ false,
/*isIUO*/ false);
builder.addComma();
builder.addCallParameter(context.getIdentifier("blue"), floatType, false,
true, /*IsInOut*/ false,
/*isIUO*/ false);
builder.addComma();
builder.addCallParameter(context.getIdentifier("alpha"), floatType, false,
true, /*IsInOut*/ false,
/*isIUO*/ false);
builder.addRightParen();
});
auto stringType = context.getStringDecl()->getDeclaredType();
addFromProto(LK::ImageLiteral, "", [&](Builder &builder) {
builder.addTextChunk("#imageLiteral");
builder.addLeftParen();
builder.addCallParameter(context.getIdentifier("resourceName"),
stringType, false, true, /*IsInOut*/ false,
/*isIUO*/ false);
builder.addRightParen();
});
// Add tuple completion (item, item).
{
CodeCompletionResultBuilder builder(Sink, CodeCompletionResult::Literal,
SemanticContextKind::None, {});
builder.setLiteralKind(LK::Tuple);
builder.addLeftParen();
builder.addSimpleNamedParameter("values");
builder.addRightParen();
for (auto T : ExpectedTypes) {
if (!T)
continue;
if (T->is<TupleType>()) {
addTypeAnnotation(builder, T);
builder.setExpectedTypeRelation(CodeCompletionResult::Identical);
break;
}
}
}
}
struct FilteredDeclConsumer : public swift::VisibleDeclConsumer {
swift::VisibleDeclConsumer &Consumer;
DeclFilter Filter;
FilteredDeclConsumer(swift::VisibleDeclConsumer &Consumer,
DeclFilter Filter) : Consumer(Consumer), Filter(Filter) {}
void foundDecl(ValueDecl *VD, DeclVisibilityKind Kind) override {
if (Filter(VD, Kind))
Consumer.foundDecl(VD, Kind);
}
};
void getValueCompletionsInDeclContext(SourceLoc Loc,
DeclFilter Filter = DefaultFilter,
bool IncludeTopLevel = false,
bool RequestCache = true,
bool LiteralCompletions = true) {
ExprType = Type();
Kind = LookupKind::ValueInDeclContext;
NeedLeadingDot = false;
FilteredDeclConsumer Consumer(*this, Filter);
lookupVisibleDecls(Consumer, CurrDeclContext, TypeResolver.get(),
/*IncludeTopLevel=*/IncludeTopLevel, Loc);
if (RequestCache)
RequestedCachedResults = RequestedResultsTy::toplevelResults();
// Manually add any expected nominal types from imported modules so that
// they get their expected type relation. Don't include protocols, since
// they can't be initialized from the type name.
// FIXME: this does not include types that conform to an expected protocol.
// FIXME: this creates duplicate results.
for (auto T : ExpectedTypes) {
if (auto NT = T->getAs<NominalType>()) {
if (auto NTD = NT->getDecl()) {
if (!isa<ProtocolDecl>(NTD) &&
NTD->getModuleContext() != CurrDeclContext->getParentModule()) {
addNominalTypeRef(NT->getDecl(),
DeclVisibilityKind::VisibleAtTopLevel);
}
}
}
}
if (CompletionContext) {
// FIXME: this is an awful simplification that says all and only enums can
// use implicit member syntax (leading dot). Computing the accurate answer
// using lookup (e.g. getUnresolvedMemberCompletions) is too expensive,
// and for some clients this approximation is good enough.
CompletionContext->MayUseImplicitMemberExpr =
std::any_of(ExpectedTypes.begin(), ExpectedTypes.end(), [](Type T) {
if (auto *NTD = T->getAnyNominal())
return isa<EnumDecl>(NTD);
return false;
});
}
if (LiteralCompletions)
addValueLiteralCompletions();
// If the expected type is ObjectiveC.Selector, add #selector. If
// it's String, add #keyPath.
if (Ctx.LangOpts.EnableObjCInterop) {
bool addedSelector = false;
bool addedKeyPath = false;
for (auto T : ExpectedTypes) {
T = T->lookThroughAllOptionalTypes();
if (auto structDecl = T->getStructOrBoundGenericStruct()) {
if (!addedSelector &&
structDecl->getName() == Ctx.Id_Selector &&
structDecl->getParentModule()->getName() == Ctx.Id_ObjectiveC) {
addPoundSelector(/*needPound=*/true);
if (addedKeyPath) break;
addedSelector = true;
continue;
}
}
if (!addedKeyPath && T->getAnyNominal() == Ctx.getStringDecl()) {
addPoundKeyPath(/*needPound=*/true);
if (addedSelector) break;
addedKeyPath = true;
continue;
}
}
}
}
struct LookupByName : public swift::VisibleDeclConsumer {
CompletionLookup &Lookup;
std::vector<std::string> &SortedNames;
llvm::SmallPtrSet<Decl*, 3> HandledDecls;
bool isNameHit(StringRef Name) {
return std::binary_search(SortedNames.begin(), SortedNames.end(), Name);
}
void unboxType(Type T) {
if (T->hasParenSugar()) {
unboxType(T->getDesugaredType());
} else if (T->is<TupleType>()) {
for (auto Ele : T->getAs<TupleType>()->getElements()) {
unboxType(Ele.getType());
}
} else if (auto FT = T->getAs<FunctionType>()) {
unboxType(FT->getInput());
unboxType(FT->getResult());
} else if (auto NTD = T->getNominalOrBoundGenericNominal()){
if (HandledDecls.insert(NTD).second)
Lookup.getUnresolvedMemberCompletions(T);
}
}
LookupByName(CompletionLookup &Lookup, std::vector<std::string> &SortedNames) :
Lookup(Lookup), SortedNames(SortedNames) {
std::sort(SortedNames.begin(), SortedNames.end());
}
void handleDeclRange(const DeclRange &Members,
DeclVisibilityKind Reason) {
for (auto M : Members) {
if (auto VD = dyn_cast<ValueDecl>(M)) {
foundDecl(VD, Reason);
}
}
}
void foundDecl(ValueDecl *VD, DeclVisibilityKind Reason) override {
if (auto NTD = dyn_cast<NominalTypeDecl>(VD)) {
if (isNameHit(NTD->getNameStr())) {
unboxType(NTD->getDeclaredType());
}
handleDeclRange(NTD->getMembers(), Reason);
for (auto Ex : NTD->getExtensions()) {
handleDeclRange(Ex->getMembers(), Reason);
}
} else if (!VD->getBaseName().isSpecial() &&
isNameHit(VD->getBaseName().getIdentifier().str())) {
if (VD->hasInterfaceType())
unboxType(VD->getInterfaceType());
}
}
};
void getUnresolvedMemberCompletions(ArrayRef<Type> Types) {
NeedLeadingDot = !HaveDot;
for (auto T : Types) {
if (T && T->getNominalOrBoundGenericNominal()) {
// We can only say .foo where foo is a static member of the contextual
// type and has the same type (or if the member is a function, then the
// same result type) as the contextual type.
FilteredDeclConsumer consumer(*this, [=](ValueDecl *VD, DeclVisibilityKind reason) {
if (!VD->hasInterfaceType()) {
TypeResolver->resolveDeclSignature(VD);
if (!VD->hasInterfaceType())
return false;
}
auto declTy = VD->getInterfaceType();
while (auto FT = declTy->getAs<AnyFunctionType>())
declTy = FT->getResult();
return declTy->isEqual(T);
});
auto baseType = MetatypeType::get(T);
llvm::SaveAndRestore<LookupKind> SaveLook(Kind, LookupKind::ValueExpr);
llvm::SaveAndRestore<Type> SaveType(ExprType, baseType);
llvm::SaveAndRestore<bool> SaveUnresolved(IsUnresolvedMember, true);
lookupVisibleMemberDecls(consumer, baseType, CurrDeclContext,
TypeResolver.get(),
/*includeInstanceMembers=*/false);
}
}
}
void getUnresolvedMemberCompletions(std::vector<std::string> &FuncNames,
bool HasReturn) {
NeedLeadingDot = !HaveDot;
LookupByName Lookup(*this, FuncNames);
lookupVisibleDecls(Lookup, CurrDeclContext, TypeResolver.get(), true);
if (HasReturn)
if (auto ReturnType = getReturnTypeFromContext(CurrDeclContext))
Lookup.unboxType(ReturnType);
}
static bool getPositionInTupleExpr(DeclContext &DC, Expr *Target,
TupleExpr *Tuple, unsigned &Pos,
bool &HasName) {
auto &SM = DC.getASTContext().SourceMgr;
Pos = 0;
for (auto E : Tuple->getElements()) {
if (SM.isBeforeInBuffer(E->getEndLoc(), Target->getStartLoc())) {
Pos ++;
continue;
}
HasName = !Tuple->getElementName(Pos).empty();
return true;
}
return false;
}
void addArgNameCompletionResults(ArrayRef<StringRef> Names) {
for (auto Name : Names) {
CodeCompletionResultBuilder Builder(Sink,
CodeCompletionResult::ResultKind::Keyword,
SemanticContextKind::ExpressionSpecific, {});
Builder.addTextChunk(Name);
Builder.addCallParameterColon();
Builder.addTypeAnnotation("Argument name");
}
}
static void collectArgumentExpectation(unsigned Position, bool HasName,
ArrayRef<Type> Types, SourceLoc Loc,
std::vector<Type> &ExpectedTypes,
std::vector<StringRef> &ExpectedNames) {
SmallPtrSet<TypeBase *, 4> seenTypes;
SmallPtrSet<const char *, 4> seenNames;
for (auto Type : Types) {
if (auto TT = Type->getAs<TupleType>()) {
if (Position >= TT->getElements().size()) {
continue;
}
auto Ele = TT->getElement(Position);
if (Ele.hasName() && !HasName) {
if (seenNames.insert(Ele.getName().get()).second)
ExpectedNames.push_back(Ele.getName().str());
} else {
if (seenTypes.insert(Ele.getType().getPointer()).second)
ExpectedTypes.push_back(Ele.getType());
}
} else if (Position == 0) {
// The only param.
TypeBase *T = Type->getDesugaredType();
if (seenTypes.insert(T).second)
ExpectedTypes.push_back(T);
}
}
}
bool lookupArgCompletionsAtPosition(unsigned Position, bool HasName,
ArrayRef<Type> Types, SourceLoc Loc) {
std::vector<Type> ExpectedTypes;
std::vector<StringRef> ExpectedNames;
collectArgumentExpectation(Position, HasName, Types, Loc, ExpectedTypes,
ExpectedNames);
addArgNameCompletionResults(ExpectedNames);
if (!ExpectedTypes.empty()) {
setExpectedTypes(ExpectedTypes);
getValueCompletionsInDeclContext(Loc, DefaultFilter);
}
return true;
}
static bool isPotentialSignatureMatch(ArrayRef<Type> TupleEles,
ArrayRef<Type> ExprTypes,
DeclContext *DC) {
// Not likely to be a match if users provide more arguments than expected.
if (ExprTypes.size() >= TupleEles.size())
return false;
for (unsigned I = 0; I < ExprTypes.size(); ++ I) {
auto Ty = ExprTypes[I];
if (Ty && !Ty->is<ErrorType>()) {
if (!isConvertibleTo(Ty, TupleEles[I], *DC)) {
return false;
}
}
}
return true;
}
static void removeUnlikelyOverloads(SmallVectorImpl<Type> &PossibleArgTypes,
ArrayRef<Type> TupleEleTypes,
DeclContext *DC) {
for (auto It = PossibleArgTypes.begin(); It != PossibleArgTypes.end(); ) {
llvm::SmallVector<Type, 3> ExpectedTypes;
if (isa<TupleType>((*It).getPointer())) {
auto Elements = (*It)->getAs<TupleType>()->getElements();
for (auto Ele : Elements)
ExpectedTypes.push_back(Ele.getType());
} else {
ExpectedTypes.push_back(*It);
}
if (isPotentialSignatureMatch(ExpectedTypes, TupleEleTypes, DC)) {
++ It;
} else {
PossibleArgTypes.erase(It);
}
}
}
static bool collectionInputTypes(DeclContext &DC, CallExpr *callExpr,
SmallVectorImpl<Type> &possibleTypes) {
auto *fnExpr = callExpr->getFn();
if (auto type = fnExpr->getType()) {
if (auto *funcType = type->getAs<AnyFunctionType>())
possibleTypes.push_back(funcType->getInput());
} else if (auto *DRE = dyn_cast<DeclRefExpr>(fnExpr)) {
if (auto *decl = DRE->getDecl()) {
auto declType = decl->getInterfaceType();
if (auto *funcType = declType->getAs<AnyFunctionType>())
possibleTypes.push_back(funcType->getInput());
}
} else if (auto *OSRE = dyn_cast<OverloadSetRefExpr>(fnExpr)) {
for (auto *decl : OSRE->getDecls()) {
auto declType = decl->getInterfaceType();
if (auto *funcType = declType->getAs<AnyFunctionType>())
possibleTypes.push_back(funcType->getInput());
}
} else {
ConcreteDeclRef ref = nullptr;
auto fnType = getTypeOfCompletionContextExpr(DC.getASTContext(),
&DC, CompletionTypeCheckKind::Normal,
fnExpr, ref);
if (!fnType)
return false;
if (auto *AFT = (*fnType)->getAs<AnyFunctionType>())
possibleTypes.push_back(AFT->getInput());
}
return !possibleTypes.empty();
}
static bool collectPossibleArgTypes(DeclContext &DC, CallExpr *CallE,
Expr *CCExpr,
SmallVectorImpl<Type> &PossibleTypes,
unsigned &Position, bool &HasName) {
if (!collectionInputTypes(DC, CallE, PossibleTypes))
return false;
if (auto *tuple = dyn_cast<TupleExpr>(CallE->getArg())) {
for (unsigned i = 0, n = tuple->getNumElements(); i != n; ++i) {
if (isa<CodeCompletionExpr>(tuple->getElement(i))) {
HasName = !tuple->getElementName(i).empty();
Position = i;
return true;
}
}
return getPositionInTupleExpr(DC, CCExpr, tuple, Position, HasName);
} else if (isa<ParenExpr>(CallE->getArg())) {
HasName = false;
Position = 0;
return true;
}
return false;
}
static bool
collectArgumentExpectation(DeclContext &DC, CallExpr *CallE, Expr *CCExpr,
std::vector<Type> &ExpectedTypes,
std::vector<StringRef> &ExpectedNames) {
SmallVector<Type, 2> PossibleTypes;
unsigned Position;
bool HasName;
if (collectPossibleArgTypes(DC, CallE, CCExpr, PossibleTypes, Position,
HasName)) {
collectArgumentExpectation(Position, HasName, PossibleTypes,
CCExpr->getStartLoc(), ExpectedTypes, ExpectedNames);
return !ExpectedTypes.empty() || !ExpectedNames.empty();
}
return false;
}
bool getCallArgCompletions(DeclContext &DC, CallExpr *CallE, Expr *CCExpr) {
SmallVector<Type, 2> PossibleTypes;
unsigned Position;
bool HasName;
bool hasPossibleArgTypes = collectPossibleArgTypes(DC, CallE, CCExpr,
PossibleTypes, Position,
HasName);
bool hasCompletions = lookupArgCompletionsAtPosition(Position, HasName,
PossibleTypes,
CCExpr->getStartLoc());
return hasPossibleArgTypes && hasCompletions;
}
void getTypeContextEnumElementCompletions(SourceLoc Loc) {
llvm::SaveAndRestore<LookupKind> ChangeLookupKind(
Kind, LookupKind::EnumElement);
NeedLeadingDot = !HaveDot;
const DeclContext *FunctionDC = CurrDeclContext;
const AbstractFunctionDecl *CurrentFunction = nullptr;
while (FunctionDC->isLocalContext()) {
if (auto *AFD = dyn_cast<AbstractFunctionDecl>(FunctionDC)) {
CurrentFunction = AFD;
break;
}
FunctionDC = FunctionDC->getParent();
}
if (!CurrentFunction)
return;
auto *Switch = cast_or_null<SwitchStmt>(
findNearestStmt(CurrentFunction, Loc, StmtKind::Switch));
if (!Switch)
return;
auto Ty = Switch->getSubjectExpr()->getType();
if (!Ty)
return;
auto *TheEnumDecl = dyn_cast_or_null<EnumDecl>(Ty->getAnyNominal());
if (!TheEnumDecl)
return;
for (auto Element : TheEnumDecl->getAllElements()) {
foundDecl(Element, DeclVisibilityKind::MemberOfCurrentNominal);
}
}
void getTypeCompletions(Type BaseType) {
Kind = LookupKind::Type;
this->BaseType = BaseType;
NeedLeadingDot = !HaveDot;
Type MetaBase = MetatypeType::get(BaseType);
lookupVisibleMemberDecls(*this, MetaBase,
CurrDeclContext, TypeResolver.get(),
IncludeInstanceMembers);
addKeyword("Type", MetaBase);
addKeyword("self", BaseType, SemanticContextKind::CurrentNominal);
}
static bool canUseAttributeOnDecl(DeclAttrKind DAK, bool IsInSil,
Optional<DeclKind> DK) {
if (DeclAttribute::isUserInaccessible(DAK))
return false;
if (DeclAttribute::isDeclModifier(DAK))
return false;
if (DeclAttribute::shouldBeRejectedByParser(DAK))
return false;
if (!IsInSil && DeclAttribute::isSilOnly(DAK))
return false;
if (!DK.hasValue())
return true;
return DeclAttribute::canAttributeAppearOnDeclKind(DAK, DK.getValue());
}
void getAttributeDeclCompletions(bool IsInSil, Optional<DeclKind> DK) {
// FIXME: also include user-defined attribute keywords
StringRef TargetName = "Declaration";
if (DK.hasValue()) {
switch (DK.getValue()) {
#define DECL(Id, ...) \
case DeclKind::Id: \
TargetName = #Id; \
break;
#include "swift/AST/DeclNodes.def"
}
}
std::string Description = TargetName.str() + " Attribute";
#define DECL_ATTR(KEYWORD, NAME, ...) \
if (canUseAttributeOnDecl(DAK_##NAME, IsInSil, DK)) \
addDeclAttrKeyword(#KEYWORD, Description);
#include "swift/AST/Attr.def"
}
void getAttributeDeclParamCompletions(DeclAttrKind AttrKind, int ParamIndex) {
if (AttrKind == DAK_Available) {
if (ParamIndex == 0) {
addDeclAttrParamKeyword("*", "Platform", false);
#define AVAILABILITY_PLATFORM(X, PrettyName) \
addDeclAttrParamKeyword(#X, "Platform", false);
#include "swift/AST/PlatformKinds.def"
} else {
addDeclAttrParamKeyword("unavailable", "", false);
addDeclAttrParamKeyword("message", "Specify message", true);
addDeclAttrParamKeyword("renamed", "Specify replacing name", true);
addDeclAttrParamKeyword("introduced", "Specify version number", true);
addDeclAttrParamKeyword("deprecated", "Specify version number", true);
}
}
}
void getPoundAvailablePlatformCompletions() {
// The platform names should be identical to those in @available.
getAttributeDeclParamCompletions(DAK_Available, 0);
}
void getTypeCompletionsInDeclContext(SourceLoc Loc) {
Kind = LookupKind::TypeInDeclContext;
lookupVisibleDecls(*this, CurrDeclContext, TypeResolver.get(),
/*IncludeTopLevel=*/false, Loc);
RequestedCachedResults =
RequestedResultsTy::toplevelResults().onlyTypes();
}
void getToplevelCompletions(bool OnlyTypes) {
Kind = OnlyTypes ? LookupKind::TypeInDeclContext
: LookupKind::ValueInDeclContext;
NeedLeadingDot = false;
ModuleDecl *M = CurrDeclContext->getParentModule();
AccessFilteringDeclConsumer FilteringConsumer(CurrDeclContext, *this,
TypeResolver.get());
M->lookupVisibleDecls({}, FilteringConsumer, NLKind::UnqualifiedLookup);
}
void getVisibleDeclsOfModule(const ModuleDecl *TheModule,
ArrayRef<std::string> AccessPath,
bool ResultsHaveLeadingDot) {
Kind = LookupKind::ImportFromModule;
NeedLeadingDot = ResultsHaveLeadingDot;
llvm::SmallVector<std::pair<Identifier, SourceLoc>, 1> LookupAccessPath;
for (auto Piece : AccessPath) {
LookupAccessPath.push_back(
std::make_pair(Ctx.getIdentifier(Piece), SourceLoc()));
}
AccessFilteringDeclConsumer FilteringConsumer(CurrDeclContext, *this,
TypeResolver.get());
TheModule->lookupVisibleDecls(LookupAccessPath, FilteringConsumer,
NLKind::UnqualifiedLookup);
}
};
class CompletionOverrideLookup : public swift::VisibleDeclConsumer {
CodeCompletionResultSink &Sink;
OwnedResolver TypeResolver;
const DeclContext *CurrDeclContext;
SmallVectorImpl<StringRef> &ParsedKeywords;
bool hasFuncIntroducer = false;
bool hasVarIntroducer = false;
bool hasTypealiasIntroducer = false;
bool hasInitializerModifier = false;
bool hasAccessModifier = false;
bool hasOverride = false;
bool hasOverridabilityModifier = false;
public:
CompletionOverrideLookup(CodeCompletionResultSink &Sink, ASTContext &Ctx,
const DeclContext *CurrDeclContext,
SmallVectorImpl<StringRef> &ParsedKeywords)
: Sink(Sink), TypeResolver(createLazyResolver(Ctx)),
CurrDeclContext(CurrDeclContext), ParsedKeywords(ParsedKeywords) {
hasFuncIntroducer = isKeywordSpecified("func");
hasVarIntroducer = isKeywordSpecified("var") ||
isKeywordSpecified("let");
hasTypealiasIntroducer = isKeywordSpecified("typealias");
hasInitializerModifier = isKeywordSpecified("required") ||
isKeywordSpecified("convenience");
hasAccessModifier = isKeywordSpecified("private") ||
isKeywordSpecified("fileprivate") ||
isKeywordSpecified("internal") ||
isKeywordSpecified("public") ||
isKeywordSpecified("open");
hasOverride = isKeywordSpecified("override");
hasOverridabilityModifier = isKeywordSpecified("final") ||
isKeywordSpecified("open");
}
bool isKeywordSpecified(StringRef Word) {
return std::find(ParsedKeywords.begin(), ParsedKeywords.end(), Word)
!= ParsedKeywords.end();
}
bool missingOverride(DeclVisibilityKind Reason) {
return !hasOverride && Reason == DeclVisibilityKind::MemberOfSuper &&
!CurrDeclContext->getAsProtocolOrProtocolExtensionContext();
}
void addAccessControl(const ValueDecl *VD,
CodeCompletionResultBuilder &Builder) {
assert(CurrDeclContext->getAsNominalTypeOrNominalTypeExtensionContext());
auto AccessOfContext =
CurrDeclContext->getAsNominalTypeOrNominalTypeExtensionContext()
->getFormalAccess();
auto Access = std::min(VD->getFormalAccess(), AccessOfContext);
// Only emit 'public', not needed otherwise.
if (Access >= AccessLevel::Public)
Builder.addAccessControlKeyword(Access);
}
void addValueOverride(const ValueDecl *VD, DeclVisibilityKind Reason,
CodeCompletionResultBuilder &Builder,
bool hasDeclIntroducer) {
class DeclNameOffsetLocatorPrinter : public StreamPrinter {
public:
using StreamPrinter::StreamPrinter;
Optional<unsigned> NameOffset;
void printDeclLoc(const Decl *D) override {
if (!NameOffset.hasValue())
NameOffset = OS.tell();
}
};
llvm::SmallString<256> DeclStr;
unsigned NameOffset = 0;
{
llvm::raw_svector_ostream OS(DeclStr);
DeclNameOffsetLocatorPrinter Printer(OS);
PrintOptions Options;
if (auto transformType = CurrDeclContext->getDeclaredTypeInContext())
Options.setBaseType(transformType);
Options.PrintDefaultParameterPlaceholder = false;
Options.PrintImplicitAttrs = false;
Options.ExclusiveAttrList.push_back(TAK_escaping);
Options.PrintOverrideKeyword = false;
Options.PrintPropertyAccessors = false;
VD->print(Printer, Options);
NameOffset = Printer.NameOffset.getValue();
}
if (!hasDeclIntroducer && !hasAccessModifier)
addAccessControl(VD, Builder);
// FIXME: if we're missing 'override', but have the decl introducer we
// should delete it and re-add both in the correct order.
if (!hasDeclIntroducer && missingOverride(Reason))
Builder.addOverrideKeyword();
if (!hasDeclIntroducer)
Builder.addDeclIntroducer(DeclStr.str().substr(0, NameOffset));
Builder.addTextChunk(DeclStr.str().substr(NameOffset));
}
void addMethodOverride(const FuncDecl *FD, DeclVisibilityKind Reason) {
CodeCompletionResultBuilder Builder(
Sink, CodeCompletionResult::ResultKind::Declaration,
SemanticContextKind::Super, {});
Builder.setAssociatedDecl(FD);
addValueOverride(FD, Reason, Builder, hasFuncIntroducer);
Builder.addBraceStmtWithCursor();
}
void addVarOverride(const VarDecl *VD, DeclVisibilityKind Reason) {
// Overrides cannot use 'let', but if the 'override' keyword is specified
// then the intention is clear, so provide the results anyway. The compiler
// can then provide an error telling you to use 'var' instead.
// If we don't need override then it's a protocol requirement, so show it.
if (missingOverride(Reason) && hasVarIntroducer &&
isKeywordSpecified("let"))
return;
CodeCompletionResultBuilder Builder(
Sink, CodeCompletionResult::ResultKind::Declaration,
SemanticContextKind::Super, {});
Builder.setAssociatedDecl(VD);
addValueOverride(VD, Reason, Builder, hasVarIntroducer);
}
void addTypeAlias(const AssociatedTypeDecl *ATD, DeclVisibilityKind Reason) {
CodeCompletionResultBuilder Builder(Sink,
CodeCompletionResult::ResultKind::Declaration,
SemanticContextKind::Super, {});
Builder.setAssociatedDecl(ATD);
if (!hasTypealiasIntroducer && !hasAccessModifier)
addAccessControl(ATD, Builder);
if (!hasTypealiasIntroducer)
Builder.addDeclIntroducer("typealias ");
Builder.addTextChunk(ATD->getName().str());
Builder.addTextChunk(" = ");
Builder.addSimpleNamedParameter("Type");
}
void addConstructor(const ConstructorDecl *CD, DeclVisibilityKind Reason) {
CodeCompletionResultBuilder Builder(
Sink,
CodeCompletionResult::ResultKind::Declaration,
SemanticContextKind::Super, {});
Builder.setAssociatedDecl(CD);
if (!hasAccessModifier)
addAccessControl(CD, Builder);
if (missingOverride(Reason) && CD->isDesignatedInit() && !CD->isRequired())
Builder.addOverrideKeyword();
// Emit 'required' if we're in class context, 'required' is not specified,
// and 1) this is a protocol conformance and the class is not final, or 2)
// this is subclass and the initializer is marked as required.
bool needRequired = false;
auto C = CurrDeclContext->getAsClassOrClassExtensionContext();
if (C && !isKeywordSpecified("required")) {
if (Reason ==
DeclVisibilityKind::MemberOfProtocolImplementedByCurrentNominal &&
!C->isFinal())
needRequired = true;
else if (Reason == DeclVisibilityKind::MemberOfSuper && CD->isRequired())
needRequired = true;
}
llvm::SmallString<256> DeclStr;
if (needRequired)
DeclStr += "required ";
{
llvm::raw_svector_ostream OS(DeclStr);
PrintOptions Options;
Options.PrintImplicitAttrs = false;
Options.SkipAttributes = true;
Options.PrintDefaultParameterPlaceholder = false;
CD->print(OS, Options);
}
Builder.addTextChunk(DeclStr);
Builder.addBraceStmtWithCursor();
}
// Implement swift::VisibleDeclConsumer.
void foundDecl(ValueDecl *D, DeclVisibilityKind Reason) override {
if (Reason == DeclVisibilityKind::MemberOfCurrentNominal)
return;
if (shouldHideDeclFromCompletionResults(D))
return;
if (D->getAttrs().hasAttribute<FinalAttr>())
return;
if (!D->hasInterfaceType())
TypeResolver->resolveDeclSignature(D);
bool hasIntroducer = hasFuncIntroducer ||
hasVarIntroducer ||
hasTypealiasIntroducer;
if (auto *FD = dyn_cast<FuncDecl>(D)) {
// We cannot override operators as members.
if (FD->isBinaryOperator() || FD->isUnaryOperator())
return;
// We cannot override individual accessors.
if (isa<AccessorDecl>(FD))
return;
if (hasFuncIntroducer || (!hasIntroducer && !hasInitializerModifier))
addMethodOverride(FD, Reason);
return;
}
if (auto *VD = dyn_cast<VarDecl>(D)) {
if (hasVarIntroducer || (!hasIntroducer && !hasInitializerModifier))
addVarOverride(VD, Reason);
return;
}
if (auto *CD = dyn_cast<ConstructorDecl>(D)) {
if (!isa<ProtocolDecl>(CD->getDeclContext()))
return;
if (hasIntroducer || hasOverride || hasOverridabilityModifier)
return;
if (CD->isRequired() || CD->isDesignatedInit())
addConstructor(CD, Reason);
return;
}
}
void addDesignatedInitializers(Type CurrTy) {
if (hasFuncIntroducer || hasVarIntroducer || hasTypealiasIntroducer ||
hasOverridabilityModifier)
return;
assert(CurrTy);
const auto *CD = dyn_cast_or_null<ClassDecl>(CurrTy->getAnyNominal());
if (!CD)
return;
if (!CD->getSuperclass())
return;
CD = CD->getSuperclass()->getClassOrBoundGenericClass();
for (const auto *Member : CD->getMembers()) {
const auto *Constructor = dyn_cast<ConstructorDecl>(Member);
if (!Constructor)
continue;
if (Constructor->hasStubImplementation())
continue;
if (Constructor->isDesignatedInit())
addConstructor(Constructor, DeclVisibilityKind::MemberOfSuper);
}
}
void addAssociatedTypes(Type CurrTy) {
if (!hasTypealiasIntroducer &&
(hasFuncIntroducer || hasVarIntroducer || hasInitializerModifier ||
hasOverride || hasOverridabilityModifier))
return;
NominalTypeDecl *NTD = CurrTy->getAnyNominal();
for (auto Conformance : NTD->getAllConformances()) {
auto Proto = Conformance->getProtocol();
if (!Proto->isAccessibleFrom(CurrDeclContext))
continue;
auto NormalConformance = Conformance->getRootNormalConformance();
for (auto Member : Proto->getMembers()) {
auto *ATD = dyn_cast<AssociatedTypeDecl>(Member);
if (!ATD)
continue;
// FIXME: Also exclude the type alias that has already been specified.
if (!NormalConformance->hasTypeWitness(ATD) ||
!ATD->getDefaultDefinitionLoc().isNull())
continue;
addTypeAlias(ATD,
DeclVisibilityKind::MemberOfProtocolImplementedByCurrentNominal);
}
}
}
void getOverrideCompletions(SourceLoc Loc) {
if (!CurrDeclContext->getAsNominalTypeOrNominalTypeExtensionContext())
return;
if (isa<ProtocolDecl>(CurrDeclContext))
return;
Type CurrTy = CurrDeclContext->getDeclaredTypeInContext();
if (CurrTy && !CurrTy->is<ErrorType>()) {
lookupVisibleMemberDecls(*this, CurrTy, CurrDeclContext,
TypeResolver.get(),
/*includeInstanceMembers=*/false);
addDesignatedInitializers(CurrTy);
addAssociatedTypes(CurrTy);
}
}
};
} // end anonymous namespace
static void addSelectorModifierKeywords(CodeCompletionResultSink &sink) {
auto addKeyword = [&](StringRef Name, CodeCompletionKeywordKind Kind) {
CodeCompletionResultBuilder Builder(
sink,
CodeCompletionResult::ResultKind::Keyword,
SemanticContextKind::None, {});
Builder.setKeywordKind(Kind);
Builder.addTextChunk(Name);
Builder.addCallParameterColon();
Builder.addSimpleTypedParameter("@objc property", /*IsVarArg=*/false);
};
addKeyword("getter", CodeCompletionKeywordKind::None);
addKeyword("setter", CodeCompletionKeywordKind::None);
}
void CodeCompletionCallbacksImpl::completeDotExpr(Expr *E, SourceLoc DotLoc) {
assert(P.Tok.is(tok::code_complete));
// Don't produce any results in an enum element.
if (InEnumElementRawValue)
return;
Kind = CompletionKind::DotExpr;
if (E->getKind() == ExprKind::KeyPath)
Kind = CompletionKind::SwiftKeyPath;
if (ParseExprSelectorContext != ObjCSelectorContext::None) {
PreferFunctionReferencesToCalls = true;
CompleteExprSelectorContext = ParseExprSelectorContext;
}
ParsedExpr = E;
this->DotLoc = DotLoc;
CurDeclContext = P.CurDeclContext;
}
void CodeCompletionCallbacksImpl::completeStmtOrExpr() {
assert(P.Tok.is(tok::code_complete));
Kind = CompletionKind::StmtOrExpr;
CurDeclContext = P.CurDeclContext;
}
void CodeCompletionCallbacksImpl::completePostfixExprBeginning(CodeCompletionExpr *E) {
assert(P.Tok.is(tok::code_complete));
// Don't produce any results in an enum element.
if (InEnumElementRawValue)
return;
Kind = CompletionKind::PostfixExprBeginning;
if (ParseExprSelectorContext != ObjCSelectorContext::None) {
PreferFunctionReferencesToCalls = true;
CompleteExprSelectorContext = ParseExprSelectorContext;
if (CompleteExprSelectorContext == ObjCSelectorContext::MethodSelector) {
addSelectorModifierKeywords(CompletionContext.getResultSink());
}
}
CurDeclContext = P.CurDeclContext;
CodeCompleteTokenExpr = E;
}
void CodeCompletionCallbacksImpl::completeForEachSequenceBeginning(
CodeCompletionExpr *E) {
assert(P.Tok.is(tok::code_complete));
Kind = CompletionKind::ForEachSequence;
CurDeclContext = P.CurDeclContext;
CodeCompleteTokenExpr = E;
}
void CodeCompletionCallbacksImpl::completePostfixExpr(Expr *E, bool hasSpace) {
assert(P.Tok.is(tok::code_complete));
// Don't produce any results in an enum element.
if (InEnumElementRawValue)
return;
HasSpace = hasSpace;
Kind = CompletionKind::PostfixExpr;
if (ParseExprSelectorContext != ObjCSelectorContext::None) {
PreferFunctionReferencesToCalls = true;
CompleteExprSelectorContext = ParseExprSelectorContext;
}
ParsedExpr = E;
CurDeclContext = P.CurDeclContext;
}
void CodeCompletionCallbacksImpl::completePostfixExprParen(Expr *E,
Expr *CodeCompletionE) {
assert(P.Tok.is(tok::code_complete));
// Don't produce any results in an enum element.
if (InEnumElementRawValue)
return;
Kind = CompletionKind::PostfixExprParen;
ParsedExpr = E;
CurDeclContext = P.CurDeclContext;
CodeCompleteTokenExpr = static_cast<CodeCompletionExpr*>(CodeCompletionE);
ShouldCompleteCallPatternAfterParen = true;
if (Context.LangOpts.CodeCompleteCallPatternHeuristics) {
// Lookahead one token to decide what kind of call completions to provide.
// When it appears that there is already code for the call present, just
// complete values and/or argument labels. Otherwise give the entire call
// pattern.
Token next = P.peekToken();
if (!next.isAtStartOfLine() && !next.is(tok::eof) && !next.is(tok::r_paren)) {
ShouldCompleteCallPatternAfterParen = false;
}
}
}
void CodeCompletionCallbacksImpl::completeExprSuper(SuperRefExpr *SRE) {
// Don't produce any results in an enum element.
if (InEnumElementRawValue)
return;
Kind = CompletionKind::SuperExpr;
if (ParseExprSelectorContext != ObjCSelectorContext::None) {
PreferFunctionReferencesToCalls = true;
CompleteExprSelectorContext = ParseExprSelectorContext;
}
ParsedExpr = SRE;
CurDeclContext = P.CurDeclContext;
}
void CodeCompletionCallbacksImpl::completeExprSuperDot(SuperRefExpr *SRE) {
// Don't produce any results in an enum element.
if (InEnumElementRawValue)
return;
Kind = CompletionKind::SuperExprDot;
if (ParseExprSelectorContext != ObjCSelectorContext::None) {
PreferFunctionReferencesToCalls = true;
CompleteExprSelectorContext = ParseExprSelectorContext;
}
ParsedExpr = SRE;
CurDeclContext = P.CurDeclContext;
}
void CodeCompletionCallbacksImpl::completeExprKeyPath(KeyPathExpr *KPE,
bool HasDot) {
Kind = HasDot ? CompletionKind::KeyPathExprDot : CompletionKind::KeyPathExpr;
ParsedExpr = KPE;
CurDeclContext = P.CurDeclContext;
}
void CodeCompletionCallbacksImpl::completePoundAvailablePlatform() {
Kind = CompletionKind::PoundAvailablePlatform;
CurDeclContext = P.CurDeclContext;
}
void CodeCompletionCallbacksImpl::completeTypeSimpleBeginning() {
Kind = CompletionKind::TypeSimpleBeginning;
CurDeclContext = P.CurDeclContext;
}
void CodeCompletionCallbacksImpl::completeDeclAttrParam(DeclAttrKind DK,
int Index) {
Kind = CompletionKind::AttributeDeclParen;
AttrKind = DK;
AttrParamIndex = Index;
CurDeclContext = P.CurDeclContext;
}
void CodeCompletionCallbacksImpl::completeDeclAttrKeyword(Decl *D,
bool Sil,
bool Param) {
Kind = CompletionKind::AttributeBegin;
IsInSil = Sil;
if (Param) {
AttTargetDK = DeclKind::Param;
} else if (D) {
AttTargetDK = D->getKind();
}
CurDeclContext = P.CurDeclContext;
}
void CodeCompletionCallbacksImpl::completeTypeIdentifierWithDot(
IdentTypeRepr *ITR) {
if (!ITR) {
completeTypeSimpleBeginning();
return;
}
Kind = CompletionKind::TypeIdentifierWithDot;
ParsedTypeLoc = TypeLoc(ITR);
CurDeclContext = P.CurDeclContext;
}
void CodeCompletionCallbacksImpl::completeTypeIdentifierWithoutDot(
IdentTypeRepr *ITR) {
assert(ITR);
Kind = CompletionKind::TypeIdentifierWithoutDot;
ParsedTypeLoc = TypeLoc(ITR);
CurDeclContext = P.CurDeclContext;
}
void CodeCompletionCallbacksImpl::completeCaseStmtBeginning() {
assert(!InEnumElementRawValue);
Kind = CompletionKind::CaseStmtBeginning;
CurDeclContext = P.CurDeclContext;
}
void CodeCompletionCallbacksImpl::completeCaseStmtDotPrefix() {
assert(!InEnumElementRawValue);
Kind = CompletionKind::CaseStmtDotPrefix;
CurDeclContext = P.CurDeclContext;
}
void CodeCompletionCallbacksImpl::completeImportDecl(
std::vector<std::pair<Identifier, SourceLoc>> &Path) {
Kind = CompletionKind::Import;
CurDeclContext = P.CurDeclContext;
DotLoc = Path.empty() ? SourceLoc() : Path.back().second;
if (DotLoc.isInvalid())
return;
auto Importer = static_cast<ClangImporter *>(CurDeclContext->getASTContext().
getClangModuleLoader());
std::vector<std::string> SubNames;
Importer->collectSubModuleNames(Path, SubNames);
ASTContext &Ctx = CurDeclContext->getASTContext();
for (StringRef Sub : SubNames) {
Path.push_back(std::make_pair(Ctx.getIdentifier(Sub), SourceLoc()));
SubModuleNameVisibilityPairs.push_back(
std::make_pair(Sub.str(), Ctx.getLoadedModule(Path)));
Path.pop_back();
}
}
void CodeCompletionCallbacksImpl::completeUnresolvedMember(UnresolvedMemberExpr *E,
ArrayRef<StringRef> Identifiers, bool HasReturn) {
Kind = CompletionKind::UnresolvedMember;
CurDeclContext = P.CurDeclContext;
UnresolvedExpr = E;
UnresolvedExprInReturn = HasReturn;
for (auto Id : Identifiers) {
TokensBeforeUnresolvedExpr.push_back(Id);
}
}
void CodeCompletionCallbacksImpl::completeAssignmentRHS(AssignExpr *E) {
AssignmentExpr = E;
ParsedExpr = E->getDest();
CurDeclContext = P.CurDeclContext;
Kind = CompletionKind::AssignmentRHS;
}
void CodeCompletionCallbacksImpl::completeCallArg(CallExpr *E) {
if (Kind == CompletionKind::PostfixExprBeginning ||
Kind == CompletionKind::None) {
CurDeclContext = P.CurDeclContext;
Kind = CompletionKind::CallArg;
FuncCallExpr = E;
ParsedExpr = E;
}
}
void CodeCompletionCallbacksImpl::completeReturnStmt(CodeCompletionExpr *E) {
CurDeclContext = P.CurDeclContext;
CodeCompleteTokenExpr = E;
Kind = CompletionKind::ReturnStmtExpr;
}
void CodeCompletionCallbacksImpl::completeAfterPound(CodeCompletionExpr *E,
StmtKind ParentKind) {
CurDeclContext = P.CurDeclContext;
CodeCompleteTokenExpr = E;
Kind = CompletionKind::AfterPound;
ParentStmtKind = ParentKind;
}
void CodeCompletionCallbacksImpl::completeGenericParams(TypeLoc TL) {
CurDeclContext = P.CurDeclContext;
Kind = CompletionKind::GenericParams;
ParsedTypeLoc = TL;
}
void CodeCompletionCallbacksImpl::completeNominalMemberBeginning(
SmallVectorImpl<StringRef> &Keywords) {
assert(!InEnumElementRawValue);
ParsedKeywords.clear();
ParsedKeywords.append(Keywords.begin(), Keywords.end());
Kind = CompletionKind::NominalMemberBeginning;
CurDeclContext = P.CurDeclContext;
}
static bool isDynamicLookup(Type T) {
return T->getRValueType()->isAnyObject();
}
static bool isClangSubModule(ModuleDecl *TheModule) {
if (auto ClangMod = TheModule->findUnderlyingClangModule())
return ClangMod->isSubModule();
return false;
}
static void addDeclKeywords(CodeCompletionResultSink &Sink) {
auto AddKeyword = [&](StringRef Name, CodeCompletionKeywordKind Kind) {
if (Name == "let" || Name == "var") {
// Treat keywords that could be the start of a pattern specially.
return;
}
CodeCompletionResultBuilder Builder(
Sink, CodeCompletionResult::ResultKind::Keyword,
SemanticContextKind::None, {});
Builder.setKeywordKind(Kind);
Builder.addTextChunk(Name);
};
#define DECL_KEYWORD(kw) AddKeyword(#kw, CodeCompletionKeywordKind::kw_##kw);
#include "swift/Syntax/TokenKinds.def"
// Context-sensitive keywords.
auto AddCSKeyword = [&](StringRef Name) {
AddKeyword(Name, CodeCompletionKeywordKind::None);
};
#define CONTEXTUAL_CASE(KW) AddCSKeyword(#KW);
#define CONTEXTUAL_DECL_ATTR(KW, ...) CONTEXTUAL_CASE(KW)
#define CONTEXTUAL_DECL_ATTR_ALIAS(KW, ...) CONTEXTUAL_CASE(KW)
#define CONTEXTUAL_SIMPLE_DECL_ATTR(KW, ...) CONTEXTUAL_CASE(KW)
#include <swift/AST/Attr.def>
#undef CONTEXTUAL_CASE
}
static void addStmtKeywords(CodeCompletionResultSink &Sink, bool MaybeFuncBody) {
auto AddKeyword = [&](StringRef Name, CodeCompletionKeywordKind Kind) {
if (!MaybeFuncBody && Kind == CodeCompletionKeywordKind::kw_return)
return;
CodeCompletionResultBuilder Builder(
Sink, CodeCompletionResult::ResultKind::Keyword,
SemanticContextKind::None, {});
Builder.setKeywordKind(Kind);
Builder.addTextChunk(Name);
};
#define STMT_KEYWORD(kw) AddKeyword(#kw, CodeCompletionKeywordKind::kw_##kw);
#include "swift/Syntax/TokenKinds.def"
// Throw is not marked as a STMT_KEYWORD.
AddKeyword("throw", CodeCompletionKeywordKind::kw_throw);
}
static void addLetVarKeywords(CodeCompletionResultSink &Sink) {
auto AddKeyword = [&](StringRef Name, CodeCompletionKeywordKind Kind) {
CodeCompletionResultBuilder Builder(
Sink, CodeCompletionResult::ResultKind::Keyword,
SemanticContextKind::None, {});
Builder.setKeywordKind(Kind);
Builder.addTextChunk(Name);
};
AddKeyword("let", CodeCompletionKeywordKind::kw_let);
AddKeyword("var", CodeCompletionKeywordKind::kw_var);
}
static void addExprKeywords(CodeCompletionResultSink &Sink) {
auto AddKeyword = [&](StringRef Name, StringRef TypeAnnotation, CodeCompletionKeywordKind Kind) {
CodeCompletionResultBuilder Builder(
Sink, CodeCompletionResult::ResultKind::Keyword,
SemanticContextKind::None, {});
Builder.setKeywordKind(Kind);
Builder.addTextChunk(Name);
if (!TypeAnnotation.empty())
Builder.addTypeAnnotation(TypeAnnotation);
};
// Expr keywords.
AddKeyword("try", StringRef(), CodeCompletionKeywordKind::kw_try);
AddKeyword("try!", StringRef(), CodeCompletionKeywordKind::kw_try);
AddKeyword("try?", StringRef(), CodeCompletionKeywordKind::kw_try);
// FIXME: The pedantically correct way to find the type is to resolve the
// Swift.StringLiteralType type.
AddKeyword("#function", "String", CodeCompletionKeywordKind::pound_function);
AddKeyword("#file", "String", CodeCompletionKeywordKind::pound_file);
// Same: Swift.IntegerLiteralType.
AddKeyword("#line", "Int", CodeCompletionKeywordKind::pound_line);
AddKeyword("#column", "Int", CodeCompletionKeywordKind::pound_column);
AddKeyword("#dsohandle", "UnsafeMutableRawPointer", CodeCompletionKeywordKind::pound_dsohandle);
}
static void addAnyTypeKeyword(CodeCompletionResultSink &Sink) {
CodeCompletionResultBuilder Builder(
Sink, CodeCompletionResult::ResultKind::Keyword,
SemanticContextKind::None, {});
Builder.setKeywordKind(CodeCompletionKeywordKind::None);
Builder.addTextChunk("Any");
Builder.addTypeAnnotation("Any");
}
void CodeCompletionCallbacksImpl::addKeywords(CodeCompletionResultSink &Sink,
bool MaybeFuncBody) {
switch (Kind) {
case CompletionKind::None:
case CompletionKind::DotExpr:
case CompletionKind::AttributeDeclParen:
case CompletionKind::AttributeBegin:
case CompletionKind::PoundAvailablePlatform:
case CompletionKind::Import:
case CompletionKind::UnresolvedMember:
case CompletionKind::CallArg:
case CompletionKind::AfterPound:
case CompletionKind::GenericParams:
case CompletionKind::KeyPathExpr:
case CompletionKind::KeyPathExprDot:
case CompletionKind::SwiftKeyPath:
break;
case CompletionKind::StmtOrExpr:
addDeclKeywords(Sink);
addStmtKeywords(Sink, MaybeFuncBody);
LLVM_FALLTHROUGH;
case CompletionKind::AssignmentRHS:
case CompletionKind::ReturnStmtExpr:
case CompletionKind::PostfixExprBeginning:
case CompletionKind::ForEachSequence:
addSuperKeyword(Sink);
addLetVarKeywords(Sink);
addExprKeywords(Sink);
addAnyTypeKeyword(Sink);
break;
case CompletionKind::PostfixExpr:
case CompletionKind::PostfixExprParen:
case CompletionKind::SuperExpr:
case CompletionKind::SuperExprDot:
case CompletionKind::CaseStmtBeginning:
case CompletionKind::CaseStmtDotPrefix:
case CompletionKind::TypeIdentifierWithDot:
case CompletionKind::TypeIdentifierWithoutDot:
break;
case CompletionKind::TypeSimpleBeginning:
addAnyTypeKeyword(Sink);
break;
case CompletionKind::NominalMemberBeginning:
addDeclKeywords(Sink);
addLetVarKeywords(Sink);
break;
}
}
namespace {
class ExprParentFinder : public ASTWalker {
friend class CodeCompletionTypeContextAnalyzer;
Expr *ChildExpr;
llvm::function_ref<bool(ASTNode)> Predicate;
bool arePositionsSame(Expr *E1, Expr *E2) {
return E1->getSourceRange().Start == E2->getSourceRange().Start &&
E1->getSourceRange().End == E2->getSourceRange().End;
}
public:
llvm::SmallVector<ASTNode, 5> Ancestors;
ASTNode ParentClosest;
ASTNode ParentFarthest;
ExprParentFinder(Expr* ChildExpr,
llvm::function_ref<bool(ASTNode)> Predicate) :
ChildExpr(ChildExpr), Predicate(Predicate) {}
std::pair<bool, Expr *> walkToExprPre(Expr *E) override {
if (E == ChildExpr || arePositionsSame(E, ChildExpr)) {
if (!Ancestors.empty()) {
ParentClosest = Ancestors.back();
ParentFarthest = Ancestors.front();
}
return {false, nullptr};
}
if (Predicate(E))
Ancestors.push_back(E);
return { true, E };
}
Expr *walkToExprPost(Expr *E) override {
if (Predicate(E))
Ancestors.pop_back();
return E;
}
std::pair<bool, Stmt *> walkToStmtPre(Stmt *S) override {
if (Predicate(S))
Ancestors.push_back(S);
return { true, S };
}
Stmt *walkToStmtPost(Stmt *S) override {
if (Predicate(S))
Ancestors.pop_back();
return S;
}
bool walkToDeclPre(Decl *D) override {
if (Predicate(D))
Ancestors.push_back(D);
return true;
}
bool walkToDeclPost(Decl *D) override {
if (Predicate(D))
Ancestors.pop_back();
return true;
}
};
} // end anonymous namespace
/// Given an expression and its context, the analyzer tries to figure out the
/// expected type of the expression by analyzing its context.
class CodeCompletionTypeContextAnalyzer {
DeclContext *DC;
Expr *ParsedExpr;
SourceManager &SM;
ASTContext &Context;
ExprParentFinder Finder;
public:
CodeCompletionTypeContextAnalyzer(DeclContext *DC, Expr *ParsedExpr) : DC(DC),
ParsedExpr(ParsedExpr), SM(DC->getASTContext().SourceMgr),
Context(DC->getASTContext()), Finder(ParsedExpr, [](ASTNode Node) {
if (auto E = Node.dyn_cast<Expr *>()) {
switch(E->getKind()) {
case ExprKind::Call:
case ExprKind::Assign:
return true;
default:
return false;
}
} else if (auto S = Node.dyn_cast<Stmt *>()) {
switch (S->getKind()) {
case StmtKind::Return:
case StmtKind::ForEach:
case StmtKind::RepeatWhile:
case StmtKind::If:
case StmtKind::While:
case StmtKind::Guard:
return true;
default:
return false;
}
} else if (auto D = Node.dyn_cast<Decl *>()) {
switch (D->getKind()) {
case DeclKind::PatternBinding:
return true;
default:
return false;
}
} else
return false;
}) {}
void analyzeExpr(Expr *Parent, llvm::function_ref<void(Type)> Callback,
SmallVectorImpl<StringRef> &PossibleNames) {
switch (Parent->getKind()) {
case ExprKind::Call: {
std::vector<Type> PotentialTypes;
std::vector<StringRef> ExpectedNames;
CompletionLookup::collectArgumentExpectation(
*DC, cast<CallExpr>(Parent), ParsedExpr, PotentialTypes,
ExpectedNames);
for (Type Ty : PotentialTypes)
Callback(Ty);
for (auto name : ExpectedNames)
PossibleNames.push_back(name);
break;
}
case ExprKind::Assign: {
auto &SM = DC->getASTContext().SourceMgr;
auto *AE = cast<AssignExpr>(Parent);
// Make sure code completion is on the right hand side.
if (SM.isBeforeInBuffer(AE->getEqualLoc(), ParsedExpr->getStartLoc())) {
// The destination is of the expected type.
auto *destExpr = AE->getDest();
if (auto type = destExpr->getType()) {
Callback(type);
} else if (auto *DRE = dyn_cast<DeclRefExpr>(destExpr)) {
if (auto *decl = DRE->getDecl())
Callback(decl->getInterfaceType());
}
}
break;
}
default:
llvm_unreachable("Unhandled expression kinds.");
}
}
void analyzeStmt(Stmt *Parent, llvm::function_ref<void(Type)> Callback) {
switch (Parent->getKind()) {
case StmtKind::Return:
Callback(getReturnTypeFromContext(DC));
break;
case StmtKind::ForEach:
if (auto SEQ = cast<ForEachStmt>(Parent)->getSequence()) {
if (containsTarget(SEQ)) {
Callback(Context.getSequenceDecl()->getDeclaredInterfaceType());
}
}
break;
case StmtKind::RepeatWhile:
case StmtKind::If:
case StmtKind::While:
case StmtKind::Guard:
if (isBoolConditionOf(Parent)) {
Callback(Context.getBoolDecl()->getDeclaredInterfaceType());
}
break;
default:
llvm_unreachable("Unhandled statement kinds.");
}
}
bool isBoolConditionOf(Stmt *parent) {
if (auto *repeat = dyn_cast<RepeatWhileStmt>(parent)) {
return repeat->getCond() && containsTarget(repeat->getCond());
}
if (auto *conditional = dyn_cast<LabeledConditionalStmt>(parent)) {
for (StmtConditionElement cond : conditional->getCond()) {
if (auto *E = cond.getBooleanOrNull()) {
if (containsTarget(E)) {
return true;
}
}
}
}
return false;
}
bool containsTarget(Expr *E) {
assert(E && "expected parent expression");
return SM.rangeContains(E->getSourceRange(), ParsedExpr->getSourceRange());
}
void analyzeDecl(Decl *D, llvm::function_ref<void(Type)> Callback) {
switch (D->getKind()) {
case DeclKind::PatternBinding: {
auto PBD = cast<PatternBindingDecl>(D);
for (unsigned I = 0; I < PBD->getNumPatternEntries(); ++ I) {
if (auto Init = PBD->getInit(I)) {
if (containsTarget(Init)) {
if (PBD->getPattern(I)->hasType()) {
Callback(PBD->getPattern(I)->getType());
break;
}
}
}
}
break;
}
default:
llvm_unreachable("Unhandled decl kinds.");
}
}
bool Analyze(llvm::SmallVectorImpl<Type> &PossibleTypes) {
SmallVector<StringRef, 1> PossibleNames;
return Analyze(PossibleTypes, PossibleNames) && !PossibleTypes.empty();
}
bool Analyze(SmallVectorImpl<Type> &PossibleTypes,
SmallVectorImpl<StringRef> &PossibleNames) {
// We cannot analyze without target.
if (!ParsedExpr)
return false;
DC->walkContext(Finder);
auto Callback = [&] (Type Result) {
if (Result &&
Result->getKind() != TypeKind::Error)
PossibleTypes.push_back(Result->getRValueType());
};
for (auto It = Finder.Ancestors.rbegin(); It != Finder.Ancestors.rend();
++ It) {
if (auto Parent = It->dyn_cast<Expr *>()) {
analyzeExpr(Parent, Callback, PossibleNames);
} else if (auto Parent = It->dyn_cast<Stmt *>()) {
analyzeStmt(Parent, Callback);
} else if (auto Parent = It->dyn_cast<Decl *>()) {
analyzeDecl(Parent, Callback);
}
if (!PossibleTypes.empty() || !PossibleNames.empty())
return true;
}
return false;
}
};
void CodeCompletionCallbacksImpl::doneParsing() {
CompletionContext.CodeCompletionKind = Kind;
if (Kind == CompletionKind::None) {
return;
}
bool MaybeFuncBody = true;
if (CurDeclContext) {
auto *CD = CurDeclContext->getLocalContext();
if (!CD || CD->getContextKind() == DeclContextKind::Initializer ||
CD->getContextKind() == DeclContextKind::TopLevelCodeDecl)
MaybeFuncBody = false;
}
// Add keywords even if type checking fails completely.
addKeywords(CompletionContext.getResultSink(), MaybeFuncBody);
if (auto *DC = dyn_cast_or_null<DeclContext>(ParsedDecl)) {
if (DC->isChildContextOf(CurDeclContext))
CurDeclContext = DC;
}
if (!typecheckContext(CurDeclContext))
return;
Optional<Type> ExprType;
ConcreteDeclRef ReferencedDecl = nullptr;
if (ParsedExpr) {
if (auto typechecked = typeCheckParsedExpr()) {
ExprType = typechecked->first;
ReferencedDecl = typechecked->second;
ParsedExpr->setType(*ExprType);
}
if (!ExprType && Kind != CompletionKind::PostfixExprParen &&
Kind != CompletionKind::CallArg &&
Kind != CompletionKind::KeyPathExpr &&
Kind != CompletionKind::KeyPathExprDot)
return;
}
if (!ParsedTypeLoc.isNull() && !typecheckParsedType())
return;
CompletionLookup Lookup(CompletionContext.getResultSink(), P.Context,
CurDeclContext, &CompletionContext);
if (ExprType) {
Lookup.setIsStaticMetatype(ParsedExpr->isStaticallyDerivedMetatype());
}
if (auto *DRE = dyn_cast_or_null<DeclRefExpr>(ParsedExpr)) {
Lookup.setIsSelfRefExpr(DRE->getDecl()->getFullName() == Context.Id_self);
}
if (isInsideObjCSelector())
Lookup.includeInstanceMembers();
if (PreferFunctionReferencesToCalls)
Lookup.setPreferFunctionReferencesToCalls();
auto DoPostfixExprBeginning = [&] (){
SourceLoc Loc = P.Context.SourceMgr.getCodeCompletionLoc();
Lookup.getValueCompletionsInDeclContext(Loc);
};
switch (Kind) {
case CompletionKind::None:
llvm_unreachable("should be already handled");
return;
case CompletionKind::DotExpr: {
Lookup.setHaveDot(DotLoc);
if (isDynamicLookup(*ExprType))
Lookup.setIsDynamicLookup();
if (isa<BindOptionalExpr>(ParsedExpr) || isa<ForceValueExpr>(ParsedExpr))
Lookup.setIsUnwrappedOptional(true);
::CodeCompletionTypeContextAnalyzer TypeAnalyzer(CurDeclContext, ParsedExpr);
llvm::SmallVector<Type, 2> PossibleTypes;
if (TypeAnalyzer.Analyze(PossibleTypes)) {
Lookup.setExpectedTypes(PossibleTypes);
}
Lookup.getValueExprCompletions(*ExprType, ReferencedDecl.getDecl());
break;
}
case CompletionKind::SwiftKeyPath: {
Lookup.setHaveDot(DotLoc);
Lookup.setIsSwiftKeyPathExpr();
if (auto BGT = (*ExprType)->getAs<BoundGenericType>()) {
auto AllArgs = BGT->getGenericArgs();
if (AllArgs.size() == 2) {
// The second generic type argument of KeyPath<Root, Value> should be
// the value we pull code completion results from.
Lookup.getValueExprCompletions(AllArgs[1]);
}
}
break;
}
case CompletionKind::StmtOrExpr:
DoPostfixExprBeginning();
break;
case CompletionKind::ForEachSequence:
case CompletionKind::PostfixExprBeginning: {
::CodeCompletionTypeContextAnalyzer Analyzer(CurDeclContext,
CodeCompleteTokenExpr);
llvm::SmallVector<Type, 1> Types;
if (Analyzer.Analyze(Types)) {
Lookup.setExpectedTypes(Types);
}
DoPostfixExprBeginning();
break;
}
case CompletionKind::PostfixExpr: {
Lookup.setHaveLeadingSpace(HasSpace);
if (isDynamicLookup(*ExprType))
Lookup.setIsDynamicLookup();
Lookup.getValueExprCompletions(*ExprType, ReferencedDecl.getDecl());
Lookup.getOperatorCompletions(ParsedExpr, leadingSequenceExprs);
break;
}
case CompletionKind::PostfixExprParen: {
Lookup.setHaveLParen(true);
::CodeCompletionTypeContextAnalyzer TypeAnalyzer(CurDeclContext,
CodeCompleteTokenExpr);
SmallVector<Type, 2> PossibleTypes;
SmallVector<StringRef, 2> PossibleNames;
if (TypeAnalyzer.Analyze(PossibleTypes, PossibleNames)) {
Lookup.setExpectedTypes(PossibleTypes);
}
if (ExprType) {
if (ShouldCompleteCallPatternAfterParen) {
Lookup.getValueExprCompletions(*ExprType, ReferencedDecl.getDecl());
} else {
// Add argument labels, then fallthrough to get values.
Lookup.addArgNameCompletionResults(PossibleNames);
}
}
if (!Lookup.FoundFunctionCalls ||
(Lookup.FoundFunctionCalls &&
Lookup.FoundFunctionsWithoutFirstKeyword)) {
Lookup.setHaveLParen(false);
DoPostfixExprBeginning();
}
break;
}
case CompletionKind::SuperExpr: {
Lookup.setIsSuperRefExpr();
Lookup.getValueExprCompletions(*ExprType, ReferencedDecl.getDecl());
break;
}
case CompletionKind::SuperExprDot: {
Lookup.setIsSuperRefExpr();
Lookup.setHaveDot(SourceLoc());
Lookup.getValueExprCompletions(*ExprType, ReferencedDecl.getDecl());
break;
}
case CompletionKind::KeyPathExprDot:
Lookup.setHaveDot(SourceLoc());
LLVM_FALLTHROUGH;
case CompletionKind::KeyPathExpr: {
Lookup.setIsKeyPathExpr();
Lookup.includeInstanceMembers();
if (ExprType) {
if (isDynamicLookup(*ExprType))
Lookup.setIsDynamicLookup();
Lookup.getValueExprCompletions(*ExprType, ReferencedDecl.getDecl());
} else {
SourceLoc Loc = P.Context.SourceMgr.getCodeCompletionLoc();
Lookup.getValueCompletionsInDeclContext(Loc, KeyPathFilter,
false, true, false);
}
break;
}
case CompletionKind::TypeSimpleBeginning: {
Lookup.getTypeCompletionsInDeclContext(
P.Context.SourceMgr.getCodeCompletionLoc());
break;
}
case CompletionKind::TypeIdentifierWithDot: {
Lookup.setHaveDot(SourceLoc());
Lookup.getTypeCompletions(ParsedTypeLoc.getType());
break;
}
case CompletionKind::TypeIdentifierWithoutDot: {
Lookup.getTypeCompletions(ParsedTypeLoc.getType());
break;
}
case CompletionKind::CaseStmtBeginning: {
SourceLoc Loc = P.Context.SourceMgr.getCodeCompletionLoc();
Lookup.getValueCompletionsInDeclContext(Loc);
Lookup.getTypeContextEnumElementCompletions(Loc);
break;
}
case CompletionKind::CaseStmtDotPrefix: {
Lookup.setHaveDot(SourceLoc());
SourceLoc Loc = P.Context.SourceMgr.getCodeCompletionLoc();
Lookup.getTypeContextEnumElementCompletions(Loc);
break;
}
case CompletionKind::NominalMemberBeginning: {
Lookup.discardTypeResolver();
CompletionOverrideLookup OverrideLookup(CompletionContext.getResultSink(),
P.Context, CurDeclContext,
ParsedKeywords);
OverrideLookup.getOverrideCompletions(SourceLoc());
break;
}
case CompletionKind::AttributeBegin: {
Lookup.getAttributeDeclCompletions(IsInSil, AttTargetDK);
break;
}
case CompletionKind::AttributeDeclParen: {
Lookup.getAttributeDeclParamCompletions(AttrKind, AttrParamIndex);
break;
}
case CompletionKind::PoundAvailablePlatform: {
Lookup.getPoundAvailablePlatformCompletions();
break;
}
case CompletionKind::Import: {
if (DotLoc.isValid())
Lookup.addSubModuleNames(SubModuleNameVisibilityPairs);
else
Lookup.addImportModuleNames();
break;
}
case CompletionKind::UnresolvedMember : {
Lookup.setHaveDot(SourceLoc());
SmallVector<Type, 1> PossibleTypes;
ExprParentFinder Walker(UnresolvedExpr, [&](ASTNode Node) {
return Node.is<Expr *>();
});
CurDeclContext->walkContext(Walker);
bool Success = false;
if (auto PE = Walker.ParentFarthest.get<Expr *>()) {
prepareForRetypechecking(PE);
Success = typeCheckUnresolvedExpr(*CurDeclContext, UnresolvedExpr, PE,
PossibleTypes);
Lookup.getUnresolvedMemberCompletions(PossibleTypes);
}
if (!Success) {
Lookup.getUnresolvedMemberCompletions(
TokensBeforeUnresolvedExpr,
UnresolvedExprInReturn);
}
break;
}
case CompletionKind::AssignmentRHS : {
SourceLoc Loc = P.Context.SourceMgr.getCodeCompletionLoc();
if (auto destType = ParsedExpr->getType())
Lookup.setExpectedTypes(destType->getRValueType());
Lookup.getValueCompletionsInDeclContext(Loc, DefaultFilter);
break;
}
case CompletionKind::CallArg : {
if (!CodeCompleteTokenExpr || !Lookup.getCallArgCompletions(*CurDeclContext,
FuncCallExpr,
CodeCompleteTokenExpr))
DoPostfixExprBeginning();
break;
}
case CompletionKind::ReturnStmtExpr : {
SourceLoc Loc = P.Context.SourceMgr.getCodeCompletionLoc();
if (auto FD = dyn_cast<AbstractFunctionDecl>(CurDeclContext)) {
if (auto FT = FD->getInterfaceType()->getAs<FunctionType>()) {
Lookup.setExpectedTypes(FT->getResult());
}
}
Lookup.getValueCompletionsInDeclContext(Loc);
break;
}
case CompletionKind::AfterPound: {
Lookup.addPoundAvailable(ParentStmtKind);
Lookup.addPoundSelector(/*needPound=*/false);
Lookup.addPoundKeyPath(/*needPound=*/false);
break;
}
case CompletionKind::GenericParams:
if (auto GT = ParsedTypeLoc.getType()->getAnyGeneric()) {
if (auto Params = GT->getGenericParams()) {
for (auto GP : Params->getParams()) {
Lookup.addGenericTypeParamRef(GP,
DeclVisibilityKind::GenericParameter);
}
}
}
break;
}
if (Lookup.RequestedCachedResults) {
// Use the current SourceFile as the DeclContext so that we can use it to
// perform qualified lookup, and to get the correct visibility for
// @testable imports.
const SourceFile &SF = P.SF;
auto &Request = Lookup.RequestedCachedResults.getValue();
llvm::DenseSet<CodeCompletionCache::Key> ImportsSeen;
auto handleImport = [&](ModuleDecl::ImportedModule Import) {
ModuleDecl *TheModule = Import.second;
ModuleDecl::AccessPathTy Path = Import.first;
if (TheModule->getFiles().empty())
return;
// Clang submodules are ignored and there's no lookup cost involved,
// so just ignore them and don't put the empty results in the cache
// because putting a lot of objects in the cache will push out
// other lookups.
if (isClangSubModule(TheModule))
return;
std::vector<std::string> AccessPath;
for (auto Piece : Path) {
AccessPath.push_back(Piece.first.str());
}
StringRef ModuleFilename = TheModule->getModuleFilename();
// ModuleFilename can be empty if something strange happened during
// module loading, for example, the module file is corrupted.
if (!ModuleFilename.empty()) {
auto &Ctx = TheModule->getASTContext();
CodeCompletionCache::Key K{ModuleFilename, TheModule->getName().str(),
AccessPath, Request.NeedLeadingDot,
SF.hasTestableImport(TheModule),
Ctx.LangOpts.CodeCompleteInitsInPostfixExpr};
using PairType = llvm::DenseSet<swift::ide::CodeCompletionCache::Key,
llvm::DenseMapInfo<CodeCompletionCache::Key>>::iterator;
std::pair<PairType, bool> Result = ImportsSeen.insert(K);
if (!Result.second)
return; // already handled.
RequestedModules.push_back(
{std::move(K), TheModule, Request.OnlyTypes});
}
};
if (Request.TheModule) {
Lookup.discardTypeResolver();
// FIXME: actually check imports.
const_cast<ModuleDecl*>(Request.TheModule)
->forAllVisibleModules({}, handleImport);
} else {
// Add results from current module.
Lookup.getToplevelCompletions(Request.OnlyTypes);
Lookup.discardTypeResolver();
// Add results for all imported modules.
SmallVector<ModuleDecl::ImportedModule, 4> Imports;
auto *SF = CurDeclContext->getParentSourceFile();
SF->getImportedModules(Imports, ModuleDecl::ImportFilter::All);
for (auto Imported : Imports) {
ModuleDecl *TheModule = Imported.second;
ModuleDecl::AccessPathTy AccessPath = Imported.first;
TheModule->forAllVisibleModules(AccessPath, handleImport);
}
}
Lookup.RequestedCachedResults.reset();
}
CompletionContext.HasExpectedTypeRelation = Lookup.hasExpectedTypes();
deliverCompletionResults();
}
void CodeCompletionCallbacksImpl::deliverCompletionResults() {
// Use the current SourceFile as the DeclContext so that we can use it to
// perform qualified lookup, and to get the correct visibility for
// @testable imports.
DeclContext *DCForModules = &P.SF;
Consumer.handleResultsAndModules(CompletionContext, RequestedModules,
DCForModules);
RequestedModules.clear();
DeliveredResults = true;
}
void PrintingCodeCompletionConsumer::handleResults(
MutableArrayRef<CodeCompletionResult *> Results) {
unsigned NumResults = 0;
for (auto Result : Results) {
if (!IncludeKeywords && Result->getKind() == CodeCompletionResult::Keyword)
continue;
NumResults++;
}
if (NumResults == 0)
return;
OS << "Begin completions, " << NumResults << " items\n";
for (auto Result : Results) {
if (!IncludeKeywords && Result->getKind() == CodeCompletionResult::Keyword)
continue;
Result->print(OS);
llvm::SmallString<64> Name;
llvm::raw_svector_ostream NameOs(Name);
Result->getCompletionString()->getName(NameOs);
OS << "; name=" << Name;
StringRef comment = Result->getBriefDocComment();
if (IncludeComments && !comment.empty()) {
OS << "; comment=" << comment;
}
OS << "\n";
}
OS << "End completions\n";
}
namespace {
class CodeCompletionCallbacksFactoryImpl
: public CodeCompletionCallbacksFactory {
CodeCompletionContext &CompletionContext;
CodeCompletionConsumer &Consumer;
public:
CodeCompletionCallbacksFactoryImpl(CodeCompletionContext &CompletionContext,
CodeCompletionConsumer &Consumer)
: CompletionContext(CompletionContext), Consumer(Consumer) {}
CodeCompletionCallbacks *createCodeCompletionCallbacks(Parser &P) override {
return new CodeCompletionCallbacksImpl(P, CompletionContext, Consumer);
}
};
} // end anonymous namespace
CodeCompletionCallbacksFactory *
swift::ide::makeCodeCompletionCallbacksFactory(
CodeCompletionContext &CompletionContext,
CodeCompletionConsumer &Consumer) {
return new CodeCompletionCallbacksFactoryImpl(CompletionContext, Consumer);
}
void swift::ide::lookupCodeCompletionResultsFromModule(
CodeCompletionResultSink &targetSink, const ModuleDecl *module,
ArrayRef<std::string> accessPath, bool needLeadingDot,
const DeclContext *currDeclContext) {
CompletionLookup Lookup(targetSink, module->getASTContext(), currDeclContext);
Lookup.getVisibleDeclsOfModule(module, accessPath, needLeadingDot);
}
void swift::ide::copyCodeCompletionResults(CodeCompletionResultSink &targetSink,
CodeCompletionResultSink &sourceSink,
bool onlyTypes) {
// We will be adding foreign results (from another sink) into TargetSink.
// TargetSink should have an owning pointer to the allocator that keeps the
// results alive.
targetSink.ForeignAllocators.push_back(sourceSink.Allocator);
if (onlyTypes) {
std::copy_if(sourceSink.Results.begin(), sourceSink.Results.end(),
std::back_inserter(targetSink.Results),
[](CodeCompletionResult *R) -> bool {
if (R->getKind() != CodeCompletionResult::Declaration)
return false;
switch(R->getAssociatedDeclKind()) {
case CodeCompletionDeclKind::PrecedenceGroup:
case CodeCompletionDeclKind::Module:
case CodeCompletionDeclKind::Class:
case CodeCompletionDeclKind::Struct:
case CodeCompletionDeclKind::Enum:
case CodeCompletionDeclKind::Protocol:
case CodeCompletionDeclKind::TypeAlias:
case CodeCompletionDeclKind::AssociatedType:
case CodeCompletionDeclKind::GenericTypeParam:
return true;
case CodeCompletionDeclKind::EnumElement:
case CodeCompletionDeclKind::Constructor:
case CodeCompletionDeclKind::Destructor:
case CodeCompletionDeclKind::Subscript:
case CodeCompletionDeclKind::StaticMethod:
case CodeCompletionDeclKind::InstanceMethod:
case CodeCompletionDeclKind::PrefixOperatorFunction:
case CodeCompletionDeclKind::PostfixOperatorFunction:
case CodeCompletionDeclKind::InfixOperatorFunction:
case CodeCompletionDeclKind::FreeFunction:
case CodeCompletionDeclKind::StaticVar:
case CodeCompletionDeclKind::InstanceVar:
case CodeCompletionDeclKind::LocalVar:
case CodeCompletionDeclKind::GlobalVar:
return false;
}
llvm_unreachable("Unhandled CodeCompletionDeclKind in switch.");
});
} else {
targetSink.Results.insert(targetSink.Results.end(),
sourceSink.Results.begin(),
sourceSink.Results.end());
}
}
void SimpleCachingCodeCompletionConsumer::handleResultsAndModules(
CodeCompletionContext &context,
ArrayRef<RequestedCachedModule> requestedModules,
DeclContext *DCForModules) {
for (auto &R : requestedModules) {
// FIXME(thread-safety): lock the whole AST context. We might load a
// module.
llvm::Optional<CodeCompletionCache::ValueRefCntPtr> V =
context.Cache.get(R.Key);
if (!V.hasValue()) {
// No cached results found. Fill the cache.
V = context.Cache.createValue();
lookupCodeCompletionResultsFromModule(
(*V)->Sink, R.TheModule, R.Key.AccessPath,
R.Key.ResultsHaveLeadingDot, DCForModules);
context.Cache.set(R.Key, *V);
}
assert(V.hasValue());
copyCodeCompletionResults(context.getResultSink(), (*V)->Sink, R.OnlyTypes);
}
handleResults(context.takeResults());
}
|
#include "main.hpp"
#include <iostream>
#include <chrono>
inline char* __clib;
inline char* __clob;
extern "C" {
inline int I64ToStr(int64_t v) {
return sprintf_s(__clib, 32, "%lld", v);
};
inline int U64ToStr(uint64_t v) {
return sprintf_s(__clib, 32, "%llu", v);
};
inline int DblToStr(double v) {
return sprintf_s(__clib, 32, "%.16g", v);
};
inline void CLStr(int v) {
std::cout << std::string_view(__clob, v) << std::endl;
};
inline double DateNow() { using namespace std::chrono; return (double)duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count(); };
}
int main() {
__clib = (char*)GetCLIB();
__clob = (char*)GetCLOB();
TestConsoleLog();
}
|
/*
* Copyright (c) 2015 The WebRTC project authors. All Rights Reserved.
*
* Use of this source code is governed by a BSD-style license
* that can be found in the LICENSE file in the root of the source
* tree. An additional intellectual property rights grant can be found
* in the file PATENTS. All contributing project authors may
* be found in the AUTHORS file in the root of the source tree.
*/
#include <memory>
#include <vector>
#include "audio/audio_state.h"
#include "call/test/mock_audio_send_stream.h"
#include BOSS_WEBRTC_U_modules__audio_device__include__mock_audio_device_h //original-code:"modules/audio_device/include/mock_audio_device.h"
#include "modules/audio_mixer/audio_mixer_impl.h"
#include BOSS_WEBRTC_U_modules__audio_processing__include__mock_audio_processing_h //original-code:"modules/audio_processing/include/mock_audio_processing.h"
#include BOSS_WEBRTC_U_rtc_base__refcountedobject_h //original-code:"rtc_base/refcountedobject.h"
#include BOSS_WEBRTC_U_test__gtest_h //original-code:"test/gtest.h"
namespace webrtc {
namespace test {
namespace {
constexpr int kSampleRate = 16000;
constexpr int kNumberOfChannels = 1;
struct ConfigHelper {
ConfigHelper() : audio_mixer(AudioMixerImpl::Create()) {
audio_state_config.audio_mixer = audio_mixer;
audio_state_config.audio_processing =
new rtc::RefCountedObject<testing::NiceMock<MockAudioProcessing>>();
audio_state_config.audio_device_module =
new rtc::RefCountedObject<MockAudioDeviceModule>();
}
AudioState::Config& config() { return audio_state_config; }
rtc::scoped_refptr<AudioMixer> mixer() { return audio_mixer; }
private:
AudioState::Config audio_state_config;
rtc::scoped_refptr<AudioMixer> audio_mixer;
};
class FakeAudioSource : public AudioMixer::Source {
public:
// TODO(aleloi): Valid overrides commented out, because the gmock
// methods don't use any override declarations, and we want to avoid
// warnings from -Winconsistent-missing-override. See
// http://crbug.com/428099.
int Ssrc() const /*override*/ { return 0; }
int PreferredSampleRate() const /*override*/ { return kSampleRate; }
MOCK_METHOD2(GetAudioFrameWithInfo,
AudioFrameInfo(int sample_rate_hz, AudioFrame* audio_frame));
};
std::vector<int16_t> Create10msSilentTestData(int sample_rate_hz,
size_t num_channels) {
const int samples_per_channel = sample_rate_hz / 100;
std::vector<int16_t> audio_data(samples_per_channel * num_channels, 0);
return audio_data;
}
std::vector<int16_t> Create10msTestData(int sample_rate_hz,
size_t num_channels) {
const int samples_per_channel = sample_rate_hz / 100;
std::vector<int16_t> audio_data(samples_per_channel * num_channels, 0);
// Fill the first channel with a 1kHz sine wave.
const float inc = (2 * 3.14159265f * 1000) / sample_rate_hz;
float w = 0.f;
for (int i = 0; i < samples_per_channel; ++i) {
audio_data[i * num_channels] =
static_cast<int16_t>(32767.f * std::sin(w));
w += inc;
}
return audio_data;
}
std::vector<uint32_t> ComputeChannelLevels(AudioFrame* audio_frame) {
const size_t num_channels = audio_frame->num_channels_;
const size_t samples_per_channel = audio_frame->samples_per_channel_;
std::vector<uint32_t> levels(num_channels, 0);
for (size_t i = 0; i < samples_per_channel; ++i) {
for (size_t j = 0; j < num_channels; ++j) {
levels[j] += std::abs(audio_frame->data()[i * num_channels + j]);
}
}
return levels;
}
} // namespace
TEST(AudioStateTest, Create) {
ConfigHelper helper;
auto audio_state = AudioState::Create(helper.config());
EXPECT_TRUE(audio_state.get());
}
TEST(AudioStateTest, ConstructDestruct) {
ConfigHelper helper;
std::unique_ptr<internal::AudioState> audio_state(
new internal::AudioState(helper.config()));
}
TEST(AudioStateTest, RecordedAudioArrivesAtSingleStream) {
ConfigHelper helper;
std::unique_ptr<internal::AudioState> audio_state(
new internal::AudioState(helper.config()));
MockAudioSendStream stream;
audio_state->AddSendingStream(&stream, 8000, 2);
EXPECT_CALL(stream, SendAudioDataForMock(testing::AllOf(
testing::Field(&AudioFrame::sample_rate_hz_, testing::Eq(8000)),
testing::Field(&AudioFrame::num_channels_, testing::Eq(2u)))))
.WillOnce(
// Verify that channels are not swapped by default.
testing::Invoke([](AudioFrame* audio_frame) {
auto levels = ComputeChannelLevels(audio_frame);
EXPECT_LT(0u, levels[0]);
EXPECT_EQ(0u, levels[1]);
}));
MockAudioProcessing* ap =
static_cast<MockAudioProcessing*>(audio_state->audio_processing());
EXPECT_CALL(*ap, set_stream_delay_ms(0));
EXPECT_CALL(*ap, set_stream_key_pressed(false));
EXPECT_CALL(*ap, ProcessStream(testing::_));
constexpr int kSampleRate = 16000;
constexpr size_t kNumChannels = 2;
auto audio_data = Create10msTestData(kSampleRate, kNumChannels);
uint32_t new_mic_level = 667;
audio_state->audio_transport()->RecordedDataIsAvailable(
&audio_data[0], kSampleRate / 100, kNumChannels * 2,
kNumChannels, kSampleRate, 0, 0, 0, false, new_mic_level);
EXPECT_EQ(667u, new_mic_level);
audio_state->RemoveSendingStream(&stream);
}
TEST(AudioStateTest, RecordedAudioArrivesAtMultipleStreams) {
ConfigHelper helper;
std::unique_ptr<internal::AudioState> audio_state(
new internal::AudioState(helper.config()));
MockAudioSendStream stream_1;
MockAudioSendStream stream_2;
audio_state->AddSendingStream(&stream_1, 8001, 2);
audio_state->AddSendingStream(&stream_2, 32000, 1);
EXPECT_CALL(stream_1, SendAudioDataForMock(testing::AllOf(
testing::Field(&AudioFrame::sample_rate_hz_, testing::Eq(16000)),
testing::Field(&AudioFrame::num_channels_, testing::Eq(1u)))))
.WillOnce(
// Verify that there is output signal.
testing::Invoke([](AudioFrame* audio_frame) {
auto levels = ComputeChannelLevels(audio_frame);
EXPECT_LT(0u, levels[0]);
}));
EXPECT_CALL(stream_2, SendAudioDataForMock(testing::AllOf(
testing::Field(&AudioFrame::sample_rate_hz_, testing::Eq(16000)),
testing::Field(&AudioFrame::num_channels_, testing::Eq(1u)))))
.WillOnce(
// Verify that there is output signal.
testing::Invoke([](AudioFrame* audio_frame) {
auto levels = ComputeChannelLevels(audio_frame);
EXPECT_LT(0u, levels[0]);
}));
MockAudioProcessing* ap =
static_cast<MockAudioProcessing*>(audio_state->audio_processing());
EXPECT_CALL(*ap, set_stream_delay_ms(5));
EXPECT_CALL(*ap, set_stream_key_pressed(true));
EXPECT_CALL(*ap, ProcessStream(testing::_));
constexpr int kSampleRate = 16000;
constexpr size_t kNumChannels = 1;
auto audio_data = Create10msTestData(kSampleRate, kNumChannels);
uint32_t new_mic_level = 667;
audio_state->audio_transport()->RecordedDataIsAvailable(
&audio_data[0], kSampleRate / 100, kNumChannels * 2,
kNumChannels, kSampleRate, 5, 0, 0, true, new_mic_level);
EXPECT_EQ(667u, new_mic_level);
audio_state->RemoveSendingStream(&stream_1);
audio_state->RemoveSendingStream(&stream_2);
}
TEST(AudioStateTest, EnableChannelSwap) {
constexpr int kSampleRate = 16000;
constexpr size_t kNumChannels = 2;
ConfigHelper helper;
std::unique_ptr<internal::AudioState> audio_state(
new internal::AudioState(helper.config()));
audio_state->SetStereoChannelSwapping(true);
MockAudioSendStream stream;
audio_state->AddSendingStream(&stream, kSampleRate, kNumChannels);
EXPECT_CALL(stream, SendAudioDataForMock(testing::_))
.WillOnce(
// Verify that channels are swapped.
testing::Invoke([](AudioFrame* audio_frame) {
auto levels = ComputeChannelLevels(audio_frame);
EXPECT_EQ(0u, levels[0]);
EXPECT_LT(0u, levels[1]);
}));
auto audio_data = Create10msTestData(kSampleRate, kNumChannels);
uint32_t new_mic_level = 667;
audio_state->audio_transport()->RecordedDataIsAvailable(
&audio_data[0], kSampleRate / 100, kNumChannels * 2,
kNumChannels, kSampleRate, 0, 0, 0, false, new_mic_level);
EXPECT_EQ(667u, new_mic_level);
audio_state->RemoveSendingStream(&stream);
}
TEST(AudioStateTest, InputLevelStats) {
constexpr int kSampleRate = 16000;
constexpr size_t kNumChannels = 1;
ConfigHelper helper;
std::unique_ptr<internal::AudioState> audio_state(
new internal::AudioState(helper.config()));
// Push a silent buffer -> Level stats should be zeros except for duration.
{
auto audio_data = Create10msSilentTestData(kSampleRate, kNumChannels);
uint32_t new_mic_level = 667;
audio_state->audio_transport()->RecordedDataIsAvailable(
&audio_data[0], kSampleRate / 100, kNumChannels * 2,
kNumChannels, kSampleRate, 0, 0, 0, false, new_mic_level);
auto stats = audio_state->GetAudioInputStats();
EXPECT_EQ(0, stats.audio_level);
EXPECT_EQ(0, stats.quantized_audio_level);
EXPECT_THAT(stats.total_energy, testing::DoubleEq(0.0));
EXPECT_THAT(stats.total_duration, testing::DoubleEq(0.01));
}
// Push 10 non-silent buffers -> Level stats should be non-zero.
{
auto audio_data = Create10msTestData(kSampleRate, kNumChannels);
uint32_t new_mic_level = 667;
for (int i = 0; i < 10; ++i) {
audio_state->audio_transport()->RecordedDataIsAvailable(
&audio_data[0], kSampleRate / 100, kNumChannels * 2,
kNumChannels, kSampleRate, 0, 0, 0, false, new_mic_level);
}
auto stats = audio_state->GetAudioInputStats();
EXPECT_EQ(32767, stats.audio_level);
EXPECT_EQ(9, stats.quantized_audio_level);
EXPECT_THAT(stats.total_energy, testing::DoubleEq(0.01));
EXPECT_THAT(stats.total_duration, testing::DoubleEq(0.11));
}
}
TEST(AudioStateTest,
QueryingTransportForAudioShouldResultInGetAudioCallOnMixerSource) {
ConfigHelper helper;
auto audio_state = AudioState::Create(helper.config());
FakeAudioSource fake_source;
helper.mixer()->AddSource(&fake_source);
EXPECT_CALL(fake_source, GetAudioFrameWithInfo(testing::_, testing::_))
.WillOnce(
testing::Invoke([](int sample_rate_hz, AudioFrame* audio_frame) {
audio_frame->sample_rate_hz_ = sample_rate_hz;
audio_frame->samples_per_channel_ = sample_rate_hz / 100;
audio_frame->num_channels_ = kNumberOfChannels;
return AudioMixer::Source::AudioFrameInfo::kNormal;
}));
int16_t audio_buffer[kSampleRate / 100 * kNumberOfChannels];
size_t n_samples_out;
int64_t elapsed_time_ms;
int64_t ntp_time_ms;
audio_state->audio_transport()->NeedMorePlayData(
kSampleRate / 100, kNumberOfChannels * 2, kNumberOfChannels, kSampleRate,
audio_buffer, n_samples_out, &elapsed_time_ms, &ntp_time_ms);
}
} // namespace test
} // namespace webrtc
|
; A287746: First differences of A154293.
; 1,5,5,2,7,15,11,4,13,25,17,6,19,35,23,8,25,45,29,10,31,55,35,12,37,65,41,14,43,75,47,16,49,85,53,18,55,95,59,20,61,105,65,22,67,115,71,24,73,125,77,26,79,135,83,28,85,145,89,30,91,155,95,32,97,165,101,34,103,175
mov $3,2
mov $5,$0
lpb $3,1
mov $0,$5
sub $3,1
add $0,$3
cal $0,69497 ; Triangular numbers of the form 6k.
mov $2,$0
mul $2,2
mov $4,$3
mov $6,$2
lpb $4,1
mov $1,$6
sub $4,1
lpe
lpe
lpb $5,1
sub $1,$6
mov $5,0
lpe
sub $1,12
div $1,12
add $1,1
|
; long __CALLEE__ lseek_callee(int fd, long offset, int whence)
; 06.2008 aralbrec
XLIB lseek_callee
XDEF ASMDISP_LSEEK_CALLEE
LIB l_jpix, stdio_fdcommon1
LIB stdio_error_ebadf_mc, stdio_error_mc
INCLUDE "../stdio.def"
.lseek_callee
pop af
pop bc
pop hl
pop de
exx
pop hl
push af
.asmentry
; enter : c' = whence
; de'hl' = offset
; l = fd
; exit : dehl = new file pos, carry reset
; dehl = -1, carry set for fail
call stdio_fdcommon1 ; ix = fdstruct *
jp nc, cont
call stdio_error_ebadf_mc ; problem with fd
ld e,l
ld d,h
ret
.cont
exx
ld a,STDIO_MSG_SEEK
call l_jpix
ret nc
call stdio_error_mc
ld e,l
ld d,h
ret
defc ASMDISP_LSEEK_CALLEE = asmentry - lseek_callee
|
; A016631: Decimal expansion of log(8).
; Submitted by Jon Maiga
; 2,0,7,9,4,4,1,5,4,1,6,7,9,8,3,5,9,2,8,2,5,1,6,9,6,3,6,4,3,7,4,5,2,9,7,0,4,2,2,6,5,0,0,4,0,3,0,8,0,7,6,5,7,6,2,3,6,2,0,4,0,0,2,8,4,8,0,1,8,0,8,6,5,9,0,9,0,8,4,1,4,6,8,1,7,5,8,9,9,8,0,9,8,9,2,5,6,0,6,2
mov $2,3
mov $3,$0
mul $3,5
lpb $3
mul $1,$3
mov $5,$3
mul $5,2
add $5,2
mul $2,$5
add $1,$2
cmp $4,0
mov $5,$0
add $5,$4
div $1,$5
div $2,$5
sub $3,1
lpe
div $1,2
mul $1,3
mov $6,10
pow $6,$0
mov $4,$6
cmp $4,1
add $6,$4
div $2,$6
div $1,$2
add $1,$6
mov $0,$1
mod $0,10
|
; A038051: G.f.: B(x/(1-x)) where B is g.f. of A000169.
; Submitted by Christian Krause
; 1,3,14,98,944,11642,175108,3108310,63601168,1473864722,38152990484,1091172974102,34169139856024,1162736848398010,42723615842296540,1685853467536076798,71101435046807892512,3191843270961299033762,151956292916451992949028,7647074174061818952373990,405606999662504909399728936,22615669177980119502059398538,1322439897031698017874896162924,80922100128062025203683631234894,5171620437802512539280839046073648,344563499798843579910112872647767282,23893103682892007688714280338875922868
mov $4,$0
add $0,1
lpb $0
sub $0,1
mov $2,$1
add $2,1
pow $2,$1
mov $3,$4
bin $3,$1
add $1,1
mul $3,$2
add $5,$3
lpe
mov $0,$5
|
###############################################################################
# Copyright 2018 Intel Corporation
# All Rights Reserved.
#
# If this software was obtained under the Intel Simplified Software License,
# the following terms apply:
#
# The source code, information and material ("Material") contained herein is
# owned by Intel Corporation or its suppliers or licensors, and title to such
# Material remains with Intel Corporation or its suppliers or licensors. The
# Material contains proprietary information of Intel or its suppliers and
# licensors. The Material is protected by worldwide copyright laws and treaty
# provisions. No part of the Material may be used, copied, reproduced,
# modified, published, uploaded, posted, transmitted, distributed or disclosed
# in any way without Intel's prior express written permission. No license under
# any patent, copyright or other intellectual property rights in the Material
# is granted to or conferred upon you, either expressly, by implication,
# inducement, estoppel or otherwise. Any license under such intellectual
# property rights must be express and approved by Intel in writing.
#
# Unless otherwise agreed by Intel in writing, you may not remove or alter this
# notice or any other notice embedded in Materials by Intel or Intel's
# suppliers or licensors in any way.
#
#
# If this software was obtained under the Apache License, Version 2.0 (the
# "License"), the following terms apply:
#
# You may not use this file except in compliance with the License. You may
# obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
#
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
#
# See the License for the specific language governing permissions and
# limitations under the License.
###############################################################################
.section .note.GNU-stack,"",%progbits
.text
.p2align 4, 0x90
ENCODE_DATA:
u128_str:
.byte 15,14,13,12,11,10,9,8,7,6,5,4,3,2,1,0
increment:
.quad 1,0
.p2align 4, 0x90
.globl AuthEncrypt_RIJ128_AES_NI
.type AuthEncrypt_RIJ128_AES_NI, @function
AuthEncrypt_RIJ128_AES_NI:
push %ebp
mov %esp, %ebp
push %ebx
push %esi
push %edi
movl (28)(%ebp), %eax
movdqa (%eax), %xmm0
movdqa (16)(%eax), %xmm2
movdqa (32)(%eax), %xmm1
lea ENCODE_DATA, %eax
movdqa ((u128_str-ENCODE_DATA))(%eax), %xmm7
pshufb %xmm7, %xmm2
pshufb %xmm7, %xmm1
movdqa %xmm1, %xmm3
pandn %xmm2, %xmm3
pand %xmm1, %xmm2
movl (16)(%ebp), %edx
movl (20)(%ebp), %ecx
lea (,%edx,4), %edx
lea (,%edx,4), %edx
lea (%edx,%ecx), %ecx
neg %edx
mov %edx, %ebx
movl (8)(%ebp), %esi
movl (12)(%ebp), %edi
.p2align 4, 0x90
.Lblk_loopgas_1:
movdqu (%esi), %xmm4
pxor %xmm4, %xmm0
movdqa %xmm3, %xmm5
paddq ((increment-ENCODE_DATA))(%eax), %xmm2
pand %xmm1, %xmm2
por %xmm2, %xmm5
pshufb %xmm7, %xmm5
movdqa (%edx,%ecx), %xmm6
add $(16), %edx
pxor %xmm6, %xmm5
pxor %xmm6, %xmm0
movdqa (%edx,%ecx), %xmm6
.p2align 4, 0x90
.Lcipher_loopgas_1:
aesenc %xmm6, %xmm5
aesenc %xmm6, %xmm0
movdqa (16)(%edx,%ecx), %xmm6
add $(16), %edx
jnz .Lcipher_loopgas_1
aesenclast %xmm6, %xmm5
aesenclast %xmm6, %xmm0
pxor %xmm5, %xmm4
movdqu %xmm4, (%edi)
mov %ebx, %edx
add $(16), %esi
add $(16), %edi
subl $(16), (24)(%ebp)
jnz .Lblk_loopgas_1
movl (28)(%ebp), %eax
movdqu %xmm0, (%eax)
movdqu %xmm5, (16)(%eax)
pop %edi
pop %esi
pop %ebx
pop %ebp
ret
.Lfe1:
.size AuthEncrypt_RIJ128_AES_NI, .Lfe1-(AuthEncrypt_RIJ128_AES_NI)
.p2align 4, 0x90
.globl DecryptAuth_RIJ128_AES_NI
.type DecryptAuth_RIJ128_AES_NI, @function
DecryptAuth_RIJ128_AES_NI:
push %ebp
mov %esp, %ebp
push %ebx
push %esi
push %edi
movl (28)(%ebp), %eax
movdqa (%eax), %xmm0
movdqa (16)(%eax), %xmm2
movdqa (32)(%eax), %xmm1
lea ENCODE_DATA, %eax
movdqa ((u128_str-ENCODE_DATA))(%eax), %xmm7
pshufb %xmm7, %xmm2
pshufb %xmm7, %xmm1
movdqa %xmm1, %xmm3
pandn %xmm2, %xmm3
pand %xmm1, %xmm2
movl (16)(%ebp), %edx
movl (20)(%ebp), %ecx
lea (,%edx,4), %edx
lea (,%edx,4), %edx
lea (%edx,%ecx), %ecx
neg %edx
mov %edx, %ebx
movl (8)(%ebp), %esi
movl (12)(%ebp), %edi
.p2align 4, 0x90
.Lblk_loopgas_2:
movdqu (%esi), %xmm4
movdqa %xmm3, %xmm5
paddq ((increment-ENCODE_DATA))(%eax), %xmm2
pand %xmm1, %xmm2
por %xmm2, %xmm5
pshufb %xmm7, %xmm5
movdqa (%edx,%ecx), %xmm6
add $(16), %edx
pxor %xmm6, %xmm5
movdqa (%edx,%ecx), %xmm6
.p2align 4, 0x90
.Lcipher_loopgas_2:
aesenc %xmm6, %xmm5
movdqa (16)(%edx,%ecx), %xmm6
add $(16), %edx
jnz .Lcipher_loopgas_2
aesenclast %xmm6, %xmm5
pxor %xmm5, %xmm4
movdqu %xmm4, (%edi)
mov %ebx, %edx
movdqa (%edx,%ecx), %xmm6
add $(16), %edx
pxor %xmm4, %xmm0
pxor %xmm6, %xmm0
movdqa (%edx,%ecx), %xmm6
.p2align 4, 0x90
.Lauth_loopgas_2:
aesenc %xmm6, %xmm0
movdqa (16)(%edx,%ecx), %xmm6
add $(16), %edx
jnz .Lauth_loopgas_2
aesenclast %xmm6, %xmm0
mov %ebx, %edx
add $(16), %esi
add $(16), %edi
subl $(16), (24)(%ebp)
jnz .Lblk_loopgas_2
movl (28)(%ebp), %eax
movdqu %xmm0, (%eax)
movdqu %xmm6, (16)(%eax)
pop %edi
pop %esi
pop %ebx
pop %ebp
ret
.Lfe2:
.size DecryptAuth_RIJ128_AES_NI, .Lfe2-(DecryptAuth_RIJ128_AES_NI)
|
// Copyright (c) 2017-2021, Mudita Sp. z.o.o. All rights reserved.
// For licensing, see https://github.com/mudita/MuditaOS/LICENSE.md
#pragma once
#include "Image.hpp"
#include "StatusBarWidgetBase.hpp"
#include <service-bluetooth/Constants.hpp>
namespace gui::status_bar
{
class BT : public StatusBarWidgetBase<Image>
{
public:
BT(Item *parent, uint32_t x, uint32_t y);
void setBluetoothMode(sys::bluetooth::BluetoothMode mode);
};
} // namespace gui::status_bar
|
/*
Module : AAPhysicalMars.cpp
Purpose: Implementation for the algorithms which obtain the physical parameters of Mars
Created: PJN / 04-01-2004
History: PJN / 16-09-2015 1. CAAPhysicalMars::Calculate now includes a "bool bHighPrecision" parameter
which if set to true means the code uses the full VSOP87 theory rather than the
truncated theory as presented in Meeus's book.
Copyright (c) 2003 - 2018 by PJ Naughter (Web: www.naughter.com, Email: pjna@naughter.com)
All rights reserved.
Copyright / Usage Details:
You are allowed to include the source code in any product (commercial, shareware, freeware or otherwise)
when your product is released in binary form. You are allowed to modify the source code in any way you want
except you cannot modify the copyright details at the top of each module. If you want to distribute source
code with your application, then you are only allowed to distribute versions released by the author. This is
to maintain a single distribution point for the source code.
*/
///////////////////////////////// Includes ////////////////////////////////////
#include "stdafx.h"
#include "AAPhysicalMars.h"
#include "AAMars.h"
#include "AAEarth.h"
#include "AASun.h"
#include "AANutation.h"
#include "AACoordinateTransformation.h"
#include "AAElliptical.h"
#include "AAMoonIlluminatedFraction.h"
#include "AAIlluminatedFraction.h"
#include <cmath>
using namespace std;
//////////////////////////////// Implementation ///////////////////////////////
CAAPhysicalMarsDetails CAAPhysicalMars::Calculate(double JD, bool bHighPrecision)
{
//What will be the return value
CAAPhysicalMarsDetails details;
//Step 1
double T = (JD - 2451545) / 36525;
double Lambda0 = 352.9065 + 1.17330*T;
double Lambda0rad = CAACoordinateTransformation::DegreesToRadians(Lambda0);
double Beta0 = 63.2818 - 0.00394*T;
double Beta0rad = CAACoordinateTransformation::DegreesToRadians(Beta0);
//Step 2
double l0 = CAAEarth::EclipticLongitude(JD, bHighPrecision);
double l0rad = CAACoordinateTransformation::DegreesToRadians(l0);
double b0 = CAAEarth::EclipticLatitude(JD, bHighPrecision);
double b0rad = CAACoordinateTransformation::DegreesToRadians(b0);
double R = CAAEarth::RadiusVector(JD, bHighPrecision);
double PreviousLightTravelTime = 0;
double LightTravelTime = 0;
double x = 0;
double y = 0;
double z = 0;
bool bIterate = true;
double DELTA = 0;
double l = 0;
double lrad = 0;
double b = 0;
double r = 0;
while (bIterate)
{
double JD2 = JD - LightTravelTime;
//Step 3
l = CAAMars::EclipticLongitude(JD2, bHighPrecision);
lrad = CAACoordinateTransformation::DegreesToRadians(l);
b = CAAMars::EclipticLatitude(JD2, bHighPrecision);
double brad = CAACoordinateTransformation::DegreesToRadians(b);
r = CAAMars::RadiusVector(JD2, bHighPrecision);
//Step 4
x = r*cos(brad)*cos(lrad) - R*cos(l0rad);
y = r*cos(brad)*sin(lrad) - R*sin(l0rad);
z = r*sin(brad) - R*sin(b0rad);
DELTA = sqrt(x*x + y*y + z*z);
LightTravelTime = CAAElliptical::DistanceToLightTime(DELTA);
//Prepare for the next loop around
bIterate = (fabs(LightTravelTime - PreviousLightTravelTime) > 2e-6); //2e-6 correponds to 0.17 of a second
if (bIterate)
PreviousLightTravelTime = LightTravelTime;
}
//Step 5
double lambdarad = atan2(y, x);
double lambda = CAACoordinateTransformation::RadiansToDegrees(lambdarad);
double betarad = atan2(z, sqrt(x*x + y*y));
double beta = CAACoordinateTransformation::RadiansToDegrees(betarad);
//Step 6
details.DE = CAACoordinateTransformation::RadiansToDegrees(asin(-sin(Beta0rad)*sin(betarad) - cos(Beta0rad)*cos(betarad)*cos(Lambda0rad - lambdarad)));
//Step 7
double N = 49.5581 + 0.7721*T;
double Nrad = CAACoordinateTransformation::DegreesToRadians(N);
double ldash = l - 0.00697/r;
double ldashrad = CAACoordinateTransformation::DegreesToRadians(ldash);
double bdash = b - 0.000225*(cos(lrad - Nrad)/r);
double bdashrad = CAACoordinateTransformation::DegreesToRadians(bdash);
//Step 8
details.DS = CAACoordinateTransformation::RadiansToDegrees(asin(-sin(Beta0rad)*sin(bdashrad) - cos(Beta0rad)*cos(bdashrad)*cos(Lambda0rad - ldashrad)));
//Step 9
double W = CAACoordinateTransformation::MapTo0To360Range(11.504 + 350.89200025*(JD - LightTravelTime - 2433282.5));
//Step 10
double e0 = CAANutation::MeanObliquityOfEcliptic(JD);
double e0rad = CAACoordinateTransformation::DegreesToRadians(e0);
CAA2DCoordinate PoleEquatorial = CAACoordinateTransformation::Ecliptic2Equatorial(Lambda0, Beta0, e0);
double alpha0rad = CAACoordinateTransformation::HoursToRadians(PoleEquatorial.X);
double delta0rad = CAACoordinateTransformation::DegreesToRadians(PoleEquatorial.Y);
//Step 11
double u = y*cos(e0rad) - z*sin(e0rad);
double v = y*sin(e0rad) + z*cos(e0rad);
double alpharad = atan2(u, x);
double alpha = CAACoordinateTransformation::RadiansToHours(alpharad);
double deltarad = atan2(v, sqrt(x*x + u*u));
double delta = CAACoordinateTransformation::RadiansToDegrees(deltarad);
double xi = atan2(sin(delta0rad)*cos(deltarad)*cos(alpha0rad - alpharad) - sin(deltarad)*cos(delta0rad), cos(deltarad)*sin(alpha0rad - alpharad));
//Step 12
details.w = CAACoordinateTransformation::MapTo0To360Range(W - CAACoordinateTransformation::RadiansToDegrees(xi));
//Step 13
double NutationInLongitude = CAANutation::NutationInLongitude(JD);
double NutationInObliquity = CAANutation::NutationInObliquity(JD);
//Step 14
lambda += 0.005693*cos(l0rad - lambdarad)/cos(betarad);
beta += 0.005693*sin(l0rad - lambdarad)*sin(betarad);
//Step 15
Lambda0 += NutationInLongitude/3600;
lambda += NutationInLongitude/3600;
e0 += NutationInObliquity/3600;
//Step 16
CAA2DCoordinate ApparentPoleEquatorial = CAACoordinateTransformation::Ecliptic2Equatorial(Lambda0, Beta0, e0);
double alpha0dash = CAACoordinateTransformation::HoursToRadians(ApparentPoleEquatorial.X);
double delta0dash = CAACoordinateTransformation::DegreesToRadians(ApparentPoleEquatorial.Y);
CAA2DCoordinate ApparentMars = CAACoordinateTransformation::Ecliptic2Equatorial(lambda, beta, e0);
double alphadash = CAACoordinateTransformation::HoursToRadians(ApparentMars.X);
double deltadash = CAACoordinateTransformation::DegreesToRadians(ApparentMars.Y);
//Step 17
details.P = CAACoordinateTransformation::MapTo0To360Range(CAACoordinateTransformation::RadiansToDegrees(atan2(cos(delta0dash)*sin(alpha0dash - alphadash), sin(delta0dash)*cos(deltadash) - cos(delta0dash)*sin(deltadash)*cos(alpha0dash - alphadash))));
//Step 18
double SunLambda = CAASun::GeometricEclipticLongitude(JD, bHighPrecision);
double SunBeta = CAASun::GeometricEclipticLatitude(JD, bHighPrecision);
CAA2DCoordinate SunEquatorial = CAACoordinateTransformation::Ecliptic2Equatorial(SunLambda, SunBeta, e0);
details.X = CAAMoonIlluminatedFraction::PositionAngle(SunEquatorial.X, SunEquatorial.Y, alpha, delta);
//Step 19
details.d = 9.36 / DELTA;
details.k = CAAIlluminatedFraction::IlluminatedFraction(r, R, DELTA);
details.q = (1 - details.k)*details.d;
return details;
}
|
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
; TERM_01_OUTPUT_CHAR
; basic terminal output driver for generic system
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;
; Windowed output terminal for fixed width fonts.
;
; ;;;;;;;;;;;;;;;;;;;;
; DRIVER CLASS DIAGRAM
; ;;;;;;;;;;;;;;;;;;;;
;
; CONSOLE_01_OUTPUT_TERMINAL (root, abstract)
; CONSOLE_01_OUTPUT_TERMINAL_CHAR (abstract)
; TERM_01_OUTPUT_CHAR (concrete)
;
; Can be instantiated to implement a CONSOLE_01_OUTPUT_TERMINAL.
;
; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;
; MESSAGES CONSUMED FROM STDIO
; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;
; * STDIO_MSG_PUTC
; Generates multiple OTERM_MSG_PUTC messages.
;
; * STDIO_MSG_WRIT
; Generates multiple OTERM_MSG_PUTC messages.
;
; * STDIO_MSG_SEEK -> no error, do nothing
; * STDIO_MSG_FLSH -> no error, do nothing
; * STDIO_MSG_ICTL
; * STDIO_MSG_CLOS -> no error, do nothing
;
; Any other messages are reported as errors via
; error_enotsup_zc
;
; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
; MESSAGES CONSUMED FROM CONSOLE_01_OUTPUT_TERMINAL
; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;
; * OTERM_MSG_PUTC
;
; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
; MESSAGES CONSUMED FROM CONSOLE_01_INPUT_TERMINAL
; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;
; * ITERM_MSG_PUTC
; * ITERM_MSG_BS
; * ITERM_MSG_BS_PWD
; * ITERM_MSG_ERASE_CURSOR
; * ITERM_MSG_ERASE_CURSOR_PWD
; * ITERM_MSG_READLINE_BEGIN
; * ITERM_MSG_READLINE_END
; * ITERM_MSG_BELL
;
; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
; MESSAGES CONSUMED FROM CONSOLE_01_OUTPUT_TERMINAL_CHAR
; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;
; * OTERM_MSG_PRINTC
; * OTERM_MSG_BELL
; * OTERM_MSG_SCROLL
; * OTERM_MSG_CLS
; * OTERM_MSG_PAUSE
;
; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
; MESSAGES GENERATED FOR DERIVED DRIVERS
; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;
; * OTERM_MSG_TTY (optional)
;
; enter : c = char to output
; exit : c = char to output (possibly modified)
; carry reset if tty emulation absorbs char
; can use: af, bc, de, hl
;
; The driver should call the tty emulation module.
; If not implemented characters are output without processing.
;
; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
; IOCTLs UNDERSTOOD BY THIS DRIVER
; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;
; * IOCTL_OTERM_CRLF
; enable / disable crlf processing
;
; * IOCTL_OTERM_BELL
; enable / disable terminal bell
;
; * IOCTL_OTERM_SIGNAL
; enable / disable signal bell
;
; * IOCTL_OTERM_COOK
; enable / disable cook mode (tty emulation)
;
; * IOCTL_OTERM_PAUSE
; enable / disable pause when window filled
;
; * IOCTL_OTERM_PAGE
; select scroll or page mode
;
; * IOCTL_OTERM_CLEAR
; enable / disable clear window when in page mode
;
; * IOCTL_OTERM_CLS
; clear window, set (x,y) = (0,0)
;
; * IOCTL_OTERM_RESET_SCROLL
; reset scroll count
;
; * IOCTL_OTERM_GET_WINDOW_COORD
; get coord of top left corner of window
;
; * IOCTL_OTERM_SET_WINDOW_COORD
; set coord of top left corner of window
;
; * IOCTL_OTERM_GET_WINDOW_RECT
; get window size
;
; * IOCTL_OTERM_SET_WINDOW_RECT
; set window size
;
; * IOCTL_OTERM_GET_CURSOR_COORD
;
; * IOCTL_OTERM_SET_CURSOR_COORD
;
; * IOCTL_OTERM_GET_OTERM
;
; * IOCTL_OTERM_SCROLL
;
; ;;;;;;;;;;;;;;;;;;;;;;;;;;
; BYTES RESERVED IN FDSTRUCT
; ;;;;;;;;;;;;;;;;;;;;;;;;;;
;
; offset (wrt FDSTRUCT.JP) description
;
; 8..13 mutex
; 14 x coordinate
; 15 y coordinate
; 16 window.x
; 17 window.width
; 18 window.y
; 19 window.height
; 20 scroll_limit
SECTION code_driver
SECTION code_driver_terminal_output
PUBLIC term_01_output_char
EXTERN OTERM_MSG_PRINTC, ITERM_MSG_BELL, OTERM_MSG_SCROLL
EXTERN OTERM_MSG_CLS, OTERM_MSG_PAUSE, OTERM_MSG_BELL
EXTERN console_01_output_terminal_char
EXTERN term_01_output_char_oterm_msg_printc, term_01_output_char_iterm_msg_bell
EXTERN term_01_output_char_oterm_msg_scroll, term_01_output_char_oterm_msg_cls
EXTERN term_01_output_char_oterm_msg_pause, term_01_output_char_oterm_msg_bell
term_01_output_char:
cp OTERM_MSG_PRINTC
jp z, term_01_output_char_oterm_msg_printc
cp ITERM_MSG_BELL
jp z, term_01_output_char_iterm_msg_bell
cp OTERM_MSG_SCROLL
jp z, term_01_output_char_oterm_msg_scroll
jp c, console_01_output_terminal_char ; forward to library
cp OTERM_MSG_CLS
jp z, term_01_output_char_oterm_msg_cls
cp OTERM_MSG_PAUSE
jp z, term_01_output_char_oterm_msg_pause
cp OTERM_MSG_BELL
jp z, term_01_output_char_oterm_msg_bell
jp console_01_output_terminal_char ; forward to library
|
; This is meaningless code to test the assembler and decoder. Please don't run this
test:
ldr r1, [r2 + 32]
ldr lr, [sp + r3 << 2]
str [r2 + 32], r1
str [r2 + r3 >> 2], r1
mov r0, 20
mov r0, r3 << 3
movt r10, 0x12
; The formatting issues are on purpose
add sp, lr, r14
add r12, r8, 0b1001 ; same line!
addc sp, lr, r14
addc r12, r8, 0b1001
sub r8, r6, r4 << 3
sub r12, r8, 100
rsub r8, r6, r4 >> 6
rsub r12, r8, 100
subc r8, r6, r4
subc r12, r8, 100
rsubc r8, r6, r4
rsubc r12, r8, 100
mul r8, r6, r4 >> 6
and r8, r6, r4 << 3
and r12, r8, 100
or r8, r6, r4 << 3
or r12, r8, 100
xor r8, r6, r4 << 3
xor r12, r8, 100
not r8, r6
cmp r0, r8
cmp r0, 0x0
cmp r0, r1
cmp r0, 0x8
int 0xf213
jmp label ; Is the jump correct?
jmp test
label:
mov r0, 'a'
int "b"
|
/*
* Copyright (C) 2015 The Android Open Source Project
*
* 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 <gtest/gtest.h>
#include <utils/LinearAllocator.h>
#include <tests/common/TestUtils.h>
using namespace android;
using namespace android::uirenderer;
struct SimplePair {
int one = 1;
int two = 2;
};
TEST(LinearAllocator, create) {
LinearAllocator la;
EXPECT_EQ(0u, la.usedSize());
la.alloc<char>(64);
// There's some internal tracking as well as padding
// so the usedSize isn't strictly defined
EXPECT_LE(64u, la.usedSize());
EXPECT_GT(80u, la.usedSize());
auto pair = la.create<SimplePair>();
EXPECT_LE(64u + sizeof(SimplePair), la.usedSize());
EXPECT_GT(80u + sizeof(SimplePair), la.usedSize());
EXPECT_EQ(1, pair->one);
EXPECT_EQ(2, pair->two);
}
TEST(LinearAllocator, dtor) {
int destroyed[10] = { 0 };
{
LinearAllocator la;
for (int i = 0; i < 5; i++) {
la.create<TestUtils::SignalingDtor>()->setSignal(destroyed + i);
la.create<SimplePair>();
}
la.alloc<char>(100);
for (int i = 0; i < 5; i++) {
la.create<TestUtils::SignalingDtor>(destroyed + 5 + i);
la.create_trivial<SimplePair>();
}
la.alloc<char>(100);
for (int i = 0; i < 10; i++) {
EXPECT_EQ(0, destroyed[i]);
}
}
for (int i = 0; i < 10; i++) {
EXPECT_EQ(1, destroyed[i]);
}
}
TEST(LinearAllocator, rewind) {
int destroyed = 0;
{
LinearAllocator la;
auto addr = la.alloc<char>(100);
EXPECT_LE(100u, la.usedSize());
la.rewindIfLastAlloc(addr, 100);
EXPECT_GT(16u, la.usedSize());
size_t emptySize = la.usedSize();
auto sigdtor = la.create<TestUtils::SignalingDtor>();
sigdtor->setSignal(&destroyed);
EXPECT_EQ(0, destroyed);
EXPECT_LE(emptySize, la.usedSize());
la.rewindIfLastAlloc(sigdtor);
EXPECT_EQ(1, destroyed);
EXPECT_EQ(emptySize, la.usedSize());
}
// Checking for a double-destroy case
EXPECT_EQ(1, destroyed);
}
TEST(LinearStdAllocator, simpleAllocate) {
LinearAllocator la;
LinearStdAllocator<void*> stdAllocator(la);
std::vector<char, LinearStdAllocator<char> > v(stdAllocator);
v.push_back(0);
char* initialLocation = &v[0];
v.push_back(10);
v.push_back(20);
v.push_back(30);
// expect to have allocated (since no space reserved), so [0] will have moved to
// slightly further down in the same LinearAllocator page
EXPECT_LT(initialLocation, &v[0]);
EXPECT_GT(initialLocation + 20, &v[0]);
// expect to have allocated again inserting 4 more entries
char* lastLocation = &v[0];
v.push_back(40);
v.push_back(50);
v.push_back(60);
v.push_back(70);
EXPECT_LT(lastLocation, &v[0]);
EXPECT_GT(lastLocation + 20, &v[0]);
}
TEST(LsaVector, dtorCheck) {
LinearAllocator allocator;
LinearStdAllocator<void*> stdAllocator(allocator);
for (int size : {1, 2, 3, 500}) {
int destroyed = 0;
{
LsaVector<std::unique_ptr<TestUtils::SignalingDtor> > vector(stdAllocator);
for (int i = 0; i < size; i++) {
vector.emplace_back(new TestUtils::SignalingDtor(&destroyed));
}
EXPECT_EQ(0, destroyed);
EXPECT_EQ(size, (int) vector.size());
}
EXPECT_EQ(size, destroyed);
}
}
|
format ELF
include 'macro.inc'
include 'procedures.inc'
section '.text' executable
use32
public enable_paging
pd_add = 0xB000
pd_size = 4
pd_num = 1024
; [pde, pde+0x1000] - PDE 1
; [pde+0x1000+1+(i-1)]
enable_paging:;(void * PD) ; ret, cause low memory mapped onto itself
push ebp
mov ebp, esp
mov eax, [ebp+8]
mov cr3, eax
mov eax, cr0
or eax, 0x80000000
mov cr0, eax
pop ebp
ret |
;
; Z88dk Generic Floating Point Math Library
;
; Shift c ix de b right by a
;
; $Id: rshift_noaf.asm,v 1.4 2016/06/21 21:16:49 dom Exp $:
SECTION code_fp
PUBLIC rshift
PUBLIC rsh8
.rshift LD B,0
.RSH2 SUB 8
JR C,RSH4 ;c => 7 or fewer shifts remain
LD B,E ;shift c ix de b right by 8...
LD E,D
LD D,IXL
;EX AF,AF'
PUSH AF
LD A,IXH
LD IXL,A
;EX AF,AF'
POP AF
LD IXH,C
LD C,0 ;...end of shifting
JR RSH2
;
.RSH4 ADD A,9
LD L,A
.RSH6 XOR A
DEC L
RET Z ;z => requested shift is complete
LD A,C
.rsh8 RRA ;shift c ix de b right by one...
LD C,A
LD A,IXH
RRA
LD IXH,A
LD A,IXL
RRA
LD IXL,A
RR D
RR E
RR B ;...end of shifting
JR RSH6
|
[XCX_TICKETS_DLC_ALL]
moduleMatches = 0xF882D5CF, 0x30B6E091, 0xAB97DE6B ; 1.0.1E, 1.0.2U, 1.0.1U
.origin = codecave
.int $mission
VarTicketsAmount:
.int 0
; ----------------------------------------------------------------------------
; WHO : menu::MenuMultiQuestInfoWindow::displayInfo((menu::MenuObject *,bool))
; menu::MenuMultiQuestResult::setup((void))
; addReward__Q2_3cfs11CfSquadUtilSFUiT1
; WHAT : Override the Tickets rewarded for a DLC mission.
; By default, the number of tickets is the money divided by 100.
_ticketsDispBefore:
lwz r24, 0x47C(r30)
lwz r24, 8(r24) ; mission type
li r26, $mission
cmplw r24, r26
li r26, 0
lis r21, VarTicketsAmount@ha
stw r26, VarTicketsAmount@l(r21)
bnelr
mr r26, r23 ; r23 = exp
cmpwi r24, 5
bne saveAmount
li r24, 100
divw r26, r22, r24 ; r22 = money
saveAmount:
lis r21, VarTicketsAmount@ha
stw r26, VarTicketsAmount@l(r21)
blr
_ticketsDispAfter:
lis r5, VarTicketsAmount@ha
lwz r5, VarTicketsAmount@l(r5)
blr
_ticketsValue:
lis r27, VarTicketsAmount@ha
lwz r27, VarTicketsAmount@l(r27)
blr
[XCX_TICKETS_DLC_1E] ############################################################################################
moduleMatches = 0xF882D5CF ; 1.0.1E
0x02B94718 = bla _ticketsDispBefore
0x02B9FE2C = bla _ticketsDispAfter
0x023CC654 = bla _ticketsValue
[XCX_TICKETS_DLC_2U] ############################################################################################
moduleMatches = 0x30B6E091 ; 1.0.2U
0x02B94708 = bla _ticketsDispBefore
0x02B9FE1C = bla _ticketsDispAfter
0x023CC654 = bla _ticketsValue
[XCX_TICKETS_DLC_1U] ############################################################################################
moduleMatches = 0xAB97DE6B ; 1.0.1U
0x02B9468C = bla _ticketsDispBefore
0x02B9FD2C = bla _ticketsDispAfter
0x023CC5E4 = bla _ticketsValue
|
/*
*
* Copyright 2018 Asylo authors
*
* 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 "asylo/test/util/finite_domain_fuzz.h"
#include <gmock/gmock.h>
#include "absl/types/optional.h"
namespace asylo {
// An integer with exactly one randomly chosen bit set. It will never
// pick most significant bit, as overflow behavior is sometimes
// surprising.
//
// Bitsets in signed integers require careful attention to the
// representational limits of ints. The range of an int is
// [-2^(sizeof(int) * 8 - 1), 2^(sizeof(int) * 8 - 1) - 1]. Therefore
// the amount of positive flags values is sizeof(int) * 8 - 2 to avoid
// signed integer overflow.
int random_flag() {
// Pick a random bit index
int index = rand()%(sizeof(int) * 8 - 1);
return 1 << index;
}
absl::optional<std::vector<std::pair<int64_t, int64_t>>>
FuzzBitsetTranslationFunction(const std::vector<int64_t>& input,
const std::vector<int64_t>& output,
int iter_bound) {
auto all_cases = zip(input, output);
if (!all_cases) {
return all_cases;
}
all_cases->push_back(std::make_pair(0, 0));
// Grab multiple random flags at the same time
size_t size = input.size();
auto begin = input.begin();
auto end = input.end();
for (int i = 0; i < iter_bound; i++) {
// Test multiple flags in the defined domain
int in = 0;
int out = 0;
for (int j = 0; j < size; j++) {
if (rand()%2) {
in |= input[j];
out |= output[j];
}
all_cases->push_back(std::make_pair(in, out));
}
// Test multiple flags in and outside the defined domain
in = 0;
out = 0;
for (int j = 0; j < sizeof(int64_t) * 8; j++) {
int flag = random_flag();
auto found = find(begin, end, flag);
size_t index = found - begin;
// If flag is not in input, then OR it in without a translated
// output counterpart.
if (found == end) {
in |= flag;
} else {
in |= input[index];
out |= output[index];
}
}
all_cases->push_back(std::make_pair(in, out));
}
return all_cases;
}
} // namespace asylo
|
; Valid sprite IDs for each map group.
; Maps with environment ROUTE or TOWN can only use these sprites.
OutdoorSprites:
; entries correspond to map groups
dw PalletGroupSprites
dw ViridianGroupSprites
dw PewterGroupSprites
dw DungeonsGroupSprites
dw CeruleanGroupSprites
; dw VermilionGroupSprites
dw IndigoGroupSprites
dw BattleTowerGroupSprites
dw CableClubGroupSprites
PalletGroupSprites:
db SPRITE_SUICUNE
db SPRITE_SILVER_TROPHY
db SPRITE_FAMICOM
db SPRITE_POKEDEX
db SPRITE_WILL
db SPRITE_KAREN
db SPRITE_NURSE
db SPRITE_OLD_LINK_RECEPTIONIST
db SPRITE_BIG_LAPRAS
db SPRITE_BIG_ONIX
db SPRITE_SUDOWOODO
db SPRITE_BIG_SNORLAX
db SPRITE_TEACHER
db SPRITE_FISHER
db SPRITE_YOUNGSTER
db SPRITE_BLUE
db SPRITE_GRAMPS
db SPRITE_BUG_CATCHER
db SPRITE_COOLTRAINER_F
db SPRITE_SWIMMER_GIRL
db SPRITE_SWIMMER_GUY
db SPRITE_POKE_BALL
db SPRITE_FRUIT_TREE
ViridianGroupSprites:
db SPRITE_SUICUNE
db SPRITE_SILVER_TROPHY
db SPRITE_FAMICOM
db SPRITE_POKEDEX
db SPRITE_WILL
db SPRITE_KAREN
db SPRITE_NURSE
db SPRITE_OLD_LINK_RECEPTIONIST
db SPRITE_BIG_LAPRAS
db SPRITE_BIG_ONIX
db SPRITE_SUDOWOODO
db SPRITE_BIG_SNORLAX
db SPRITE_TEACHER
db SPRITE_FISHER
db SPRITE_YOUNGSTER
db SPRITE_SILVER
db SPRITE_GRAMPS
db SPRITE_BUG_CATCHER
db SPRITE_COOLTRAINER_F
db SPRITE_SWIMMER_GIRL
db SPRITE_SWIMMER_GUY
db SPRITE_POKE_BALL
db SPRITE_FRUIT_TREE
PewterGroupSprites:
db SPRITE_SUICUNE
db SPRITE_SILVER_TROPHY
db SPRITE_FAMICOM
db SPRITE_POKEDEX
db SPRITE_WILL
db SPRITE_KAREN
db SPRITE_NURSE
db SPRITE_OLD_LINK_RECEPTIONIST
db SPRITE_BIG_LAPRAS
db SPRITE_BIG_ONIX
db SPRITE_SUDOWOODO
db SPRITE_BIG_SNORLAX
db SPRITE_TEACHER
db SPRITE_FISHER
db SPRITE_YOUNGSTER
db SPRITE_COOLTRAINER_M
db SPRITE_GRAMPS
db SPRITE_BUG_CATCHER
db SPRITE_COOLTRAINER_F
db SPRITE_LASS
db SPRITE_SWIMMER_GUY
db SPRITE_POKE_BALL
db SPRITE_FRUIT_TREE
DungeonsGroupSprites:
db SPRITE_SUICUNE
db SPRITE_SILVER_TROPHY
db SPRITE_FAMICOM
db SPRITE_POKEDEX
db SPRITE_WILL
db SPRITE_KAREN
db SPRITE_NURSE
db SPRITE_OLD_LINK_RECEPTIONIST
db SPRITE_GAMEBOY_KID
db SPRITE_BIG_ONIX
db SPRITE_SUDOWOODO
db SPRITE_COOLTRAINER_F
db SPRITE_YOUNGSTER
db SPRITE_TEACHER
db SPRITE_YOUNGSTER
db SPRITE_GROWLITHE
db SPRITE_POKEFAN_M
db SPRITE_ROCKER
db SPRITE_FISHER
db SPRITE_SCIENTIST
db SPRITE_POKE_BALL
db SPRITE_BOULDER
CeruleanGroupSprites:
db SPRITE_SUICUNE
db SPRITE_SILVER_TROPHY
db SPRITE_FAMICOM
db SPRITE_POKEDEX
db SPRITE_WILL
db SPRITE_KAREN
db SPRITE_NURSE
db SPRITE_OLD_LINK_RECEPTIONIST
db SPRITE_BIG_LAPRAS
db SPRITE_BIG_ONIX
db SPRITE_SUDOWOODO
db SPRITE_BIG_SNORLAX
db SPRITE_COOLTRAINER_M
db SPRITE_ROCKET_GIRL
db SPRITE_COOLTRAINER_F
db SPRITE_FISHER
db SPRITE_YOUNGSTER
db SPRITE_LASS
db SPRITE_POKEFAN_M
db SPRITE_ROCKET
db SPRITE_MISTY
db SPRITE_POKE_BALL
db SPRITE_SLOWPOKE
IndigoGroupSprites:
db SPRITE_SUICUNE
db SPRITE_SILVER_TROPHY
db SPRITE_FAMICOM
db SPRITE_POKEDEX
db SPRITE_WILL
db SPRITE_KAREN
db SPRITE_NURSE
db SPRITE_OLD_LINK_RECEPTIONIST
db SPRITE_BIG_LAPRAS
db SPRITE_BIG_ONIX
db SPRITE_SUDOWOODO
db SPRITE_BIG_SNORLAX
db SPRITE_POKEFAN_M
db SPRITE_BUENA
db SPRITE_GRAMPS
db SPRITE_YOUNGSTER
db SPRITE_FISHER
db SPRITE_TEACHER
db SPRITE_SUPER_NERD
db SPRITE_MACHOP
db SPRITE_BIKER
db SPRITE_POKE_BALL
db SPRITE_BOULDER
BattleTowerGroupSprites:
db SPRITE_SUICUNE
db SPRITE_SILVER_TROPHY
db SPRITE_FAMICOM
db SPRITE_POKEDEX
db SPRITE_WILL
db SPRITE_KAREN
db SPRITE_NURSE
db SPRITE_OLD_LINK_RECEPTIONIST
db SPRITE_BIG_LAPRAS
db SPRITE_BIG_ONIX
db SPRITE_SUDOWOODO
db SPRITE_BIG_SNORLAX
db SPRITE_SAILOR
db SPRITE_FISHING_GURU
db SPRITE_GENTLEMAN
db SPRITE_SUPER_NERD
db SPRITE_HO_OH
db SPRITE_TEACHER
db SPRITE_COOLTRAINER_F
db SPRITE_YOUNGSTER
db SPRITE_FAIRY
db SPRITE_POKE_BALL
db SPRITE_ROCK
CableClubGroupSprites:
db SPRITE_OAK
db SPRITE_FISHER
db SPRITE_TEACHER
db SPRITE_TWIN
db SPRITE_POKEFAN_M
db SPRITE_GRAMPS
db SPRITE_FAIRY
db SPRITE_SILVER
db SPRITE_FISHING_GURU
db SPRITE_POKE_BALL
db SPRITE_POKEDEX
|
; A077981: Expansion of 1/(1+2*x-2*x^2-2*x^3).
; Submitted by Christian Krause
; 1,-2,6,-14,36,-88,220,-544,1352,-3352,8320,-20640,51216,-127072,315296,-782304,1941056,-4816128,11949760,-29649664,73566592,-182532992,452899840,-1123732480,2788198656,-6918062592,17165057536,-42589842944,105673675776,-262196922368,650561510400,-1614169513984,4005068204032,-9937352415232,24656502210560,-61177572843520,151793445277696,-376629031821312,934489808510976,-2318650790109184,5753023133597696,-14274368230391808,35417481147760640,-87877652489109504,218041530812956672,-541003404308611072
mov $1,1
mov $3,-1
lpb $0
sub $0,1
mul $2,2
sub $3,$1
add $1,$3
add $2,$3
add $1,$2
sub $2,$1
add $1,$2
sub $2,$1
lpe
mov $0,$1
|
.file "(extract)es.c"
.text
.globl pari_flush
.type pari_flush, @function
pari_flush:
pushl %ebx
subl $8, %esp
call .L00000009
.L00000009:
popl %ebx
addl $_GLOBAL_OFFSET_TABLE_+1, %ebx
movl pariOut@GOT(%ebx), %ecx
movl (%ecx), %edx
call *8(%edx)
.L0000001B:
addl $8, %esp
popl %ebx
ret
.size pari_flush, .-pari_flush
# ----------------------
.ident "GCC: (GNU) 3.2.3 20030502 (Red Hat Linux 3.2.3-59)"
.section .note.GNU-stack,"",@progbits
|
; A052672: E.g.f. (1-x)/(1-x-2x^2+x^3).
; Submitted by Christian Krause
; 1,0,4,6,120,600,10080,95760,1693440,23950080,475372800,8821612800,199743667200,4533271142400,116906088499200,3112264995840000,90679371374592000,2757644630028288000,89895729202126848000
mov $2,$0
seq $0,52547 ; Expansion of (1-x)/(1-x-2*x^2+x^3).
lpb $2
mul $0,$2
sub $2,1
lpe
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.