text
stringlengths
5
1.04M
#include <Storages/MergeTree/DataPartsExchange.h> #include <DataStreams/NativeBlockOutputStream.h> #include <Disks/SingleDiskVolume.h> #include <Disks/createVolume.h> #include <IO/HTTPCommon.h> #include <Server/HTTP/HTMLForm.h> #include <Server/HTTP/HTTPServerResponse.h> #include <Storages/MergeTree/MergeTreeDataPartInMemory.h> #include <Storages/MergeTree/MergedBlockOutputStream.h> #include <Storages/MergeTree/ReplicatedFetchList.h> #include <Storages/StorageReplicatedMergeTree.h> #include <Common/CurrentMetrics.h> #include <Common/NetException.h> #include <IO/createReadBufferFromFileBase.h> #include <common/scope_guard.h> #include <Poco/Net/HTTPRequest.h> namespace fs = std::filesystem; namespace CurrentMetrics { extern const Metric ReplicatedSend; } namespace DB { namespace ErrorCodes { extern const int DIRECTORY_ALREADY_EXISTS; extern const int NO_SUCH_DATA_PART; extern const int ABORTED; extern const int BAD_SIZE_OF_FILE_IN_DATA_PART; extern const int CANNOT_WRITE_TO_OSTREAM; extern const int CHECKSUM_DOESNT_MATCH; extern const int INSECURE_PATH; extern const int CORRUPTED_DATA; extern const int LOGICAL_ERROR; extern const int S3_ERROR; extern const int INCORRECT_PART_TYPE; } namespace DataPartsExchange { namespace { constexpr auto REPLICATION_PROTOCOL_VERSION_WITH_PARTS_SIZE = 1; constexpr auto REPLICATION_PROTOCOL_VERSION_WITH_PARTS_SIZE_AND_TTL_INFOS = 2; constexpr auto REPLICATION_PROTOCOL_VERSION_WITH_PARTS_TYPE = 3; constexpr auto REPLICATION_PROTOCOL_VERSION_WITH_PARTS_DEFAULT_COMPRESSION = 4; constexpr auto REPLICATION_PROTOCOL_VERSION_WITH_PARTS_UUID = 5; constexpr auto REPLICATION_PROTOCOL_VERSION_WITH_PARTS_S3_COPY = 6; constexpr auto REPLICATION_PROTOCOL_VERSION_WITH_PARTS_PROJECTION = 7; std::string getEndpointId(const std::string & node_id) { return "DataPartsExchange:" + node_id; } /// Simple functor for tracking fetch progress in system.replicated_fetches table. struct ReplicatedFetchReadCallback { ReplicatedFetchList::Entry & replicated_fetch_entry; explicit ReplicatedFetchReadCallback(ReplicatedFetchList::Entry & replicated_fetch_entry_) : replicated_fetch_entry(replicated_fetch_entry_) {} void operator() (size_t bytes_count) { replicated_fetch_entry->bytes_read_compressed.store(bytes_count, std::memory_order_relaxed); /// It's possible when we fetch part from very old clickhouse version /// which doesn't send total size. if (replicated_fetch_entry->total_size_bytes_compressed != 0) { replicated_fetch_entry->progress.store( static_cast<double>(bytes_count) / replicated_fetch_entry->total_size_bytes_compressed, std::memory_order_relaxed); } } }; } Service::Service(StorageReplicatedMergeTree & data_) : data(data_), log(&Poco::Logger::get(data.getLogName() + " (Replicated PartsService)")) {} std::string Service::getId(const std::string & node_id) const { return getEndpointId(node_id); } void Service::processQuery(const HTMLForm & params, ReadBuffer & /*body*/, WriteBuffer & out, HTTPServerResponse & response) { int client_protocol_version = parse<int>(params.get("client_protocol_version", "0")); String part_name = params.get("part"); const auto data_settings = data.getSettings(); /// Validation of the input that may come from malicious replica. MergeTreePartInfo::fromPartName(part_name, data.format_version); static std::atomic_uint total_sends {0}; if ((data_settings->replicated_max_parallel_sends && total_sends >= data_settings->replicated_max_parallel_sends) || (data_settings->replicated_max_parallel_sends_for_table && data.current_table_sends >= data_settings->replicated_max_parallel_sends_for_table)) { response.setStatus(std::to_string(HTTP_TOO_MANY_REQUESTS)); response.setReason("Too many concurrent fetches, try again later"); response.set("Retry-After", "10"); response.setChunkedTransferEncoding(false); return; } /// We pretend to work as older server version, to be sure that client will correctly process our version response.addCookie({"server_protocol_version", toString(std::min(client_protocol_version, REPLICATION_PROTOCOL_VERSION_WITH_PARTS_PROJECTION))}); ++total_sends; SCOPE_EXIT({--total_sends;}); ++data.current_table_sends; SCOPE_EXIT({--data.current_table_sends;}); LOG_TRACE(log, "Sending part {}", part_name); MergeTreeData::DataPartPtr part; auto report_broken_part = [&]() { if (part && part->isProjectionPart()) { data.reportBrokenPart(part->getParentPart()->name); } else { data.reportBrokenPart(part_name); } }; try { part = findPart(part_name); CurrentMetrics::Increment metric_increment{CurrentMetrics::ReplicatedSend}; if (client_protocol_version >= REPLICATION_PROTOCOL_VERSION_WITH_PARTS_SIZE) writeBinary(part->checksums.getTotalSizeOnDisk(), out); if (client_protocol_version >= REPLICATION_PROTOCOL_VERSION_WITH_PARTS_SIZE_AND_TTL_INFOS) { WriteBufferFromOwnString ttl_infos_buffer; part->ttl_infos.write(ttl_infos_buffer); writeBinary(ttl_infos_buffer.str(), out); } if (client_protocol_version >= REPLICATION_PROTOCOL_VERSION_WITH_PARTS_TYPE) writeStringBinary(part->getType().toString(), out); if (client_protocol_version >= REPLICATION_PROTOCOL_VERSION_WITH_PARTS_UUID) writeUUIDText(part->uuid, out); bool try_use_s3_copy = false; if (data_settings->allow_s3_zero_copy_replication && client_protocol_version >= REPLICATION_PROTOCOL_VERSION_WITH_PARTS_S3_COPY) { /// if source and destination are in the same S3 storage we try to use S3 CopyObject request first int send_s3_metadata = parse<int>(params.get("send_s3_metadata", "0")); if (send_s3_metadata == 1) { auto disk = part->volume->getDisk(); if (disk->getType() == DB::DiskType::Type::S3) { try_use_s3_copy = true; } } } if (try_use_s3_copy) { response.addCookie({"send_s3_metadata", "1"}); sendPartS3Metadata(part, out); } else if (client_protocol_version >= REPLICATION_PROTOCOL_VERSION_WITH_PARTS_PROJECTION) { const auto & projections = part->getProjectionParts(); writeBinary(projections.size(), out); if (isInMemoryPart(part)) sendPartFromMemory(part, out, projections); else sendPartFromDisk(part, out, client_protocol_version, projections); } else { if (isInMemoryPart(part)) sendPartFromMemory(part, out); else sendPartFromDisk(part, out, client_protocol_version); } } catch (const NetException &) { /// Network error or error on remote side. No need to enqueue part for check. throw; } catch (const Exception & e) { if (e.code() != ErrorCodes::ABORTED && e.code() != ErrorCodes::CANNOT_WRITE_TO_OSTREAM) report_broken_part(); throw; } catch (...) { report_broken_part(); throw; } } void Service::sendPartFromMemory( const MergeTreeData::DataPartPtr & part, WriteBuffer & out, const std::map<String, std::shared_ptr<IMergeTreeDataPart>> & projections) { auto metadata_snapshot = data.getInMemoryMetadataPtr(); for (const auto & [name, projection] : projections) { auto projection_sample_block = metadata_snapshot->projections.get(name).sample_block; auto part_in_memory = asInMemoryPart(projection); if (!part_in_memory) throw Exception("Projection " + name + " of part " + part->name + " is not stored in memory", ErrorCodes::LOGICAL_ERROR); writeStringBinary(name, out); projection->checksums.write(out); NativeBlockOutputStream block_out(out, 0, projection_sample_block); block_out.write(part_in_memory->block); } auto part_in_memory = asInMemoryPart(part); if (!part_in_memory) throw Exception("Part " + part->name + " is not stored in memory", ErrorCodes::LOGICAL_ERROR); NativeBlockOutputStream block_out(out, 0, metadata_snapshot->getSampleBlock()); part->checksums.write(out); block_out.write(part_in_memory->block); data.getSendsThrottler()->add(part_in_memory->block.bytes()); } MergeTreeData::DataPart::Checksums Service::sendPartFromDisk( const MergeTreeData::DataPartPtr & part, WriteBuffer & out, int client_protocol_version, const std::map<String, std::shared_ptr<IMergeTreeDataPart>> & projections) { /// We'll take a list of files from the list of checksums. MergeTreeData::DataPart::Checksums checksums = part->checksums; /// Add files that are not in the checksum list. auto file_names_without_checksums = part->getFileNamesWithoutChecksums(); for (const auto & file_name : file_names_without_checksums) { if (client_protocol_version < REPLICATION_PROTOCOL_VERSION_WITH_PARTS_DEFAULT_COMPRESSION && file_name == IMergeTreeDataPart::DEFAULT_COMPRESSION_CODEC_FILE_NAME) continue; checksums.files[file_name] = {}; } auto disk = part->volume->getDisk(); MergeTreeData::DataPart::Checksums data_checksums; for (const auto & [name, projection] : part->getProjectionParts()) { // Get rid of projection files checksums.files.erase(name + ".proj"); auto it = projections.find(name); if (it != projections.end()) { writeStringBinary(name, out); MergeTreeData::DataPart::Checksums projection_checksum = sendPartFromDisk(it->second, out, client_protocol_version); data_checksums.addFile(name + ".proj", projection_checksum.getTotalSizeOnDisk(), projection_checksum.getTotalChecksumUInt128()); } else if (part->checksums.has(name + ".proj")) { // We don't send this projection, just add out checksum to bypass the following check const auto & our_checksum = part->checksums.files.find(name + ".proj")->second; data_checksums.addFile(name + ".proj", our_checksum.file_size, our_checksum.file_hash); } } writeBinary(checksums.files.size(), out); for (const auto & it : checksums.files) { String file_name = it.first; String path = fs::path(part->getFullRelativePath()) / file_name; UInt64 size = disk->getFileSize(path); writeStringBinary(it.first, out); writeBinary(size, out); auto file_in = disk->readFile(path); HashingWriteBuffer hashing_out(out); copyDataWithThrottler(*file_in, hashing_out, blocker.getCounter(), data.getSendsThrottler()); if (blocker.isCancelled()) throw Exception("Transferring part to replica was cancelled", ErrorCodes::ABORTED); if (hashing_out.count() != size) throw Exception("Unexpected size of file " + path, ErrorCodes::BAD_SIZE_OF_FILE_IN_DATA_PART); writePODBinary(hashing_out.getHash(), out); if (!file_names_without_checksums.count(file_name)) data_checksums.addFile(file_name, hashing_out.count(), hashing_out.getHash()); } part->checksums.checkEqual(data_checksums, false); return data_checksums; } void Service::sendPartS3Metadata(const MergeTreeData::DataPartPtr & part, WriteBuffer & out) { /// We'll take a list of files from the list of checksums. MergeTreeData::DataPart::Checksums checksums = part->checksums; /// Add files that are not in the checksum list. auto file_names_without_checksums = part->getFileNamesWithoutChecksums(); for (const auto & file_name : file_names_without_checksums) checksums.files[file_name] = {}; auto disk = part->volume->getDisk(); if (disk->getType() != DB::DiskType::Type::S3) throw Exception("S3 disk is not S3 anymore", ErrorCodes::LOGICAL_ERROR); part->storage.lockSharedData(*part); String part_id = part->getUniqueId(); writeStringBinary(part_id, out); writeBinary(checksums.files.size(), out); for (const auto & it : checksums.files) { String file_name = it.first; String metadata_file = fs::path(disk->getPath()) / part->getFullRelativePath() / file_name; fs::path metadata(metadata_file); if (!fs::exists(metadata)) throw Exception("S3 metadata '" + file_name + "' is not exists", ErrorCodes::CORRUPTED_DATA); if (!fs::is_regular_file(metadata)) throw Exception("S3 metadata '" + file_name + "' is not a file", ErrorCodes::CORRUPTED_DATA); UInt64 file_size = fs::file_size(metadata); writeStringBinary(it.first, out); writeBinary(file_size, out); auto file_in = createReadBufferFromFileBase(metadata_file, 0, 0, 0, nullptr, DBMS_DEFAULT_BUFFER_SIZE); HashingWriteBuffer hashing_out(out); copyDataWithThrottler(*file_in, hashing_out, blocker.getCounter(), data.getSendsThrottler()); if (blocker.isCancelled()) throw Exception("Transferring part to replica was cancelled", ErrorCodes::ABORTED); if (hashing_out.count() != file_size) throw Exception("Unexpected size of file " + metadata_file, ErrorCodes::BAD_SIZE_OF_FILE_IN_DATA_PART); writePODBinary(hashing_out.getHash(), out); } } MergeTreeData::DataPartPtr Service::findPart(const String & name) { /// It is important to include PreCommitted and Outdated parts here because remote replicas cannot reliably /// determine the local state of the part, so queries for the parts in these states are completely normal. auto part = data.getPartIfExists( name, {MergeTreeDataPartState::PreCommitted, MergeTreeDataPartState::Committed, MergeTreeDataPartState::Outdated}); if (part) return part; throw Exception("No part " + name + " in table", ErrorCodes::NO_SUCH_DATA_PART); } MergeTreeData::MutableDataPartPtr Fetcher::fetchPart( const StorageMetadataPtr & metadata_snapshot, ContextPtr context, const String & part_name, const String & replica_path, const String & host, int port, const ConnectionTimeouts & timeouts, const String & user, const String & password, const String & interserver_scheme, ThrottlerPtr throttler, bool to_detached, const String & tmp_prefix_, std::optional<CurrentlySubmergingEmergingTagger> * tagger_ptr, bool try_use_s3_copy, const DiskPtr disk_s3) { if (blocker.isCancelled()) throw Exception("Fetching of part was cancelled", ErrorCodes::ABORTED); /// Validation of the input that may come from malicious replica. auto part_info = MergeTreePartInfo::fromPartName(part_name, data.format_version); const auto data_settings = data.getSettings(); Poco::URI uri; uri.setScheme(interserver_scheme); uri.setHost(host); uri.setPort(port); uri.setQueryParameters( { {"endpoint", getEndpointId(replica_path)}, {"part", part_name}, {"client_protocol_version", toString(REPLICATION_PROTOCOL_VERSION_WITH_PARTS_PROJECTION)}, {"compress", "false"} }); if (try_use_s3_copy && disk_s3 && disk_s3->getType() != DB::DiskType::Type::S3) throw Exception("Try to fetch shared s3 part on non-s3 disk", ErrorCodes::LOGICAL_ERROR); Disks disks_s3; if (!data_settings->allow_s3_zero_copy_replication) try_use_s3_copy = false; if (try_use_s3_copy) { if (disk_s3) disks_s3.push_back(disk_s3); else { disks_s3 = data.getDisksByType(DiskType::Type::S3); if (disks_s3.empty()) try_use_s3_copy = false; } } if (try_use_s3_copy) { uri.addQueryParameter("send_s3_metadata", "1"); } Poco::Net::HTTPBasicCredentials creds{}; if (!user.empty()) { creds.setUsername(user); creds.setPassword(password); } PooledReadWriteBufferFromHTTP in{ uri, Poco::Net::HTTPRequest::HTTP_POST, {}, timeouts, creds, DBMS_DEFAULT_BUFFER_SIZE, 0, /* no redirects */ data_settings->replicated_max_parallel_fetches_for_host }; int server_protocol_version = parse<int>(in.getResponseCookie("server_protocol_version", "0")); int send_s3 = parse<int>(in.getResponseCookie("send_s3_metadata", "0")); if (send_s3 == 1) { if (server_protocol_version < REPLICATION_PROTOCOL_VERSION_WITH_PARTS_S3_COPY) throw Exception("Got 'send_s3_metadata' cookie with old protocol version", ErrorCodes::LOGICAL_ERROR); if (!try_use_s3_copy) throw Exception("Got 'send_s3_metadata' cookie when was not requested", ErrorCodes::LOGICAL_ERROR); size_t sum_files_size = 0; readBinary(sum_files_size, in); IMergeTreeDataPart::TTLInfos ttl_infos; String ttl_infos_string; readBinary(ttl_infos_string, in); ReadBufferFromString ttl_infos_buffer(ttl_infos_string); assertString("ttl format version: 1\n", ttl_infos_buffer); ttl_infos.read(ttl_infos_buffer); ReservationPtr reservation = data.balancedReservation(metadata_snapshot, sum_files_size, 0, part_name, part_info, {}, tagger_ptr, &ttl_infos, true); if (!reservation) reservation = data.reserveSpacePreferringTTLRules(metadata_snapshot, sum_files_size, ttl_infos, std::time(nullptr), 0, true); if (reservation) { /// When we have multi-volume storage, one of them was chosen, depends on TTL, free space, etc. /// Chosen one may be S3 or not. DiskPtr disk = reservation->getDisk(); if (disk && disk->getType() == DiskType::Type::S3) { for (const auto & d : disks_s3) { if (d->getPath() == disk->getPath()) { Disks disks_tmp = { disk }; disks_s3.swap(disks_tmp); break; } } } } String part_type = "Wide"; readStringBinary(part_type, in); if (part_type == "InMemory") throw Exception("Got 'send_s3_metadata' cookie for in-memory part", ErrorCodes::INCORRECT_PART_TYPE); UUID part_uuid = UUIDHelpers::Nil; /// Always true due to values of constants. But we keep this condition just in case. if (server_protocol_version >= REPLICATION_PROTOCOL_VERSION_WITH_PARTS_UUID) //-V547 readUUIDText(part_uuid, in); try { return downloadPartToS3(part_name, replica_path, to_detached, tmp_prefix_, std::move(disks_s3), in, throttler); } catch (const Exception & e) { if (e.code() != ErrorCodes::S3_ERROR) throw; /// Try again but without S3 copy return fetchPart(metadata_snapshot, context, part_name, replica_path, host, port, timeouts, user, password, interserver_scheme, throttler, to_detached, tmp_prefix_, nullptr, false); } } ReservationPtr reservation; size_t sum_files_size = 0; if (server_protocol_version >= REPLICATION_PROTOCOL_VERSION_WITH_PARTS_SIZE) { readBinary(sum_files_size, in); if (server_protocol_version >= REPLICATION_PROTOCOL_VERSION_WITH_PARTS_SIZE_AND_TTL_INFOS) { IMergeTreeDataPart::TTLInfos ttl_infos; String ttl_infos_string; readBinary(ttl_infos_string, in); ReadBufferFromString ttl_infos_buffer(ttl_infos_string); assertString("ttl format version: 1\n", ttl_infos_buffer); ttl_infos.read(ttl_infos_buffer); reservation = data.balancedReservation(metadata_snapshot, sum_files_size, 0, part_name, part_info, {}, tagger_ptr, &ttl_infos, true); if (!reservation) reservation = data.reserveSpacePreferringTTLRules(metadata_snapshot, sum_files_size, ttl_infos, std::time(nullptr), 0, true); } else { reservation = data.balancedReservation(metadata_snapshot, sum_files_size, 0, part_name, part_info, {}, tagger_ptr, nullptr); if (!reservation) reservation = data.reserveSpace(sum_files_size); } } else { /// We don't know real size of part because sender server version is too old reservation = data.makeEmptyReservationOnLargestDisk(); } bool sync = (data_settings->min_compressed_bytes_to_fsync_after_fetch && sum_files_size >= data_settings->min_compressed_bytes_to_fsync_after_fetch); String part_type = "Wide"; if (server_protocol_version >= REPLICATION_PROTOCOL_VERSION_WITH_PARTS_TYPE) readStringBinary(part_type, in); UUID part_uuid = UUIDHelpers::Nil; if (server_protocol_version >= REPLICATION_PROTOCOL_VERSION_WITH_PARTS_UUID) readUUIDText(part_uuid, in); auto storage_id = data.getStorageID(); String new_part_path = part_type == "InMemory" ? "memory" : fs::path(data.getFullPathOnDisk(reservation->getDisk())) / part_name / ""; auto entry = data.getContext()->getReplicatedFetchList().insert( storage_id.getDatabaseName(), storage_id.getTableName(), part_info.partition_id, part_name, new_part_path, replica_path, uri, to_detached, sum_files_size); in.setNextCallback(ReplicatedFetchReadCallback(*entry)); size_t projections = 0; if (server_protocol_version >= REPLICATION_PROTOCOL_VERSION_WITH_PARTS_PROJECTION) readBinary(projections, in); MergeTreeData::DataPart::Checksums checksums; return part_type == "InMemory" ? downloadPartToMemory(part_name, part_uuid, metadata_snapshot, context, std::move(reservation), in, projections, throttler) : downloadPartToDisk(part_name, replica_path, to_detached, tmp_prefix_, sync, reservation->getDisk(), in, projections, checksums, throttler); } MergeTreeData::MutableDataPartPtr Fetcher::downloadPartToMemory( const String & part_name, const UUID & part_uuid, const StorageMetadataPtr & metadata_snapshot, ContextPtr context, ReservationPtr reservation, PooledReadWriteBufferFromHTTP & in, size_t projections, ThrottlerPtr throttler) { auto volume = std::make_shared<SingleDiskVolume>("volume_" + part_name, reservation->getDisk(), 0); MergeTreeData::MutableDataPartPtr new_data_part = std::make_shared<MergeTreeDataPartInMemory>(data, part_name, volume); for (auto i = 0ul; i < projections; ++i) { String projection_name; readStringBinary(projection_name, in); MergeTreeData::DataPart::Checksums checksums; if (!checksums.read(in)) throw Exception("Cannot deserialize checksums", ErrorCodes::CORRUPTED_DATA); NativeBlockInputStream block_in(in, 0); auto block = block_in.read(); throttler->add(block.bytes()); MergeTreePartInfo new_part_info("all", 0, 0, 0); MergeTreeData::MutableDataPartPtr new_projection_part = std::make_shared<MergeTreeDataPartInMemory>(data, projection_name, new_part_info, volume, projection_name, new_data_part.get()); new_projection_part->is_temp = false; new_projection_part->setColumns(block.getNamesAndTypesList()); MergeTreePartition partition{}; IMergeTreeDataPart::MinMaxIndex minmax_idx{}; new_projection_part->partition = std::move(partition); new_projection_part->minmax_idx = std::move(minmax_idx); MergedBlockOutputStream part_out( new_projection_part, metadata_snapshot->projections.get(projection_name).metadata, block.getNamesAndTypesList(), {}, CompressionCodecFactory::instance().get("NONE", {})); part_out.writePrefix(); part_out.write(block); part_out.writeSuffixAndFinalizePart(new_projection_part); new_projection_part->checksums.checkEqual(checksums, /* have_uncompressed = */ true); new_data_part->addProjectionPart(projection_name, std::move(new_projection_part)); } MergeTreeData::DataPart::Checksums checksums; if (!checksums.read(in)) throw Exception("Cannot deserialize checksums", ErrorCodes::CORRUPTED_DATA); NativeBlockInputStream block_in(in, 0); auto block = block_in.read(); throttler->add(block.bytes()); new_data_part->uuid = part_uuid; new_data_part->is_temp = true; new_data_part->setColumns(block.getNamesAndTypesList()); new_data_part->minmax_idx.update(block, data.getMinMaxColumnsNames(metadata_snapshot->getPartitionKey())); new_data_part->partition.create(metadata_snapshot, block, 0, context); MergedBlockOutputStream part_out( new_data_part, metadata_snapshot, block.getNamesAndTypesList(), {}, CompressionCodecFactory::instance().get("NONE", {})); part_out.writePrefix(); part_out.write(block); part_out.writeSuffixAndFinalizePart(new_data_part); new_data_part->checksums.checkEqual(checksums, /* have_uncompressed = */ true); return new_data_part; } void Fetcher::downloadBaseOrProjectionPartToDisk( const String & replica_path, const String & part_download_path, bool sync, DiskPtr disk, PooledReadWriteBufferFromHTTP & in, MergeTreeData::DataPart::Checksums & checksums, ThrottlerPtr throttler) const { size_t files; readBinary(files, in); for (size_t i = 0; i < files; ++i) { String file_name; UInt64 file_size; readStringBinary(file_name, in); readBinary(file_size, in); /// File must be inside "absolute_part_path" directory. /// Otherwise malicious ClickHouse replica may force us to write to arbitrary path. String absolute_file_path = fs::weakly_canonical(fs::path(part_download_path) / file_name); if (!startsWith(absolute_file_path, fs::weakly_canonical(part_download_path).string())) throw Exception("File path (" + absolute_file_path + ") doesn't appear to be inside part path (" + part_download_path + ")." " This may happen if we are trying to download part from malicious replica or logical error.", ErrorCodes::INSECURE_PATH); auto file_out = disk->writeFile(fs::path(part_download_path) / file_name); HashingWriteBuffer hashing_out(*file_out); copyDataWithThrottler(in, hashing_out, file_size, blocker.getCounter(), throttler); if (blocker.isCancelled()) { /// NOTE The is_cancelled flag also makes sense to check every time you read over the network, /// performing a poll with a not very large timeout. /// And now we check it only between read chunks (in the `copyData` function). disk->removeRecursive(part_download_path); throw Exception("Fetching of part was cancelled", ErrorCodes::ABORTED); } MergeTreeDataPartChecksum::uint128 expected_hash; readPODBinary(expected_hash, in); if (expected_hash != hashing_out.getHash()) throw Exception("Checksum mismatch for file " + fullPath(disk, (fs::path(part_download_path) / file_name).string()) + " transferred from " + replica_path, ErrorCodes::CHECKSUM_DOESNT_MATCH); if (file_name != "checksums.txt" && file_name != "columns.txt" && file_name != IMergeTreeDataPart::DEFAULT_COMPRESSION_CODEC_FILE_NAME) checksums.addFile(file_name, file_size, expected_hash); if (sync) hashing_out.sync(); } } MergeTreeData::MutableDataPartPtr Fetcher::downloadPartToDisk( const String & part_name, const String & replica_path, bool to_detached, const String & tmp_prefix_, bool sync, DiskPtr disk, PooledReadWriteBufferFromHTTP & in, size_t projections, MergeTreeData::DataPart::Checksums & checksums, ThrottlerPtr throttler) { static const String TMP_PREFIX = "tmp_fetch_"; String tmp_prefix = tmp_prefix_.empty() ? TMP_PREFIX : tmp_prefix_; /// We will remove directory if it's already exists. Make precautions. if (tmp_prefix.empty() //-V560 || part_name.empty() || std::string::npos != tmp_prefix.find_first_of("/.") || std::string::npos != part_name.find_first_of("/.")) throw Exception("Logical error: tmp_prefix and part_name cannot be empty or contain '.' or '/' characters.", ErrorCodes::LOGICAL_ERROR); String part_relative_path = String(to_detached ? "detached/" : "") + tmp_prefix + part_name; String part_download_path = data.getRelativeDataPath() + part_relative_path + "/"; if (disk->exists(part_download_path)) { LOG_WARNING(log, "Directory {} already exists, probably result of a failed fetch. Will remove it before fetching part.", fullPath(disk, part_download_path)); disk->removeRecursive(part_download_path); } disk->createDirectories(part_download_path); SyncGuardPtr sync_guard; if (data.getSettings()->fsync_part_directory) sync_guard = disk->getDirectorySyncGuard(part_download_path); CurrentMetrics::Increment metric_increment{CurrentMetrics::ReplicatedFetch}; for (auto i = 0ul; i < projections; ++i) { String projection_name; readStringBinary(projection_name, in); MergeTreeData::DataPart::Checksums projection_checksum; disk->createDirectories(part_download_path + projection_name + ".proj/"); downloadBaseOrProjectionPartToDisk( replica_path, part_download_path + projection_name + ".proj/", sync, disk, in, projection_checksum, throttler); checksums.addFile( projection_name + ".proj", projection_checksum.getTotalSizeOnDisk(), projection_checksum.getTotalChecksumUInt128()); } // Download the base part downloadBaseOrProjectionPartToDisk(replica_path, part_download_path, sync, disk, in, checksums, throttler); assertEOF(in); auto volume = std::make_shared<SingleDiskVolume>("volume_" + part_name, disk, 0); MergeTreeData::MutableDataPartPtr new_data_part = data.createPart(part_name, volume, part_relative_path); new_data_part->is_temp = true; new_data_part->modification_time = time(nullptr); new_data_part->loadColumnsChecksumsIndexes(true, false); new_data_part->checksums.checkEqual(checksums, false); return new_data_part; } MergeTreeData::MutableDataPartPtr Fetcher::downloadPartToS3( const String & part_name, const String & replica_path, bool to_detached, const String & tmp_prefix_, const Disks & disks_s3, PooledReadWriteBufferFromHTTP & in, ThrottlerPtr throttler) { if (disks_s3.empty()) throw Exception("No S3 disks anymore", ErrorCodes::LOGICAL_ERROR); String part_id; readStringBinary(part_id, in); DiskPtr disk = disks_s3[0]; for (const auto & disk_s3 : disks_s3) { if (disk_s3->checkUniqueId(part_id)) { disk = disk_s3; break; } } static const String TMP_PREFIX = "tmp_fetch_"; String tmp_prefix = tmp_prefix_.empty() ? TMP_PREFIX : tmp_prefix_; String part_relative_path = String(to_detached ? "detached/" : "") + tmp_prefix + part_name; String part_download_path = fs::path(data.getRelativeDataPath()) / part_relative_path / ""; if (disk->exists(part_download_path)) throw Exception("Directory " + fullPath(disk, part_download_path) + " already exists.", ErrorCodes::DIRECTORY_ALREADY_EXISTS); CurrentMetrics::Increment metric_increment{CurrentMetrics::ReplicatedFetch}; disk->createDirectories(part_download_path); size_t files; readBinary(files, in); auto volume = std::make_shared<SingleDiskVolume>("volume_" + part_name, disk); for (size_t i = 0; i < files; ++i) { String file_name; UInt64 file_size; readStringBinary(file_name, in); readBinary(file_size, in); String data_path = fs::path(part_download_path) / file_name; String metadata_file = fullPath(disk, data_path); { auto file_out = std::make_unique<WriteBufferFromFile>(metadata_file, DBMS_DEFAULT_BUFFER_SIZE, -1, 0666, nullptr, 0); HashingWriteBuffer hashing_out(*file_out); copyDataWithThrottler(in, hashing_out, file_size, blocker.getCounter(), throttler); if (blocker.isCancelled()) { /// NOTE The is_cancelled flag also makes sense to check every time you read over the network, /// performing a poll with a not very large timeout. /// And now we check it only between read chunks (in the `copyData` function). disk->removeSharedRecursive(part_download_path, true); throw Exception("Fetching of part was cancelled", ErrorCodes::ABORTED); } MergeTreeDataPartChecksum::uint128 expected_hash; readPODBinary(expected_hash, in); if (expected_hash != hashing_out.getHash()) { throw Exception("Checksum mismatch for file " + metadata_file + " transferred from " + replica_path, ErrorCodes::CHECKSUM_DOESNT_MATCH); } } } assertEOF(in); MergeTreeData::MutableDataPartPtr new_data_part = data.createPart(part_name, volume, part_relative_path); new_data_part->is_temp = true; new_data_part->modification_time = time(nullptr); new_data_part->loadColumnsChecksumsIndexes(true, false); new_data_part->storage.lockSharedData(*new_data_part); return new_data_part; } } }
#include "panelwidget.h" #include "qscrollarea.h" #include "qframe.h" #include "qboxlayout.h" PanelWidget::PanelWidget(QWidget *parent) : QWidget(parent) { scrollArea = new QScrollArea(this); scrollArea->setObjectName("scrollAreaMain"); scrollArea->setWidgetResizable(true); scrollAreaWidgetContents = new QWidget(); scrollAreaWidgetContents->setGeometry(QRect(0, 0, 100, 100)); verticalLayout = new QVBoxLayout(scrollAreaWidgetContents); verticalLayout->setSpacing(0); verticalLayout->setContentsMargins(0, 0, 0, 0); frame = new QFrame(scrollAreaWidgetContents); frame->setObjectName("frameMain"); gridLayout = new QGridLayout(frame); gridLayout->setSpacing(0); verticalLayout->addWidget(frame); scrollArea->setWidget(scrollAreaWidgetContents); frame->setStyleSheet("QFrame#frameMain{border-width:0px}"); } void PanelWidget::resizeEvent(QResizeEvent *) { scrollArea->resize(this->size()); } QSize PanelWidget::sizeHint() const { return QSize(300, 200); } QSize PanelWidget::minimumSizeHint() const { return QSize(20, 20); } void PanelWidget::setWidget(QList<QWidget *> widgets, int columnCount) { qDeleteAll(frame->findChildren<QWidget *>()); int row = 0; int column = 0; int index = 0; foreach (QWidget *widget, widgets) { gridLayout->addWidget(widget, row, column); column++; index++; if (index % columnCount == 0) { row++; column = 0; } } row++; QSpacerItem *verticalSpacer = new QSpacerItem(1, 1, QSizePolicy::Minimum, QSizePolicy::Expanding); gridLayout->addItem(verticalSpacer, row, 0); } void PanelWidget::setMargin(int left, int top, int right, int bottom) { gridLayout->setContentsMargins(left, top, right, bottom); } void PanelWidget::setMargin(int margin) { setMargin(margin, margin, margin, margin); } void PanelWidget::setSpacing(int space) { gridLayout->setSpacing(space); }
/*! * Copyright (c) 2017 by Contributors * \file loop_partition.cc */ #include <tvm/ir.h> #include <tvm/ir_visitor.h> #include <tvm/ir_mutator.h> #include <tvm/ir_pass.h> #include <tvm/arithmetic.h> #include <unordered_map> #include <unordered_set> #include "../arithmetic/int_set_internal.h" #include "../runtime/thread_storage_scope.h" namespace tvm { namespace ir { using arith::IntSet; using arith::DeduceBound; using arith::Intersect; // a partition means the expr is equal to true in the interval struct Partition { Expr expr; IntSet interval; }; bool ExprUseVars(Expr expr, const std::unordered_set<const Variable*>& vars) { bool success = false; PostOrderVisit(expr, [&vars, &success](const NodeRef& node) { if (const Variable* v = node.as<Variable>()) { if (vars.count(v)) { success = true; return; } } }); return success; } // Select potential candidate IRs that can be partitioned. // Rule: // - the range should not be const // - there exist a condition expression in the scope that use the var class CandidateSelector final : public IRVisitor { public: using VarIsUsed = bool; explicit CandidateSelector(bool split_const_loop) : split_const_loop_(split_const_loop) {} void Visit_(const For* op) { // partition const loop when sets split_const_loop_ if (!is_const(op->min) || !is_const(op->extent) || split_const_loop_) { const Variable* var = op->loop_var.get(); record_.insert({var, false}); IRVisitor::Visit_(op); if (record_.at(var) && !no_split_) { candidates.insert(op); } record_.erase(var); } else { IRVisitor::Visit_(op); } } void Visit_(const AttrStmt* op) { if (op->attr_key == attr::thread_extent) { const IterVarNode *iv = op->node.as<IterVarNode>(); CHECK(iv); Var var = iv->var; runtime::ThreadScope scope = runtime::ThreadScope::make(iv->thread_tag); if ((scope.rank == 0) && (!is_const(op->value) || split_const_loop_)) { record_.insert({var.get(), false}); IRVisitor::Visit_(op); if (record_.at(var.get()) && !no_split_) { candidates.insert(op); } record_.erase(var.get()); return; } } IRVisitor::Visit_(op); } void Visit_(const Block* op) { bool temp = no_split_; this->Visit(op->first); // erase the no split state of first when visit rest. std::swap(temp, no_split_); this->Visit(op->rest); // restore the no split flag. no_split_ = no_split_ || temp; } void Visit_(const Call* op) { if (op->is_intrinsic(Call::likely)) { in_likely_ = true; IRVisitor::Visit_(op); in_likely_ = false; } else if (op->is_intrinsic(intrinsic::tvm_thread_allreduce)) { // no split if the body contains allreduce. no_split_ = true; return; } else { IRVisitor::Visit_(op); } } void Visit_(const Variable* op) { if (in_likely_ && record_.count(op)) { record_.at(op) = true; } } std::unordered_set<const Node*> candidates; private: bool in_likely_{false}; bool no_split_{false}; bool split_const_loop_{false}; std::unordered_map<const Variable*, VarIsUsed> record_; }; // Find valid partition for specific variable class PartitionFinder : public IRVisitor { public: explicit PartitionFinder(VarExpr current_var, const std::unordered_map<const Variable*, IntSet>& hint_map, const std::unordered_map<const Variable*, IntSet>& relax_map) : current_var_(current_var), hint_map_(hint_map), relax_map_(relax_map) { for (const auto& kv : hint_map) { out_vars_.insert(kv.first); } for (const auto& kv : relax_map) { out_vars_.insert(kv.first); } } void Visit_(const For* op) { if (ExprUseVars(op->min, out_vars_) || ExprUseVars(op->extent, out_vars_)) return; const Variable* var = op->loop_var.get(); hint_map_.insert({var, IntSet::interval(op->min, op->min + op->extent - 1)}); relax_map_.insert({var, IntSet::interval(op->min, op->min + op->extent - 1)}); IRVisitor::Visit_(op); relax_map_.erase(var); hint_map_.erase(var); } void Visit_(const AttrStmt* op) { // handle thread_axis if (op->attr_key == attr::thread_extent) { const IterVarNode* thread_axis = op->node.as<IterVarNode>(); CHECK(thread_axis); const Variable* var = thread_axis->var.get(); IntSet dom = IntSet::range(Range(make_zero(op->value.type()), op->value)); hint_map_.insert({var, dom}); relax_map_.insert({var, dom}); IRVisitor::Visit_(op); relax_map_.erase(var); hint_map_.erase(var); } else { IRVisitor::Visit_(op); } } void Visit_(const Call* op) { if (op->is_intrinsic(Call::likely)) { Expr cond = op->args[0]; if (ExprUseVars(cond, std::unordered_set<const Variable*>({current_var_.get()}))) { IntSet interval = DeduceBound(current_var_, cond, hint_map_, relax_map_); if (!interval.is_nothing()) { partitions[cond.get()] = Partition{cond, interval}; } } } else { IRVisitor::Visit_(op); } } std::unordered_map<const Node*, Partition> partitions; private: VarExpr current_var_; std::unordered_set<const Variable*> out_vars_; std::unordered_map<const Variable*, IntSet> hint_map_; std::unordered_map<const Variable*, IntSet> relax_map_; }; // Eliminate the condition expressions by partitions class ConditionEliminator : public IRMutator { public: explicit ConditionEliminator(const std::unordered_map<const Node*, Partition>& ps) : ps_(ps) {} using IRMutator::Mutate; Expr Mutate(Expr e) final { if (ps_.count(e.get())) return Mutate(const_true()); return IRMutator::Mutate(e); } private: const std::unordered_map<const Node*, Partition>& ps_; }; // Insert the partition branch at the innermost thread scope class ThreadPartitionInserter : public IRMutator { public: explicit ThreadPartitionInserter(const std::unordered_map<const Node*, Partition>& ps, Expr cond) : ps_(ps), cond_(cond), innermost_thread_scope_(false) {} Stmt Mutate_(const AttrStmt* op, const Stmt& s) final { if (op->attr_key == attr::thread_extent) { innermost_thread_scope_ = true; Stmt stmt = IRMutator::Mutate_(op, s); // add branch code inside the innermost thread scope if (innermost_thread_scope_) { Stmt simplified_body = ConditionEliminator(ps_).Mutate(op->body); Stmt body = IfThenElse::make(cond_, simplified_body, op->body); Expr value = this->Mutate(op->value); stmt = AttrStmt::make(op->node, op->attr_key, value, body); } innermost_thread_scope_ = false; return stmt; } else { return IRMutator::Mutate_(op, s); } } private: const std::unordered_map<const Node*, Partition>& ps_; Expr cond_; bool innermost_thread_scope_; }; // Try to do partition at the candidate IRs class LoopPartitioner : public IRMutator { public: explicit LoopPartitioner(std::unordered_set<const Node*> candidates) : candidates_(candidates) {} Stmt Mutate_(const For* op, const Stmt& stmt) { if (candidates_.count(op)) { Stmt s = TryPartition(op, stmt, op->loop_var, op->min, op->min + op->extent - 1, op->body, false); if (s.defined()) return s; } // normal path when loop parittion fails // normal loop variable can be put into hint map. hint_map_.insert({op->loop_var.get(), IntSet::interval(op->min, op->min + op->extent - 1)}); Stmt res = IRMutator::Mutate_(op, stmt); hint_map_.erase(op->loop_var.get()); return res; } Stmt Mutate_(const AttrStmt* op, const Stmt& stmt) { if (op->attr_key != attr::thread_extent) { return IRMutator::Mutate_(op, stmt); } const IterVarNode *iv = op->node.as<IterVarNode>(); CHECK(iv); Var var = iv->var; if (candidates_.count(op)) { Stmt s = TryPartition(op, stmt, var, 0, op->value - 1, op->body, true); if (s.defined()) return s; } // normal path when loop parittion fails. runtime::ThreadScope scope = runtime::ThreadScope::make(iv->thread_tag); Stmt res; if (scope.rank == 1) { // threadIdx should be put into relax map, in case of divergence. relax_map_.insert({var.get(), IntSet::interval(make_zero(var.type()), op->value - 1)}); res = IRMutator::Mutate_(op, stmt); relax_map_.erase(var.get()); } else { hint_map_.insert({var.get(), IntSet::interval(make_zero(var.type()), op->value - 1)}); res = IRMutator::Mutate_(op, stmt); hint_map_.erase(var.get()); } return res; } private: Stmt TryPartition(const Node* op, const Stmt& stmt, VarExpr var, Expr min, Expr max, Stmt body, bool partition_thread_scope); inline Stmt MakeFor(const Node* op, Expr extent, Stmt body); /* Candidate IRs that may be partitioned potentially */ std::unordered_set<const Node*> candidates_; std::unordered_map<const Variable*, IntSet> hint_map_; std::unordered_map<const Variable*, IntSet> relax_map_; }; Stmt LoopPartitioner::TryPartition(const Node* node, const Stmt& stmt, VarExpr var, Expr min, Expr max, Stmt body, bool partition_thread_scope) { PartitionFinder finder(var, hint_map_, relax_map_); finder.Visit(body); const auto& partitions = finder.partitions; if (partitions.empty()) return Stmt(); Array<IntSet> sets; // merge partitions (take their intersect) for (const auto& kv : partitions) { sets.push_back(kv.second.interval); } IntSet true_itrv = Intersect(sets); Expr body_begin; Stmt pre_stmt; if (true_itrv.as<arith::IntervalSet>()->i.has_lower_bound()) { body_begin = true_itrv.min(); if (!can_prove(body_begin == min)) { Expr cond = (body_begin - min >= 0); if (!can_prove(cond)) { LOG(WARNING) << "Cannot prove: " << cond << ", when generating the pre doubt loop"; body_begin = Max::make(body_begin, min); } // [min, body_begin) if (!partition_thread_scope) { Stmt pre_body = Substitute(body, {{Var{var}, var + min}}); pre_stmt = MakeFor(node, body_begin - min, pre_body); } } } else { body_begin = min; } Expr post_doubt_begin; Stmt post_stmt; if (true_itrv.as<arith::IntervalSet>()->i.has_upper_bound()) { post_doubt_begin = true_itrv.max() + 1; if (!can_prove(true_itrv.max() == max)) { Expr cond = (max - post_doubt_begin >= 0); if (!can_prove(cond)) { LOG(WARNING) << "Cannot prove: " << cond << ", when generating the post doubt loop"; post_doubt_begin = Min::make(post_doubt_begin, max); } // [post_doubt_begin, max] if (!partition_thread_scope) { Stmt post_body = Substitute(body, {{Var{var}, var + post_doubt_begin}}); post_stmt = MakeFor(node, max - post_doubt_begin + 1, post_body); } } } else { post_doubt_begin = max + 1; } Stmt s; if (!partition_thread_scope) { // [body_begin, post_doubt_begin) Stmt simplified_body = ConditionEliminator(partitions).Mutate(body); Stmt new_body = Substitute(simplified_body, {{Var{var}, var + body_begin}}); s = MakeFor(node, post_doubt_begin - body_begin, new_body); if (pre_stmt.defined()) s = Block::make(pre_stmt, s); if (post_stmt.defined()) s = Block::make(s, post_stmt); } else { Expr cond = const_true(); if (!can_prove(body_begin == min)) cond = cond && (var >= body_begin); if (!can_prove(post_doubt_begin == (max + 1))) cond = cond && (var < post_doubt_begin); s = ThreadPartitionInserter(partitions, cond).Mutate(stmt); } s = ConvertSSA(s); return s; } inline Stmt LoopPartitioner::MakeFor(const Node *node, Expr extent, Stmt body) { const For *for_node = static_cast<const For*>(node); CHECK(for_node); return For::make(for_node->loop_var, 0, extent, for_node->for_type, for_node->device_api, body); } class RemoveLikelyTags : public IRMutator { public: using IRMutator::Mutate; Expr Mutate_(const Call *op, const Expr& e) { if (op->is_intrinsic(Call::likely)) { CHECK_EQ(op->args.size(), 1); return IRMutator::Mutate(op->args[0]); } else { return IRMutator::Mutate_(op, e); } } }; Stmt LoopPartition(Stmt stmt, bool split_const_loop) { CandidateSelector selector(split_const_loop); selector.Visit(stmt); stmt = LoopPartitioner(selector.candidates).Mutate(stmt); stmt = RemoveLikelyTags().Mutate(stmt); return stmt; } } // namespace ir } // namespace tvm
/* Copyright 2020 Adobe. All rights reserved. This file is licensed 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 REPRESENTATIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ #include "xml/XMLParser.h" #include <libxml/tree.h> #include <libxml/parser.h> namespace SVGNative { namespace xml { class LibXMLNode final : public XMLNode { public: LibXMLNode(xmlNode* node) : mNode{node} {} const char* GetName() const override { if (!mNode) return nullptr; return (const char*)(mNode->name); } const char* GetValue() const override { if (!mNode) return nullptr; return (const char*)(mNode->content); } std::unique_ptr<XMLNode> GetFirstNode() override { if (!mNode) return nullptr; auto children = mNode->children; while (children && children->type != XML_ELEMENT_NODE) children = children->next; if (children) { auto newNode = new LibXMLNode{children}; return std::unique_ptr<XMLNode>(newNode); } return nullptr; } std::unique_ptr<XMLNode> GetNextSibling() override { if (!mNode) return nullptr; auto nextSibling = mNode->next; while (nextSibling && nextSibling->type != XML_ELEMENT_NODE) nextSibling = nextSibling->next; if (nextSibling) { auto newNode = new LibXMLNode{nextSibling}; return std::unique_ptr<XMLNode>(newNode); } return nullptr; } Attribute GetAttribute(const char* attrName, const char*) const override { if (!mNode) return {false, nullptr}; auto attr = xmlHasProp(mNode, (const xmlChar*)attrName); if (attr) return {true, (const char*)xmlGetProp(mNode, (const xmlChar*)(attrName))}; return {false, nullptr}; } private: xmlNode* mNode{}; }; class LibXMLDocument final : public XMLDocument { public: static std::unique_ptr<XMLDocument> CreateXMLDocument(const char* documentString) { auto newDocument = new LibXMLDocument(documentString); return std::unique_ptr<XMLDocument>(newDocument); } LibXMLDocument(const char* documentString) { mDocument = xmlReadDoc((const xmlChar*)documentString, nullptr, nullptr, XML_PARSE_RECOVER); } ~LibXMLDocument() { xmlFreeDoc(mDocument); xmlCleanupParser(); } std::unique_ptr<XMLNode> GetFirstNode() override { if (!mDocument) return nullptr; if (auto firstNode = xmlDocGetRootElement(mDocument)) { auto newNode = new LibXMLNode{firstNode}; return std::unique_ptr<XMLNode>(newNode); } return nullptr; } private: xmlDocPtr mDocument{}; }; std::unique_ptr<XMLDocument> XMLDocument::CreateXMLDocument(const char* documentString) { return LibXMLDocument::CreateXMLDocument(documentString); } } // namespace xml } // namespace SVGNative
//===-- lib/Semantics/resolve-labels.cpp ----------------------------------===// // // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // //===----------------------------------------------------------------------===// #include "resolve-labels.h" #include "flang/Common/enum-set.h" #include "flang/Common/template.h" #include "flang/Parser/parse-tree-visitor.h" #include "flang/Semantics/semantics.h" #include <cctype> #include <cstdarg> #include <type_traits> namespace Fortran::semantics { using namespace parser::literals; ENUM_CLASS( TargetStatementEnum, Do, Branch, Format, CompatibleDo, CompatibleBranch) using LabeledStmtClassificationSet = common::EnumSet<TargetStatementEnum, TargetStatementEnum_enumSize>; using IndexList = std::vector<std::pair<parser::CharBlock, parser::CharBlock>>; // A ProxyForScope is an integral proxy for a Fortran scope. This is required // because the parse tree does not actually have the scopes required. using ProxyForScope = unsigned; struct LabeledStatementInfoTuplePOD { ProxyForScope proxyForScope; parser::CharBlock parserCharBlock; LabeledStmtClassificationSet labeledStmtClassificationSet; bool isExecutableConstructEndStmt; }; using TargetStmtMap = std::map<parser::Label, LabeledStatementInfoTuplePOD>; struct SourceStatementInfoTuplePOD { SourceStatementInfoTuplePOD(const parser::Label &parserLabel, const ProxyForScope &proxyForScope, const parser::CharBlock &parserCharBlock) : parserLabel{parserLabel}, proxyForScope{proxyForScope}, parserCharBlock{parserCharBlock} {} parser::Label parserLabel; ProxyForScope proxyForScope; parser::CharBlock parserCharBlock; }; using SourceStmtList = std::vector<SourceStatementInfoTuplePOD>; enum class Legality { never, always, formerly }; bool HasScope(ProxyForScope scope) { return scope != ProxyForScope{0u}; } // F18:R1131 template <typename A> constexpr Legality IsLegalDoTerm(const parser::Statement<A> &) { if (std::is_same_v<A, common::Indirection<parser::EndDoStmt>> || std::is_same_v<A, parser::EndDoStmt>) { return Legality::always; } else if (std::is_same_v<A, parser::EndForallStmt> || std::is_same_v<A, parser::EndWhereStmt>) { // Executable construct end statements are also supported as // an extension but they need special care because the associated // construct create their own scope. return Legality::formerly; } else { return Legality::never; } } constexpr Legality IsLegalDoTerm( const parser::Statement<parser::ActionStmt> &actionStmt) { if (std::holds_alternative<parser::ContinueStmt>(actionStmt.statement.u)) { // See F08:C816 return Legality::always; } else if (!(std::holds_alternative< common::Indirection<parser::ArithmeticIfStmt>>( actionStmt.statement.u) || std::holds_alternative<common::Indirection<parser::CycleStmt>>( actionStmt.statement.u) || std::holds_alternative<common::Indirection<parser::ExitStmt>>( actionStmt.statement.u) || std::holds_alternative<common::Indirection<parser::StopStmt>>( actionStmt.statement.u) || std::holds_alternative<common::Indirection<parser::GotoStmt>>( actionStmt.statement.u) || std::holds_alternative< common::Indirection<parser::ReturnStmt>>( actionStmt.statement.u))) { return Legality::formerly; } else { return Legality::never; } } template <typename A> constexpr bool IsFormat(const parser::Statement<A> &) { return std::is_same_v<A, common::Indirection<parser::FormatStmt>>; } template <typename A> constexpr Legality IsLegalBranchTarget(const parser::Statement<A> &) { if (std::is_same_v<A, parser::ActionStmt> || std::is_same_v<A, parser::AssociateStmt> || std::is_same_v<A, parser::EndAssociateStmt> || std::is_same_v<A, parser::IfThenStmt> || std::is_same_v<A, parser::EndIfStmt> || std::is_same_v<A, parser::SelectCaseStmt> || std::is_same_v<A, parser::EndSelectStmt> || std::is_same_v<A, parser::SelectRankStmt> || std::is_same_v<A, parser::SelectTypeStmt> || std::is_same_v<A, common::Indirection<parser::LabelDoStmt>> || std::is_same_v<A, parser::NonLabelDoStmt> || std::is_same_v<A, parser::EndDoStmt> || std::is_same_v<A, common::Indirection<parser::EndDoStmt>> || std::is_same_v<A, parser::BlockStmt> || std::is_same_v<A, parser::EndBlockStmt> || std::is_same_v<A, parser::CriticalStmt> || std::is_same_v<A, parser::EndCriticalStmt> || std::is_same_v<A, parser::ForallConstructStmt> || std::is_same_v<A, parser::ForallStmt> || std::is_same_v<A, parser::WhereConstructStmt> || std::is_same_v<A, parser::EndFunctionStmt> || std::is_same_v<A, parser::EndMpSubprogramStmt> || std::is_same_v<A, parser::EndProgramStmt> || std::is_same_v<A, parser::EndSubroutineStmt>) { return Legality::always; } else { return Legality::never; } } template <typename A> constexpr LabeledStmtClassificationSet ConstructBranchTargetFlags( const parser::Statement<A> &statement) { LabeledStmtClassificationSet labeledStmtClassificationSet{}; if (IsLegalDoTerm(statement) == Legality::always) { labeledStmtClassificationSet.set(TargetStatementEnum::Do); } else if (IsLegalDoTerm(statement) == Legality::formerly) { labeledStmtClassificationSet.set(TargetStatementEnum::CompatibleDo); } if (IsLegalBranchTarget(statement) == Legality::always) { labeledStmtClassificationSet.set(TargetStatementEnum::Branch); } else if (IsLegalBranchTarget(statement) == Legality::formerly) { labeledStmtClassificationSet.set(TargetStatementEnum::CompatibleBranch); } if (IsFormat(statement)) { labeledStmtClassificationSet.set(TargetStatementEnum::Format); } return labeledStmtClassificationSet; } static unsigned SayLabel(parser::Label label) { return static_cast<unsigned>(label); } struct UnitAnalysis { UnitAnalysis() { scopeModel.push_back(0); } SourceStmtList doStmtSources; SourceStmtList formatStmtSources; SourceStmtList otherStmtSources; SourceStmtList assignStmtSources; TargetStmtMap targetStmts; std::vector<ProxyForScope> scopeModel; }; // Some parse tree record for statements simply wrap construct names; // others include them as tuple components. Given a statement, // return a pointer to its name if it has one. template <typename A> const parser::CharBlock *GetStmtName(const parser::Statement<A> &stmt) { const std::optional<parser::Name> *name{nullptr}; if constexpr (WrapperTrait<A>) { if constexpr (std::is_same_v<decltype(A::v), parser::Name>) { return &stmt.statement.v.source; } else { name = &stmt.statement.v; } } else if constexpr (std::is_same_v<A, parser::SelectRankStmt> || std::is_same_v<A, parser::SelectTypeStmt>) { name = &std::get<0>(stmt.statement.t); } else if constexpr (common::HasMember<parser::Name, decltype(stmt.statement.t)>) { return &std::get<parser::Name>(stmt.statement.t).source; } else { name = &std::get<std::optional<parser::Name>>(stmt.statement.t); } if (name && *name) { return &(*name)->source; } return nullptr; } class ParseTreeAnalyzer { public: ParseTreeAnalyzer(ParseTreeAnalyzer &&that) = default; ParseTreeAnalyzer(SemanticsContext &context) : context_{context} {} template <typename A> constexpr bool Pre(const A &x) { using LabeledProgramUnitStmts = std::tuple<parser::MainProgram, parser::FunctionSubprogram, parser::SubroutineSubprogram, parser::SeparateModuleSubprogram>; if constexpr (common::HasMember<A, LabeledProgramUnitStmts>) { const auto &endStmt{std::get<std::tuple_size_v<decltype(x.t)> - 1>(x.t)}; if (endStmt.label) { // The END statement for a subprogram appears after any internal // subprograms. Visit that statement in advance so that results // are placed in the correct programUnits_ slot. auto targetFlags{ConstructBranchTargetFlags(endStmt)}; AddTargetLabelDefinition( endStmt.label.value(), targetFlags, currentScope_); } } return true; } template <typename A> constexpr void Post(const A &) {} template <typename A> bool Pre(const parser::Statement<A> &statement) { currentPosition_ = statement.source; const auto &label = statement.label; if (!label) { return true; } using LabeledConstructStmts = std::tuple<parser::AssociateStmt, parser::BlockStmt, parser::ChangeTeamStmt, parser::CriticalStmt, parser::IfThenStmt, parser::NonLabelDoStmt, parser::SelectCaseStmt, parser::SelectRankStmt, parser::SelectTypeStmt>; using LabeledConstructEndStmts = std::tuple<parser::EndAssociateStmt, parser::EndBlockStmt, parser::EndChangeTeamStmt, parser::EndCriticalStmt, parser::EndDoStmt, parser::EndForallStmt, parser::EndIfStmt, parser::EndSelectStmt, parser::EndWhereStmt>; using LabeledProgramUnitEndStmts = std::tuple<parser::EndFunctionStmt, parser::EndMpSubprogramStmt, parser::EndProgramStmt, parser::EndSubroutineStmt>; auto targetFlags{ConstructBranchTargetFlags(statement)}; if constexpr (common::HasMember<A, LabeledConstructStmts>) { AddTargetLabelDefinition(label.value(), targetFlags, ParentScope()); } else if constexpr (common::HasMember<A, LabeledConstructEndStmts>) { constexpr bool isExecutableConstructEndStmt{true}; AddTargetLabelDefinition(label.value(), targetFlags, currentScope_, isExecutableConstructEndStmt); } else if constexpr (!common::HasMember<A, LabeledProgramUnitEndStmts>) { // Program unit END statements have already been processed. AddTargetLabelDefinition(label.value(), targetFlags, currentScope_); } return true; } // see 11.1.1 bool Pre(const parser::ProgramUnit &) { return InitializeNewScopeContext(); } bool Pre(const parser::InternalSubprogram &) { return InitializeNewScopeContext(); } bool Pre(const parser::ModuleSubprogram &) { return InitializeNewScopeContext(); } bool Pre(const parser::AssociateConstruct &associateConstruct) { return PushConstructName(associateConstruct); } bool Pre(const parser::BlockConstruct &blockConstruct) { return PushConstructName(blockConstruct); } bool Pre(const parser::ChangeTeamConstruct &changeTeamConstruct) { return PushConstructName(changeTeamConstruct); } bool Pre(const parser::CriticalConstruct &criticalConstruct) { return PushConstructName(criticalConstruct); } bool Pre(const parser::DoConstruct &doConstruct) { return PushConstructName(doConstruct); } bool Pre(const parser::IfConstruct &ifConstruct) { return PushConstructName(ifConstruct); } bool Pre(const parser::IfConstruct::ElseIfBlock &) { return SwitchToNewScope(); } bool Pre(const parser::IfConstruct::ElseBlock &) { return SwitchToNewScope(); } bool Pre(const parser::CaseConstruct &caseConstruct) { return PushConstructName(caseConstruct); } bool Pre(const parser::CaseConstruct::Case &) { return SwitchToNewScope(); } bool Pre(const parser::SelectRankConstruct &selectRankConstruct) { return PushConstructName(selectRankConstruct); } bool Pre(const parser::SelectRankConstruct::RankCase &) { return SwitchToNewScope(); } bool Pre(const parser::SelectTypeConstruct &selectTypeConstruct) { return PushConstructName(selectTypeConstruct); } bool Pre(const parser::SelectTypeConstruct::TypeCase &) { return SwitchToNewScope(); } bool Pre(const parser::WhereConstruct &whereConstruct) { return PushConstructName(whereConstruct); } bool Pre(const parser::ForallConstruct &forallConstruct) { return PushConstructName(forallConstruct); } void Post(const parser::AssociateConstruct &associateConstruct) { PopConstructName(associateConstruct); } void Post(const parser::BlockConstruct &blockConstruct) { PopConstructName(blockConstruct); } void Post(const parser::ChangeTeamConstruct &changeTeamConstruct) { PopConstructName(changeTeamConstruct); } void Post(const parser::CriticalConstruct &criticalConstruct) { PopConstructName(criticalConstruct); } void Post(const parser::DoConstruct &doConstruct) { PopConstructName(doConstruct); } void Post(const parser::IfConstruct &ifConstruct) { PopConstructName(ifConstruct); } void Post(const parser::CaseConstruct &caseConstruct) { PopConstructName(caseConstruct); } void Post(const parser::SelectRankConstruct &selectRankConstruct) { PopConstructName(selectRankConstruct); } void Post(const parser::SelectTypeConstruct &selectTypeConstruct) { PopConstructName(selectTypeConstruct); } void Post(const parser::WhereConstruct &whereConstruct) { PopConstructName(whereConstruct); } void Post(const parser::ForallConstruct &forallConstruct) { PopConstructName(forallConstruct); } // Checks for missing or mismatching names on various constructs (e.g., IF) // and their intermediate or terminal statements that allow optional // construct names(e.g., ELSE). When an optional construct name is present, // the construct as a whole must have a name that matches. template <typename FIRST, typename CONSTRUCT, typename STMT> void CheckOptionalName(const char *constructTag, const CONSTRUCT &a, const parser::Statement<STMT> &stmt) { if (const parser::CharBlock * name{GetStmtName(stmt)}) { const auto &firstStmt{std::get<parser::Statement<FIRST>>(a.t)}; if (const parser::CharBlock * firstName{GetStmtName(firstStmt)}) { if (*firstName != *name) { context_.Say(*name, "%s name mismatch"_err_en_US, constructTag) .Attach(*firstName, "should be"_en_US); } } else { context_.Say(*name, "%s name not allowed"_err_en_US, constructTag) .Attach(firstStmt.source, "in unnamed %s"_en_US, constructTag); } } } // C1414 void Post(const parser::BlockData &blockData) { CheckOptionalName<parser::BlockDataStmt>("BLOCK DATA subprogram", blockData, std::get<parser::Statement<parser::EndBlockDataStmt>>(blockData.t)); } // C1564 void Post(const parser::InterfaceBody::Function &func) { CheckOptionalName<parser::FunctionStmt>("FUNCTION", func, std::get<parser::Statement<parser::EndFunctionStmt>>(func.t)); } // C1564 void Post(const parser::FunctionSubprogram &functionSubprogram) { CheckOptionalName<parser::FunctionStmt>("FUNCTION", functionSubprogram, std::get<parser::Statement<parser::EndFunctionStmt>>( functionSubprogram.t)); } // C1502 void Post(const parser::InterfaceBlock &interfaceBlock) { if (const auto &endGenericSpec{ std::get<parser::Statement<parser::EndInterfaceStmt>>( interfaceBlock.t) .statement.v}) { const auto &interfaceStmt{ std::get<parser::Statement<parser::InterfaceStmt>>(interfaceBlock.t)}; if (std::holds_alternative<parser::Abstract>(interfaceStmt.statement.u)) { context_ .Say(endGenericSpec->source, "END INTERFACE generic name (%s) may not appear for ABSTRACT INTERFACE"_err_en_US, endGenericSpec->source) .Attach( interfaceStmt.source, "corresponding ABSTRACT INTERFACE"_en_US); } else if (const auto &genericSpec{ std::get<std::optional<parser::GenericSpec>>( interfaceStmt.statement.u)}) { bool ok{genericSpec->source == endGenericSpec->source}; if (!ok) { // Accept variant spellings of .LT. &c. const auto *endOp{ std::get_if<parser::DefinedOperator>(&endGenericSpec->u)}; const auto *op{std::get_if<parser::DefinedOperator>(&genericSpec->u)}; if (endOp && op) { const auto *endIntrin{ std::get_if<parser::DefinedOperator::IntrinsicOperator>( &endOp->u)}; const auto *intrin{ std::get_if<parser::DefinedOperator::IntrinsicOperator>( &op->u)}; ok = endIntrin && intrin && *endIntrin == *intrin; } } if (!ok) { context_ .Say(endGenericSpec->source, "END INTERFACE generic name (%s) does not match generic INTERFACE (%s)"_err_en_US, endGenericSpec->source, genericSpec->source) .Attach(genericSpec->source, "corresponding INTERFACE"_en_US); } } else { context_ .Say(endGenericSpec->source, "END INTERFACE generic name (%s) may not appear for non-generic INTERFACE"_err_en_US, endGenericSpec->source) .Attach(interfaceStmt.source, "corresponding INTERFACE"_en_US); } } } // C1402 void Post(const parser::Module &module) { CheckOptionalName<parser::ModuleStmt>("MODULE", module, std::get<parser::Statement<parser::EndModuleStmt>>(module.t)); } // C1569 void Post(const parser::SeparateModuleSubprogram &separateModuleSubprogram) { CheckOptionalName<parser::MpSubprogramStmt>("MODULE PROCEDURE", separateModuleSubprogram, std::get<parser::Statement<parser::EndMpSubprogramStmt>>( separateModuleSubprogram.t)); } // C1401 void Post(const parser::MainProgram &mainProgram) { if (const parser::CharBlock * endName{GetStmtName(std::get<parser::Statement<parser::EndProgramStmt>>( mainProgram.t))}) { if (const auto &program{ std::get<std::optional<parser::Statement<parser::ProgramStmt>>>( mainProgram.t)}) { if (*endName != program->statement.v.source) { context_.Say(*endName, "END PROGRAM name mismatch"_err_en_US) .Attach(program->statement.v.source, "should be"_en_US); } } else { context_.Say(*endName, "END PROGRAM has name without PROGRAM statement"_err_en_US); } } } // C1413 void Post(const parser::Submodule &submodule) { CheckOptionalName<parser::SubmoduleStmt>("SUBMODULE", submodule, std::get<parser::Statement<parser::EndSubmoduleStmt>>(submodule.t)); } // C1567 void Post(const parser::InterfaceBody::Subroutine &sub) { CheckOptionalName<parser::SubroutineStmt>("SUBROUTINE", sub, std::get<parser::Statement<parser::EndSubroutineStmt>>(sub.t)); } // C1567 void Post(const parser::SubroutineSubprogram &subroutineSubprogram) { CheckOptionalName<parser::SubroutineStmt>("SUBROUTINE", subroutineSubprogram, std::get<parser::Statement<parser::EndSubroutineStmt>>( subroutineSubprogram.t)); } // C739 void Post(const parser::DerivedTypeDef &derivedTypeDef) { CheckOptionalName<parser::DerivedTypeStmt>("derived type definition", derivedTypeDef, std::get<parser::Statement<parser::EndTypeStmt>>(derivedTypeDef.t)); } void Post(const parser::LabelDoStmt &labelDoStmt) { AddLabelReferenceFromDoStmt(std::get<parser::Label>(labelDoStmt.t)); } void Post(const parser::GotoStmt &gotoStmt) { AddLabelReference(gotoStmt.v); } void Post(const parser::ComputedGotoStmt &computedGotoStmt) { AddLabelReference(std::get<std::list<parser::Label>>(computedGotoStmt.t)); } void Post(const parser::ArithmeticIfStmt &arithmeticIfStmt) { AddLabelReference(std::get<1>(arithmeticIfStmt.t)); AddLabelReference(std::get<2>(arithmeticIfStmt.t)); AddLabelReference(std::get<3>(arithmeticIfStmt.t)); } void Post(const parser::AssignStmt &assignStmt) { AddLabelReferenceFromAssignStmt(std::get<parser::Label>(assignStmt.t)); } void Post(const parser::AssignedGotoStmt &assignedGotoStmt) { AddLabelReference(std::get<std::list<parser::Label>>(assignedGotoStmt.t)); } void Post(const parser::AltReturnSpec &altReturnSpec) { AddLabelReference(altReturnSpec.v); } void Post(const parser::ErrLabel &errLabel) { AddLabelReference(errLabel.v); } void Post(const parser::EndLabel &endLabel) { AddLabelReference(endLabel.v); } void Post(const parser::EorLabel &eorLabel) { AddLabelReference(eorLabel.v); } void Post(const parser::Format &format) { if (const auto *labelPointer{std::get_if<parser::Label>(&format.u)}) { AddLabelReferenceToFormatStmt(*labelPointer); } } void Post(const parser::CycleStmt &cycleStmt) { if (cycleStmt.v) { CheckLabelContext("CYCLE", cycleStmt.v->source); } } void Post(const parser::ExitStmt &exitStmt) { if (exitStmt.v) { CheckLabelContext("EXIT", exitStmt.v->source); } } const std::vector<UnitAnalysis> &ProgramUnits() const { return programUnits_; } SemanticsContext &ErrorHandler() { return context_; } private: bool PushSubscope() { programUnits_.back().scopeModel.push_back(currentScope_); currentScope_ = programUnits_.back().scopeModel.size() - 1; return true; } bool InitializeNewScopeContext() { programUnits_.emplace_back(UnitAnalysis{}); currentScope_ = 0u; return PushSubscope(); } void PopScope() { currentScope_ = programUnits_.back().scopeModel[currentScope_]; } ProxyForScope ParentScope() { return programUnits_.back().scopeModel[currentScope_]; } bool SwitchToNewScope() { PopScope(); return PushSubscope(); } template <typename A> bool PushConstructName(const A &a) { const auto &optionalName{std::get<0>(std::get<0>(a.t).statement.t)}; if (optionalName) { constructNames_.emplace_back(optionalName->ToString()); } return PushSubscope(); } bool PushConstructName(const parser::BlockConstruct &blockConstruct) { const auto &optionalName{ std::get<parser::Statement<parser::BlockStmt>>(blockConstruct.t) .statement.v}; if (optionalName) { constructNames_.emplace_back(optionalName->ToString()); } return PushSubscope(); } template <typename A> void PopConstructNameIfPresent(const A &a) { const auto &optionalName{std::get<0>(std::get<0>(a.t).statement.t)}; if (optionalName) { constructNames_.pop_back(); } } void PopConstructNameIfPresent(const parser::BlockConstruct &blockConstruct) { const auto &optionalName{ std::get<parser::Statement<parser::BlockStmt>>(blockConstruct.t) .statement.v}; if (optionalName) { constructNames_.pop_back(); } } template <typename A> void PopConstructName(const A &a) { CheckName(a); PopScope(); PopConstructNameIfPresent(a); } template <typename FIRST, typename CASEBLOCK, typename CASE, typename CONSTRUCT> void CheckSelectNames(const char *tag, const CONSTRUCT &construct) { CheckEndName<FIRST, parser::EndSelectStmt>(tag, construct); for (const auto &inner : std::get<std::list<CASEBLOCK>>(construct.t)) { CheckOptionalName<FIRST>( tag, construct, std::get<parser::Statement<CASE>>(inner.t)); } } // C1144 void PopConstructName(const parser::CaseConstruct &caseConstruct) { CheckSelectNames<parser::SelectCaseStmt, parser::CaseConstruct::Case, parser::CaseStmt>("SELECT CASE", caseConstruct); PopScope(); PopConstructNameIfPresent(caseConstruct); } // C1154, C1156 void PopConstructName( const parser::SelectRankConstruct &selectRankConstruct) { CheckSelectNames<parser::SelectRankStmt, parser::SelectRankConstruct::RankCase, parser::SelectRankCaseStmt>( "SELECT RANK", selectRankConstruct); PopScope(); PopConstructNameIfPresent(selectRankConstruct); } // C1165 void PopConstructName( const parser::SelectTypeConstruct &selectTypeConstruct) { CheckSelectNames<parser::SelectTypeStmt, parser::SelectTypeConstruct::TypeCase, parser::TypeGuardStmt>( "SELECT TYPE", selectTypeConstruct); PopScope(); PopConstructNameIfPresent(selectTypeConstruct); } // Checks for missing or mismatching names on various constructs (e.g., BLOCK) // and their END statements. Both names must be present if either one is. template <typename FIRST, typename END, typename CONSTRUCT> void CheckEndName(const char *constructTag, const CONSTRUCT &a) { const auto &constructStmt{std::get<parser::Statement<FIRST>>(a.t)}; const auto &endStmt{std::get<parser::Statement<END>>(a.t)}; const parser::CharBlock *endName{GetStmtName(endStmt)}; if (const parser::CharBlock * constructName{GetStmtName(constructStmt)}) { if (endName) { if (*constructName != *endName) { context_ .Say(*endName, "%s construct name mismatch"_err_en_US, constructTag) .Attach(*constructName, "should be"_en_US); } } else { context_ .Say(endStmt.source, "%s construct name required but missing"_err_en_US, constructTag) .Attach(*constructName, "should be"_en_US); } } else if (endName) { context_ .Say(*endName, "%s construct name unexpected"_err_en_US, constructTag) .Attach( constructStmt.source, "unnamed %s statement"_en_US, constructTag); } } // C1106 void CheckName(const parser::AssociateConstruct &associateConstruct) { CheckEndName<parser::AssociateStmt, parser::EndAssociateStmt>( "ASSOCIATE", associateConstruct); } // C1117 void CheckName(const parser::CriticalConstruct &criticalConstruct) { CheckEndName<parser::CriticalStmt, parser::EndCriticalStmt>( "CRITICAL", criticalConstruct); } // C1131 void CheckName(const parser::DoConstruct &doConstruct) { CheckEndName<parser::NonLabelDoStmt, parser::EndDoStmt>("DO", doConstruct); } // C1035 void CheckName(const parser::ForallConstruct &forallConstruct) { CheckEndName<parser::ForallConstructStmt, parser::EndForallStmt>( "FORALL", forallConstruct); } // C1109 void CheckName(const parser::BlockConstruct &blockConstruct) { CheckEndName<parser::BlockStmt, parser::EndBlockStmt>( "BLOCK", blockConstruct); } // C1112 void CheckName(const parser::ChangeTeamConstruct &changeTeamConstruct) { CheckEndName<parser::ChangeTeamStmt, parser::EndChangeTeamStmt>( "CHANGE TEAM", changeTeamConstruct); } // C1142 void CheckName(const parser::IfConstruct &ifConstruct) { CheckEndName<parser::IfThenStmt, parser::EndIfStmt>("IF", ifConstruct); for (const auto &elseIfBlock : std::get<std::list<parser::IfConstruct::ElseIfBlock>>(ifConstruct.t)) { CheckOptionalName<parser::IfThenStmt>("IF construct", ifConstruct, std::get<parser::Statement<parser::ElseIfStmt>>(elseIfBlock.t)); } if (const auto &elseBlock{ std::get<std::optional<parser::IfConstruct::ElseBlock>>( ifConstruct.t)}) { CheckOptionalName<parser::IfThenStmt>("IF construct", ifConstruct, std::get<parser::Statement<parser::ElseStmt>>(elseBlock->t)); } } // C1033 void CheckName(const parser::WhereConstruct &whereConstruct) { CheckEndName<parser::WhereConstructStmt, parser::EndWhereStmt>( "WHERE", whereConstruct); for (const auto &maskedElsewhere : std::get<std::list<parser::WhereConstruct::MaskedElsewhere>>( whereConstruct.t)) { CheckOptionalName<parser::WhereConstructStmt>("WHERE construct", whereConstruct, std::get<parser::Statement<parser::MaskedElsewhereStmt>>( maskedElsewhere.t)); } if (const auto &elsewhere{ std::get<std::optional<parser::WhereConstruct::Elsewhere>>( whereConstruct.t)}) { CheckOptionalName<parser::WhereConstructStmt>("WHERE construct", whereConstruct, std::get<parser::Statement<parser::ElsewhereStmt>>(elsewhere->t)); } } // C1134, C1166 void CheckLabelContext( const char *const stmtString, const parser::CharBlock &constructName) { const auto iter{std::find(constructNames_.crbegin(), constructNames_.crend(), constructName.ToString())}; if (iter == constructNames_.crend()) { context_.Say(constructName, "%s construct-name is not in scope"_err_en_US, stmtString); } } // 6.2.5, paragraph 2 void CheckLabelInRange(parser::Label label) { if (label < 1 || label > 99999) { context_.Say(currentPosition_, "Label '%u' is out of range"_err_en_US, SayLabel(label)); } } // 6.2.5., paragraph 2 void AddTargetLabelDefinition(parser::Label label, LabeledStmtClassificationSet labeledStmtClassificationSet, ProxyForScope scope, bool isExecutableConstructEndStmt = false) { CheckLabelInRange(label); const auto pair{programUnits_.back().targetStmts.emplace(label, LabeledStatementInfoTuplePOD{scope, currentPosition_, labeledStmtClassificationSet, isExecutableConstructEndStmt})}; if (!pair.second) { context_.Say(currentPosition_, "Label '%u' is not distinct"_err_en_US, SayLabel(label)); } } void AddLabelReferenceFromDoStmt(parser::Label label) { CheckLabelInRange(label); programUnits_.back().doStmtSources.emplace_back( label, currentScope_, currentPosition_); } void AddLabelReferenceToFormatStmt(parser::Label label) { CheckLabelInRange(label); programUnits_.back().formatStmtSources.emplace_back( label, currentScope_, currentPosition_); } void AddLabelReferenceFromAssignStmt(parser::Label label) { CheckLabelInRange(label); programUnits_.back().assignStmtSources.emplace_back( label, currentScope_, currentPosition_); } void AddLabelReference(parser::Label label) { CheckLabelInRange(label); programUnits_.back().otherStmtSources.emplace_back( label, currentScope_, currentPosition_); } void AddLabelReference(const std::list<parser::Label> &labels) { for (const parser::Label &label : labels) { AddLabelReference(label); } } std::vector<UnitAnalysis> programUnits_; SemanticsContext &context_; parser::CharBlock currentPosition_; ProxyForScope currentScope_; std::vector<std::string> constructNames_; }; bool InInclusiveScope(const std::vector<ProxyForScope> &scopes, ProxyForScope tail, ProxyForScope head) { for (; tail != head; tail = scopes[tail]) { if (!HasScope(tail)) { return false; } } return true; } ParseTreeAnalyzer LabelAnalysis( SemanticsContext &context, const parser::Program &program) { ParseTreeAnalyzer analysis{context}; Walk(program, analysis); return analysis; } bool InBody(const parser::CharBlock &position, const std::pair<parser::CharBlock, parser::CharBlock> &pair) { if (position.begin() >= pair.first.begin()) { if (position.begin() < pair.second.end()) { return true; } } return false; } LabeledStatementInfoTuplePOD GetLabel( const TargetStmtMap &labels, const parser::Label &label) { const auto iter{labels.find(label)}; if (iter == labels.cend()) { return {0u, nullptr, LabeledStmtClassificationSet{}, false}; } else { return iter->second; } } // 11.1.7.3 void CheckBranchesIntoDoBody(const SourceStmtList &branches, const TargetStmtMap &labels, const IndexList &loopBodies, SemanticsContext &context) { for (const auto &branch : branches) { const auto &label{branch.parserLabel}; auto branchTarget{GetLabel(labels, label)}; if (HasScope(branchTarget.proxyForScope)) { const auto &fromPosition{branch.parserCharBlock}; const auto &toPosition{branchTarget.parserCharBlock}; for (const auto &body : loopBodies) { if (!InBody(fromPosition, body) && InBody(toPosition, body)) { context.Say(fromPosition, "branch into loop body from outside"_en_US) .Attach(body.first, "the loop branched into"_en_US); } } } } } void CheckDoNesting(const IndexList &loopBodies, SemanticsContext &context) { for (auto i1{loopBodies.cbegin()}; i1 != loopBodies.cend(); ++i1) { const auto &v1{*i1}; for (auto i2{i1 + 1}; i2 != loopBodies.cend(); ++i2) { const auto &v2{*i2}; if (v2.first.begin() < v1.second.end() && v1.second.begin() < v2.second.begin()) { context.Say(v1.first, "DO loop doesn't properly nest"_err_en_US) .Attach(v2.first, "DO loop conflicts"_en_US); } } } } parser::CharBlock SkipLabel(const parser::CharBlock &position) { const std::size_t maxPosition{position.size()}; if (maxPosition && parser::IsDecimalDigit(position[0])) { std::size_t i{1l}; for (; (i < maxPosition) && parser::IsDecimalDigit(position[i]); ++i) { } for (; (i < maxPosition) && std::isspace(position[i]); ++i) { } return parser::CharBlock{position.begin() + i, position.end()}; } return position; } ProxyForScope ParentScope( const std::vector<ProxyForScope> &scopes, ProxyForScope scope) { return scopes[scope]; } void CheckLabelDoConstraints(const SourceStmtList &dos, const SourceStmtList &branches, const TargetStmtMap &labels, const std::vector<ProxyForScope> &scopes, SemanticsContext &context) { IndexList loopBodies; for (const auto &stmt : dos) { const auto &label{stmt.parserLabel}; const auto &scope{stmt.proxyForScope}; const auto &position{stmt.parserCharBlock}; auto doTarget{GetLabel(labels, label)}; if (!HasScope(doTarget.proxyForScope)) { // C1133 context.Say( position, "Label '%u' cannot be found"_err_en_US, SayLabel(label)); } else if (doTarget.parserCharBlock.begin() < position.begin()) { // R1119 context.Say(position, "Label '%u' doesn't lexically follow DO stmt"_err_en_US, SayLabel(label)); } else if ((InInclusiveScope(scopes, scope, doTarget.proxyForScope) && doTarget.labeledStmtClassificationSet.test( TargetStatementEnum::CompatibleDo)) || (doTarget.isExecutableConstructEndStmt && ParentScope(scopes, doTarget.proxyForScope) == scope)) { if (context.warnOnNonstandardUsage() || context.ShouldWarn( common::LanguageFeature::OldLabelDoEndStatements)) { context .Say(position, "A DO loop should terminate with an END DO or CONTINUE"_en_US) .Attach(doTarget.parserCharBlock, "DO loop currently ends at statement:"_en_US); } } else if (!InInclusiveScope(scopes, scope, doTarget.proxyForScope)) { context.Say(position, "Label '%u' is not in DO loop scope"_err_en_US, SayLabel(label)); } else if (!doTarget.labeledStmtClassificationSet.test( TargetStatementEnum::Do)) { context.Say(doTarget.parserCharBlock, "A DO loop should terminate with an END DO or CONTINUE"_err_en_US); } else { loopBodies.emplace_back(SkipLabel(position), doTarget.parserCharBlock); } } CheckBranchesIntoDoBody(branches, labels, loopBodies, context); CheckDoNesting(loopBodies, context); } // 6.2.5 void CheckScopeConstraints(const SourceStmtList &stmts, const TargetStmtMap &labels, const std::vector<ProxyForScope> &scopes, SemanticsContext &context) { for (const auto &stmt : stmts) { const auto &label{stmt.parserLabel}; const auto &scope{stmt.proxyForScope}; const auto &position{stmt.parserCharBlock}; auto target{GetLabel(labels, label)}; if (!HasScope(target.proxyForScope)) { context.Say( position, "Label '%u' was not found"_err_en_US, SayLabel(label)); } else if (!InInclusiveScope(scopes, scope, target.proxyForScope)) { // Clause 11.1.2.1 prohibits transfer of control to the interior of a // block from outside the block, but this does not apply to formats. // C1038 and C1034 forbid statements in FORALL and WHERE constructs // (resp.) from being branch targets. if (target.labeledStmtClassificationSet.test( TargetStatementEnum::Format)) { continue; } context.Say(position, "Label '%u' is in a construct that prevents its use as a branch target here"_en_US, SayLabel(label)); } } } void CheckBranchTargetConstraints(const SourceStmtList &stmts, const TargetStmtMap &labels, SemanticsContext &context) { for (const auto &stmt : stmts) { const auto &label{stmt.parserLabel}; auto branchTarget{GetLabel(labels, label)}; if (HasScope(branchTarget.proxyForScope)) { if (!branchTarget.labeledStmtClassificationSet.test( TargetStatementEnum::Branch) && !branchTarget.labeledStmtClassificationSet.test( TargetStatementEnum::CompatibleBranch)) { // error context .Say(branchTarget.parserCharBlock, "Label '%u' is not a branch target"_err_en_US, SayLabel(label)) .Attach(stmt.parserCharBlock, "Control flow use of '%u'"_en_US, SayLabel(label)); } else if (!branchTarget.labeledStmtClassificationSet.test( TargetStatementEnum::Branch)) { // warning context .Say(branchTarget.parserCharBlock, "Label '%u' is not a branch target"_en_US, SayLabel(label)) .Attach(stmt.parserCharBlock, "Control flow use of '%u'"_en_US, SayLabel(label)); } } } } void CheckBranchConstraints(const SourceStmtList &branches, const TargetStmtMap &labels, const std::vector<ProxyForScope> &scopes, SemanticsContext &context) { CheckScopeConstraints(branches, labels, scopes, context); CheckBranchTargetConstraints(branches, labels, context); } void CheckDataXferTargetConstraints(const SourceStmtList &stmts, const TargetStmtMap &labels, SemanticsContext &context) { for (const auto &stmt : stmts) { const auto &label{stmt.parserLabel}; auto ioTarget{GetLabel(labels, label)}; if (HasScope(ioTarget.proxyForScope)) { if (!ioTarget.labeledStmtClassificationSet.test( TargetStatementEnum::Format)) { context .Say(ioTarget.parserCharBlock, "'%u' not a FORMAT"_err_en_US, SayLabel(label)) .Attach(stmt.parserCharBlock, "data transfer use of '%u'"_en_US, SayLabel(label)); } } } } void CheckDataTransferConstraints(const SourceStmtList &dataTransfers, const TargetStmtMap &labels, const std::vector<ProxyForScope> &scopes, SemanticsContext &context) { CheckScopeConstraints(dataTransfers, labels, scopes, context); CheckDataXferTargetConstraints(dataTransfers, labels, context); } void CheckAssignTargetConstraints(const SourceStmtList &stmts, const TargetStmtMap &labels, SemanticsContext &context) { for (const auto &stmt : stmts) { const auto &label{stmt.parserLabel}; auto target{GetLabel(labels, label)}; if (HasScope(target.proxyForScope) && !target.labeledStmtClassificationSet.test( TargetStatementEnum::Branch) && !target.labeledStmtClassificationSet.test( TargetStatementEnum::Format)) { context .Say(target.parserCharBlock, target.labeledStmtClassificationSet.test( TargetStatementEnum::CompatibleBranch) ? "Label '%u' is not a branch target or FORMAT"_en_US : "Label '%u' is not a branch target or FORMAT"_err_en_US, SayLabel(label)) .Attach(stmt.parserCharBlock, "ASSIGN statement use of '%u'"_en_US, SayLabel(label)); } } } void CheckAssignConstraints(const SourceStmtList &assigns, const TargetStmtMap &labels, const std::vector<ProxyForScope> &scopes, SemanticsContext &context) { CheckScopeConstraints(assigns, labels, scopes, context); CheckAssignTargetConstraints(assigns, labels, context); } bool CheckConstraints(ParseTreeAnalyzer &&parseTreeAnalysis) { auto &context{parseTreeAnalysis.ErrorHandler()}; for (const auto &programUnit : parseTreeAnalysis.ProgramUnits()) { const auto &dos{programUnit.doStmtSources}; const auto &branches{programUnit.otherStmtSources}; const auto &labels{programUnit.targetStmts}; const auto &scopes{programUnit.scopeModel}; CheckLabelDoConstraints(dos, branches, labels, scopes, context); CheckBranchConstraints(branches, labels, scopes, context); const auto &dataTransfers{programUnit.formatStmtSources}; CheckDataTransferConstraints(dataTransfers, labels, scopes, context); const auto &assigns{programUnit.assignStmtSources}; CheckAssignConstraints(assigns, labels, scopes, context); } return !context.AnyFatalError(); } bool ValidateLabels(SemanticsContext &context, const parser::Program &program) { return CheckConstraints(LabelAnalysis(context, program)); } } // namespace Fortran::semantics
// Tencent is pleased to support the open source community by making ncnn available. // // Copyright (C) 2017 THL A29 Limited, a Tencent company. All rights reserved. // // Licensed under the BSD 3-Clause License (the "License"); you may not use this file except // in compliance with the License. You may obtain a copy of the License at // // https://opensource.org/licenses/BSD-3-Clause // // 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 "convolution.h" #include "layer_type.h" namespace ncnn { Convolution::Convolution() { one_blob_only = true; support_inplace = false; } int Convolution::load_param(const ParamDict& pd) { num_output = pd.get(0, 0); kernel_w = pd.get(1, 0); kernel_h = pd.get(11, kernel_w); dilation_w = pd.get(2, 1); dilation_h = pd.get(12, dilation_w); stride_w = pd.get(3, 1); stride_h = pd.get(13, stride_w); pad_left = pd.get(4, 0); pad_right = pd.get(15, pad_left); pad_top = pd.get(14, pad_left); pad_bottom = pd.get(16, pad_top); pad_value = pd.get(18, 0.f); bias_term = pd.get(5, 0); weight_data_size = pd.get(6, 0); int8_scale_term = pd.get(8, 0); activation_type = pd.get(9, 0); activation_params = pd.get(10, Mat()); impl_type = pd.get(17, 0); if (int8_scale_term) { #if NCNN_INT8 support_int8_storage = true; #else NCNN_LOGE("please build ncnn with NCNN_INT8 enabled for int8 inference"); return -1; #endif } return 0; } int Convolution::load_model(const ModelBin& mb) { weight_data = mb.load(weight_data_size, 0); if (weight_data.empty()) return -100; if (bias_term) { bias_data = mb.load(num_output, 1); if (bias_data.empty()) return -100; } #if NCNN_INT8 if (int8_scale_term) { weight_data_int8_scales = mb.load(num_output, 1); bottom_blob_int8_scales = mb.load(1, 1); } if (int8_scale_term > 100) { top_blob_int8_scales = mb.load(1, 1); } #endif // NCNN_INT8 return 0; } int Convolution::create_pipeline(const Option& opt) { #if NCNN_INT8 // runtime quantize the weight data if (opt.use_int8_inference && weight_data.elemsize == (size_t)4u && int8_scale_term) { const int maxk = kernel_w * kernel_h; const int num_input = weight_data_size / num_output / maxk; Mat weight_data_r2 = weight_data.reshape(maxk, num_input, num_output); Mat weight_data_int8; Option opt_q = opt; opt_q.blob_allocator = weight_data.allocator; opt_q.use_packing_layout = false; quantize_to_int8(weight_data_r2, weight_data_int8, weight_data_int8_scales, opt_q); if (weight_data_int8.empty()) return -100; weight_data = weight_data_int8.reshape(weight_data_size); } #endif // NCNN_INT8 return 0; } int Convolution::forward(const Mat& bottom_blob, Mat& top_blob, const Option& opt) const { // convolv with NxN kernel // value = value + bias #if NCNN_INT8 if (opt.use_int8_inference && weight_data.elemsize == (size_t)1u) { return forward_int8(bottom_blob, top_blob, opt); } #endif // flattened blob, implement as InnerProduct if (bottom_blob.dims == 1 && kernel_w == 1 && kernel_h == 1) { int num_input = weight_data_size / num_output; if (bottom_blob.w * bottom_blob.elempack == num_input) { // call InnerProduct ncnn::Layer* op = ncnn::create_layer(ncnn::LayerType::InnerProduct); // set param ncnn::ParamDict pd; pd.set(0, num_output); pd.set(1, bias_term); pd.set(2, weight_data_size); pd.set(8, int8_scale_term); pd.set(9, activation_type); pd.set(10, activation_params); op->load_param(pd); // set weights ncnn::Mat weights[4]; weights[0] = weight_data; weights[1] = bias_data; #if NCNN_INT8 if (int8_scale_term) { weights[2] = weight_data_int8_scales; weights[3] = bottom_blob_int8_scales; } #endif op->load_model(ModelBinFromMatArray(weights)); op->create_pipeline(opt); // forward op->forward(bottom_blob, top_blob, opt); op->destroy_pipeline(opt); delete op; return 0; } } int w = bottom_blob.w; int h = bottom_blob.h; int channels = bottom_blob.c; size_t elemsize = bottom_blob.elemsize; // NCNN_LOGE("Convolution input %d x %d pad = %d %d ksize=%d %d stride=%d %d", w, h, pad_w, pad_h, kernel_w, kernel_h, stride_w, stride_h); const int kernel_extent_w = dilation_w * (kernel_w - 1) + 1; const int kernel_extent_h = dilation_h * (kernel_h - 1) + 1; Mat bottom_blob_bordered; make_padding(bottom_blob, bottom_blob_bordered, opt); if (bottom_blob_bordered.empty()) return -100; w = bottom_blob_bordered.w; h = bottom_blob_bordered.h; int outw = (w - kernel_extent_w) / stride_w + 1; int outh = (h - kernel_extent_h) / stride_h + 1; const int maxk = kernel_w * kernel_h; // kernel offsets std::vector<int> _space_ofs(maxk); int* space_ofs = &_space_ofs[0]; { int p1 = 0; int p2 = 0; int gap = w * dilation_h - kernel_w * dilation_w; for (int i = 0; i < kernel_h; i++) { for (int j = 0; j < kernel_w; j++) { space_ofs[p1] = p2; p1++; p2 += dilation_w; } p2 += gap; } } // float32 top_blob.create(outw, outh, num_output, elemsize, opt.blob_allocator); if (top_blob.empty()) return -100; // num_output #pragma omp parallel for num_threads(opt.num_threads) for (int p = 0; p < num_output; p++) { float* outptr = top_blob.channel(p); for (int i = 0; i < outh; i++) { for (int j = 0; j < outw; j++) { float sum = 0.f; if (bias_term) sum = bias_data[p]; const float* kptr = (const float*)weight_data + maxk * channels * p; // channels for (int q = 0; q < channels; q++) { const Mat m = bottom_blob_bordered.channel(q); const float* sptr = m.row(i * stride_h) + j * stride_w; for (int k = 0; k < maxk; k++) // 29.23 { float val = sptr[space_ofs[k]]; // 20.72 float wt = kptr[k]; sum += val * wt; // 41.45 } kptr += maxk; } if (activation_type == 1) { sum = std::max(sum, 0.f); } else if (activation_type == 2) { float slope = activation_params[0]; sum = sum > 0.f ? sum : sum * slope; } else if (activation_type == 3) { float min = activation_params[0]; float max = activation_params[1]; if (sum < min) sum = min; if (sum > max) sum = max; } else if (activation_type == 4) { sum = static_cast<float>(1.f / (1.f + exp(-sum))); } else if (activation_type == 5) { const float MISH_THRESHOLD = 20; float x = sum, y; if (x > MISH_THRESHOLD) y = x; else if (x < -MISH_THRESHOLD) y = expf(x); else y = logf(expf(x) + 1); sum = static_cast<float>(x * tanh(y)); } outptr[j] = sum; } outptr += outw; } } return 0; } void Convolution::make_padding(const Mat& bottom_blob, Mat& bottom_blob_bordered, const Option& opt) const { int w = bottom_blob.w; int h = bottom_blob.h; const int kernel_extent_w = dilation_w * (kernel_w - 1) + 1; const int kernel_extent_h = dilation_h * (kernel_h - 1) + 1; bottom_blob_bordered = bottom_blob; if (pad_left > 0 || pad_right > 0 || pad_top > 0 || pad_bottom > 0) { Option opt_b = opt; opt_b.blob_allocator = opt.workspace_allocator; copy_make_border(bottom_blob, bottom_blob_bordered, pad_top, pad_bottom, pad_left, pad_right, BORDER_CONSTANT, pad_value, opt_b); } else if (pad_left == -233 && pad_right == -233 && pad_top == -233 && pad_bottom == -233) { // tensorflow padding=SAME or onnx padding=SAME_UPPER int wpad = kernel_extent_w + (w - 1) / stride_w * stride_w - w; int hpad = kernel_extent_h + (h - 1) / stride_h * stride_h - h; if (wpad > 0 || hpad > 0) { Option opt_b = opt; opt_b.blob_allocator = opt.workspace_allocator; copy_make_border(bottom_blob, bottom_blob_bordered, hpad / 2, hpad - hpad / 2, wpad / 2, wpad - wpad / 2, BORDER_CONSTANT, pad_value, opt_b); } } else if (pad_left == -234 && pad_right == -234 && pad_top == -234 && pad_bottom == -234) { // onnx padding=SAME_LOWER int wpad = kernel_extent_w + (w - 1) / stride_w * stride_w - w; int hpad = kernel_extent_h + (h - 1) / stride_h * stride_h - h; if (wpad > 0 || hpad > 0) { Option opt_b = opt; opt_b.blob_allocator = opt.workspace_allocator; copy_make_border(bottom_blob, bottom_blob_bordered, hpad - hpad / 2, hpad / 2, wpad - wpad / 2, wpad / 2, BORDER_CONSTANT, pad_value, opt_b); } } } #if NCNN_INT8 static inline signed char float2int8(float v) { int int32 = static_cast<int>(round(v)); if (int32 > 127) return 127; if (int32 < -127) return -127; return (signed char)int32; } int Convolution::forward_int8(const Mat& bottom_blob, Mat& top_blob, const Option& opt) const { int w = bottom_blob.w; int h = bottom_blob.h; int channels = bottom_blob.c; size_t elemsize = bottom_blob.elemsize; // NCNN_LOGE("Convolution input %d x %d ksize=%d %d stride=%d %d", w, h, kernel_w, kernel_h, stride_w, stride_h); const int kernel_extent_w = dilation_w * (kernel_w - 1) + 1; const int kernel_extent_h = dilation_h * (kernel_h - 1) + 1; Mat bottom_blob_unbordered = bottom_blob; if (elemsize != 1) { Option opt_g = opt; opt_g.blob_allocator = opt.workspace_allocator; quantize_to_int8(bottom_blob, bottom_blob_unbordered, bottom_blob_int8_scales, opt_g); } Mat bottom_blob_bordered; make_padding(bottom_blob_unbordered, bottom_blob_bordered, opt); if (bottom_blob_bordered.empty()) return -100; w = bottom_blob_bordered.w; h = bottom_blob_bordered.h; int outw = (w - kernel_extent_w) / stride_w + 1; int outh = (h - kernel_extent_h) / stride_h + 1; const int maxk = kernel_w * kernel_h; // kernel offsets std::vector<int> _space_ofs(maxk); int* space_ofs = &_space_ofs[0]; { int p1 = 0; int p2 = 0; int gap = w * dilation_h - kernel_w * dilation_w; for (int i = 0; i < kernel_h; i++) { for (int j = 0; j < kernel_w; j++) { space_ofs[p1] = p2; p1++; p2 += dilation_w; } p2 += gap; } } // int8 bool use_int8_requantize = int8_scale_term > 100; size_t out_elemsize = use_int8_requantize ? 1u : 4u; top_blob.create(outw, outh, num_output, out_elemsize, opt.blob_allocator); if (top_blob.empty()) return -100; // num_output #pragma omp parallel for num_threads(opt.num_threads) for (int p = 0; p < num_output; p++) { signed char* outptr = top_blob.channel(p); for (int i = 0; i < outh; i++) { for (int j = 0; j < outw; j++) { int sum = 0; const signed char* kptr = (const signed char*)weight_data + maxk * channels * p; // channels for (int q = 0; q < channels; q++) { const Mat m = bottom_blob_bordered.channel(q); const signed char* sptr = m.row<signed char>(i * stride_h) + j * stride_w; for (int k = 0; k < maxk; k++) { int val = sptr[space_ofs[k]]; int wt = kptr[k]; sum += val * wt; } kptr += maxk; } float scale_in; if (weight_data_int8_scales[p] == 0) scale_in = 0; else scale_in = 1.f / (bottom_blob_int8_scales[0] * weight_data_int8_scales[p]); float sumfp32 = sum * scale_in; if (bias_term) sumfp32 += bias_data[p]; if (activation_type == 1) { sumfp32 = std::max(sumfp32, 0.f); } else if (activation_type == 2) { float slope = activation_params[0]; sumfp32 = sumfp32 > 0.f ? sumfp32 : sumfp32 * slope; } else if (activation_type == 3) { float min = activation_params[0]; float max = activation_params[1]; if (sumfp32 < min) sumfp32 = min; if (sumfp32 > max) sumfp32 = max; } else if (activation_type == 4) { sumfp32 = static_cast<float>(1.f / (1.f + exp(-sumfp32))); } else if (activation_type == 5) { const float MISH_THRESHOLD = 20; float x = sumfp32, y; if (x > MISH_THRESHOLD) y = x; else if (x < -MISH_THRESHOLD) y = expf(x); else y = logf(expf(x) + 1); sumfp32 = static_cast<float>(x * tanh(y)); } if (use_int8_requantize) { // requantize float scale_out = top_blob_int8_scales[0]; signed char sums8 = float2int8(sumfp32 * scale_out); outptr[0] = sums8; outptr += 1; } else { // dequantize ((float*)outptr)[0] = sumfp32; outptr += 4; } } } } return 0; } #endif // NCNN_INT8 } // namespace ncnn
/* * Copyright (c) 2010-2017 OTClient <https://github.com/edubart/otclient> * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ #include "string.h" #include "format.h" #include <boost/algorithm/string.hpp> #include <cctype> #include <physfs.h> #ifdef _MSC_VER #pragma warning(disable:4267) // '?' : conversion from 'A' to 'B', possible loss of data #endif namespace stdext { std::string resolve_path(const std::string& filePath, std::string sourcePath) { if(stdext::starts_with(filePath, "/")) return filePath; if(!stdext::ends_with(sourcePath, "/")) { std::size_t slashPos = sourcePath.find_last_of("/"); if(slashPos == std::string::npos) throw_exception(format("invalid source path '%s', for file '%s'", sourcePath, filePath)); sourcePath = sourcePath.substr(0, slashPos + 1); } return sourcePath + filePath; } std::string date_time_string() { char date[32]; std::time_t tnow; std::time(&tnow); std::tm *ts = std::localtime(&tnow); std::strftime(date, 32, "%b %d %Y %H:%M:%S", ts); return std::string(date); } std::string dec_to_hex(uint64_t num) { std::string str; std::ostringstream o; o << std::hex << num; str = o.str(); return str; } uint64_t hex_to_dec(const std::string& str) { uint64_t num; std::istringstream i(str); i >> std::hex >> num; return num; } bool is_valid_utf8(const std::string& src) { const unsigned char *bytes = (const unsigned char *)src.c_str(); while(*bytes) { if( (// ASCII // use bytes[0] <= 0x7F to allow ASCII control characters bytes[0] == 0x09 || bytes[0] == 0x0A || bytes[0] == 0x0D || (0x20 <= bytes[0] && bytes[0] <= 0x7E) ) ) { bytes += 1; continue; } if( (// non-overlong 2-byte (0xC2 <= bytes[0] && bytes[0] <= 0xDF) && (0x80 <= bytes[1] && bytes[1] <= 0xBF) ) ) { bytes += 2; continue; } if( (// excluding overlongs bytes[0] == 0xE0 && (0xA0 <= bytes[1] && bytes[1] <= 0xBF) && (0x80 <= bytes[2] && bytes[2] <= 0xBF) ) || (// straight 3-byte ((0xE1 <= bytes[0] && bytes[0] <= 0xEC) || bytes[0] == 0xEE || bytes[0] == 0xEF) && (0x80 <= bytes[1] && bytes[1] <= 0xBF) && (0x80 <= bytes[2] && bytes[2] <= 0xBF) ) || (// excluding surrogates bytes[0] == 0xED && (0x80 <= bytes[1] && bytes[1] <= 0x9F) && (0x80 <= bytes[2] && bytes[2] <= 0xBF) ) ) { bytes += 3; continue; } if( (// planes 1-3 bytes[0] == 0xF0 && (0x90 <= bytes[1] && bytes[1] <= 0xBF) && (0x80 <= bytes[2] && bytes[2] <= 0xBF) && (0x80 <= bytes[3] && bytes[3] <= 0xBF) ) || (// planes 4-15 (0xF1 <= bytes[0] && bytes[0] <= 0xF3) && (0x80 <= bytes[1] && bytes[1] <= 0xBF) && (0x80 <= bytes[2] && bytes[2] <= 0xBF) && (0x80 <= bytes[3] && bytes[3] <= 0xBF) ) || (// plane 16 bytes[0] == 0xF4 && (0x80 <= bytes[1] && bytes[1] <= 0x8F) && (0x80 <= bytes[2] && bytes[2] <= 0xBF) && (0x80 <= bytes[3] && bytes[3] <= 0xBF) ) ) { bytes += 4; continue; } return false; } return true; } std::string utf8_to_latin1(const std::string& src) { std::string out; for(uint i=0;i<src.length();) { uchar c = src[i++]; if((c >= 32 && c < 128) || c == 0x0d || c == 0x0a || c == 0x09) out += c; else if(c == 0xc2 || c == 0xc3) { uchar c2 = src[i++]; if(c == 0xc2) { if(c2 > 0xa1 && c2 < 0xbb) out += c2; } else if(c == 0xc3) out += 64 + c2; } else if(c >= 0xc4 && c <= 0xdf) i += 1; else if(c >= 0xe0 && c <= 0xed) i += 2; else if(c >= 0xf0 && c <= 0xf4) i += 3; } return out; } std::string latin1_to_utf8(const std::string& src) { std::string out; for(uchar c : src) { if((c >= 32 && c < 128) || c == 0x0d || c == 0x0a || c == 0x09) out += c; else { out += 0xc2 + (c > 0xbf); out += 0x80 + (c & 0x3f); } } return out; } #ifdef WIN32 #include <winsock2.h> #include <windows.h> std::wstring utf8_to_utf16(const std::string& src) { std::wstring res; wchar_t out[4096]; if(MultiByteToWideChar(CP_UTF8, 0, src.c_str(), -1, out, 4096)) res = out; return res; } std::string utf16_to_utf8(const std::wstring& src) { std::string res; char out[4096]; if(WideCharToMultiByte(CP_UTF8, 0, src.c_str(), -1, out, 4096, NULL, NULL)) res = out; return res; } std::wstring latin1_to_utf16(const std::string& src) { return utf8_to_utf16(latin1_to_utf8(src)); } std::string utf16_to_latin1(const std::wstring& src) { return utf8_to_latin1(utf16_to_utf8(src)); } #endif void tolower(std::string& str) { std::transform(str.begin(), str.end(), str.begin(), lochar); } void toupper(std::string& str) { std::transform(str.begin(), str.end(), str.begin(), upchar); } void trim(std::string& str) { boost::trim(str); } char upchar(char c) { if((c >= 97 && c <= 122) || (uchar)c >= 224) c -= 32; return c; } char lochar(char c) { if((c >= 65 && c <= 90) || ((uchar)c >= 192 && (uchar)c <= 223)) c += 32; return c; } void ucwords(std::string& str) { uint32 strLen = str.length(); if(strLen == 0) return; str[0] = upchar(str[0]); for(uint32 i = 1; i < strLen; ++i) { if(str[i - 1] == ' ') str[i] = upchar(str[i]); } } bool ends_with(const std::string& str, const std::string& test) { return boost::ends_with(str, test); } bool starts_with(const std::string& str, const std::string& test) { return boost::starts_with(str, test); } void replace_all(std::string& str, const std::string& search, const std::string& replacement) { return boost::replace_all(str, search, replacement); } std::vector<std::string> split(const std::string& str, const std::string& separators) { std::vector<std::string> splitted; boost::split(splitted, str, boost::is_any_of(std::string(separators))); return splitted; } }
/// @ref gtc_quaternion /// @file glm/gtc/quaternion.inl #include "../trigonometric.hpp" #include "../geometric.hpp" #include "../exponential.hpp" #include <limits> namespace glm{ namespace detail { template <typename T, precision P, bool Aligned> struct compute_dot<tquat, T, P, Aligned> { static GLM_FUNC_QUALIFIER T call(tquat<T, P> const& x, tquat<T, P> const& y) { tvec4<T, P> tmp(x.x * y.x, x.y * y.y, x.z * y.z, x.w * y.w); return (tmp.x + tmp.y) + (tmp.z + tmp.w); } }; template <typename T, precision P, bool Aligned> struct compute_quat_add { static tquat<T, P> call(tquat<T, P> const& q, tquat<T, P> const& p) { return tquat<T, P>(q.w + p.w, q.x + p.x, q.y + p.y, q.z + p.z); } }; template <typename T, precision P, bool Aligned> struct compute_quat_sub { static tquat<T, P> call(tquat<T, P> const& q, tquat<T, P> const& p) { return tquat<T, P>(q.w - p.w, q.x - p.x, q.y - p.y, q.z - p.z); } }; template <typename T, precision P, bool Aligned> struct compute_quat_mul_scalar { static tquat<T, P> call(tquat<T, P> const& q, T s) { return tquat<T, P>(q.w * s, q.x * s, q.y * s, q.z * s); } }; template <typename T, precision P, bool Aligned> struct compute_quat_div_scalar { static tquat<T, P> call(tquat<T, P> const& q, T s) { return tquat<T, P>(q.w / s, q.x / s, q.y / s, q.z / s); } }; template <typename T, precision P, bool Aligned> struct compute_quat_mul_vec4 { static tvec4<T, P> call(tquat<T, P> const & q, tvec4<T, P> const & v) { return tvec4<T, P>(q * tvec3<T, P>(v), v.w); } }; }//namespace detail // -- Component accesses -- template <typename T, precision P> GLM_FUNC_QUALIFIER GLM_CONSTEXPR typename tquat<T, P>::length_type tquat<T, P>::length() const { return 4; } template <typename T, precision P> GLM_FUNC_QUALIFIER T & tquat<T, P>::operator[](typename tquat<T, P>::length_type i) { assert(i >= 0 && i < this->length()); return (&x)[i]; } template <typename T, precision P> GLM_FUNC_QUALIFIER T const & tquat<T, P>::operator[](typename tquat<T, P>::length_type i) const { assert(i >= 0 && i < this->length()); return (&x)[i]; } // -- Implicit basic constructors -- # if !GLM_HAS_DEFAULTED_FUNCTIONS || !defined(GLM_FORCE_NO_CTOR_INIT) template <typename T, precision P> GLM_FUNC_QUALIFIER GLM_CONSTEXPR tquat<T, P>::tquat() # ifndef GLM_FORCE_NO_CTOR_INIT : x(0), y(0), z(0), w(1) # endif {} # endif # if !GLM_HAS_DEFAULTED_FUNCTIONS template <typename T, precision P> GLM_FUNC_QUALIFIER GLM_CONSTEXPR tquat<T, P>::tquat(tquat<T, P> const & q) : x(q.x), y(q.y), z(q.z), w(q.w) {} # endif//!GLM_HAS_DEFAULTED_FUNCTIONS template <typename T, precision P> template <precision Q> GLM_FUNC_QUALIFIER GLM_CONSTEXPR tquat<T, P>::tquat(tquat<T, Q> const & q) : x(q.x), y(q.y), z(q.z), w(q.w) {} // -- Explicit basic constructors -- template <typename T, precision P> GLM_FUNC_QUALIFIER GLM_CONSTEXPR_CTOR tquat<T, P>::tquat(ctor) {} template <typename T, precision P> GLM_FUNC_QUALIFIER GLM_CONSTEXPR tquat<T, P>::tquat(T const & s, tvec3<T, P> const & v) : x(v.x), y(v.y), z(v.z), w(s) {} template <typename T, precision P> GLM_FUNC_QUALIFIER GLM_CONSTEXPR tquat<T, P>::tquat(T const & w, T const & x, T const & y, T const & z) : x(x), y(y), z(z), w(w) {} // -- Conversion constructors -- template <typename T, precision P> template <typename U, precision Q> GLM_FUNC_QUALIFIER GLM_CONSTEXPR tquat<T, P>::tquat(tquat<U, Q> const & q) : x(static_cast<T>(q.x)) , y(static_cast<T>(q.y)) , z(static_cast<T>(q.z)) , w(static_cast<T>(q.w)) {} //template <typename valType> //GLM_FUNC_QUALIFIER tquat<valType>::tquat //( // valType const & pitch, // valType const & yaw, // valType const & roll //) //{ // tvec3<valType> eulerAngle(pitch * valType(0.5), yaw * valType(0.5), roll * valType(0.5)); // tvec3<valType> c = glm::cos(eulerAngle * valType(0.5)); // tvec3<valType> s = glm::sin(eulerAngle * valType(0.5)); // // this->w = c.x * c.y * c.z + s.x * s.y * s.z; // this->x = s.x * c.y * c.z - c.x * s.y * s.z; // this->y = c.x * s.y * c.z + s.x * c.y * s.z; // this->z = c.x * c.y * s.z - s.x * s.y * c.z; //} template <typename T, precision P> GLM_FUNC_QUALIFIER tquat<T, P>::tquat(tvec3<T, P> const & u, tvec3<T, P> const & v) { tvec3<T, P> const LocalW(cross(u, v)); T Dot = detail::compute_dot<tvec3, T, P, detail::is_aligned<P>::value>::call(u, v); tquat<T, P> q(T(1) + Dot, LocalW.x, LocalW.y, LocalW.z); *this = normalize(q); } template <typename T, precision P> GLM_FUNC_QUALIFIER tquat<T, P>::tquat(tvec3<T, P> const & eulerAngle) { tvec3<T, P> c = glm::cos(eulerAngle * T(0.5)); tvec3<T, P> s = glm::sin(eulerAngle * T(0.5)); this->w = c.x * c.y * c.z + s.x * s.y * s.z; this->x = s.x * c.y * c.z - c.x * s.y * s.z; this->y = c.x * s.y * c.z + s.x * c.y * s.z; this->z = c.x * c.y * s.z - s.x * s.y * c.z; } template <typename T, precision P> GLM_FUNC_QUALIFIER tquat<T, P>::tquat(tmat3x3<T, P> const & m) { *this = quat_cast(m); } template <typename T, precision P> GLM_FUNC_QUALIFIER tquat<T, P>::tquat(tmat4x4<T, P> const & m) { *this = quat_cast(m); } # if GLM_HAS_EXPLICIT_CONVERSION_OPERATORS template <typename T, precision P> GLM_FUNC_QUALIFIER tquat<T, P>::operator tmat3x3<T, P>() { return mat3_cast(*this); } template <typename T, precision P> GLM_FUNC_QUALIFIER tquat<T, P>::operator tmat4x4<T, P>() { return mat4_cast(*this); } # endif//GLM_HAS_EXPLICIT_CONVERSION_OPERATORS template <typename T, precision P> GLM_FUNC_QUALIFIER tquat<T, P> conjugate(tquat<T, P> const & q) { return tquat<T, P>(q.w, -q.x, -q.y, -q.z); } template <typename T, precision P> GLM_FUNC_QUALIFIER tquat<T, P> inverse(tquat<T, P> const & q) { return conjugate(q) / dot(q, q); } // -- Unary arithmetic operators -- # if !GLM_HAS_DEFAULTED_FUNCTIONS template <typename T, precision P> GLM_FUNC_QUALIFIER tquat<T, P> & tquat<T, P>::operator=(tquat<T, P> const & q) { this->w = q.w; this->x = q.x; this->y = q.y; this->z = q.z; return *this; } # endif//!GLM_HAS_DEFAULTED_FUNCTIONS template <typename T, precision P> template <typename U> GLM_FUNC_QUALIFIER tquat<T, P> & tquat<T, P>::operator=(tquat<U, P> const & q) { this->w = static_cast<T>(q.w); this->x = static_cast<T>(q.x); this->y = static_cast<T>(q.y); this->z = static_cast<T>(q.z); return *this; } template <typename T, precision P> template <typename U> GLM_FUNC_QUALIFIER tquat<T, P> & tquat<T, P>::operator+=(tquat<U, P> const& q) { return (*this = detail::compute_quat_add<T, P, detail::is_aligned<P>::value>::call(*this, tquat<T, P>(q))); } template <typename T, precision P> template <typename U> GLM_FUNC_QUALIFIER tquat<T, P> & tquat<T, P>::operator-=(tquat<U, P> const& q) { return (*this = detail::compute_quat_sub<T, P, detail::is_aligned<P>::value>::call(*this, tquat<T, P>(q))); } template <typename T, precision P> template <typename U> GLM_FUNC_QUALIFIER tquat<T, P> & tquat<T, P>::operator*=(tquat<U, P> const & r) { tquat<T, P> const p(*this); tquat<T, P> const q(r); this->w = p.w * q.w - p.x * q.x - p.y * q.y - p.z * q.z; this->x = p.w * q.x + p.x * q.w + p.y * q.z - p.z * q.y; this->y = p.w * q.y + p.y * q.w + p.z * q.x - p.x * q.z; this->z = p.w * q.z + p.z * q.w + p.x * q.y - p.y * q.x; return *this; } template <typename T, precision P> template <typename U> GLM_FUNC_QUALIFIER tquat<T, P> & tquat<T, P>::operator*=(U s) { return (*this = detail::compute_quat_mul_scalar<T, P, detail::is_aligned<P>::value>::call(*this, static_cast<U>(s))); } template <typename T, precision P> template <typename U> GLM_FUNC_QUALIFIER tquat<T, P> & tquat<T, P>::operator/=(U s) { return (*this = detail::compute_quat_div_scalar<T, P, detail::is_aligned<P>::value>::call(*this, static_cast<U>(s))); } // -- Unary bit operators -- template <typename T, precision P> GLM_FUNC_QUALIFIER tquat<T, P> operator+(tquat<T, P> const & q) { return q; } template <typename T, precision P> GLM_FUNC_QUALIFIER tquat<T, P> operator-(tquat<T, P> const & q) { return tquat<T, P>(-q.w, -q.x, -q.y, -q.z); } // -- Binary operators -- template <typename T, precision P> GLM_FUNC_QUALIFIER tquat<T, P> operator+(tquat<T, P> const & q, tquat<T, P> const & p) { return tquat<T, P>(q) += p; } template <typename T, precision P> GLM_FUNC_QUALIFIER tquat<T, P> operator*(tquat<T, P> const & q, tquat<T, P> const & p) { return tquat<T, P>(q) *= p; } template <typename T, precision P> GLM_FUNC_QUALIFIER tvec3<T, P> operator*(tquat<T, P> const & q, tvec3<T, P> const & v) { tvec3<T, P> const QuatVector(q.x, q.y, q.z); tvec3<T, P> const uv(glm::cross(QuatVector, v)); tvec3<T, P> const uuv(glm::cross(QuatVector, uv)); return v + ((uv * q.w) + uuv) * static_cast<T>(2); } template <typename T, precision P> GLM_FUNC_QUALIFIER tvec3<T, P> operator*(tvec3<T, P> const & v, tquat<T, P> const & q) { return glm::inverse(q) * v; } template <typename T, precision P> GLM_FUNC_QUALIFIER tvec4<T, P> operator*(tquat<T, P> const& q, tvec4<T, P> const& v) { return detail::compute_quat_mul_vec4<T, P, detail::is_aligned<P>::value>::call(q, v); } template <typename T, precision P> GLM_FUNC_QUALIFIER tvec4<T, P> operator*(tvec4<T, P> const & v, tquat<T, P> const & q) { return glm::inverse(q) * v; } template <typename T, precision P> GLM_FUNC_QUALIFIER tquat<T, P> operator*(tquat<T, P> const & q, T const & s) { return tquat<T, P>( q.w * s, q.x * s, q.y * s, q.z * s); } template <typename T, precision P> GLM_FUNC_QUALIFIER tquat<T, P> operator*(T const & s, tquat<T, P> const & q) { return q * s; } template <typename T, precision P> GLM_FUNC_QUALIFIER tquat<T, P> operator/(tquat<T, P> const & q, T const & s) { return tquat<T, P>( q.w / s, q.x / s, q.y / s, q.z / s); } // -- Boolean operators -- template <typename T, precision P> GLM_FUNC_QUALIFIER bool operator==(tquat<T, P> const & q1, tquat<T, P> const & q2) { return (q1.x == q2.x) && (q1.y == q2.y) && (q1.z == q2.z) && (q1.w == q2.w); } template <typename T, precision P> GLM_FUNC_QUALIFIER bool operator!=(tquat<T, P> const & q1, tquat<T, P> const & q2) { return (q1.x != q2.x) || (q1.y != q2.y) || (q1.z != q2.z) || (q1.w != q2.w); } // -- Operations -- template <typename T, precision P> GLM_FUNC_QUALIFIER T length(tquat<T, P> const & q) { return glm::sqrt(dot(q, q)); } template <typename T, precision P> GLM_FUNC_QUALIFIER tquat<T, P> normalize(tquat<T, P> const & q) { T len = length(q); if(len <= T(0)) // Problem return tquat<T, P>(1, 0, 0, 0); T oneOverLen = T(1) / len; return tquat<T, P>(q.w * oneOverLen, q.x * oneOverLen, q.y * oneOverLen, q.z * oneOverLen); } template <typename T, precision P> GLM_FUNC_QUALIFIER tquat<T, P> cross(tquat<T, P> const & q1, tquat<T, P> const & q2) { return tquat<T, P>( q1.w * q2.w - q1.x * q2.x - q1.y * q2.y - q1.z * q2.z, q1.w * q2.x + q1.x * q2.w + q1.y * q2.z - q1.z * q2.y, q1.w * q2.y + q1.y * q2.w + q1.z * q2.x - q1.x * q2.z, q1.w * q2.z + q1.z * q2.w + q1.x * q2.y - q1.y * q2.x); } /* // (x * sin(1 - a) * angle / sin(angle)) + (y * sin(a) * angle / sin(angle)) template <typename T, precision P> GLM_FUNC_QUALIFIER tquat<T, P> mix(tquat<T, P> const & x, tquat<T, P> const & y, T const & a) { if(a <= T(0)) return x; if(a >= T(1)) return y; float fCos = dot(x, y); tquat<T, P> y2(y); //BUG!!! tquat<T, P> y2; if(fCos < T(0)) { y2 = -y; fCos = -fCos; } //if(fCos > 1.0f) // problem float k0, k1; if(fCos > T(0.9999)) { k0 = T(1) - a; k1 = T(0) + a; //BUG!!! 1.0f + a; } else { T fSin = sqrt(T(1) - fCos * fCos); T fAngle = atan(fSin, fCos); T fOneOverSin = static_cast<T>(1) / fSin; k0 = sin((T(1) - a) * fAngle) * fOneOverSin; k1 = sin((T(0) + a) * fAngle) * fOneOverSin; } return tquat<T, P>( k0 * x.w + k1 * y2.w, k0 * x.x + k1 * y2.x, k0 * x.y + k1 * y2.y, k0 * x.z + k1 * y2.z); } template <typename T, precision P> GLM_FUNC_QUALIFIER tquat<T, P> mix2 ( tquat<T, P> const & x, tquat<T, P> const & y, T const & a ) { bool flip = false; if(a <= static_cast<T>(0)) return x; if(a >= static_cast<T>(1)) return y; T cos_t = dot(x, y); if(cos_t < T(0)) { cos_t = -cos_t; flip = true; } T alpha(0), beta(0); if(T(1) - cos_t < 1e-7) beta = static_cast<T>(1) - alpha; else { T theta = acos(cos_t); T sin_t = sin(theta); beta = sin(theta * (T(1) - alpha)) / sin_t; alpha = sin(alpha * theta) / sin_t; } if(flip) alpha = -alpha; return normalize(beta * x + alpha * y); } */ template <typename T, precision P> GLM_FUNC_QUALIFIER tquat<T, P> mix(tquat<T, P> const & x, tquat<T, P> const & y, T a) { T cosTheta = dot(x, y); // Perform a linear interpolation when cosTheta is close to 1 to avoid side effect of sin(angle) becoming a zero denominator if(cosTheta > T(1) - epsilon<T>()) { // Linear interpolation return tquat<T, P>( mix(x.w, y.w, a), mix(x.x, y.x, a), mix(x.y, y.y, a), mix(x.z, y.z, a)); } else { // Essential Mathematics, page 467 T angle = acos(cosTheta); return (sin((T(1) - a) * angle) * x + sin(a * angle) * y) / sin(angle); } } template <typename T, precision P> GLM_FUNC_QUALIFIER tquat<T, P> lerp(tquat<T, P> const & x, tquat<T, P> const & y, T a) { // Lerp is only defined in [0, 1] assert(a >= static_cast<T>(0)); assert(a <= static_cast<T>(1)); return x * (T(1) - a) + (y * a); } template <typename T, precision P> GLM_FUNC_QUALIFIER tquat<T, P> slerp(tquat<T, P> const & x, tquat<T, P> const & y, T a) { tquat<T, P> z = y; T cosTheta = dot(x, y); // If cosTheta < 0, the interpolation will take the long way around the sphere. // To fix this, one quat must be negated. if (cosTheta < T(0)) { z = -y; cosTheta = -cosTheta; } // Perform a linear interpolation when cosTheta is close to 1 to avoid side effect of sin(angle) becoming a zero denominator if(cosTheta > T(1) - epsilon<T>()) { // Linear interpolation return tquat<T, P>( mix(x.w, z.w, a), mix(x.x, z.x, a), mix(x.y, z.y, a), mix(x.z, z.z, a)); } else { // Essential Mathematics, page 467 T angle = acos(cosTheta); return (sin((T(1) - a) * angle) * x + sin(a * angle) * z) / sin(angle); } } template <typename T, precision P> GLM_FUNC_QUALIFIER tquat<T, P> rotate(tquat<T, P> const & q, T const & angle, tvec3<T, P> const & v) { tvec3<T, P> Tmp = v; // Axis of rotation must be normalised T len = glm::length(Tmp); if(abs(len - T(1)) > T(0.001)) { T oneOverLen = static_cast<T>(1) / len; Tmp.x *= oneOverLen; Tmp.y *= oneOverLen; Tmp.z *= oneOverLen; } T const AngleRad(angle); T const Sin = sin(AngleRad * T(0.5)); return q * tquat<T, P>(cos(AngleRad * T(0.5)), Tmp.x * Sin, Tmp.y * Sin, Tmp.z * Sin); //return gtc::quaternion::cross(q, tquat<T, P>(cos(AngleRad * T(0.5)), Tmp.x * fSin, Tmp.y * fSin, Tmp.z * fSin)); } template <typename T, precision P> GLM_FUNC_QUALIFIER tvec3<T, P> eulerAngles(tquat<T, P> const & x) { return tvec3<T, P>(pitch(x), yaw(x), roll(x)); } template <typename T, precision P> GLM_FUNC_QUALIFIER T roll(tquat<T, P> const & q) { return T(atan(T(2) * (q.x * q.y + q.w * q.z), q.w * q.w + q.x * q.x - q.y * q.y - q.z * q.z)); } template <typename T, precision P> GLM_FUNC_QUALIFIER T pitch(tquat<T, P> const & q) { return T(atan(T(2) * (q.y * q.z + q.w * q.x), q.w * q.w - q.x * q.x - q.y * q.y + q.z * q.z)); } template <typename T, precision P> GLM_FUNC_QUALIFIER T yaw(tquat<T, P> const & q) { return asin(clamp(T(-2) * (q.x * q.z - q.w * q.y), T(-1), T(1))); } template <typename T, precision P> GLM_FUNC_QUALIFIER tmat3x3<T, P> mat3_cast(tquat<T, P> const & q) { tmat3x3<T, P> Result(T(1)); T qxx(q.x * q.x); T qyy(q.y * q.y); T qzz(q.z * q.z); T qxz(q.x * q.z); T qxy(q.x * q.y); T qyz(q.y * q.z); T qwx(q.w * q.x); T qwy(q.w * q.y); T qwz(q.w * q.z); Result[0][0] = 1 - 2 * (qyy + qzz); Result[0][1] = 2 * (qxy + qwz); Result[0][2] = 2 * (qxz - qwy); Result[1][0] = 2 * (qxy - qwz); Result[1][1] = 1 - 2 * (qxx + qzz); Result[1][2] = 2 * (qyz + qwx); Result[2][0] = 2 * (qxz + qwy); Result[2][1] = 2 * (qyz - qwx); Result[2][2] = 1 - 2 * (qxx + qyy); return Result; } template <typename T, precision P> GLM_FUNC_QUALIFIER tmat4x4<T, P> mat4_cast(tquat<T, P> const & q) { return tmat4x4<T, P>(mat3_cast(q)); } template <typename T, precision P> GLM_FUNC_QUALIFIER tquat<T, P> quat_cast(tmat3x3<T, P> const & m) { T fourXSquaredMinus1 = m[0][0] - m[1][1] - m[2][2]; T fourYSquaredMinus1 = m[1][1] - m[0][0] - m[2][2]; T fourZSquaredMinus1 = m[2][2] - m[0][0] - m[1][1]; T fourWSquaredMinus1 = m[0][0] + m[1][1] + m[2][2]; int biggestIndex = 0; T fourBiggestSquaredMinus1 = fourWSquaredMinus1; if(fourXSquaredMinus1 > fourBiggestSquaredMinus1) { fourBiggestSquaredMinus1 = fourXSquaredMinus1; biggestIndex = 1; } if(fourYSquaredMinus1 > fourBiggestSquaredMinus1) { fourBiggestSquaredMinus1 = fourYSquaredMinus1; biggestIndex = 2; } if(fourZSquaredMinus1 > fourBiggestSquaredMinus1) { fourBiggestSquaredMinus1 = fourZSquaredMinus1; biggestIndex = 3; } T biggestVal = sqrt(fourBiggestSquaredMinus1 + T(1)) * T(0.5); T mult = static_cast<T>(0.25) / biggestVal; tquat<T, P> Result(uninitialize); switch(biggestIndex) { case 0: Result.w = biggestVal; Result.x = (m[1][2] - m[2][1]) * mult; Result.y = (m[2][0] - m[0][2]) * mult; Result.z = (m[0][1] - m[1][0]) * mult; break; case 1: Result.w = (m[1][2] - m[2][1]) * mult; Result.x = biggestVal; Result.y = (m[0][1] + m[1][0]) * mult; Result.z = (m[2][0] + m[0][2]) * mult; break; case 2: Result.w = (m[2][0] - m[0][2]) * mult; Result.x = (m[0][1] + m[1][0]) * mult; Result.y = biggestVal; Result.z = (m[1][2] + m[2][1]) * mult; break; case 3: Result.w = (m[0][1] - m[1][0]) * mult; Result.x = (m[2][0] + m[0][2]) * mult; Result.y = (m[1][2] + m[2][1]) * mult; Result.z = biggestVal; break; default: // Silence a -Wswitch-default warning in GCC. Should never actually get here. Assert is just for sanity. assert(false); break; } return Result; } template <typename T, precision P> GLM_FUNC_QUALIFIER tquat<T, P> quat_cast(tmat4x4<T, P> const & m4) { return quat_cast(tmat3x3<T, P>(m4)); } template <typename T, precision P> GLM_FUNC_QUALIFIER T angle(tquat<T, P> const & x) { return acos(x.w) * T(2); } template <typename T, precision P> GLM_FUNC_QUALIFIER tvec3<T, P> axis(tquat<T, P> const & x) { T tmp1 = static_cast<T>(1) - x.w * x.w; if(tmp1 <= static_cast<T>(0)) return tvec3<T, P>(0, 0, 1); T tmp2 = static_cast<T>(1) / sqrt(tmp1); return tvec3<T, P>(x.x * tmp2, x.y * tmp2, x.z * tmp2); } template <typename T, precision P> GLM_FUNC_QUALIFIER tquat<T, P> angleAxis(T const & angle, tvec3<T, P> const & v) { tquat<T, P> Result(uninitialize); T const a(angle); T const s = glm::sin(a * static_cast<T>(0.5)); Result.w = glm::cos(a * static_cast<T>(0.5)); Result.x = v.x * s; Result.y = v.y * s; Result.z = v.z * s; return Result; } template <typename T, precision P> GLM_FUNC_QUALIFIER tvec4<bool, P> lessThan(tquat<T, P> const & x, tquat<T, P> const & y) { tvec4<bool, P> Result(uninitialize); for(length_t i = 0; i < x.length(); ++i) Result[i] = x[i] < y[i]; return Result; } template <typename T, precision P> GLM_FUNC_QUALIFIER tvec4<bool, P> lessThanEqual(tquat<T, P> const & x, tquat<T, P> const & y) { tvec4<bool, P> Result(uninitialize); for(length_t i = 0; i < x.length(); ++i) Result[i] = x[i] <= y[i]; return Result; } template <typename T, precision P> GLM_FUNC_QUALIFIER tvec4<bool, P> greaterThan(tquat<T, P> const & x, tquat<T, P> const & y) { tvec4<bool, P> Result(uninitialize); for(length_t i = 0; i < x.length(); ++i) Result[i] = x[i] > y[i]; return Result; } template <typename T, precision P> GLM_FUNC_QUALIFIER tvec4<bool, P> greaterThanEqual(tquat<T, P> const & x, tquat<T, P> const & y) { tvec4<bool, P> Result(uninitialize); for(length_t i = 0; i < x.length(); ++i) Result[i] = x[i] >= y[i]; return Result; } template <typename T, precision P> GLM_FUNC_QUALIFIER tvec4<bool, P> equal(tquat<T, P> const & x, tquat<T, P> const & y) { tvec4<bool, P> Result(uninitialize); for(length_t i = 0; i < x.length(); ++i) Result[i] = x[i] == y[i]; return Result; } template <typename T, precision P> GLM_FUNC_QUALIFIER tvec4<bool, P> notEqual(tquat<T, P> const & x, tquat<T, P> const & y) { tvec4<bool, P> Result(uninitialize); for(length_t i = 0; i < x.length(); ++i) Result[i] = x[i] != y[i]; return Result; } template <typename T, precision P> GLM_FUNC_QUALIFIER tvec4<bool, P> isnan(tquat<T, P> const& q) { GLM_STATIC_ASSERT(std::numeric_limits<T>::is_iec559, "'isnan' only accept floating-point inputs"); return tvec4<bool, P>(isnan(q.x), isnan(q.y), isnan(q.z), isnan(q.w)); } template <typename T, precision P> GLM_FUNC_QUALIFIER tvec4<bool, P> isinf(tquat<T, P> const& q) { GLM_STATIC_ASSERT(std::numeric_limits<T>::is_iec559, "'isinf' only accept floating-point inputs"); return tvec4<bool, P>(isinf(q.x), isinf(q.y), isinf(q.z), isinf(q.w)); } }//namespace glm #if GLM_ARCH != GLM_ARCH_PURE && GLM_HAS_ALIGNED_TYPE # include "quaternion_simd.inl" #endif
// Copyright 2021 The Autoware Foundation // // 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. #ifndef OSQP_INTERFACE__OSQP_INTERFACE_HPP_ #define OSQP_INTERFACE__OSQP_INTERFACE_HPP_ #include <limits> #include <memory> #include <string> #include <tuple> #include <vector> #include "common/types.hpp" #include "eigen3/Eigen/Core" #include "osqp/osqp.h" #include "osqp_interface/visibility_control.hpp" #include "osqp_interface/csc_matrix_conv.hpp" namespace autoware { namespace common { namespace osqp { constexpr c_float INF = OSQP_INFTY; using autoware::common::types::float64_t; using autoware::common::types::bool8_t; /** * Implementation of a native C++ interface for the OSQP solver. * */ class OSQP_INTERFACE_PUBLIC OSQPInterface { private: std::unique_ptr<OSQPWorkspace, std::function<void(OSQPWorkspace *)>> m_work; std::unique_ptr<OSQPSettings> m_settings; std::unique_ptr<OSQPData> m_data; // store last work info since work is cleaned up at every execution to prevent memory leak. OSQPInfo m_latest_work_info; // Number of parameters to optimize int64_t m_param_n; // Flag to check if the current work exists bool8_t m_work_initialized = false; // Exitflag int64_t m_exitflag; // Runs the solver on the stored problem. std::tuple<std::vector<float64_t>, std::vector<float64_t>, int64_t, int64_t, int64_t> solve(); static void OSQPWorkspaceDeleter(OSQPWorkspace * ptr) noexcept; public: /// \brief Constructor without problem formulation explicit OSQPInterface( const c_float eps_abs = std::numeric_limits<c_float>::epsilon(), const bool8_t polish = true); /// \brief Constructor with problem setup /// \param P: (n,n) matrix defining relations between parameters. /// \param A: (m,n) matrix defining parameter constraints relative to the lower and upper bound. /// \param q: (n) vector defining the linear cost of the problem. /// \param l: (m) vector defining the lower bound problem constraint. /// \param u: (m) vector defining the upper bound problem constraint. /// \param eps_abs: Absolute convergence tolerance. OSQPInterface( const Eigen::MatrixXd & P, const Eigen::MatrixXd & A, const std::vector<float64_t> & q, const std::vector<float64_t> & l, const std::vector<float64_t> & u, const c_float eps_abs); OSQPInterface( const CSC_Matrix & P, const CSC_Matrix & A, const std::vector<float64_t> & q, const std::vector<float64_t> & l, const std::vector<float64_t> & u, const c_float eps_abs); /**************** * OPTIMIZATION ****************/ /// \brief Solves the stored convex quadratic program (QP) problem using the OSQP solver. // /// \return The function returns a tuple containing the solution as two float vectors. /// \return The first element of the tuple contains the 'primal' solution. /// \return The second element contains the 'lagrange multiplier' solution. /// \return The third element contains an integer with solver polish status information. /// \details How to use: /// \details 1. Generate the Eigen matrices P, A and vectors q, l, u according to the problem. /// \details 2. Initialize the interface and set up the problem. /// \details osqp_interface = OSQPInterface(P, A, q, l, u, 1e-6); /// \details 3. Call the optimization function. /// \details std::tuple<std::vector<float64_t>, std::vector<float64_t>> result; /// \details result = osqp_interface.optimize(); /// \details 4. Access the optimized parameters. /// \details std::vector<float> param = std::get<0>(result); /// \details float64_t x_0 = param[0]; /// \details float64_t x_1 = param[1]; std::tuple<std::vector<float64_t>, std::vector<float64_t>, int64_t, int64_t, int64_t> optimize(); /// \brief Solves convex quadratic programs (QPs) using the OSQP solver. /// \return The function returns a tuple containing the solution as two float vectors. /// \return The first element of the tuple contains the 'primal' solution. /// \return The second element contains the 'lagrange multiplier' solution. /// \return The third element contains an integer with solver polish status information. /// \details How to use: /// \details 1. Generate the Eigen matrices P, A and vectors q, l, u according to the problem. /// \details 2. Initialize the interface. /// \details osqp_interface = OSQPInterface(1e-6); /// \details 3. Call the optimization function with the problem formulation. /// \details std::tuple<std::vector<float64_t>, std::vector<float64_t>> result; /// \details result = osqp_interface.optimize(P, A, q, l, u, 1e-6); /// \details 4. Access the optimized parameters. /// \details std::vector<float> param = std::get<0>(result); /// \details float64_t x_0 = param[0]; /// \details float64_t x_1 = param[1]; std::tuple<std::vector<float64_t>, std::vector<float64_t>, int64_t, int64_t, int64_t> optimize( const Eigen::MatrixXd & P, const Eigen::MatrixXd & A, const std::vector<float64_t> & q, const std::vector<float64_t> & l, const std::vector<float64_t> & u); /// \brief Converts the input data and sets up the workspace object. /// \param P (n,n) matrix defining relations between parameters. /// \param A (m,n) matrix defining parameter constraints relative to the lower and upper bound. /// \param q (n) vector defining the linear cost of the problem. /// \param l (m) vector defining the lower bound problem constraint. /// \param u (m) vector defining the upper bound problem constraint. int64_t initializeProblem( const Eigen::MatrixXd & P, const Eigen::MatrixXd & A, const std::vector<float64_t> & q, const std::vector<float64_t> & l, const std::vector<float64_t> & u); int64_t initializeProblem( CSC_Matrix P, CSC_Matrix A, const std::vector<float64_t> & q, const std::vector<float64_t> & l, const std::vector<float64_t> & u); // Updates problem parameters while keeping solution in memory. // // Args: // P_new: (n,n) matrix defining relations between parameters. // A_new: (m,n) matrix defining parameter constraints relative to the lower and upper bound. // q_new: (n) vector defining the linear cost of the problem. // l_new: (m) vector defining the lower bound problem constraint. // u_new: (m) vector defining the upper bound problem constraint. void updateP(const Eigen::MatrixXd & P_new); void updateCscP(const CSC_Matrix & P_csc); void updateA(const Eigen::MatrixXd & A_new); void updateCscA(const CSC_Matrix & A_csc); void updateQ(const std::vector<double> & q_new); void updateL(const std::vector<double> & l_new); void updateU(const std::vector<double> & u_new); void updateBounds(const std::vector<double> & l_new, const std::vector<double> & u_new); void updateEpsAbs(const double eps_abs); void updateEpsRel(const double eps_rel); void updateMaxIter(const int iter); void updateVerbose(const bool verbose); void updateRhoInterval(const int rho_interval); void updateRho(const double rho); void updateAlpha(const double alpha); /// \brief Get the number of iteration taken to solve the problem inline int64_t getTakenIter() const {return static_cast<int64_t>(m_latest_work_info.iter);} /// \brief Get the status message for the latest problem solved inline std::string getStatusMessage() const { return static_cast<std::string>(m_latest_work_info.status); } /// \brief Get the status value for the latest problem solved inline int64_t getStatus() const {return static_cast<int64_t>(m_latest_work_info.status_val);} /// \brief Get the status polish for the latest problem solved inline int64_t getStatusPolish() const { return static_cast<int64_t>(m_latest_work_info.status_polish); } /// \brief Get the runtime of the latest problem solved inline float64_t getRunTime() const {return m_latest_work_info.run_time;} /// \brief Get the objective value the latest problem solved inline float64_t getObjVal() const {return m_latest_work_info.obj_val;} /// \brief Returns flag asserting interface condition (Healthy condition: 0). inline int64_t getExitFlag() const {return m_exitflag;} }; } // namespace osqp } // namespace common } // namespace autoware #endif // OSQP_INTERFACE__OSQP_INTERFACE_HPP_
#include<iostream> #include<cstdlib> #include<queue> #include<cstdio> using namespace std; /* C++ Program to Round Robin*/ typedef struct process { int id,at,bt,st,ft,pr; float wt,tat; }process; process p[10],p1[10],temp; queue<int> q1; int accept(int ch); void turnwait(int n); void display(int n); void ganttrr(int n); int main() { int i,n,ts,ch,j,x; p[0].tat=0; p[0].wt=0; n=accept(ch); ganttrr(n); turnwait(n); display(n); return 0; } int accept(int ch) { int i,n; cout<<"Enter the Total Number of Process: "; cin>>n; if(n==0) { printf("Invalid"); exit(1); } cout<<endl; for(i=1;i<=n;i++) { printf("Enter an Arrival Time of the Process P%d: ",i); scanf("%d",&p[i].at); p[i].id=i; } cout<<endl; for(i=1;i<=n;i++) { printf("Enter a Burst Time of the Process P%d: ",i); scanf("%d",&p[i].bt); } for(i=1;i<=n;i++) { p1[i]=p[i]; } return n; } void ganttrr(int n) { int i,ts,m,nextval,nextarr; nextval=p1[1].at; i=1; cout<<"\nEnter the Time Slice or Quantum: "; cin>>ts; for(i=1;i<=n && p1[i].at<=nextval;i++) { q1.push(p1[i].id); } while(!q1.empty()) { m=q1.front(); q1.pop(); if(p1[m].bt>=ts) { nextval=nextval+ts; } else { nextval=nextval+p1[m].bt; } if(p1[m].bt>=ts) { p1[m].bt=p1[m].bt-ts; } else { p1[m].bt=0; } while(i<=n&&p1[i].at<=nextval) { q1.push(p1[i].id); i++; } if(p1[m].bt>0) { q1.push(m); } if(p1[m].bt<=0) { p[m].ft=nextval; } } } void turnwait(int n) { int i; for(i=1;i<=n;i++) { p[i].tat=p[i].ft-p[i].at; p[i].wt=p[i].tat-p[i].bt; p[0].tat=p[0].tat+p[i].tat; p[0].wt=p[0].wt+p[i].wt; } p[0].tat=p[0].tat/n; p[0].wt=p[0].wt/n; } void display(int n) { int i; printf("\nProcess\tAT\tBT\tCT\tTAT\t\tWT"); for(i=1;i<=n;i++) { printf("\nP%d\t%d\t%d\t%d\t%f\t%f",p[i].id,p[i].at,p[i].bt,p[i].ft,p[i].tat,p[i].wt); } cout<<"\n=====================================================\n"; printf("\nAverage Turn Around Time: %f",p[0].tat); printf("\nAverage Waiting Time: %f\n",p[0].wt); }
// Copyright (c) 2011-present, Facebook, Inc. All rights reserved. // This source code is licensed under both the GPLv2 (found in the // COPYING file in the root directory) and Apache 2.0 License // (found in the LICENSE.Apache file in the root directory). // #include "monitoring/statistics.h" #include <algorithm> #include <cinttypes> #include <cstdio> #include "port/likely.h" #include "rocksdb/statistics.h" namespace ROCKSDB_NAMESPACE { // The order of items listed in Tickers should be the same as // the order listed in TickersNameMap const std::vector<std::pair<Tickers, std::string>> TickersNameMap = { {BLOCK_CACHE_MISS, "rocksdb.block.cache.miss"}, {BLOCK_CACHE_HIT, "rocksdb.block.cache.hit"}, {BLOCK_CACHE_ADD, "rocksdb.block.cache.add"}, {BLOCK_CACHE_ADD_FAILURES, "rocksdb.block.cache.add.failures"}, {BLOCK_CACHE_INDEX_MISS, "rocksdb.block.cache.index.miss"}, {BLOCK_CACHE_INDEX_HIT, "rocksdb.block.cache.index.hit"}, {BLOCK_CACHE_INDEX_ADD, "rocksdb.block.cache.index.add"}, {BLOCK_CACHE_INDEX_BYTES_INSERT, "rocksdb.block.cache.index.bytes.insert"}, {BLOCK_CACHE_INDEX_BYTES_EVICT, "rocksdb.block.cache.index.bytes.evict"}, {BLOCK_CACHE_FILTER_MISS, "rocksdb.block.cache.filter.miss"}, {BLOCK_CACHE_FILTER_HIT, "rocksdb.block.cache.filter.hit"}, {BLOCK_CACHE_FILTER_ADD, "rocksdb.block.cache.filter.add"}, {BLOCK_CACHE_FILTER_BYTES_INSERT, "rocksdb.block.cache.filter.bytes.insert"}, {BLOCK_CACHE_FILTER_BYTES_EVICT, "rocksdb.block.cache.filter.bytes.evict"}, {BLOCK_CACHE_DATA_MISS, "rocksdb.block.cache.data.miss"}, {BLOCK_CACHE_DATA_HIT, "rocksdb.block.cache.data.hit"}, {BLOCK_CACHE_DATA_ADD, "rocksdb.block.cache.data.add"}, {BLOCK_CACHE_DATA_BYTES_INSERT, "rocksdb.block.cache.data.bytes.insert"}, {BLOCK_CACHE_BYTES_READ, "rocksdb.block.cache.bytes.read"}, {BLOCK_CACHE_BYTES_WRITE, "rocksdb.block.cache.bytes.write"}, {BLOOM_FILTER_USEFUL, "rocksdb.bloom.filter.useful"}, {BLOOM_FILTER_FULL_POSITIVE, "rocksdb.bloom.filter.full.positive"}, {BLOOM_FILTER_FULL_TRUE_POSITIVE, "rocksdb.bloom.filter.full.true.positive"}, {BLOOM_FILTER_MICROS, "rocksdb.bloom.filter.micros"}, {PERSISTENT_CACHE_HIT, "rocksdb.persistent.cache.hit"}, {PERSISTENT_CACHE_MISS, "rocksdb.persistent.cache.miss"}, {SIM_BLOCK_CACHE_HIT, "rocksdb.sim.block.cache.hit"}, {SIM_BLOCK_CACHE_MISS, "rocksdb.sim.block.cache.miss"}, {MEMTABLE_HIT, "rocksdb.memtable.hit"}, {MEMTABLE_MISS, "rocksdb.memtable.miss"}, {GET_HIT_L0, "rocksdb.l0.hit"}, {GET_HIT_L1, "rocksdb.l1.hit"}, {GET_HIT_L2_AND_UP, "rocksdb.l2andup.hit"}, {COMPACTION_KEY_DROP_NEWER_ENTRY, "rocksdb.compaction.key.drop.new"}, {COMPACTION_KEY_DROP_OBSOLETE, "rocksdb.compaction.key.drop.obsolete"}, {COMPACTION_KEY_DROP_RANGE_DEL, "rocksdb.compaction.key.drop.range_del"}, {COMPACTION_KEY_DROP_USER, "rocksdb.compaction.key.drop.user"}, {COMPACTION_RANGE_DEL_DROP_OBSOLETE, "rocksdb.compaction.range_del.drop.obsolete"}, {COMPACTION_OPTIMIZED_DEL_DROP_OBSOLETE, "rocksdb.compaction.optimized.del.drop.obsolete"}, {COMPACTION_CANCELLED, "rocksdb.compaction.cancelled"}, {NUMBER_KEYS_WRITTEN, "rocksdb.number.keys.written"}, {NUMBER_KEYS_READ, "rocksdb.number.keys.read"}, {NUMBER_KEYS_UPDATED, "rocksdb.number.keys.updated"}, {BYTES_WRITTEN, "rocksdb.bytes.written"}, {BYTES_READ, "rocksdb.bytes.read"}, {NUMBER_DB_SEEK, "rocksdb.number.db.seek"}, {NUMBER_DB_NEXT, "rocksdb.number.db.next"}, {NUMBER_DB_PREV, "rocksdb.number.db.prev"}, {NUMBER_DB_SEEK_FOUND, "rocksdb.number.db.seek.found"}, {NUMBER_DB_NEXT_FOUND, "rocksdb.number.db.next.found"}, {NUMBER_DB_PREV_FOUND, "rocksdb.number.db.prev.found"}, {ITER_BYTES_READ, "rocksdb.db.iter.bytes.read"}, {NO_FILE_CLOSES, "rocksdb.no.file.closes"}, {NO_FILE_OPENS, "rocksdb.no.file.opens"}, {NO_FILE_ERRORS, "rocksdb.no.file.errors"}, {STALL_L0_SLOWDOWN_MICROS, "rocksdb.l0.slowdown.micros"}, {STALL_MEMTABLE_COMPACTION_MICROS, "rocksdb.memtable.compaction.micros"}, {STALL_L0_NUM_FILES_MICROS, "rocksdb.l0.num.files.stall.micros"}, {STALL_MICROS, "rocksdb.stall.micros"}, {DB_MUTEX_WAIT_MICROS, "rocksdb.db.mutex.wait.micros"}, {RATE_LIMIT_DELAY_MILLIS, "rocksdb.rate.limit.delay.millis"}, {NO_ITERATORS, "rocksdb.num.iterators"}, {NUMBER_MULTIGET_CALLS, "rocksdb.number.multiget.get"}, {NUMBER_MULTIGET_KEYS_READ, "rocksdb.number.multiget.keys.read"}, {NUMBER_MULTIGET_BYTES_READ, "rocksdb.number.multiget.bytes.read"}, {NUMBER_FILTERED_DELETES, "rocksdb.number.deletes.filtered"}, {NUMBER_MERGE_FAILURES, "rocksdb.number.merge.failures"}, {BLOOM_FILTER_PREFIX_CHECKED, "rocksdb.bloom.filter.prefix.checked"}, {BLOOM_FILTER_PREFIX_USEFUL, "rocksdb.bloom.filter.prefix.useful"}, {NUMBER_OF_RESEEKS_IN_ITERATION, "rocksdb.number.reseeks.iteration"}, {GET_UPDATES_SINCE_CALLS, "rocksdb.getupdatessince.calls"}, {BLOCK_CACHE_COMPRESSED_MISS, "rocksdb.block.cachecompressed.miss"}, {BLOCK_CACHE_COMPRESSED_HIT, "rocksdb.block.cachecompressed.hit"}, {BLOCK_CACHE_COMPRESSED_ADD, "rocksdb.block.cachecompressed.add"}, {BLOCK_CACHE_COMPRESSED_ADD_FAILURES, "rocksdb.block.cachecompressed.add.failures"}, {WAL_FILE_SYNCED, "rocksdb.wal.synced"}, {WAL_FILE_BYTES, "rocksdb.wal.bytes"}, {WRITE_DONE_BY_SELF, "rocksdb.write.self"}, {WRITE_DONE_BY_OTHER, "rocksdb.write.other"}, {WRITE_TIMEDOUT, "rocksdb.write.timeout"}, {WRITE_WITH_WAL, "rocksdb.write.wal"}, {COMPACT_READ_BYTES, "rocksdb.compact.read.bytes"}, {COMPACT_WRITE_BYTES, "rocksdb.compact.write.bytes"}, {FLUSH_WRITE_BYTES, "rocksdb.flush.write.bytes"}, {NUMBER_DIRECT_LOAD_TABLE_PROPERTIES, "rocksdb.number.direct.load.table.properties"}, {NUMBER_SUPERVERSION_ACQUIRES, "rocksdb.number.superversion_acquires"}, {NUMBER_SUPERVERSION_RELEASES, "rocksdb.number.superversion_releases"}, {NUMBER_SUPERVERSION_CLEANUPS, "rocksdb.number.superversion_cleanups"}, {NUMBER_BLOCK_COMPRESSED, "rocksdb.number.block.compressed"}, {NUMBER_BLOCK_DECOMPRESSED, "rocksdb.number.block.decompressed"}, {NUMBER_BLOCK_NOT_COMPRESSED, "rocksdb.number.block.not_compressed"}, {MERGE_OPERATION_TOTAL_TIME, "rocksdb.merge.operation.time.nanos"}, {FILTER_OPERATION_TOTAL_TIME, "rocksdb.filter.operation.time.nanos"}, {ROW_CACHE_HIT, "rocksdb.row.cache.hit"}, {ROW_CACHE_MISS, "rocksdb.row.cache.miss"}, {READ_AMP_ESTIMATE_USEFUL_BYTES, "rocksdb.read.amp.estimate.useful.bytes"}, {READ_AMP_TOTAL_READ_BYTES, "rocksdb.read.amp.total.read.bytes"}, {NUMBER_RATE_LIMITER_DRAINS, "rocksdb.number.rate_limiter.drains"}, {NUMBER_ITER_SKIP, "rocksdb.number.iter.skip"}, {BLOB_DB_NUM_PUT, "rocksdb.blobdb.num.put"}, {BLOB_DB_NUM_WRITE, "rocksdb.blobdb.num.write"}, {BLOB_DB_NUM_GET, "rocksdb.blobdb.num.get"}, {BLOB_DB_NUM_MULTIGET, "rocksdb.blobdb.num.multiget"}, {BLOB_DB_NUM_SEEK, "rocksdb.blobdb.num.seek"}, {BLOB_DB_NUM_NEXT, "rocksdb.blobdb.num.next"}, {BLOB_DB_NUM_PREV, "rocksdb.blobdb.num.prev"}, {BLOB_DB_NUM_KEYS_WRITTEN, "rocksdb.blobdb.num.keys.written"}, {BLOB_DB_NUM_KEYS_READ, "rocksdb.blobdb.num.keys.read"}, {BLOB_DB_BYTES_WRITTEN, "rocksdb.blobdb.bytes.written"}, {BLOB_DB_BYTES_READ, "rocksdb.blobdb.bytes.read"}, {BLOB_DB_WRITE_INLINED, "rocksdb.blobdb.write.inlined"}, {BLOB_DB_WRITE_INLINED_TTL, "rocksdb.blobdb.write.inlined.ttl"}, {BLOB_DB_WRITE_BLOB, "rocksdb.blobdb.write.blob"}, {BLOB_DB_WRITE_BLOB_TTL, "rocksdb.blobdb.write.blob.ttl"}, {BLOB_DB_BLOB_FILE_BYTES_WRITTEN, "rocksdb.blobdb.blob.file.bytes.written"}, {BLOB_DB_BLOB_FILE_BYTES_READ, "rocksdb.blobdb.blob.file.bytes.read"}, {BLOB_DB_BLOB_FILE_SYNCED, "rocksdb.blobdb.blob.file.synced"}, {BLOB_DB_BLOB_INDEX_EXPIRED_COUNT, "rocksdb.blobdb.blob.index.expired.count"}, {BLOB_DB_BLOB_INDEX_EXPIRED_SIZE, "rocksdb.blobdb.blob.index.expired.size"}, {BLOB_DB_BLOB_INDEX_EVICTED_COUNT, "rocksdb.blobdb.blob.index.evicted.count"}, {BLOB_DB_BLOB_INDEX_EVICTED_SIZE, "rocksdb.blobdb.blob.index.evicted.size"}, {BLOB_DB_GC_NUM_FILES, "rocksdb.blobdb.gc.num.files"}, {BLOB_DB_GC_NUM_NEW_FILES, "rocksdb.blobdb.gc.num.new.files"}, {BLOB_DB_GC_FAILURES, "rocksdb.blobdb.gc.failures"}, {BLOB_DB_GC_NUM_KEYS_OVERWRITTEN, "rocksdb.blobdb.gc.num.keys.overwritten"}, {BLOB_DB_GC_NUM_KEYS_EXPIRED, "rocksdb.blobdb.gc.num.keys.expired"}, {BLOB_DB_GC_NUM_KEYS_RELOCATED, "rocksdb.blobdb.gc.num.keys.relocated"}, {BLOB_DB_GC_BYTES_OVERWRITTEN, "rocksdb.blobdb.gc.bytes.overwritten"}, {BLOB_DB_GC_BYTES_EXPIRED, "rocksdb.blobdb.gc.bytes.expired"}, {BLOB_DB_GC_BYTES_RELOCATED, "rocksdb.blobdb.gc.bytes.relocated"}, {BLOB_DB_FIFO_NUM_FILES_EVICTED, "rocksdb.blobdb.fifo.num.files.evicted"}, {BLOB_DB_FIFO_NUM_KEYS_EVICTED, "rocksdb.blobdb.fifo.num.keys.evicted"}, {BLOB_DB_FIFO_BYTES_EVICTED, "rocksdb.blobdb.fifo.bytes.evicted"}, {TXN_PREPARE_MUTEX_OVERHEAD, "rocksdb.txn.overhead.mutex.prepare"}, {TXN_OLD_COMMIT_MAP_MUTEX_OVERHEAD, "rocksdb.txn.overhead.mutex.old.commit.map"}, {TXN_DUPLICATE_KEY_OVERHEAD, "rocksdb.txn.overhead.duplicate.key"}, {TXN_SNAPSHOT_MUTEX_OVERHEAD, "rocksdb.txn.overhead.mutex.snapshot"}, {TXN_GET_TRY_AGAIN, "rocksdb.txn.get.tryagain"}, {NUMBER_MULTIGET_KEYS_FOUND, "rocksdb.number.multiget.keys.found"}, {NO_ITERATOR_CREATED, "rocksdb.num.iterator.created"}, {NO_ITERATOR_DELETED, "rocksdb.num.iterator.deleted"}, {BLOCK_CACHE_COMPRESSION_DICT_MISS, "rocksdb.block.cache.compression.dict.miss"}, {BLOCK_CACHE_COMPRESSION_DICT_HIT, "rocksdb.block.cache.compression.dict.hit"}, {BLOCK_CACHE_COMPRESSION_DICT_ADD, "rocksdb.block.cache.compression.dict.add"}, {BLOCK_CACHE_COMPRESSION_DICT_BYTES_INSERT, "rocksdb.block.cache.compression.dict.bytes.insert"}, {BLOCK_CACHE_COMPRESSION_DICT_BYTES_EVICT, "rocksdb.block.cache.compression.dict.bytes.evict"}, }; const std::vector<std::pair<Histograms, std::string>> HistogramsNameMap = { {DB_GET, "rocksdb.db.get.micros"}, {DB_WRITE, "rocksdb.db.write.micros"}, {COMPACTION_TIME, "rocksdb.compaction.times.micros"}, {COMPACTION_CPU_TIME, "rocksdb.compaction.times.cpu_micros"}, {SUBCOMPACTION_SETUP_TIME, "rocksdb.subcompaction.setup.times.micros"}, {TABLE_SYNC_MICROS, "rocksdb.table.sync.micros"}, {COMPACTION_OUTFILE_SYNC_MICROS, "rocksdb.compaction.outfile.sync.micros"}, {WAL_FILE_SYNC_MICROS, "rocksdb.wal.file.sync.micros"}, {MANIFEST_FILE_SYNC_MICROS, "rocksdb.manifest.file.sync.micros"}, {TABLE_OPEN_IO_MICROS, "rocksdb.table.open.io.micros"}, {DB_MULTIGET, "rocksdb.db.multiget.micros"}, {READ_BLOCK_COMPACTION_MICROS, "rocksdb.read.block.compaction.micros"}, {READ_BLOCK_GET_MICROS, "rocksdb.read.block.get.micros"}, {WRITE_RAW_BLOCK_MICROS, "rocksdb.write.raw.block.micros"}, {STALL_L0_SLOWDOWN_COUNT, "rocksdb.l0.slowdown.count"}, {STALL_MEMTABLE_COMPACTION_COUNT, "rocksdb.memtable.compaction.count"}, {STALL_L0_NUM_FILES_COUNT, "rocksdb.num.files.stall.count"}, {HARD_RATE_LIMIT_DELAY_COUNT, "rocksdb.hard.rate.limit.delay.count"}, {SOFT_RATE_LIMIT_DELAY_COUNT, "rocksdb.soft.rate.limit.delay.count"}, {NUM_FILES_IN_SINGLE_COMPACTION, "rocksdb.numfiles.in.singlecompaction"}, {DB_SEEK, "rocksdb.db.seek.micros"}, {WRITE_STALL, "rocksdb.db.write.stall"}, {SST_READ_MICROS, "rocksdb.sst.read.micros"}, {NUM_SUBCOMPACTIONS_SCHEDULED, "rocksdb.num.subcompactions.scheduled"}, {BYTES_PER_READ, "rocksdb.bytes.per.read"}, {BYTES_PER_WRITE, "rocksdb.bytes.per.write"}, {BYTES_PER_MULTIGET, "rocksdb.bytes.per.multiget"}, {BYTES_COMPRESSED, "rocksdb.bytes.compressed"}, {BYTES_DECOMPRESSED, "rocksdb.bytes.decompressed"}, {COMPRESSION_TIMES_NANOS, "rocksdb.compression.times.nanos"}, {DECOMPRESSION_TIMES_NANOS, "rocksdb.decompression.times.nanos"}, {READ_NUM_MERGE_OPERANDS, "rocksdb.read.num.merge_operands"}, {BLOB_DB_KEY_SIZE, "rocksdb.blobdb.key.size"}, {BLOB_DB_VALUE_SIZE, "rocksdb.blobdb.value.size"}, {BLOB_DB_WRITE_MICROS, "rocksdb.blobdb.write.micros"}, {BLOB_DB_GET_MICROS, "rocksdb.blobdb.get.micros"}, {BLOB_DB_MULTIGET_MICROS, "rocksdb.blobdb.multiget.micros"}, {BLOB_DB_SEEK_MICROS, "rocksdb.blobdb.seek.micros"}, {BLOB_DB_NEXT_MICROS, "rocksdb.blobdb.next.micros"}, {BLOB_DB_PREV_MICROS, "rocksdb.blobdb.prev.micros"}, {BLOB_DB_BLOB_FILE_WRITE_MICROS, "rocksdb.blobdb.blob.file.write.micros"}, {BLOB_DB_BLOB_FILE_READ_MICROS, "rocksdb.blobdb.blob.file.read.micros"}, {BLOB_DB_BLOB_FILE_SYNC_MICROS, "rocksdb.blobdb.blob.file.sync.micros"}, {BLOB_DB_GC_MICROS, "rocksdb.blobdb.gc.micros"}, {BLOB_DB_COMPRESSION_MICROS, "rocksdb.blobdb.compression.micros"}, {BLOB_DB_DECOMPRESSION_MICROS, "rocksdb.blobdb.decompression.micros"}, {FLUSH_TIME, "rocksdb.db.flush.micros"}, {SST_BATCH_SIZE, "rocksdb.sst.batch.size"}, }; std::shared_ptr<Statistics> CreateDBStatistics() { return std::make_shared<StatisticsImpl>(nullptr); } StatisticsImpl::StatisticsImpl(std::shared_ptr<Statistics> stats) : stats_(std::move(stats)) {} StatisticsImpl::~StatisticsImpl() {} uint64_t StatisticsImpl::getTickerCount(uint32_t tickerType) const { MutexLock lock(&aggregate_lock_); return getTickerCountLocked(tickerType); } uint64_t StatisticsImpl::getTickerCountLocked(uint32_t tickerType) const { assert(tickerType < TICKER_ENUM_MAX); uint64_t res = 0; for (size_t core_idx = 0; core_idx < per_core_stats_.Size(); ++core_idx) { res += per_core_stats_.AccessAtCore(core_idx)->tickers_[tickerType]; } return res; } void StatisticsImpl::histogramData(uint32_t histogramType, HistogramData* const data) const { MutexLock lock(&aggregate_lock_); getHistogramImplLocked(histogramType)->Data(data); } std::unique_ptr<HistogramImpl> StatisticsImpl::getHistogramImplLocked( uint32_t histogramType) const { assert(histogramType < HISTOGRAM_ENUM_MAX); std::unique_ptr<HistogramImpl> res_hist(new HistogramImpl()); for (size_t core_idx = 0; core_idx < per_core_stats_.Size(); ++core_idx) { res_hist->Merge( per_core_stats_.AccessAtCore(core_idx)->histograms_[histogramType]); } return res_hist; } std::string StatisticsImpl::getHistogramString(uint32_t histogramType) const { MutexLock lock(&aggregate_lock_); return getHistogramImplLocked(histogramType)->ToString(); } void StatisticsImpl::setTickerCount(uint32_t tickerType, uint64_t count) { { MutexLock lock(&aggregate_lock_); setTickerCountLocked(tickerType, count); } if (stats_ && tickerType < TICKER_ENUM_MAX) { stats_->setTickerCount(tickerType, count); } } void StatisticsImpl::setTickerCountLocked(uint32_t tickerType, uint64_t count) { assert(tickerType < TICKER_ENUM_MAX); for (size_t core_idx = 0; core_idx < per_core_stats_.Size(); ++core_idx) { if (core_idx == 0) { per_core_stats_.AccessAtCore(core_idx)->tickers_[tickerType] = count; } else { per_core_stats_.AccessAtCore(core_idx)->tickers_[tickerType] = 0; } } } uint64_t StatisticsImpl::getAndResetTickerCount(uint32_t tickerType) { uint64_t sum = 0; { MutexLock lock(&aggregate_lock_); assert(tickerType < TICKER_ENUM_MAX); for (size_t core_idx = 0; core_idx < per_core_stats_.Size(); ++core_idx) { sum += per_core_stats_.AccessAtCore(core_idx)->tickers_[tickerType].exchange( 0, std::memory_order_relaxed); } } if (stats_ && tickerType < TICKER_ENUM_MAX) { stats_->setTickerCount(tickerType, 0); } return sum; } void StatisticsImpl::recordTick(uint32_t tickerType, uint64_t count) { assert(tickerType < TICKER_ENUM_MAX); per_core_stats_.Access()->tickers_[tickerType].fetch_add( count, std::memory_order_relaxed); if (stats_ && tickerType < TICKER_ENUM_MAX) { stats_->recordTick(tickerType, count); } } void StatisticsImpl::recordInHistogram(uint32_t histogramType, uint64_t value) { assert(histogramType < HISTOGRAM_ENUM_MAX); if (get_stats_level() <= StatsLevel::kExceptHistogramOrTimers) { return; } per_core_stats_.Access()->histograms_[histogramType].Add(value); if (stats_ && histogramType < HISTOGRAM_ENUM_MAX) { stats_->recordInHistogram(histogramType, value); } } Status StatisticsImpl::Reset() { MutexLock lock(&aggregate_lock_); for (uint32_t i = 0; i < TICKER_ENUM_MAX; ++i) { setTickerCountLocked(i, 0); } for (uint32_t i = 0; i < HISTOGRAM_ENUM_MAX; ++i) { for (size_t core_idx = 0; core_idx < per_core_stats_.Size(); ++core_idx) { per_core_stats_.AccessAtCore(core_idx)->histograms_[i].Clear(); } } return Status::OK(); } namespace { // a buffer size used for temp string buffers const int kTmpStrBufferSize = 200; } // namespace std::string StatisticsImpl::ToString() const { MutexLock lock(&aggregate_lock_); std::string res; res.reserve(20000); for (const auto& t : TickersNameMap) { assert(t.first < TICKER_ENUM_MAX); char buffer[kTmpStrBufferSize]; snprintf(buffer, kTmpStrBufferSize, "%s COUNT : %" PRIu64 "\n", t.second.c_str(), getTickerCountLocked(t.first)); res.append(buffer); } for (const auto& h : HistogramsNameMap) { assert(h.first < HISTOGRAM_ENUM_MAX); char buffer[kTmpStrBufferSize]; HistogramData hData; getHistogramImplLocked(h.first)->Data(&hData); // don't handle failures - buffer should always be big enough and arguments // should be provided correctly int ret = snprintf(buffer, kTmpStrBufferSize, "%s P50 : %f P95 : %f P99 : %f P100 : %f COUNT : %" PRIu64 " SUM : %" PRIu64 "\n", h.second.c_str(), hData.median, hData.percentile95, hData.percentile99, hData.max, hData.count, hData.sum); if (ret < 0 || ret >= kTmpStrBufferSize) { assert(false); continue; } res.append(buffer); } res.shrink_to_fit(); return res; } bool StatisticsImpl::getTickerMap( std::map<std::string, uint64_t>* stats_map) const { assert(stats_map); if (!stats_map) return false; stats_map->clear(); MutexLock lock(&aggregate_lock_); for (const auto& t : TickersNameMap) { assert(t.first < TICKER_ENUM_MAX); (*stats_map)[t.second.c_str()] = getTickerCountLocked(t.first); } return true; } bool StatisticsImpl::HistEnabledForType(uint32_t type) const { return type < HISTOGRAM_ENUM_MAX; } } // namespace ROCKSDB_NAMESPACE
#include "ModuleCamera.h" #include "Application.h" #include "ModuleInput.h" #include "ModuleProgram.h" #include "glew-2.1.0\include\GL\glew.h" #include "SDL\include\SDL.h" #include "MathGeoLib\include\MathGeoLib.h" ModuleCamera::ModuleCamera() { } ModuleCamera::~ModuleCamera() { } bool ModuleCamera::Init() { frustum.type = FrustumType::PerspectiveFrustum; frustum.pos = math::float3(0.0f, 1.0f, 10.0f); frustum.front = -float3::unitZ; frustum.up = float3::unitY; frustum.nearPlaneDistance = 0.1f; frustum.farPlaneDistance = 100.0f; frustum.verticalFov = math::pi / 4.0f; frustum.horizontalFov = 2.f * atanf(tanf(frustum.verticalFov * 0.5f) * ((float)screenWidth / (float)screenHeight)); return true; } update_status ModuleCamera::PreUpdate() { if (App->input->GetMouseButtonDown(SDL_BUTTON_RIGHT) == KEY_REPEAT) { if (App->input->GetKey(SDL_SCANCODE_Q) == KEY_REPEAT) { Move(UP); } if (App->input->GetKey(SDL_SCANCODE_E) == KEY_REPEAT) { Move(DOWN); } if (App->input->GetKey(SDL_SCANCODE_W) == KEY_REPEAT) { Move(FORWARD); } if (App->input->GetKey(SDL_SCANCODE_S) == KEY_REPEAT) { Move(BACKWARD); } if (App->input->GetKey(SDL_SCANCODE_A) == KEY_REPEAT) { Move(LEFT); } if (App->input->GetKey(SDL_SCANCODE_D) == KEY_REPEAT) { Move(RIGHT); } if (App->input->GetKey(SDL_SCANCODE_LSHIFT) == KEY_DOWN) { mSpeed = mSpeed * 2; rSpeed = rSpeed * 2; } if (App->input->GetKey(SDL_SCANCODE_LSHIFT) == KEY_UP) { mSpeed = mSpeed / 2; rSpeed = rSpeed / 2; } MouseUpdate(); } if (App->input->GetMouseButtonDown(SDL_BUTTON_RIGHT) == KEY_UP) { firstMouse = true; } if (App->input->GetMouseButtonDown(SDL_BUTTON_X1) == KEY_DOWN) { fovX -= 1; SetHorizontalFOV(fovX); } else if (App->input->GetMouseButtonDown(SDL_BUTTON_X2) == KEY_DOWN) { fovX += 1; SetHorizontalFOV(fovX); } if (App->input->GetKey(SDL_SCANCODE_F) == KEY_DOWN) { Focus(); } if (App->input->GetKey(SDL_SCANCODE_LALT) == KEY_REPEAT && App->input->GetMouseButtonDown(SDL_BUTTON_LEFT)) { Orbit(); } return UPDATE_CONTINUE; } update_status ModuleCamera::Update() { math::float4x4 model(math::float4x4::identity); glUseProgram(App->program->axisProgram); glUniformMatrix4fv(glGetUniformLocation(App->program->axisProgram, "model"), 1, GL_TRUE, &model[0][0]); glUniformMatrix4fv(glGetUniformLocation(App->program->axisProgram, "view"), 1, GL_TRUE, &App->camera->LookAt(App->camera->cameraPosition, App->camera->cameraFront, App->camera->cameraUp)[0][0]); glUniformMatrix4fv(glGetUniformLocation(App->program->axisProgram, "proj"), 1, GL_TRUE, &App->camera->frustum.ProjectionMatrix()[0][0]); RefenceGround(); ReferenceAxis(); glDrawArrays(GL_LINES, 0, 1); glUseProgram(0); return UPDATE_CONTINUE; } void ModuleCamera::Orbit() { } void ModuleCamera::Focus() { /*math::AABB boundingBox = math::AABB(App->modelLoader->minPoint, App->modelLoader->maxPoint); math::float3 center = boundingBox.FaceCenterPoint(5); //Reset all variables (position, front, up, fov, pitch, yaw, firstmouse) frustum.pos = cameraPosition = math::float3(center.x, center.y, 0.0f); frustum.front = cameraFront = math::float3(0.0f, 0.0f, -1.0f); frustum.up = cameraUp = math::float3(0.0f, 1.0f, 0.0f); frustum.verticalFov = math::pi / 4.0f; frustum.horizontalFov = 2.f * atanf(tanf(frustum.verticalFov * 0.5f) * ((float)screenWidth / (float)screenHeight)); fovY = 45.0f; fovX = 45.0f; pitch = 0; yaw = 0; firstMouse = true; //Add distance still we can see all the bounding box while (!App->camera->frustum.Contains(boundingBox)) { App->camera->cameraPosition.z = App->camera->frustum.pos.z += 10; }*/ } math::float4x4 ModuleCamera::LookAt(const math::float3& cameraPosition, math::float3& cameraFront, const math::float3& cameraUp) { math::float4x4 matrix; cameraFront.Normalize(); math::float3 side(cameraFront.Cross(cameraUp)); side.Normalize(); math::float3 up(side.Cross(cameraFront)); matrix[0][0] = side.x; matrix[0][1] = side.y; matrix[0][2] = side.z; matrix[1][0] = up.x; matrix[1][1] = up.y; matrix[1][2] = up.z; matrix[2][0] = -cameraFront.x; matrix[2][1] = -cameraFront.y; matrix[2][2] = -cameraFront.z; matrix[0][3] = -side.Dot(cameraPosition); matrix[1][3] = -up.Dot(cameraPosition); matrix[2][3] = cameraFront.Dot(cameraPosition); matrix[3][0] = 0.0f; matrix[3][1] = 0.0f; matrix[3][2] = 0.0f; matrix[3][3] = 1.0f; return matrix; } void ModuleCamera::Move(const Directions dir) { switch (dir) { case UP: frustum.pos = cameraPosition += cameraUp.Normalized() * mSpeed; break; case DOWN: frustum.pos = cameraPosition -= cameraUp.Normalized() * mSpeed; break; case FORWARD: frustum.pos = cameraPosition += cameraFront.Normalized() * mSpeed; break; case BACKWARD: frustum.pos = cameraPosition -= cameraFront.Normalized() * mSpeed; break; case LEFT: frustum.pos = cameraPosition += cameraUp.Cross(cameraFront).Normalized() * mSpeed; break; case RIGHT: frustum.pos = cameraPosition -= cameraUp.Cross(cameraFront).Normalized() * mSpeed; break; } } void ModuleCamera::MouseUpdate() { iPoint mousePosition = App->input->GetMousePosition(); if (firstMouse) { lastX = mousePosition.x; lastY = mousePosition.y; firstMouse = false; } float xoffset = (float)mousePosition.x - (float)lastX; float yoffset = (float)lastY - (float)mousePosition.y; lastX = mousePosition.x; lastY = mousePosition.y; xoffset *= 0.5f; yoffset *= 0.5f; yaw += xoffset; pitch += yoffset; pitch = math::Clamp(pitch, -89.0f, 89.0f); math::float3 front; front.x = SDL_sinf(math::DegToRad(yaw)) * SDL_cosf(math::DegToRad(pitch)); front.y = SDL_sinf(math::DegToRad(pitch)); front.z = -SDL_cosf(math::DegToRad(yaw)) * SDL_cosf(math::DegToRad(pitch)); frustum.front = cameraFront = front.Normalized(); } void ModuleCamera::SetPlaneDistances(const float nearDist, const float farDist) { if (nearDist > 0.0f && nearDist < frustum.farPlaneDistance) { frustum.nearPlaneDistance = nearDist; } if (farDist > 0.0f && farDist > frustum.nearPlaneDistance) { frustum.farPlaneDistance = farDist; } } void ModuleCamera::WindowResized(const unsigned width, const unsigned height) { glViewport(0, 0, width, height); screenWidth = width; screenHeight = height; SetHorizontalFOV(fovX); SetVerticalFOV(fovY); } void ModuleCamera::SetHorizontalFOV(const float fovX) { frustum.horizontalFov = math::DegToRad(fovX); frustum.verticalFov = 2.0f * atanf(tanf(frustum.horizontalFov * 0.5f) * ((float)screenHeight / (float)screenWidth)); } void ModuleCamera::SetVerticalFOV(const float fovY) { frustum.verticalFov = math::DegToRad(fovY); frustum.horizontalFov = 2.0f * atanf(tanf(frustum.verticalFov * 0.5f) * ((float)screenWidth / (float)screenHeight)); } void ModuleCamera::RefenceGround() const { glLineWidth(1.0f); float d = 200.0f; float color[4] = { 1.0f, 1.0f, 1.0f, 1.0f }; glUniform4fv(glGetUniformLocation(App->program->axisProgram, "newColor"), 1, color); glBegin(GL_LINES); for (float i = -d; i <= d; i += 1.0f) { glVertex3f(i, 0.0f, -d); glVertex3f(i, 0.0f, d); glVertex3f(-d, 0.0f, i); glVertex3f(d, 0.0f, i); } glEnd(); } void ModuleCamera::ReferenceAxis() const { glLineWidth(2.0f); // red X float red[4] = { 1.0f, 0.0f, 0.0f, 1.0f }; glUniform4fv(glGetUniformLocation(App->program->axisProgram, "newColor"), 1, red); glBegin(GL_LINES); glVertex3f(0.0f, 0.0f, 0.0f); glVertex3f(1.0f, 0.0f, 0.0f); glVertex3f(1.0f, 0.1f, 0.0f); glVertex3f(1.1f, -0.1f, 0.0f); glVertex3f(1.1f, 0.1f, 0.0f); glVertex3f(1.0f, -0.1f, 0.0f); glEnd(); // green Y float green[4] = { 0.0f, 1.0f, 0.0f, 1.0f }; glUniform4fv(glGetUniformLocation(App->program->axisProgram, "newColor"), 1, green); glBegin(GL_LINES); glColor4f(0.0f, 1.0f, 0.0f, 1.0f); glVertex3f(0.0f, 0.0f, 0.0f); glVertex3f(0.0f, 1.0f, 0.0f); glVertex3f(-0.05f, 1.25f, 0.0f); glVertex3f(0.0f, 1.15f, 0.0f); glVertex3f(0.05f, 1.25f, 0.0f); glVertex3f(0.0f, 1.15f, 0.0f); glVertex3f(0.0f, 1.15f, 0.0f); glVertex3f(0.0f, 1.05f, 0.0f); glEnd(); // blue Z float blue[4] = { 0.0f, 0.0f, 1.0f, 1.0f }; glUniform4fv(glGetUniformLocation(App->program->axisProgram, "newColor"), 1, blue); glBegin(GL_LINES); glColor4f(0.0f, 0.0f, 1.0f, 1.0f); glVertex3f(0.0f, 0.0f, 0.0f); glVertex3f(0.0f, 0.0f, 1.0f); glVertex3f(-0.05f, 0.1f, 1.05f); glVertex3f(0.05f, 0.1f, 1.05f); glVertex3f(0.05f, 0.1f, 1.05f); glVertex3f(-0.05f, -0.1f, 1.05f); glVertex3f(-0.05f, -0.1f, 1.05f); glVertex3f(0.05f, -0.1f, 1.05f); glEnd(); glLineWidth(1.0f); } bool ModuleCamera::CleanUp() { return true; }
#include <iostream> using namespace std; class Rational { public: Rational() { p = 0; q = 1; negative = false; } Rational(int numerator, int denominator) { negative = numerator >= 0 ^ denominator >=0; p = abs(numerator); q = abs(denominator); int nod = GetNod(p, q); if(nod > 1){ p = p/nod; q = q/nod; } } int Numerator() const { return p * (negative? -1: 1); } int Denominator() const { return q; } private: int p, q; bool negative; int GetNod(int numerator, int denomitor){ int a = numerator, b = denomitor; if(a == 0 && b == 0){ return 1; } else if(a == 0){ return b; } else if(b == 0){ return a; } while (a != b) { if(a > b){ a = a - b; } else{ b = b - a; } } return a; } }; bool operator==(const Rational& lhs, const Rational& rhs){ return lhs.Denominator() == rhs.Denominator() && lhs.Numerator() == rhs.Numerator(); } Rational operator+(const Rational& lhs, const Rational& rhs){ return Rational(lhs.Numerator()*rhs.Denominator()+rhs.Numerator()*lhs.Denominator(),lhs.Denominator()*rhs.Denominator()); } Rational operator-(const Rational& lhs, const Rational&rhs){ return Rational(lhs.Numerator()*rhs.Denominator()-rhs.Numerator()*lhs.Denominator(),lhs.Denominator()*rhs.Denominator()); } int main() { { Rational r1(4, 6); Rational r2(2, 3); bool equal = r1 == r2; if (!equal) { cout << "4/6 != 2/3" << endl; return 1; } } { Rational a(2, 3); Rational b(4, 3); Rational c = a + b; bool equal = c == Rational(2, 1); if (!equal) { cout << "2/3 + 4/3 != 2" << endl; return 2; } } { Rational a(5, 7); Rational b(2, 9); Rational c = a - b; bool equal = c == Rational(31, 63); if (!equal) { cout << "5/7 - 2/9 != 31/63" << endl; return 3; } } cout << "OK" << endl; return 0; }
#include "gap_sdk.h" extern void project_main(); void intermediate_main() { project_main(); printf("Finished execution\n"); pmsis_exit(0); } int main() { return pmsis_kickoff(reinterpret_cast<void*>(intermediate_main)); }
#include <stdlib.h> #include <stdarg.h> #include <stdio.h> #include <string.h> #include <time.h> //----------------------------------------------------------------------------- // acd2d headers #include "acd2d_stat.h" #include "acd2d_drawPS.h" #include "SimplePSinC.h" //----------------------------------------------------------------------------- //extern cd_state state; extern double box[4]; //bbox, defined in acd2d_main_gui.h //----------------------------------------------------------------------------- //desired page width 600 const int PS_page_width=600; float PS_page_scale=1; //calculated based on box width inline float X(float x){return (x-box[0])*PS_page_scale;} inline float Y(float y){return (y-box[2])*PS_page_scale;} inline float convert(float v){return v*PS_page_scale;} inline Point2d convert(const Point2d& p) { return Point2d(X(p[0]),Y(p[1])); } void draw_PS_ply(SimplePSinC *ps, const cd_poly& ply) { cd_vertex * ptr=ply.getHead(); Point2d pos=convert(ptr->getPos()); ps->moveto(pos[0],pos[1]); do{ const Point2d& pos=convert(ptr->getPos()); ps->lineto(pos[0],pos[1]); ptr=ptr->getNext(); }while(ptr!=ply.getHead()); ps->fillclosepath(); ps->strokeclosepath(); } void draw_PS_ply(SimplePSinC *ps, const cd_polygon& polygon) { for(cd_polygon::const_iterator i=polygon.begin();i!=polygon.end();i++) { if(i->getType()==cd_poly::POUT) { draw_PS_ply(ps,*i); } else{ ps->setfilledrgb(1,1,1); ps->setstrokegray(0.5); draw_PS_ply(ps,*i); } } } void draw_PS_line(SimplePSinC *ps, const Point2d& s, const Point2d& t) { Point2d p1=convert(s); Point2d p2=convert(t); ps->line(p1[0],p1[1],p2[0],p2[1]); ps->stroke(); } void draw_PS_circle(SimplePSinC *ps, const Point2d& o, float r) { Point2d s1=convert(o); ps->circle(s1[0],s1[1],r); ps->fillstroke(); } inline void draw_PS_polylist(SimplePSinC *ps, const list<cd_polygon>& pl) { list<cd_polygon>::const_iterator ips=pl.begin(); for( ;ips!=pl.end();ips++ ){ const cd_polygon& polys=*ips; for( PLYCIT ip=polys.begin();ip!=polys.end();ip++ ){ //for each poly draw_PS_ply(ps, *ip); } } } void drawALL(SimplePSinC *ps, cd_2d& cd2d) { //draw todo list ps->setfilledrgb(0.3, 0.3, 0.3); ps->setstrokegray(0.5); draw_PS_polylist(ps, cd2d.getTodoList()); //draw done list ps->setfilledrgb(0.7, 0.7, 0.7); ps->setstrokegray(0.5); draw_PS_polylist(ps, cd2d.getDoneList()); } void save2PS(const string& name, cd_2d& cd2d) { SimplePSinC PS; PS.open(name,0,0,PS_page_width,PS_page_width); PS.setlinejoin(1); drawALL(&PS,cd2d); PS.close(); cout<<"- Saved screen to "<<name<<endl; }
#include <mbgl/storage/file_source.hpp> #include <mbgl/storage/offline_database.hpp> #include <mbgl/storage/offline_download.hpp> #include <mbgl/storage/resource.hpp> #include <mbgl/storage/response.hpp> #include <mbgl/storage/http_file_source.hpp> #include <mbgl/style/parser.hpp> #include <mbgl/style/sources/vector_source.hpp> #include <mbgl/style/sources/raster_source.hpp> #include <mbgl/style/sources/geojson_source.hpp> #include <mbgl/style/sources/image_source.hpp> #include <mbgl/style/conversion/json.hpp> #include <mbgl/style/conversion/tileset.hpp> #include <mbgl/text/glyph.hpp> #include <mbgl/util/mapbox.hpp> #include <mbgl/util/run_loop.hpp> #include <mbgl/util/tile_cover.hpp> #include <mbgl/util/tileset.hpp> #include <set> namespace mbgl { using namespace style; OfflineDownload::OfflineDownload(int64_t id_, OfflineRegionDefinition&& definition_, OfflineDatabase& offlineDatabase_, FileSource& onlineFileSource_) : id(id_), definition(definition_), offlineDatabase(offlineDatabase_), onlineFileSource(onlineFileSource_) { setObserver(nullptr); } OfflineDownload::~OfflineDownload() = default; void OfflineDownload::setObserver(std::unique_ptr<OfflineRegionObserver> observer_) { observer = observer_ ? std::move(observer_) : std::make_unique<OfflineRegionObserver>(); } void OfflineDownload::setState(OfflineRegionDownloadState state) { if (status.downloadState == state) { return; } status.downloadState = state; if (status.downloadState == OfflineRegionDownloadState::Active) { activateDownload(); } else { deactivateDownload(); } observer->statusChanged(status); } OfflineRegionStatus OfflineDownload::getStatus() const { if (status.downloadState == OfflineRegionDownloadState::Active) { return status; } OfflineRegionStatus result = offlineDatabase.getRegionCompletedStatus(id); result.requiredResourceCount++; optional<Response> styleResponse = offlineDatabase.get(Resource::style(definition.styleURL)); if (!styleResponse) { return result; } style::Parser parser; parser.parse(*styleResponse->data); result.requiredResourceCountIsPrecise = true; for (const auto& source : parser.sources) { SourceType type = source->getType(); auto handleTiledSource = [&] (const variant<std::string, Tileset>& urlOrTileset, const uint16_t tileSize) { if (urlOrTileset.is<Tileset>()) { result.requiredResourceCount += definition.tileCount(type, tileSize, urlOrTileset.get<Tileset>().zoomRange); } else { result.requiredResourceCount += 1; const auto& url = urlOrTileset.get<std::string>(); optional<Response> sourceResponse = offlineDatabase.get(Resource::source(url)); if (sourceResponse) { style::conversion::Error error; optional<Tileset> tileset = style::conversion::convertJSON<Tileset>(*sourceResponse->data, error); if (tileset) { result.requiredResourceCount += definition.tileCount(type, tileSize, (*tileset).zoomRange); } } else { result.requiredResourceCountIsPrecise = false; } } }; switch (type) { case SourceType::Vector: { const auto& vectorSource = *source->as<VectorSource>(); handleTiledSource(vectorSource.getURLOrTileset(), util::tileSize); break; } case SourceType::Raster: { const auto& rasterSource = *source->as<RasterSource>(); handleTiledSource(rasterSource.getURLOrTileset(), rasterSource.getTileSize()); break; } case SourceType::GeoJSON: { const auto& geojsonSource = *source->as<GeoJSONSource>(); if (geojsonSource.getURL()) { result.requiredResourceCount += 1; } break; } case SourceType::Image: { const auto& imageSource = *source->as<ImageSource>(); if (imageSource.getURL()) { result.requiredResourceCount += 1; } break; } case SourceType::Video: case SourceType::Annotations: break; } } if (!parser.glyphURL.empty()) { result.requiredResourceCount += parser.fontStacks().size() * GLYPH_RANGES_PER_FONT_STACK; } if (!parser.spriteURL.empty()) { result.requiredResourceCount += 2; } return result; } void OfflineDownload::activateDownload() { status = OfflineRegionStatus(); status.downloadState = OfflineRegionDownloadState::Active; status.requiredResourceCount++; ensureResource(Resource::style(definition.styleURL), [&](Response styleResponse) { status.requiredResourceCountIsPrecise = true; style::Parser parser; parser.parse(*styleResponse.data); for (const auto& source : parser.sources) { SourceType type = source->getType(); auto handleTiledSource = [&] (const variant<std::string, Tileset>& urlOrTileset, const uint16_t tileSize) { if (urlOrTileset.is<Tileset>()) { queueTiles(type, tileSize, urlOrTileset.get<Tileset>()); } else { const auto& url = urlOrTileset.get<std::string>(); status.requiredResourceCountIsPrecise = false; status.requiredResourceCount++; requiredSourceURLs.insert(url); ensureResource(Resource::source(url), [=](Response sourceResponse) { style::conversion::Error error; optional<Tileset> tileset = style::conversion::convertJSON<Tileset>(*sourceResponse.data, error); if (tileset) { util::mapbox::canonicalizeTileset(*tileset, url, type, tileSize); queueTiles(type, tileSize, *tileset); requiredSourceURLs.erase(url); if (requiredSourceURLs.empty()) { status.requiredResourceCountIsPrecise = true; } } }); } }; switch (type) { case SourceType::Vector: { const auto& vectorSource = *source->as<VectorSource>(); handleTiledSource(vectorSource.getURLOrTileset(), util::tileSize); break; } case SourceType::Raster: { const auto& rasterSource = *source->as<RasterSource>(); handleTiledSource(rasterSource.getURLOrTileset(), rasterSource.getTileSize()); break; } case SourceType::GeoJSON: { const auto& geojsonSource = *source->as<GeoJSONSource>(); if (geojsonSource.getURL()) { queueResource(Resource::source(*geojsonSource.getURL())); } break; } case SourceType::Image: { const auto& imageSource = *source->as<ImageSource>(); auto imageUrl = imageSource.getURL(); if (imageUrl && !imageUrl->empty()) { queueResource(Resource::image(*imageUrl)); } break; } case SourceType::Video: case SourceType::Annotations: break; } } if (!parser.glyphURL.empty()) { for (const auto& fontStack : parser.fontStacks()) { for (char16_t i = 0; i < GLYPH_RANGES_PER_FONT_STACK; i++) { queueResource(Resource::glyphs(parser.glyphURL, fontStack, getGlyphRange(i * GLYPHS_PER_GLYPH_RANGE))); } } } if (!parser.spriteURL.empty()) { queueResource(Resource::spriteImage(parser.spriteURL, definition.pixelRatio)); queueResource(Resource::spriteJSON(parser.spriteURL, definition.pixelRatio)); } continueDownload(); }); } /* Fill up our own request queue by requesting the next few resources. This is called when activating the download, or when a request completes successfully. Note "successfully"; it's not called when a requests receives an error. A request that errors will be retried after some delay. So in that sense it's still "active" and consuming resources, notably the request object, its timer, and network resources when the timer fires. We could try to squeeze in subsequent requests while we wait for the errored request to retry. But that risks overloading the upstream request queue -- defeating our own metering -- if there are a lot of errored requests that all come up for retry at the same time. And many times, the cause of a request error will apply to many requests of the same type. For instance if a server is unreachable, all the requests to that host are going to error. In that case, continuing to try subsequent resources after the first few errors is fruitless anyway. */ void OfflineDownload::continueDownload() { if (resourcesRemaining.empty() && status.complete()) { setState(OfflineRegionDownloadState::Inactive); return; } while (!resourcesRemaining.empty() && requests.size() < HTTPFileSource::maximumConcurrentRequests()) { ensureResource(resourcesRemaining.front()); resourcesRemaining.pop_front(); } } void OfflineDownload::deactivateDownload() { requiredSourceURLs.clear(); resourcesRemaining.clear(); requests.clear(); } void OfflineDownload::queueResource(Resource resource) { status.requiredResourceCount++; resourcesRemaining.push_front(std::move(resource)); } void OfflineDownload::queueTiles(SourceType type, uint16_t tileSize, const Tileset& tileset) { for (const auto& tile : definition.tileCover(type, tileSize, tileset.zoomRange)) { status.requiredResourceCount++; resourcesRemaining.push_back( Resource::tile(tileset.tiles[0], definition.pixelRatio, tile.x, tile.y, tile.z, tileset.scheme)); } } void OfflineDownload::ensureResource(const Resource& resource, std::function<void(Response)> callback) { auto workRequestsIt = requests.insert(requests.begin(), nullptr); *workRequestsIt = util::RunLoop::Get()->invokeCancellable([=]() { requests.erase(workRequestsIt); auto getResourceSizeInDatabase = [&] () -> optional<int64_t> { if (!callback) { return offlineDatabase.hasRegionResource(id, resource); } optional<std::pair<Response, uint64_t>> response = offlineDatabase.getRegionResource(id, resource); if (!response) { return {}; } callback(response->first); return response->second; }; optional<int64_t> offlineResponse = getResourceSizeInDatabase(); if (offlineResponse) { status.completedResourceCount++; status.completedResourceSize += *offlineResponse; if (resource.kind == Resource::Kind::Tile) { status.completedTileCount += 1; status.completedTileSize += *offlineResponse; } observer->statusChanged(status); continueDownload(); return; } if (checkTileCountLimit(resource)) { return; } auto fileRequestsIt = requests.insert(requests.begin(), nullptr); *fileRequestsIt = onlineFileSource.request(resource, [=](Response onlineResponse) { if (onlineResponse.error) { observer->responseError(*onlineResponse.error); return; } requests.erase(fileRequestsIt); if (callback) { callback(onlineResponse); } status.completedResourceCount++; uint64_t resourceSize = offlineDatabase.putRegionResource(id, resource, onlineResponse); status.completedResourceSize += resourceSize; if (resource.kind == Resource::Kind::Tile) { status.completedTileCount += 1; status.completedTileSize += resourceSize; } observer->statusChanged(status); if (checkTileCountLimit(resource)) { return; } continueDownload(); }); }); } bool OfflineDownload::checkTileCountLimit(const Resource& resource) { if (resource.kind == Resource::Kind::Tile && util::mapbox::isMapboxURL(resource.url) && offlineDatabase.offlineMapboxTileCountLimitExceeded()) { observer->mapboxTileCountLimitExceeded(offlineDatabase.getOfflineMapboxTileCountLimit()); setState(OfflineRegionDownloadState::Inactive); return true; } return false; } } // namespace mbgl
/* * If not stated otherwise in this file or this component's LICENSE file the * following copyright and licenses apply: * * Copyright 2020 RDK Management * * 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 "NetworkControl.h" namespace WPEFramework { namespace Plugin { SERVICE_REGISTRATION(NetworkControl, 1, 0); static Core::ProxyPoolType<Web::Response> responseFactory(4); static Core::ProxyPoolType<Web::JSONBodyType<NetworkControl::Entry>> jsonGetNetworkFactory(1); static Core::ProxyPoolType<Web::JSONBodyType<Core::JSON::ArrayType<NetworkControl::Entry>>> jsonGetNetworksFactory(1); static TCHAR NAMESERVER[] = "nameserver "; static bool AddDNSEntry(std::list<std::pair<uint16_t, Core::NodeId>> & container, const Core::NodeId& element) { bool result = false; std::list<std::pair<uint16_t, Core::NodeId>>::iterator finder(container.begin()); while ((finder != container.end()) && (finder->second != element)) { finder++; } if (finder == container.end()) { result = true; container.push_back(std::pair<uint16_t, Core::NodeId>(1, element)); } else { finder->first += 1; } return (result); } static bool RemoveDNSEntry(std::list<std::pair<uint16_t, Core::NodeId>> & container, const Core::NodeId& element) { bool result = true; std::list<std::pair<uint16_t, Core::NodeId>>::iterator finder(container.begin()); while ((finder != container.end()) && (finder->second != element)) { finder++; } if (finder == container.end()) { TRACE_L1("How could this be, it does not exist. Time for a refresh. [%s]", element.HostAddress().c_str()); } else if (finder->first == 1) { container.erase(finder); } else { result = false; finder->first -= 1; } return (result); } #ifdef __WINDOWS__ #pragma warning(disable : 4355) #endif NetworkControl::NetworkControl() : _skipURL(0) , _service(nullptr) , _responseTime(0) , _retries(0) , _persistentStoragePath() , _dns() , _interfaces() , _dhcpInterfaces() , _observer(Core::ProxyType<AdapterObserver>::Create(this)) { RegisterAll(); } #ifdef __WINDOWS__ #pragma warning(default : 4355) #endif /* virtual */ NetworkControl::~NetworkControl() { UnregisterAll(); } /* virtual */ const string NetworkControl::Initialize(PluginHost::IShell * service) { string result; Config config; config.FromString(service->ConfigLine()); _service = service; _skipURL = static_cast<uint8_t>(service->WebPrefix().length()); _responseTime = config.TimeOut.Value(); _retries = config.Retries.Value(); _dnsFile = config.DNSFile.Value(); // We will only "open" the DNS resolve file, so of ot does not exist yet, create an empty file. Core::File dnsFile(_dnsFile, true); if (dnsFile.Exists() == false) { if (dnsFile.Create() == false) { SYSLOG(Logging::Startup, (_T("Could not create DNS configuration file [%s]"), _dnsFile.c_str())); } else { dnsFile.Close(); } } // Try to create persistent storage folder _persistentStoragePath = _service->PersistentPath(); if (_persistentStoragePath.empty() == false) { if (Core::Directory(_persistentStoragePath.c_str()).CreatePath() == false) { _persistentStoragePath.clear(); TRACE_L1("Failed to create persistent storage path at %s\n", _persistentStoragePath.c_str()); } } Core::JSON::ArrayType<Entry>::Iterator index(config.Interfaces.Elements()); while (index.Next() == true) { if (index.Current().Interface.IsSet() == true) { string interfaceName(index.Current().Interface.Value()); Core::AdapterIterator adapter; uint8_t retries = (_responseTime * 2); // Some interfaces take some time, to be available. Wait a certain amount // of time in which the interface should come up. do { adapter = Core::AdapterIterator(interfaceName); if (adapter.IsValid() == false) { Core::AdapterIterator::Flush(); SleepMs(500); } } while ((retries-- != 0) && (adapter.IsValid() == false)); if (adapter.IsValid() == false) { SYSLOG(Logging::Startup, (_T("Interface [%s], not available"), interfaceName.c_str())); } else { adapter.Up(true); auto dhcpInterface = _dhcpInterfaces.emplace(std::piecewise_construct, std::make_tuple(interfaceName), std::make_tuple(Core::ProxyType<DHCPEngine>::Create(this, interfaceName, _persistentStoragePath))); _interfaces.emplace(std::piecewise_construct, std::make_tuple(interfaceName), std::make_tuple(index.Current())); JsonData::NetworkControl::NetworkData::ModeType how(index.Current().Mode); if (how == JsonData::NetworkControl::NetworkData::ModeType::MANUAL) { SYSLOG(Logging::Startup, (_T("Interface [%s] activated, no IP associated"), interfaceName.c_str())); } else { if (how == JsonData::NetworkControl::NetworkData::ModeType::DYNAMIC) { ClearAssignedIPs(adapter); if (dhcpInterface.first->second->LoadLeases() == true) { SYSLOG(Logging::Startup, (_T("Leased list for interface [%s] loaded!"), interfaceName.c_str())); } SYSLOG(Logging::Startup, (_T("Interface [%s] activated, DHCP request issued"), interfaceName.c_str())); Reload(interfaceName, true); } else { SYSLOG(Logging::Startup, (_T("Interface [%s] activated, static IP assigned"), interfaceName.c_str())); Reload(interfaceName, false); } } } } } if (config.Open.Value() == true) { // Find all adapters that are not listed. Core::AdapterIterator notListed; while (notListed.Next() == true) { const string interfaceName(notListed.Name()); if (_interfaces.find(interfaceName) == _interfaces.end()) { _dhcpInterfaces.emplace(std::piecewise_construct, std::make_tuple(interfaceName), std::make_tuple(Core::ProxyType<DHCPEngine>::Create(this, interfaceName, _persistentStoragePath))); _interfaces.emplace(std::piecewise_construct, std::make_tuple(interfaceName), std::make_tuple(StaticInfo())); } } } Core::JSON::ArrayType<Core::JSON::String>::Iterator entries(config.DNS.Elements()); while (entries.Next() == true) { Core::NodeId entry(entries.Current().Value().c_str()); if (entry.IsValid() == true) { _dns.push_back(std::pair<uint16_t, Core::NodeId>(1, entry)); } } // Update the DNS information, before we set the new IP, Do not know who triggers // the re-read of this file.... RefreshDNS(); // From now on we observer the states of the give interfaces. _observer->Open(); // On success return empty, to indicate there is no error text. return (result); } /* virtual */ void NetworkControl::Deinitialize(PluginHost::IShell * service) { // Stop observing. _observer->Close(); std::map<const string, Core::ProxyType<DHCPEngine>>::iterator index(_dhcpInterfaces.begin()); while (index != _dhcpInterfaces.end()) { index->second->CleanUp(); index++; } _dns.clear(); _dhcpInterfaces.clear(); _interfaces.clear(); _service = nullptr; } /* virtual */ string NetworkControl::Information() const { // No additional info to report. return (string()); } /* virtual */ void NetworkControl::Inbound(Web::Request & /* request */) { } /* virtual */ Core::ProxyType<Web::Response> NetworkControl::Process(const Web::Request& request) { Core::ProxyType<Web::Response> result(PluginHost::IFactories::Instance().Response()); Core::TextSegmentIterator index(Core::TextFragment(request.Path, _skipURL, static_cast<uint16_t>(request.Path.length()) - _skipURL), false, '/'); // By default, we assume everything works.. result->ErrorCode = Web::STATUS_BAD_REQUEST; result->Message = _T("Unsupported request for the [NetworkControl] service."); // By default, we skip the first slash index.Next(); if (request.Verb == Web::Request::HTTP_GET) { _adminLock.Lock(); if (index.Next() == true) { std::map<const string, StaticInfo>::iterator entry(_interfaces.find(index.Current().Text())); if (entry != _interfaces.end()) { Core::ProxyType<Web::JSONBodyType<NetworkControl::Entry>> data(jsonGetNetworkFactory.Element()); entry->second.Store(*data); data->Interface = entry->first; result->Body(data); result->ErrorCode = Web::STATUS_OK; result->Message = "OK"; } else { result->ErrorCode = Web::STATUS_NOT_FOUND; result->Message = string(_T("Could not find interface: ")) + index.Current().Text(); } } else { std::map<const string, StaticInfo>::iterator entry(_interfaces.begin()); Core::ProxyType<Web::JSONBodyType<Core::JSON::ArrayType<NetworkControl::Entry>>> data(jsonGetNetworksFactory.Element()); while (entry != _interfaces.end()) { Entry& newSlot = data->Add(); entry->second.Store(newSlot); newSlot.Interface = entry->first; entry++; } result->Body(data); result->ErrorCode = Web::STATUS_OK; result->Message = "OK"; } _adminLock.Unlock(); } else if ((index.Next() == true) && (request.Verb == Web::Request::HTTP_PUT)) { _adminLock.Lock(); std::map<const string, StaticInfo>::iterator entry(_interfaces.find(index.Current().Text())); if ((entry != _interfaces.end()) && (index.Next() == true)) { bool reload = (index.Current() == _T("Reload")); if (((reload == true) && (entry->second.Mode() != JsonData::NetworkControl::NetworkData::ModeType::STATIC)) || (index.Current() == _T("Request"))) { if (Reload(entry->first, true) == Core::ERROR_NONE) { result->ErrorCode = Web::STATUS_OK; result->Message = "OK"; } else { result->ErrorCode = Web::STATUS_INTERNAL_SERVER_ERROR; result->Message = "Could not activate the server"; } } else if (((reload == true) && (entry->second.Mode() == JsonData::NetworkControl::NetworkData::ModeType::STATIC)) || (index.Current() == _T("Assign"))) { if (Reload(entry->first, false) == Core::ERROR_NONE) { result->ErrorCode = Web::STATUS_OK; result->Message = "OK"; } else { result->ErrorCode = Web::STATUS_INTERNAL_SERVER_ERROR; result->Message = "Could not activate the server"; } } else if (index.Current() == _T("Up")) { string interfaceName(entry->first); Core::AdapterIterator adapter(interfaceName); if (adapter.IsValid() == false) { result->ErrorCode = Web::STATUS_NOT_FOUND; result->Message = string(_T("Interface: ")) + interfaceName + _T(" not found."); } else { adapter.Up(true); result->ErrorCode = Web::STATUS_OK; result->Message = string(_T("OK, ")) + interfaceName + _T(" set UP."); } } else if (index.Current() == _T("Down")) { string interfaceName(entry->first); Core::AdapterIterator adapter(interfaceName); if (adapter.IsValid() == false) { result->ErrorCode = Web::STATUS_NOT_FOUND; result->Message = string(_T("Interface: ")) + interfaceName + _T(" not found."); } else { adapter.Up(false); result->ErrorCode = Web::STATUS_OK; result->Message = string(_T("OK, ")) + interfaceName + _T(" set DOWN."); } } else if (index.Current() == _T("Flush")) { string interfaceName(entry->first); Core::AdapterIterator adapter(interfaceName); if (adapter.IsValid() == false) { result->ErrorCode = Web::STATUS_NOT_FOUND; result->Message = string(_T("Interface: ")) + interfaceName + _T(" not found."); } else { ClearAssignedIPs(adapter); result->ErrorCode = Web::STATUS_OK; result->Message = string(_T("OK, ")) + interfaceName + _T(" set DOWN."); } } } _adminLock.Unlock(); } return result; } uint32_t NetworkControl::SetIP(Core::AdapterIterator & adapter, const Core::IPNode& ipAddress, const Core::NodeId& gateway, const Core::NodeId& broadcast, bool clearOld) { if (adapter.IsValid() == true) { bool addIt = false; if (ipAddress.Type() == Core::NodeId::TYPE_IPV4) { if (clearOld == true) { ClearAssignedIPV4IPs(adapter); addIt = true; } else { Core::IPV4AddressIterator checker(adapter.IPV4Addresses()); while ((checker.Next() == true) && (checker.Address() != ipAddress)) { /* INTENTINALLY LEFT EMPTY */ } addIt = (checker.IsValid() == false); } } else if (ipAddress.Type() == Core::NodeId::TYPE_IPV6) { if (clearOld == true) { ClearAssignedIPV6IPs(adapter); addIt = true; } else { Core::IPV6AddressIterator checker(adapter.IPV6Addresses()); while ((checker.Next() == true) && (checker.Address() != ipAddress)) { /* INTENTINALLY LEFT EMPTY */ } addIt = (checker.IsValid() == false); } } if (addIt == true) { TRACE_L1("Setting IP: %s", ipAddress.HostAddress().c_str()); adapter.Add(ipAddress); } else { TRACE_L1("No need to set IP: %s", ipAddress.HostAddress().c_str()); } if (gateway.IsValid() == true) { adapter.Gateway(Core::IPNode(Core::NodeId("0.0.0.0"), 0), gateway); } Core::AdapterIterator::Flush(); PluginHost::ISubSystem* subSystem = _service->SubSystems(); ASSERT(subSystem != nullptr); if (subSystem != nullptr) { if ((subSystem->IsActive(PluginHost::ISubSystem::NETWORK) == false) && (ipAddress.IsLocalInterface() == false)) { subSystem->Set(PluginHost::ISubSystem::NETWORK, nullptr); } subSystem->Release(); } string message(string("{ \"interface\": \"") + adapter.Name() + string("\", \"status\":0, \"ip\":\"" + ipAddress.HostAddress() + "\" }")); TRACE(Trace::Information, (_T("DHCP Request set on: %s"), adapter.Name().c_str())); _service->Notify(message); } return (Core::ERROR_NONE); } /* Saves leased offer to file */ void NetworkControl::DHCPEngine::SaveLeases() { if (_leaseFilePath.empty() == false) { Core::File leaseFile(_leaseFilePath); if (leaseFile.Create() == true) { DHCPClientImplementation::Offer::JSON lease; DHCPClientImplementation::Offer& offer = _client.LeasedOffer(); lease.Set(offer); if (lease.IElement::ToFile(leaseFile) == false) { TRACE(Trace::Warning, ("Error occured while trying to save dhcp lease to file!")); } leaseFile.Close(); } else { TRACE(Trace::Warning, ("Failed to open leases file %s\n for saving", leaseFile.Name().c_str())); } } } /* Loads list of previously saved offers and adds it to unleased list for requesting in future. */ bool NetworkControl::DHCPEngine::LoadLeases() { bool result = false; if (_leaseFilePath.empty() == false) { Core::File leaseFile(_leaseFilePath); if (leaseFile.Size() != 0 && leaseFile.Open(true) == true) { DHCPClientImplementation::Offer::JSON lease; Core::OptionalType<Core::JSON::Error> error; if (lease.IElement::FromFile(leaseFile, error) == true) { _client.AddUnleasedOfferToEnd(lease.Get()); } if (error.IsSet() == true) { SYSLOG(Logging::ParsingError, (_T("Parsing failed with %s"), ErrorDisplayMessage(error.Value()).c_str())); } else { result = true; } leaseFile.Close(); } } return result; } uint32_t NetworkControl::Reload(const string& interfaceName, const bool dynamic) { uint32_t result = Core::ERROR_UNKNOWN_KEY; std::map<const string, StaticInfo>::iterator index(_interfaces.find(interfaceName)); if (index != _interfaces.end()) { if (dynamic == false) { Core::AdapterIterator adapter(interfaceName); result = SetIP(adapter, index->second.Address(), index->second.Gateway(), index->second.Broadcast()); } else { std::map<const string, Core::ProxyType<DHCPEngine>>::iterator entry(_dhcpInterfaces.find(interfaceName)); Core::AdapterIterator interface(interfaceName); if (entry != _dhcpInterfaces.end() && interface.IsValid() && interface.HasMAC() && interface.IsRunning()) { entry->second->StopWatchdog(); uint8_t mac[6]; interface.MACAddress(mac, sizeof(mac)); entry->second->UpdateMAC(mac, sizeof(mac)); entry->second->GetIP(); result = Core::ERROR_NONE; } } } return (result); } /* virtual */ uint32_t NetworkControl::AddAddress(const string& interfaceName) { return (Reload(interfaceName, true)); } /* virtual */ uint32_t NetworkControl::AddAddress(const string& interfaceName, const string& IPAddress, const string& gateway, const string& broadcast, const uint8_t netmask) { uint32_t result = Core::ERROR_UNKNOWN_KEY; std::map<const string, StaticInfo>::iterator index(_interfaces.find(interfaceName)); if (index != _interfaces.end()) { Core::IPNode address(Core::NodeId(IPAddress.c_str()), netmask); Core::NodeId ipGateway; Core::NodeId ipBroadcast; Core::AdapterIterator adapter(interfaceName); result = SetIP(adapter, address, ipGateway, ipBroadcast); } return (result); } /* virtual */ uint32_t NetworkControl::RemoveAddress(const string& interfaceName, const string& IPAddress, const string& gateway, const string& broadcast) { uint32_t result = Core::ERROR_UNKNOWN_KEY; std::map<const string, StaticInfo>::iterator index(_interfaces.find(interfaceName)); if (index != _interfaces.end()) { Core::NodeId basic(IPAddress.c_str()); Core::IPNode address(basic, basic.DefaultMask()); Core::NodeId ipGateway; Core::NodeId ipBroadcast; Core::AdapterIterator adapter(interfaceName); // Todo allow for IP adresses to be removed. //result = SetIP(adapter, index->second.Address(), ipGateway, ipBroadcast); } return (result); } /* virtual */ uint32_t NetworkControl::AddDNS(IIPNetwork::IDNSServers * dnsEntries) { uint32_t result = Core::ERROR_UNKNOWN_KEY; bool syncDNS = false; dnsEntries->Reset(); _adminLock.Lock(); while (dnsEntries->Next() == true) { const string server(dnsEntries->Server()); if (server.empty() == false) { Core::NodeId entry(server.c_str()); if (entry.IsValid() == true) { syncDNS = AddDNSEntry(_dns, entry) | syncDNS; } } } if (syncDNS == true) { RefreshDNS(); } _adminLock.Unlock(); return (result); } /* virtual */ uint32_t NetworkControl::RemoveDNS(IIPNetwork::IDNSServers * dnsEntries) { uint32_t result = Core::ERROR_UNKNOWN_KEY; bool syncDNS = false; dnsEntries->Reset(); _adminLock.Lock(); while (dnsEntries->Next() == true) { const string server(dnsEntries->Server()); if (server.empty() == false) { Core::NodeId entry(server.c_str()); if (entry.IsValid() == true) { syncDNS = RemoveDNSEntry(_dns, entry) | syncDNS; } } } if (syncDNS == true) { RefreshDNS(); } _adminLock.Unlock(); return (result); } /* Returns true if offer is to be accepted, false otherwise */ bool NetworkControl::NewOffer(const string& interfaceName, const DHCPClientImplementation::Offer& offer) { bool takeOffer = false; _adminLock.Lock(); std::map<const string, Core::ProxyType<DHCPEngine>>::const_iterator entry(_dhcpInterfaces.find(interfaceName)); if (entry != _dhcpInterfaces.end()) { TRACE(Trace::Information, ("Got new DHCP offer for ip %s\n",offer.Address().HostAddress().c_str())); // Try to request first offer that comes in if (entry->second->Classification() == DHCPClientImplementation::CLASSIFICATION_DISCOVER) { TRACE(Trace::Information, ("Sending REQUEST for IP %s", offer.Address().HostAddress().c_str())); takeOffer = true; } } else { TRACE_L1("Got IP offer for nonexisting network interface!"); } _adminLock.Unlock(); return takeOffer; } void NetworkControl::RequestAccepted(const string& interfaceName, const DHCPClientImplementation::Offer& offer) { std::map<const string, Core::ProxyType<DHCPEngine>>::const_iterator entry(_dhcpInterfaces.find(interfaceName)); TRACE(Trace::Information, ("DHCP Request for interface %s accepted, %s offered IP!\n", interfaceName.c_str(), offer.Address().HostAddress().c_str())); if (entry != _dhcpInterfaces.end()) { std::map<const string, StaticInfo>::iterator info(_interfaces.find(interfaceName)); Core::AdapterIterator adapter(interfaceName); ASSERT(info != _interfaces.end()); if (info != _interfaces.end()) { bool update = false; _adminLock.Lock(); // First add all new entries. DHCPClientImplementation::Offer::DnsIterator servers(offer.DNS()); while (servers.Next() == true) { update = AddDNSEntry(_dns, servers.Current()) | update; } // Than remove all old ones. servers = info->second.Offer().DNS(); while (servers.Next() == true) { update = RemoveDNSEntry(_dns, servers.Current()) | update; } _adminLock.Unlock(); if (update == true) { RefreshDNS(); } SetIP(adapter, Core::IPNode(offer.Address(), offer.Netmask()), offer.Gateway(), offer.Broadcast(), true); // Update leases file entry->second->SaveLeases(); // We are done for now entry->second->Completed(); TRACE_L1("New IP Granted for %s:", interfaceName.c_str()); TRACE_L1(" Source: %s", offer.Source().HostAddress().c_str()); TRACE_L1(" Address: %s", offer.Address().HostAddress().c_str()); TRACE_L1(" Broadcast: %s", offer.Broadcast().HostAddress().c_str()); TRACE_L1(" Gateway: %s", offer.Gateway().HostAddress().c_str()); TRACE_L1(" DNS: %d", offer.DNS().Count()); TRACE_L1(" Netmask: %d", offer.Netmask()); } } else { TRACE_L1("Request accepted for nonexisting network interface!"); } } void NetworkControl::RequestFailed(const string& interfaceName, const DHCPClientImplementation::Offer& offer) { TRACE(Trace::Information, ("DHCP Request for ip %s failed!\n", offer.Address().HostAddress().c_str())); std::map<const string, Core::ProxyType<DHCPEngine>>::const_iterator entry(_dhcpInterfaces.find(interfaceName)); if (entry != _dhcpInterfaces.end()) { // Lets try again! entry->second->GetIP(); } else { TRACE_L1("Request denied for nonexisting network interface!"); } } void NetworkControl::NoOffers(const string& interfaceName) { _adminLock.Lock(); std::map<const string, Core::ProxyType<DHCPEngine>>::iterator index(_dhcpInterfaces.find(interfaceName)); if (index != _dhcpInterfaces.end()) { string message(string("{ \"interface\": \"") + index->first + string("\", \"status\":11 }")); TRACE(Trace::Information, (_T("DHCP Request timed out on: %s"), index->first.c_str())); _service->Notify(message); // We can close the port now index->second->Completed(); } _adminLock.Unlock(); } void NetworkControl::RefreshDNS() { Core::DataElementFile file(_dnsFile, Core::File::SHAREABLE|Core::File::USER_READ|Core::File::USER_WRITE|Core::File::USER_EXECUTE|Core::File::GROUP_READ|Core::File::GROUP_WRITE, 0); if (file.IsValid() == false) { SYSLOG(Logging::Startup, (_T("DNS functionality could NOT be updated [%s]"), _dnsFile.c_str())); } else { string data((_T("#++SECTION: ")) + _service->Callsign() + '\n'); string endMarker((_T("#--SECTION: ")) + _service->Callsign() + '\n'); uint16_t start = 0; uint16_t end = 0; uint16_t offset = 1; uint8_t index = 0; do { index += offset - 1; offset = 0; // Find the first comparible character && check the remainder in the next step... while ((index < file.Size()) && (file[index] != data[offset])) { index++; } while ((index < file.Size()) && (offset < data.length()) && (file[index] == data[offset])) { index++; offset++; } } while ((index < file.Size()) && (offset != data.length())); start = index - offset; offset = 1; do { index += offset - 1; offset = 0; // Find the first comparible character && check the remainder in the next step... while ((index < file.Size()) && (file[index] != endMarker[offset])) { index++; } while ((index < file.Size()) && (offset < endMarker.length()) && (file[index] == endMarker[offset])) { index++; offset++; } } while ((index < file.Size()) && (offset != endMarker.length())); end = index; uint16_t reduction = end - start; if (reduction != 0) { // move everything after de marker, over the marker sections. ::memcpy(&(file[start]), &file[end], static_cast<uint16_t>(file.Size()) - end); } offset = (static_cast<uint16_t>(file.Size()) - reduction); _adminLock.Lock(); std::list<std::pair<uint16_t, Core::NodeId>>::const_iterator pointer(_dns.begin()); while (pointer != _dns.end()) { data += string(NAMESERVER, sizeof(NAMESERVER) - 1) + pointer->second.HostAddress() + '\n'; pointer++; } _adminLock.Unlock(); data += endMarker; file.Size(offset + data.length()); ::memcpy(&(file[offset]), data.c_str(), data.length()); file.Sync(); SYSLOG(Logging::Startup, (_T("DNS functionality updated [%s]"), _dnsFile.c_str())); } } void NetworkControl::Activity(const string& interfaceName) { string message; Core::AdapterIterator adapter(interfaceName); JsonData::NetworkControl::ConnectionchangeParamsData::StatusType status; if (adapter.IsValid() == true) { // Send a message with the state of the adapter. message = string(_T("{ \"interface\": \"")) + interfaceName + string(_T("\", \"running\": \"")) + string(adapter.IsRunning() ? _T("true") : _T("false")) + string(_T("\", \"up\": \"")) + string(adapter.IsUp() ? _T("true") : _T("false")) + _T("\", \"event\": \""); TRACE(Trace::Information, (_T("Adapter change report on: %s"), interfaceName.c_str())); _adminLock.Lock(); if (_interfaces.find(interfaceName) == _interfaces.end()) { _dhcpInterfaces.emplace(std::piecewise_construct, std::make_tuple(interfaceName), std::make_tuple(Core::ProxyType<DHCPEngine>::Create(this, interfaceName, _persistentStoragePath))); _interfaces.emplace(std::piecewise_construct, std::make_tuple(interfaceName), std::make_tuple(StaticInfo())); message += _T("Create\" }"); TRACE(Trace::Information, (_T("Added interface: %s"), interfaceName.c_str())); status = JsonData::NetworkControl::ConnectionchangeParamsData::StatusType::CREATED; } else { message += _T("Update\" }"); status = JsonData::NetworkControl::ConnectionchangeParamsData::StatusType::UPDATED; TRACE(Trace::Information, (_T("Updated interface: %s"), interfaceName.c_str())); } if ((adapter.IsRunning() == true) && (adapter.IsUp() == true)) { std::map<const string, StaticInfo>::iterator index(_interfaces.find(interfaceName)); if (index != _interfaces.end()) { JsonData::NetworkControl::NetworkData::ModeType how(index->second.Mode()); if (how != JsonData::NetworkControl::NetworkData::ModeType::MANUAL) { Reload(interfaceName, how == JsonData::NetworkControl::NetworkData::ModeType::DYNAMIC); } } } else { ClearAssignedIPs(adapter); Core::AdapterIterator::Flush(); } _adminLock.Unlock(); } else { // Seems like the adapter disappeared. Remove it. _adminLock.Lock(); std::map<const string, StaticInfo>::iterator info(_interfaces.find(interfaceName)); if (info != _interfaces.end()) { _interfaces.erase(info); } std::map<const string, Core::ProxyType<DHCPEngine>>::iterator dhcp(_dhcpInterfaces.find(interfaceName)); if (dhcp != _dhcpInterfaces.end()) { _dhcpInterfaces.erase(dhcp); } _adminLock.Unlock(); TRACE(Trace::Information, (_T("Removed interface: %s"), interfaceName.c_str())); status = JsonData::NetworkControl::ConnectionchangeParamsData::StatusType::REMOVED; message = string(_T("{ \"interface\": \"")) + interfaceName + string(_T("\", \"running\": \"false\", \"up\": \"false\", \"event\": \"Delete\" }")); } _service->Notify(message); event_connectionchange(interfaceName.c_str(), string(), status); } void NetworkControl::ClearAssignedIPV4IPs(Core::AdapterIterator& adapter) { Core::IPV4AddressIterator checker = adapter.IPV4Addresses(); while (checker.Next() == true) { adapter.Delete(checker.Address()); } } void NetworkControl::ClearAssignedIPV6IPs(Core::AdapterIterator& adapter) { Core::IPV6AddressIterator checker = adapter.IPV6Addresses(); while (checker.Next() == true) { adapter.Delete(checker.Address()); } } } // namespace Plugin } // namespace WPEFramework
//----------------------------------------------------------------------------- // MIT License // // Copyright (c) 2017 Jeff Hutchinson // Copyright (c) 2017 Tim Barnes // // 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. //----------------------------------------------------------------------------- #ifndef _PLATFORM_GLFW_GLFWTIMER_H_ #define _PLATFORM_GLFW_GLFWTIMER_H_ #include "platform/timer.hpp" #include <GLFW/glfw3.h> class GLFWTimer : public Timer { public: GLFWTimer(); virtual void start() override; virtual void stop() override; }; #endif
/* * Copyright (c) 2021 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <gtest/gtest.h> #include <string> #include "common.h" #include "logger.h" #include "rdb_errno.h" #include "rdb_helper.h" #include "rdb_open_callback.h" using namespace testing::ext; using namespace OHOS::NativeRdb; class RdbStoreInterfaceTest : public testing::Test { public: static void SetUpTestCase(void); static void TearDownTestCase(void); void SetUp(); void TearDown(); }; class MyOpenCallback : public RdbOpenCallback { public: int OnCreate(RdbStore &rdbStore) override; int OnUpgrade(RdbStore &rdbStore, int oldVersion, int newVersion) override; static const std::string CREATE_TABLE_TEST; }; const std::string MyOpenCallback::CREATE_TABLE_TEST = std::string("CREATE TABLE IF NOT EXISTS test ") + std::string("(id INTEGER PRIMARY KEY AUTOINCREMENT, name " "TEXT, " "age INTEGER, salary REAL, blobType BLOB)"); int MyOpenCallback::OnCreate(RdbStore &store) { return store.ExecuteSql(CREATE_TABLE_TEST); } int MyOpenCallback::OnUpgrade(RdbStore &store, int oldVersion, int newVersion) { return E_OK; } void RdbStoreInterfaceTest::SetUpTestCase(void) { } void RdbStoreInterfaceTest::TearDownTestCase(void) { } void RdbStoreInterfaceTest::SetUp(void) { } void RdbStoreInterfaceTest::TearDown(void) { } /** * @tc.name: ValueObject_TEST_001 * @tc.desc: test ValueObject * @tc.type: FUNC * @tc.require: AR000CU2BO * @tc.author: chenxi */ HWTEST_F(RdbStoreInterfaceTest, ValueObject_TEST_001, TestSize.Level1) { ValueObject obj = ValueObject(); ValueObjectType type = obj.GetType(); EXPECT_EQ(type, ValueObjectType::TYPE_NULL); } /** * @tc.name: ValueObject_TEST_002 * @tc.desc: test ValueObject * @tc.type: FUNC * @tc.require: AR000CU2BO * @tc.author: chenxi */ HWTEST_F(RdbStoreInterfaceTest, ValueObject_TEST_002, TestSize.Level1) { int inputVal = 5; int outputVal = 0; ValueObject obj = ValueObject(inputVal); ValueObjectType type = obj.GetType(); EXPECT_EQ(type, ValueObjectType::TYPE_INT); int ret = obj.GetInt(outputVal); EXPECT_EQ(ret, E_OK); EXPECT_EQ(outputVal, 5); } /** * @tc.name: ValueObject_TEST_003 * @tc.desc: test ValueObject * @tc.type: FUNC * @tc.require: AR000CU2BO * @tc.author: chenxi */ HWTEST_F(RdbStoreInterfaceTest, ValueObject_TEST_003, TestSize.Level1) { bool inputVal = true; bool outputVal = false; ValueObject obj = ValueObject(inputVal); ValueObjectType type = obj.GetType(); EXPECT_EQ(type, ValueObjectType::TYPE_BOOL); int ret = obj.GetBool(outputVal); EXPECT_EQ(ret, E_OK); EXPECT_EQ(outputVal, true); } /** * @tc.name: ValueObject_TEST_004 * @tc.desc: test ValueObject * @tc.type: FUNC * @tc.require: AR000CU2BO * @tc.author: chenxi */ HWTEST_F(RdbStoreInterfaceTest, ValueObject_TEST_004, TestSize.Level1) { std::string inputVal = "hello"; std::string outputVal = ""; ValueObject obj = ValueObject(inputVal); ValueObjectType type = obj.GetType(); EXPECT_EQ(type, ValueObjectType::TYPE_STRING); int ret = obj.GetString(outputVal); EXPECT_EQ(ret, E_OK); EXPECT_EQ(outputVal, "hello"); } /** * @tc.name: ValueObject_TEST_005 * @tc.desc: test ValueObject * @tc.type: FUNC * @tc.require: AR000CU2BO * @tc.author: chenxi */ HWTEST_F(RdbStoreInterfaceTest, ValueObject_TEST_005, TestSize.Level1) { std::vector<uint8_t> inputVal = { 'h', 'e', 'l', 'l', 'o' }; std::vector<uint8_t> outputVal; ValueObject obj = ValueObject(inputVal); ValueObjectType type = obj.GetType(); EXPECT_EQ(type, ValueObjectType::TYPE_BLOB); int ret = obj.GetBlob(outputVal); EXPECT_EQ(ret, E_OK); EXPECT_EQ(static_cast<int>(outputVal.size()), 5); EXPECT_EQ(outputVal[0], 'h'); EXPECT_EQ(outputVal[1], 'e'); EXPECT_EQ(outputVal[2], 'l'); EXPECT_EQ(outputVal[3], 'l'); EXPECT_EQ(outputVal[4], 'o'); } /** * @tc.name: ValuesBucket_001 * @tc.desc: test ValuesBucket * @tc.type: FUNC * @tc.require: AR000CU2BO * @tc.author: chenxi */ HWTEST_F(RdbStoreInterfaceTest, ValuesBucket_001, TestSize.Level1) { ValuesBucket values; values.PutInt("id", 1); values.PutNull("name"); values.PutInt("age", 18); values.PutDouble("salary", 100.5); values.PutBlob("blobType", std::vector<uint8_t>{ 1, 2, 3 }); int size = values.Size(); EXPECT_EQ(size, 5); bool contains = values.HasColumn("name"); EXPECT_EQ(contains, true); ValueObject obj; contains = values.GetObject("salary", obj); double val = 0.0; ValueObjectType type = obj.GetType(); EXPECT_EQ(type, ValueObjectType::TYPE_DOUBLE); int ret = obj.GetDouble(val); EXPECT_EQ(ret, E_OK); EXPECT_EQ(val, 100.5); values.Delete("name"); size = values.Size(); EXPECT_EQ(size, 4); contains = values.HasColumn("name"); EXPECT_EQ(contains, false); values.Clear(); size = values.Size(); EXPECT_EQ(size, 0); contains = values.HasColumn("salary"); EXPECT_EQ(contains, false); } /** * @tc.name: ValuesBucket_002 * @tc.desc: test ValuesBucket * @tc.type: FUNC * @tc.require: AR000CU2BO * @tc.author: chenxi */ HWTEST_F(RdbStoreInterfaceTest, ValuesBucket_002, TestSize.Level1) { int errCode = E_OK; const std::string dbPath = RDB_TEST_PATH + "InterfaceTest.db"; RdbStoreConfig config(dbPath); MyOpenCallback helper; std::shared_ptr<RdbStore> store = RdbHelper::GetRdbStore(config, 1, helper, errCode); EXPECT_NE(store, nullptr); EXPECT_EQ(errCode, E_OK); int64_t id; ValuesBucket values; values.PutInt("id", 1); values.PutNull("name"); values.PutInt("age", 18); values.PutDouble("salary", 100.5); values.PutBlob("blobType", std::vector<uint8_t>{ 1, 2, 3 }); int ret = store->Insert(id, "test", values); EXPECT_EQ(ret, E_OK); EXPECT_EQ(1, id); std::unique_ptr<ResultSet> resultSet = store->QuerySql("SELECT * FROM test"); EXPECT_NE(resultSet, nullptr); int columnIndex; std::string strVal; ret = resultSet->GoToFirstRow(); EXPECT_EQ(ret, E_OK); ret = resultSet->GetColumnIndex("name", columnIndex); EXPECT_EQ(ret, E_OK); ret = resultSet->GetString(columnIndex, strVal); EXPECT_EQ(ret, E_ERROR); store = nullptr; ret = RdbHelper::DeleteRdbStore(dbPath); EXPECT_EQ(ret, E_OK); } /** * @tc.name: ValuesBucket_003 * @tc.desc: test ValuesBucket * @tc.type: FUNC * @tc.require: AR000CU2BO * @tc.author: chenxi */ HWTEST_F(RdbStoreInterfaceTest, ValuesBucket_003, TestSize.Level1) { ValuesBucket values; values.PutBool("boolType", true); values.PutLong("longType", 1); int size = values.Size(); EXPECT_EQ(size, 2); bool contains = values.HasColumn("boolType"); EXPECT_EQ(contains, true); ValueObject obj; contains = values.GetObject("boolType", obj); ValueObjectType type = obj.GetType(); EXPECT_EQ(type, ValueObjectType::TYPE_BOOL); bool val1 = false; int ret = obj.GetBool(val1); EXPECT_EQ(ret, E_OK); EXPECT_EQ(val1, true); contains = values.HasColumn("longType"); EXPECT_EQ(contains, true); contains = values.GetObject("longType", obj); type = obj.GetType(); EXPECT_EQ(type, ValueObjectType::TYPE_INT); int64_t val2 = 0; ret = obj.GetLong(val2); EXPECT_EQ(ret, E_OK); EXPECT_EQ(val2, 1); }
/* Copyright (C) 2015-present The DotCpp Authors. This file is part of .C++, a native C++ implementation of popular .NET class library APIs developed to facilitate code reuse between C# and C++. http://github.com/dotcpp/dotcpp (source) http://dotcpp.org (documentation) 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 <dot/test/implement.hpp> #include <approvals/ApprovalTests.hpp> #include <approvals/Catch.hpp> #include <dot/system/object.hpp> #include <dot/system/string.hpp> namespace dot { TEST_CASE("clear object") { Object a = make_object(); Object b = make_object(); REQUIRE(a->equals(a) == true); REQUIRE(a->equals(b) == false); REQUIRE(a->hash_code() != b->hash_code()); } TEST_CASE("equals") { Object a = make_string("str"); Object b = make_string("str"); Object c = make_string("str1"); REQUIRE(a->equals(a)); REQUIRE(a->equals(b)); REQUIRE(a->equals(c) == false); REQUIRE(a->hash_code() == a->hash_code()); REQUIRE(a->hash_code() == b->hash_code()); REQUIRE(a->hash_code() != c->hash_code()); } }
#include "Engine/RenderGraph/AcquireNode.h" using namespace VoxelEngine; AcquireNode::AcquireNode(VoxelEngine::Engine& engine, RenderGraph& graph) : RenderGraph::Node(graph, *engine.getGraphics().graphicsQueue(), vk::PipelineStageFlags::TopOfPipe) { m_swapchain = &engine.getGraphics().swapchain(); vk::SemaphoreCreateInfo info = {}; m_semaphore = std::make_unique<vk::Semaphore>(m_swapchain->device(), info); addExternalWait(*m_semaphore, vk::PipelineStageFlags::ColorAttachmentOutput); m_imageUsage = std::make_unique<RenderGraph::ImageUsage>(*this, vk::ImageLayout::Undefined, vk::AccessFlags::None, vk::PipelineStageFlags::None); engine.getGraphics().onSwapchainChanged().connect<&AcquireNode::onSwapchainChanged>(this); } void AcquireNode::preRender(uint32_t currentFrame) { m_swapchain->acquireNextImage(-1, m_semaphore.get(), nullptr, m_swapchainIndex); } void AcquireNode::onSwapchainChanged(vk::Swapchain& swapchain) { m_swapchain = &swapchain; }
/** @defgroup MleParts Magic Lantern Parts */ /** * @file filewmrf.h * @ingroup MleParts * * This file implements the class for a generic File Media Reference * targeting the BRender platform. * * @author Mark S. Millard * @date May 1, 2003 */ // COPYRIGHT_BEGIN // // Copyright (C) 2000-2007 Wizzer Works // // Wizzer Works makes available all content in this file ("Content"). // Unless otherwise indicated below, the Content is provided to you // under the terms and conditions of the Common Public License Version 1.0 // ("CPL"). A copy of the CPL is available at // // http://opensource.org/licenses/cpl1.0.php // // For purposes of the CPL, "Program" will mean the Content. // // For information concerning this Makefile, contact Mark S. Millard, // of Wizzer Works at msm@wizzerworks.com. // // More information concerning Wizzer Works may be found at // // http://www.wizzerworks.com // // COPYRIGHT_END #include <mle/MleMediaRef.h> #include <mle/refucvt.h> #include <mle/filewmrf.h> MLE_MEDIAREF_SOURCE(filewmrf,filemref); filewmrf::filewmrf() { // Replace the old ref converter with one that understands URLs delRefConverter(); setRefConverter(new MleReferenceUrlConverter); }
/* Copyright 2020 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ #include "tensorflow/compiler/mlir/mlir_graph_optimization_pass.h" #include <string> #include "absl/container/flat_hash_set.h" #include "llvm/ADT/STLExtras.h" #include "llvm/Support/FormatVariadic.h" #include "llvm/Support/raw_os_ostream.h" #include "mlir/Dialect/Shape/IR/Shape.h" // from @llvm-project #include "mlir/Dialect/StandardOps/IR/Ops.h" // from @llvm-project #include "tensorflow/compiler/mlir/tensorflow/ir/tf_device.h" #include "tensorflow/compiler/mlir/tensorflow/ir/tf_executor.h" #include "tensorflow/compiler/mlir/tensorflow/ir/tf_ops.h" #include "tensorflow/compiler/mlir/tensorflow/translate/export_graphdef.h" #include "tensorflow/compiler/mlir/tensorflow/translate/import_model.h" #include "tensorflow/compiler/mlir/tensorflow/translate/mlir_roundtrip_flags.h" #include "tensorflow/compiler/mlir/tensorflow/utils/device_util.h" #include "tensorflow/compiler/mlir/tensorflow/utils/dump_mlir_util.h" #include "tensorflow/core/common_runtime/graph_constructor.h" #include "tensorflow/core/public/session_options.h" namespace tensorflow { static inline absl::string_view StringRefToView(llvm::StringRef ref) { return {ref.data(), ref.size()}; } // Dumps the MLIR module to disk. // This require the TF_DUMP_GRAPH_PREFIX to be set to a path that exist (or can // be created). static void DumpModule(mlir::ModuleOp module, std::string file_prefix) { std::string prefix = GetDumpDirFromEnvVar(); if (prefix.empty()) return; auto* env = tensorflow::Env::Default(); auto status = env->RecursivelyCreateDir(prefix); if (!status.ok()) { LOG(WARNING) << "cannot create directory '" + prefix + "': " + status.error_message(); return; } prefix += "/" + file_prefix; if (!tensorflow::Env::Default()->CreateUniqueFileName(&prefix, ".mlir")) { LOG(WARNING) << "cannot create unique filename, won't dump MLIR module."; return; } std::unique_ptr<WritableFile> file_writer; status = env->NewWritableFile(prefix, &file_writer); if (!status.ok()) { LOG(WARNING) << "cannot open file '" + prefix + "': " + status.error_message(); return; } // Print the module to a string before writing to the file. std::string txt_module; { llvm::raw_string_ostream os(txt_module); module.print(os); } status = file_writer->Append(txt_module); if (!status.ok()) { LOG(WARNING) << "error writing to file '" + prefix + "': " + status.error_message(); return; } (void)file_writer->Close(); VLOG(1) << "Dumped MLIR module to " << prefix; } MlirOptimizationPassRegistry& MlirOptimizationPassRegistry::Global() { static auto* global = new MlirOptimizationPassRegistry(); return *global; } static void RegisterDialects(mlir::DialectRegistry& registry) { // clang-format off registry.insert<mlir::StandardOpsDialect, mlir::TF::TensorFlowDialect, mlir::shape::ShapeDialect, mlir::tf_device::TensorFlowDeviceDialect, mlir::tf_executor::TensorFlowExecutorDialect>(); // clang-format on } Status MlirFunctionOptimizationPass::Run( const DeviceSet& device_set, const ConfigProto& config_proto, std::unique_ptr<Graph>* graph, FunctionLibraryDefinition* flib_def, std::vector<std::string>* control_ret_node_names, bool* control_rets_updated) { // Skip conversion from Graph to MLIR if none of the passes are enabled. const bool is_enabled = llvm::any_of(registry_->passes(), [&](auto& pass_registration) -> bool { return pass_registration.pass->IsEnabled(config_proto, **graph); }); if (!is_enabled) { LOG_FIRST_N(INFO, 1) << "None of the MLIR optimization passes are enabled " << "(registered " << registry_->passes().size() << ")"; return Status::OK(); } LOG_FIRST_N(INFO, 1) << "Running MLIR Graph Optimization Passes " << "(registered " << registry_->passes().size() << " passes)"; GraphDebugInfo debug_info; mlir::MLIRContext context; RegisterDialects(context.getDialectRegistry()); GraphImportConfig import_config; import_config.graph_as_function = true; import_config.control_outputs = *control_ret_node_names; import_config.upgrade_legacy = true; TF_ASSIGN_OR_RETURN(auto module_ref, ConvertGraphToMlir(**graph, debug_info, *flib_def, import_config, &context)); AddDevicesToOp(*module_ref, &device_set); for (auto& pass_registration : registry_->passes()) { llvm::StringRef name = pass_registration.pass->name(); VLOG(2) << "Run MLIR graph optimization pass: " << StringRefToView(name); if (VLOG_IS_ON(1)) { DumpModule(*module_ref, llvm::formatv("mlir_{0}_before_", name)); } TF_RETURN_IF_ERROR( pass_registration.pass->Run(config_proto, *module_ref, **graph)); if (VLOG_IS_ON(1)) { DumpModule(*module_ref, llvm::formatv("mlir_{0}_after_", name)); } } GraphExportConfig export_config; absl::flat_hash_set<Node*> control_ret_nodes; TF_RETURN_WITH_CONTEXT_IF_ERROR( ConvertMlirToGraph(*module_ref, export_config, graph, flib_def, &control_ret_nodes), "Error converting MLIR module back to graph"); control_ret_node_names->clear(); control_ret_node_names->reserve(control_ret_nodes.size()); for (const auto* node : control_ret_nodes) control_ret_node_names->push_back(node->name()); *control_rets_updated = true; return Status::OK(); } MlirV1CompatOptimizationPassRegistry& MlirV1CompatOptimizationPassRegistry::Global() { static auto* global = new MlirV1CompatOptimizationPassRegistry(); return *global; } Status MlirV1CompatGraphOptimizationPass::Run( const GraphOptimizationPassOptions& options) { // Skip function graphs as MlirOptimizationPassRegistry_ will be used instead. if (options.is_function_graph) return Status::OK(); // Skip conversion from Graph to MLIR if none of the passes are enabled. const bool is_enabled = absl::c_any_of(registry_->passes(), [&](auto& pass_registration) -> bool { return pass_registration.pass->IsEnabled( options.session_options->config, **options.graph); }); if (!is_enabled) { LOG_FIRST_N(INFO, 1) << "None of the MLIR optimization passes are enabled " << "(registered " << registry_->passes().size() << " passes)"; return Status::OK(); } LOG_FIRST_N(INFO, 1) << "Running MLIR Graph Optimization V1 Compat Passes " << "(registered " << registry_->passes().size() << " passes)"; GraphDebugInfo debug_info; mlir::MLIRContext context; RegisterDialects(context.getDialectRegistry()); GraphImportConfig import_config; import_config.upgrade_legacy = true; // Restrict functionalization to TPU nodes to avoid problems in v1 session // runtime. import_config.restrict_functionalization_to_tpu_nodes = true; TF_ASSIGN_OR_RETURN( auto module_ref, ConvertGraphToMlir(**options.graph, debug_info, *options.flib_def, import_config, &context)); AddDevicesToOp(*module_ref, options.device_set); for (auto& pass_registration : registry_->passes()) { llvm::StringRef name = pass_registration.pass->name(); VLOG(2) << "Run MLIR graph optimization pass: " << StringRefToView(name); if (VLOG_IS_ON(1)) { DumpModule(*module_ref, llvm::formatv("mlir_{0}_before_", name)); } TF_RETURN_IF_ERROR(pass_registration.pass->Run(options, *module_ref)); if (VLOG_IS_ON(1)) { DumpModule(*module_ref, llvm::formatv("mlir_{0}_after_", name)); } } GraphExportConfig export_config; TF_RETURN_WITH_CONTEXT_IF_ERROR( ConvertMlirToGraph(*module_ref, export_config, options.graph, options.flib_def), "Error converting MLIR module back to graph"); return Status::OK(); } } // namespace tensorflow
// FloodyFluidSimulator.cpp // Interfaces to the cFloodyFluidSimulator that represents a fluid simulator that tries to flood everything :) // https://forum.cuberite.org/thread-565.html #include "Globals.h" #include "FloodyFluidSimulator.h" #include "../BlockInfo.h" #include "../World.h" #include "../Chunk.h" #include "../BlockArea.h" #include "../Blocks/BlockHandler.h" #include "../BlockInServerPluginInterface.h" #include "../Blocks/ChunkInterface.h" // Enable or disable detailed logging #if 0 #define FLUID_FLOG FLOGD #else #define FLUID_FLOG(...) #endif cFloodyFluidSimulator::cFloodyFluidSimulator( cWorld & a_World, BLOCKTYPE a_Fluid, BLOCKTYPE a_StationaryFluid, NIBBLETYPE a_Falloff, int a_TickDelay, int a_NumNeighborsForSource ) : Super(a_World, a_Fluid, a_StationaryFluid, a_TickDelay), m_Falloff(a_Falloff), m_NumNeighborsForSource(a_NumNeighborsForSource) { } void cFloodyFluidSimulator::SimulateBlock(cChunk * a_Chunk, int a_RelX, int a_RelY, int a_RelZ) { FLUID_FLOG("Simulating block {0}: block {1}, meta {2}", a_Chunk->PositionToWorldPosition(a_RelX, a_RelY, a_RelZ), a_Chunk->GetBlock(a_RelX, a_RelY, a_RelZ), a_Chunk->GetMeta(a_RelX, a_RelY, a_RelZ) ); BLOCKTYPE MyBlock; NIBBLETYPE MyMeta; a_Chunk->GetBlockTypeMeta(a_RelX, a_RelY, a_RelZ, MyBlock, MyMeta); if (!IsAnyFluidBlock(MyBlock)) { // Can happen - if a block is scheduled for simulating and gets replaced in the meantime. FLUID_FLOG(" BadBlockType exit"); return; } // When in contact with water, lava should harden if (HardenBlock(a_Chunk, {a_RelX, a_RelY, a_RelZ}, MyBlock, MyMeta)) { // Block was changed, bail out return; } if (MyMeta != 0) { // Source blocks aren't checked for tributaries, others are. if (CheckTributaries(a_Chunk, a_RelX, a_RelY, a_RelZ, MyMeta)) { // Has no tributary, has been decreased (in CheckTributaries()), // no more processing needed (neighbors have been scheduled by the decrease) FLUID_FLOG(" CheckTributaries exit"); return; } } // New meta for the spreading to neighbors: // If this is a source block or was falling, the new meta is just the falloff // Otherwise it is the current meta plus falloff (may be larger than max height, will be checked later) NIBBLETYPE NewMeta = ((MyMeta == 0) || ((MyMeta & 0x08) != 0)) ? m_Falloff : (MyMeta + m_Falloff); if (a_RelY > 0) { bool SpreadFurther = true; BLOCKTYPE Below = a_Chunk->GetBlock(a_RelX, a_RelY - 1, a_RelZ); if (IsPassableForFluid(Below) || IsBlockLava(Below) || IsBlockWater(Below)) { // Spread only down, possibly washing away what's there or turning lava to stone / cobble / obsidian: SpreadToNeighbor(a_Chunk, a_RelX, a_RelY - 1, a_RelZ, 8); // Source blocks spread both downwards and sideways if (MyMeta != 0) { SpreadFurther = false; } } // Spread to the neighbors: if (SpreadFurther && (NewMeta < 8)) { SpreadXZ(a_Chunk, a_RelX, a_RelY, a_RelZ, NewMeta); } // If source creation is on, check for it here: if ( (m_NumNeighborsForSource > 0) && // Source creation is on (MyMeta == m_Falloff) && // Only exactly one block away from a source (fast bail-out) ( !IsPassableForFluid(Below) || // Only exactly 1 block deep (Below == m_StationaryFluidBlock) // Or a source block underneath ) && CheckNeighborsForSource(a_Chunk, a_RelX, a_RelY, a_RelZ) // Did we create a source? ) { // We created a source, no more spreading is to be done now // Also has been re-scheduled for ticking in the next wave, so no marking is needed return; } } // Mark as processed: a_Chunk->FastSetBlock(a_RelX, a_RelY, a_RelZ, m_StationaryFluidBlock, MyMeta); } void cFloodyFluidSimulator::SpreadXZ(cChunk * a_Chunk, int a_RelX, int a_RelY, int a_RelZ, NIBBLETYPE a_NewMeta) { SpreadToNeighbor(a_Chunk, a_RelX - 1, a_RelY, a_RelZ, a_NewMeta); SpreadToNeighbor(a_Chunk, a_RelX + 1, a_RelY, a_RelZ, a_NewMeta); SpreadToNeighbor(a_Chunk, a_RelX, a_RelY, a_RelZ - 1, a_NewMeta); SpreadToNeighbor(a_Chunk, a_RelX, a_RelY, a_RelZ + 1, a_NewMeta); } bool cFloodyFluidSimulator::CheckTributaries(cChunk * a_Chunk, int a_RelX, int a_RelY, int a_RelZ, NIBBLETYPE a_MyMeta) { // If we have a section above, check if there's fluid above this block that would feed it: if (a_RelY < cChunkDef::Height - 1) { if (IsAnyFluidBlock(a_Chunk->GetBlock(a_RelX, a_RelY + 1, a_RelZ))) { // This block is fed from above, no more processing needed FLUID_FLOG(" Fed from above"); return false; } } // Not fed from above, check if there's a feed from the side (but not if it's a downward-flowing block): if (a_MyMeta != 8) { BLOCKTYPE BlockType; NIBBLETYPE BlockMeta; static const Vector3i Coords[] = { Vector3i( 1, 0, 0), Vector3i(-1, 0, 0), Vector3i( 0, 0, 1), Vector3i( 0, 0, -1), } ; for (size_t i = 0; i < ARRAYCOUNT(Coords); i++) { if (!a_Chunk->UnboundedRelGetBlock(a_RelX + Coords[i].x, a_RelY, a_RelZ + Coords[i].z, BlockType, BlockMeta)) { continue; } if (IsAllowedBlock(BlockType) && IsHigherMeta(BlockMeta, a_MyMeta)) { // This block is fed, no more processing needed FLUID_FLOG(" Fed from {0}, type {1}, meta {2}", a_Chunk->PositionToWorldPosition(a_RelX+ Coords[i].x, a_RelY, a_RelZ + Coords[i].z), BlockType, BlockMeta ); return false; } } // for i - Coords[] } // if not fed from above // Block is not fed, decrease by m_Falloff levels: if (a_MyMeta >= 8) { FLUID_FLOG(" Not fed and downwards, turning into non-downwards meta {0}", m_Falloff); a_Chunk->SetBlock({a_RelX, a_RelY, a_RelZ}, m_StationaryFluidBlock, m_Falloff); } else { a_MyMeta += m_Falloff; if (a_MyMeta < 8) { FLUID_FLOG(" Not fed, decreasing from {0} to {1}", a_MyMeta - m_Falloff, a_MyMeta); a_Chunk->SetBlock({a_RelX, a_RelY, a_RelZ}, m_StationaryFluidBlock, a_MyMeta); } else { FLUID_FLOG(" Not fed, meta {0}, erasing altogether", a_MyMeta); a_Chunk->SetBlock({a_RelX, a_RelY, a_RelZ}, E_BLOCK_AIR, 0); } } return true; } void cFloodyFluidSimulator::SpreadToNeighbor(cChunk * a_NearChunk, int a_RelX, int a_RelY, int a_RelZ, NIBBLETYPE a_NewMeta) { ASSERT(a_NewMeta <= 8); // Invalid meta values ASSERT(a_NewMeta > 0); // Source blocks aren't spread Vector3i relPos(a_RelX, a_RelY, a_RelZ); a_NearChunk = a_NearChunk->GetRelNeighborChunkAdjustCoords(relPos); if ((a_NearChunk == nullptr) || (!a_NearChunk->IsValid())) { // Chunk not available return; } const auto absPos = a_NearChunk->RelativeToAbsolute(relPos); BLOCKTYPE BlockType; NIBBLETYPE BlockMeta; a_NearChunk->GetBlockTypeMeta(relPos, BlockType, BlockMeta); if (IsAllowedBlock(BlockType)) { if ((BlockMeta == a_NewMeta) || IsHigherMeta(BlockMeta, a_NewMeta)) { // Don't spread there, there's already a higher or same level there return; } } // Check water - lava interaction: if (m_FluidBlock == E_BLOCK_LAVA) { if (IsBlockWater(BlockType)) { // Lava flowing into water, change to stone / cobblestone based on direction: BLOCKTYPE NewBlock = (a_NewMeta == 8) ? E_BLOCK_STONE : E_BLOCK_COBBLESTONE; FLUID_FLOG(" Lava flowing into water, turning water at rel {0} into {1}", relPos, ItemTypeToString(NewBlock) ); a_NearChunk->SetBlock(relPos, NewBlock, 0); m_World.BroadcastSoundEffect( "block.lava.extinguish", absPos, 0.5f, 1.5f ); return; } } else if (m_FluidBlock == E_BLOCK_WATER) { if (IsBlockLava(BlockType)) { // Water flowing into lava, change to cobblestone / obsidian based on dest block: BLOCKTYPE NewBlock = (BlockMeta == 0) ? E_BLOCK_OBSIDIAN : E_BLOCK_COBBLESTONE; FLUID_FLOG(" Water flowing into lava, turning lava at rel {0} into {1}", relPos, ItemTypeToString(NewBlock) ); a_NearChunk->SetBlock(relPos, NewBlock, 0); m_World.BroadcastSoundEffect( "block.lava.extinguish", absPos, 0.5f, 1.5f ); return; } } else { ASSERT(!"Unknown fluid!"); } if (!IsPassableForFluid(BlockType)) { // Can't spread there return; } // Wash away the block there, if possible: if (CanWashAway(BlockType)) { if (cBlockHandler::For(BlockType).DoesDropOnUnsuitable()) { m_World.DropBlockAsPickups(absPos, nullptr, nullptr); } } // if (CanWashAway) // Spread: FLUID_FLOG(" Spreading to {0} with meta {1}", absPos, a_NewMeta); a_NearChunk->SetBlock(relPos, m_FluidBlock, a_NewMeta); m_World.GetSimulatorManager()->WakeUp(*a_NearChunk, relPos); HardenBlock(a_NearChunk, relPos, m_FluidBlock, a_NewMeta); } bool cFloodyFluidSimulator::CheckNeighborsForSource(cChunk * a_Chunk, int a_RelX, int a_RelY, int a_RelZ) { FLUID_FLOG(" Checking neighbors for source creation"); static const Vector3i NeighborCoords[] = { Vector3i(-1, 0, 0), Vector3i( 1, 0, 0), Vector3i( 0, 0, -1), Vector3i( 0, 0, 1), } ; int NumNeeded = m_NumNeighborsForSource; for (size_t i = 0; i < ARRAYCOUNT(NeighborCoords); i++) { int x = a_RelX + NeighborCoords[i].x; int y = a_RelY + NeighborCoords[i].y; int z = a_RelZ + NeighborCoords[i].z; BLOCKTYPE BlockType; NIBBLETYPE BlockMeta; if (!a_Chunk->UnboundedRelGetBlock(x, y, z, BlockType, BlockMeta)) { // Neighbor not available, skip it continue; } // FLUID_FLOG(" Neighbor at {0}: {1}", Vector3i{x, y, z}, ItemToFullString(cItem(BlockType, 1, BlockMeta))); if ((BlockMeta == 0) && IsAnyFluidBlock(BlockType)) { NumNeeded--; // FLUID_FLOG(" Found a neighbor source at {0}, NumNeeded := {1}", Vector3i{x, y, z}, NumNeeded); if (NumNeeded == 0) { // Found enough, turn into a source and bail out // FLUID_FLOG(" Found enough neighbor sources, turning into a source"); a_Chunk->SetBlock({a_RelX, a_RelY, a_RelZ}, m_FluidBlock, 0); return true; } } } // FLUID_FLOG(" Not enough neighbors for turning into a source, NumNeeded = {0}", NumNeeded); return false; } bool cFloodyFluidSimulator::HardenBlock(cChunk * a_Chunk, Vector3i a_RelPos, BLOCKTYPE a_BlockType, NIBBLETYPE a_Meta) { ASSERT(cChunkDef::IsValidRelPos(a_RelPos)); // Only lava blocks can harden if (!IsBlockLava(a_BlockType)) { return false; } bool ShouldHarden = false; BLOCKTYPE BlockType; NIBBLETYPE BlockMeta; static const Vector3i neighborOffsets[] = { Vector3i( 1, 0, 0), Vector3i(-1, 0, 0), Vector3i( 0, 0, 1), Vector3i( 0, 0, -1), }; for (const auto & ofs: neighborOffsets) { if (!a_Chunk->UnboundedRelGetBlock(a_RelPos + ofs, BlockType, BlockMeta)) { continue; } if (IsBlockWater(BlockType)) { ShouldHarden = true; } } // for i - Coords[] if (ShouldHarden) { if (a_Meta == 0) { // Source lava block a_Chunk->SetBlock(a_RelPos, E_BLOCK_OBSIDIAN, 0); return true; } // Ignore last lava level else if (a_Meta <= 4) { a_Chunk->SetBlock(a_RelPos, E_BLOCK_COBBLESTONE, 0); return true; } } return false; }
// Copyright (C) 2020-2022 Jonathan Müller and lexy contributors // SPDX-License-Identifier: BSL-1.0 #include <lexy/dsl/digit.hpp> #include "verify.hpp" TEST_CASE("dsl::zero") { constexpr auto rule = dsl::zero; CHECK(lexy::is_token_rule<decltype(rule)>); constexpr auto callback = token_callback; auto empty = LEXY_VERIFY(""); CHECK(empty.status == test_result::fatal_error); CHECK(empty.trace == test_trace().expected_char_class(0, "digit.zero").cancel()); auto zero = LEXY_VERIFY("0"); CHECK(zero.status == test_result::success); CHECK(zero.trace == test_trace().token("digits", "0")); auto zerozero = LEXY_VERIFY("00"); CHECK(zerozero.status == test_result::success); CHECK(zerozero.trace == test_trace().token("digits", "0")); auto nine = LEXY_VERIFY("9"); CHECK(nine.status == test_result::fatal_error); CHECK(nine.trace == test_trace().expected_char_class(0, "digit.zero").cancel()); auto utf16 = LEXY_VERIFY(u"0"); CHECK(utf16.status == test_result::success); CHECK(utf16.trace == test_trace().token("digits", "0")); } TEST_CASE("dsl::digit") { constexpr auto callback = token_callback; auto check_valid = [&](auto rule, auto... _digits) { char digits[] = {_digits...}; auto value = 0; for (auto digit : digits) { auto result = LEXY_VERIFY_RUNTIME(lexy::ascii_encoding{}, digit, digit, digit); CHECK(result.status == test_result::success); CHECK(result.trace == test_trace().token("digits", doctest::String(&digit, 1).c_str())); CHECK(rule.digit_value(digit) == value); ++value; } }; auto check_invalid = [&](auto rule, const char* name, auto... _digits) { char digits[] = {_digits...}; for (auto digit : digits) { auto result = LEXY_VERIFY_RUNTIME(lexy::ascii_encoding{}, digit, digit, digit); CHECK(result.status == test_result::fatal_error); CHECK(result.trace == test_trace().expected_char_class(0, name).cancel()); CHECK(rule.digit_value(digit) >= rule.digit_radix); } }; SUBCASE("binary") { constexpr auto rule = dsl::digit<dsl::binary>; CHECK(lexy::is_token_rule<decltype(rule)>); CHECK(rule.digit_radix == 2); auto empty = LEXY_VERIFY(""); CHECK(empty.status == test_result::fatal_error); CHECK(empty.trace == test_trace().expected_char_class(0, "digit.binary").cancel()); check_valid(rule, '0', '1'); check_invalid(rule, "digit.binary", '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f', 'A', 'B', 'C', 'D', 'E', 'F'); } SUBCASE("octal") { constexpr auto rule = dsl::digit<dsl::octal>; CHECK(lexy::is_token_rule<decltype(rule)>); CHECK(rule.digit_radix == 8); auto empty = LEXY_VERIFY(""); CHECK(empty.status == test_result::fatal_error); CHECK(empty.trace == test_trace().expected_char_class(0, "digit.octal").cancel()); check_valid(rule, '0', '1', '2', '3', '4', '5', '6', '7'); check_invalid(rule, "digit.octal", '8', '9', 'a', 'b', 'c', 'd', 'e', 'f', 'A', 'B', 'C', 'D', 'E', 'F'); } SUBCASE("decimal") { constexpr auto rule = dsl::digit<dsl::decimal>; CHECK(lexy::is_token_rule<decltype(rule)>); CHECK(rule.digit_radix == 10); auto empty = LEXY_VERIFY(""); CHECK(empty.status == test_result::fatal_error); CHECK(empty.trace == test_trace().expected_char_class(0, "digit.decimal").cancel()); check_valid(rule, '0', '1', '2', '3', '4', '5', '6', '7', '8', '9'); check_invalid(rule, "digit.decimal", 'a', 'b', 'c', 'd', 'e', 'f', 'A', 'B', 'C', 'D', 'E', 'F'); } SUBCASE("hex_lower") { constexpr auto rule = dsl::digit<dsl::hex_lower>; CHECK(lexy::is_token_rule<decltype(rule)>); CHECK(rule.digit_radix == 16); auto empty = LEXY_VERIFY(""); CHECK(empty.status == test_result::fatal_error); CHECK(empty.trace == test_trace().expected_char_class(0, "digit.hex-lower").cancel()); check_valid(rule, '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'); check_invalid(rule, "digit.hex-lower", 'A', 'B', 'C', 'D', 'E', 'F'); } SUBCASE("hex_upper") { constexpr auto rule = dsl::digit<dsl::hex_upper>; CHECK(lexy::is_token_rule<decltype(rule)>); CHECK(rule.digit_radix == 16); auto empty = LEXY_VERIFY(""); CHECK(empty.status == test_result::fatal_error); CHECK(empty.trace == test_trace().expected_char_class(0, "digit.hex-upper").cancel()); check_valid(rule, '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'); check_invalid(rule, "digit.hex-upper", 'a', 'b', 'c', 'd', 'e', 'f'); } SUBCASE("hex") { constexpr auto rule = dsl::digit<dsl::hex>; CHECK(lexy::is_token_rule<decltype(rule)>); CHECK(rule.digit_radix == 16); auto empty = LEXY_VERIFY(""); CHECK(empty.status == test_result::fatal_error); CHECK(empty.trace == test_trace().expected_char_class(0, "digit.hex").cancel()); check_valid(rule, '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'); check_valid(rule, '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'); check_invalid(rule, "digit.hex", 'g', 'x', 'y', 'z'); } } TEST_CASE("dsl::digits<>") { constexpr auto rule = dsl::digits<>; CHECK(lexy::is_token_rule<decltype(rule)>); constexpr auto callback = token_callback; auto empty = LEXY_VERIFY(""); CHECK(empty.status == test_result::fatal_error); CHECK(empty.trace == test_trace().expected_char_class(0, "digit.decimal").cancel()); auto zero = LEXY_VERIFY("0"); CHECK(zero.status == test_result::success); CHECK(zero.trace == test_trace().token("digits", "0")); auto six = LEXY_VERIFY("6"); CHECK(six.status == test_result::success); CHECK(six.trace == test_trace().token("digits", "6")); auto three_seven = LEXY_VERIFY("37"); CHECK(three_seven.status == test_result::success); CHECK(three_seven.trace == test_trace().token("digits", "37")); auto one_two_three = LEXY_VERIFY("123"); CHECK(one_two_three.status == test_result::success); CHECK(one_two_three.trace == test_trace().token("digits", "123")); auto zero_zero_seven = LEXY_VERIFY("007"); CHECK(zero_zero_seven.status == test_result::success); CHECK(zero_zero_seven.trace == test_trace().token("digits", "007")); auto utf16 = LEXY_VERIFY(u"11"); CHECK(utf16.status == test_result::success); CHECK(utf16.trace == test_trace().token("digits", "11")); } TEST_CASE("dsl::digits<>.no_leading_zero()") { constexpr auto rule = dsl::digits<>.no_leading_zero(); CHECK(lexy::is_token_rule<decltype(rule)>); constexpr auto callback = token_callback; auto empty = LEXY_VERIFY(""); CHECK(empty.status == test_result::fatal_error); CHECK(empty.trace == test_trace().expected_char_class(0, "digit.decimal").cancel()); auto zero = LEXY_VERIFY("0"); CHECK(zero.status == test_result::success); CHECK(zero.trace == test_trace().token("digits", "0")); auto six = LEXY_VERIFY("6"); CHECK(six.status == test_result::success); CHECK(six.trace == test_trace().token("digits", "6")); auto three_seven = LEXY_VERIFY("37"); CHECK(three_seven.status == test_result::success); CHECK(three_seven.trace == test_trace().token("digits", "37")); auto one_two_three = LEXY_VERIFY("123"); CHECK(one_two_three.status == test_result::success); CHECK(one_two_three.trace == test_trace().token("digits", "123")); auto zero_zero_seven = LEXY_VERIFY("007"); CHECK(zero_zero_seven.status == test_result::fatal_error); CHECK(zero_zero_seven.trace == test_trace().error_token("0").error(0, 1, "forbidden leading zero").cancel()); auto utf16 = LEXY_VERIFY(u"11"); CHECK(utf16.status == test_result::success); CHECK(utf16.trace == test_trace().token("digits", "11")); } TEST_CASE("dsl::digits<>.sep()") { constexpr auto rule = dsl::digits<>.sep(LEXY_LIT("_")); CHECK(lexy::is_token_rule<decltype(rule)>); constexpr auto callback = token_callback; auto empty = LEXY_VERIFY(""); CHECK(empty.status == test_result::fatal_error); CHECK(empty.trace == test_trace().expected_char_class(0, "digit.decimal").cancel()); auto zero = LEXY_VERIFY("0"); CHECK(zero.status == test_result::success); CHECK(zero.trace == test_trace().token("digits", "0")); auto six = LEXY_VERIFY("6"); CHECK(six.status == test_result::success); CHECK(six.trace == test_trace().token("digits", "6")); auto three_seven = LEXY_VERIFY("37"); CHECK(three_seven.status == test_result::success); CHECK(three_seven.trace == test_trace().token("digits", "37")); auto one_two_three = LEXY_VERIFY("123"); CHECK(one_two_three.status == test_result::success); CHECK(one_two_three.trace == test_trace().token("digits", "123")); auto zero_zero_seven = LEXY_VERIFY("007"); CHECK(zero_zero_seven.status == test_result::success); CHECK(zero_zero_seven.trace == test_trace().token("digits", "007")); auto with_sep = LEXY_VERIFY("1_2_3"); CHECK(with_sep.status == test_result::success); CHECK(with_sep.trace == test_trace().token("digits", "1_2_3")); auto leading_sep = LEXY_VERIFY("_1"); CHECK(leading_sep.status == test_result::fatal_error); CHECK(leading_sep.trace == test_trace().expected_char_class(0, "digit.decimal").cancel()); auto trailing_sep = LEXY_VERIFY("1_"); CHECK(trailing_sep.status == test_result::fatal_error); CHECK(trailing_sep.trace == test_trace().error_token("1_").expected_char_class(2, "digit.decimal").cancel()); auto utf16 = LEXY_VERIFY(u"11"); CHECK(utf16.status == test_result::success); CHECK(utf16.trace == test_trace().token("digits", "11")); } TEST_CASE("dsl::digits<>.sep().no_leading_zero") { constexpr auto rule = dsl::digits<>.sep(LEXY_LIT("_")).no_leading_zero(); CHECK(lexy::is_token_rule<decltype(rule)>); CHECK(equivalent_rules(rule, dsl::digits<>.no_leading_zero().sep(LEXY_LIT("_")))); constexpr auto callback = token_callback; auto empty = LEXY_VERIFY(""); CHECK(empty.status == test_result::fatal_error); CHECK(empty.trace == test_trace().expected_char_class(0, "digit.decimal").cancel()); auto zero = LEXY_VERIFY("0"); CHECK(zero.status == test_result::success); CHECK(zero.trace == test_trace().token("digits", "0")); auto six = LEXY_VERIFY("6"); CHECK(six.status == test_result::success); CHECK(six.trace == test_trace().token("digits", "6")); auto three_seven = LEXY_VERIFY("37"); CHECK(three_seven.status == test_result::success); CHECK(three_seven.trace == test_trace().token("digits", "37")); auto one_two_three = LEXY_VERIFY("123"); CHECK(one_two_three.status == test_result::success); CHECK(one_two_three.trace == test_trace().token("digits", "123")); auto zero_zero_seven = LEXY_VERIFY("007"); CHECK(zero_zero_seven.status == test_result::fatal_error); CHECK(zero_zero_seven.trace == test_trace().error_token("0").error(0, 1, "forbidden leading zero").cancel()); auto zero_sep_zero_seven = LEXY_VERIFY("0_07"); CHECK(zero_sep_zero_seven.status == test_result::fatal_error); CHECK(zero_sep_zero_seven.trace == test_trace().error_token("0").error(0, 1, "forbidden leading zero").cancel()); auto with_sep = LEXY_VERIFY("1_2_3"); CHECK(with_sep.status == test_result::success); CHECK(with_sep.trace == test_trace().token("digits", "1_2_3")); auto leading_sep = LEXY_VERIFY("_1"); CHECK(leading_sep.status == test_result::fatal_error); CHECK(leading_sep.trace == test_trace().expected_char_class(0, "digit.decimal").cancel()); auto trailing_sep = LEXY_VERIFY("1_"); CHECK(trailing_sep.status == test_result::fatal_error); CHECK(trailing_sep.trace == test_trace().error_token("1_").expected_char_class(2, "digit.decimal").cancel()); auto utf16 = LEXY_VERIFY(u"11"); CHECK(utf16.status == test_result::success); CHECK(utf16.trace == test_trace().token("digits", "11")); } TEST_CASE("digit separators") { CHECK(equivalent_rules(dsl::digit_sep_tick, LEXY_LIT("'"))); CHECK(equivalent_rules(dsl::digit_sep_underscore, LEXY_LIT("_"))); } TEST_CASE("dsl::n_digits") { constexpr auto rule = dsl::n_digits<3>; CHECK(lexy::is_token_rule<decltype(rule)>); constexpr auto callback = token_callback; auto empty = LEXY_VERIFY(""); CHECK(empty.status == test_result::fatal_error); CHECK(empty.trace == test_trace().expected_char_class(0, "digit.decimal").cancel()); auto one = LEXY_VERIFY("1"); CHECK(one.status == test_result::fatal_error); CHECK(one.trace == test_trace().error_token("1").expected_char_class(1, "digit.decimal").cancel()); auto two = LEXY_VERIFY("12"); CHECK(two.status == test_result::fatal_error); CHECK(two.trace == test_trace().error_token("12").expected_char_class(2, "digit.decimal").cancel()); auto three = LEXY_VERIFY("123"); CHECK(three.status == test_result::success); CHECK(three.trace == test_trace().token("digits", "123")); auto four = LEXY_VERIFY("1234"); CHECK(four.status == test_result::success); CHECK(four.trace == test_trace().token("digits", "123")); } TEST_CASE("dsl::n_digits.sep()") { constexpr auto rule = dsl::n_digits<3>.sep(LEXY_LIT("_")); CHECK(lexy::is_token_rule<decltype(rule)>); constexpr auto callback = token_callback; auto empty = LEXY_VERIFY(""); CHECK(empty.status == test_result::fatal_error); CHECK(empty.trace == test_trace().expected_char_class(0, "digit.decimal").cancel()); auto one = LEXY_VERIFY("1"); CHECK(one.status == test_result::fatal_error); CHECK(one.trace == test_trace().error_token("1").expected_char_class(1, "digit.decimal").cancel()); auto two = LEXY_VERIFY("12"); CHECK(two.status == test_result::fatal_error); CHECK(two.trace == test_trace().error_token("12").expected_char_class(2, "digit.decimal").cancel()); auto three = LEXY_VERIFY("123"); CHECK(three.status == test_result::success); CHECK(three.trace == test_trace().token("digits", "123")); auto four = LEXY_VERIFY("1234"); CHECK(four.status == test_result::success); CHECK(four.trace == test_trace().token("digits", "123")); auto with_sep = LEXY_VERIFY("1_2_3"); CHECK(with_sep.status == test_result::success); CHECK(with_sep.trace == test_trace().token("digits", "1_2_3")); auto leading_sep = LEXY_VERIFY("_1"); CHECK(leading_sep.status == test_result::fatal_error); CHECK(leading_sep.trace == test_trace().expected_char_class(0, "digit.decimal").cancel()); auto trailing_sep = LEXY_VERIFY("1_"); CHECK(trailing_sep.status == test_result::fatal_error); CHECK(trailing_sep.trace == test_trace().error_token("1_").expected_char_class(2, "digit.decimal").cancel()); }
// Copyright (c) 2011-2014 The Bitcoin developers // Copyright (c) 2014-2015 The Dash developers // Copyright (c) 2015-2017 The PIVX developers // Copyright (c) 2015-2017 The HERB developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "rpcconsole.h" #include "ui_rpcconsole.h" #include "clientmodel.h" #include "guiutil.h" #include "peertablemodel.h" #include "chainparams.h" #include "main.h" #include "rpcclient.h" #include "rpcserver.h" #include "util.h" #include "json/json_spirit_value.h" #include <openssl/crypto.h> #ifdef ENABLE_WALLET #include <db_cxx.h> #endif #include <QDir> #include <QKeyEvent> #include <QScrollBar> #include <QThread> #include <QTime> #if QT_VERSION < 0x050000 #include <QUrl> #endif // TODO: add a scrollback limit, as there is currently none // TODO: make it possible to filter out categories (esp debug messages when implemented) // TODO: receive errors and debug messages through ClientModel const int CONSOLE_HISTORY = 50; const QSize ICON_SIZE(24, 24); const int INITIAL_TRAFFIC_GRAPH_MINS = 30; // Repair parameters const QString SALVAGEWALLET("-salvagewallet"); const QString RESCAN("-rescan"); const QString ZAPTXES1("-zapwallettxes=1"); const QString ZAPTXES2("-zapwallettxes=2"); const QString UPGRADEWALLET("-upgradewallet"); const QString REINDEX("-reindex"); const struct { const char* url; const char* source; } ICON_MAPPING[] = { {"cmd-request", ":/icons/tx_input"}, {"cmd-reply", ":/icons/tx_output"}, {"cmd-error", ":/icons/tx_output"}, {"misc", ":/icons/tx_inout"}, {NULL, NULL}}; /* Object for executing console RPC commands in a separate thread. */ class RPCExecutor : public QObject { Q_OBJECT public slots: void request(const QString& command); signals: void reply(int category, const QString& command); }; #include "rpcconsole.moc" /** * Split shell command line into a list of arguments. Aims to emulate \c bash and friends. * * - Arguments are delimited with whitespace * - Extra whitespace at the beginning and end and between arguments will be ignored * - Text can be "double" or 'single' quoted * - The backslash \c \ is used as escape character * - Outside quotes, any character can be escaped * - Within double quotes, only escape \c " and backslashes before a \c " or another backslash * - Within single quotes, no escaping is possible and no special interpretation takes place * * @param[out] args Parsed arguments will be appended to this list * @param[in] strCommand Command line to split */ bool parseCommandLine(std::vector<std::string>& args, const std::string& strCommand) { enum CmdParseState { STATE_EATING_SPACES, STATE_ARGUMENT, STATE_SINGLEQUOTED, STATE_DOUBLEQUOTED, STATE_ESCAPE_OUTER, STATE_ESCAPE_DOUBLEQUOTED } state = STATE_EATING_SPACES; std::string curarg; foreach (char ch, strCommand) { switch (state) { case STATE_ARGUMENT: // In or after argument case STATE_EATING_SPACES: // Handle runs of whitespace switch (ch) { case '"': state = STATE_DOUBLEQUOTED; break; case '\'': state = STATE_SINGLEQUOTED; break; case '\\': state = STATE_ESCAPE_OUTER; break; case ' ': case '\n': case '\t': if (state == STATE_ARGUMENT) // Space ends argument { args.push_back(curarg); curarg.clear(); } state = STATE_EATING_SPACES; break; default: curarg += ch; state = STATE_ARGUMENT; } break; case STATE_SINGLEQUOTED: // Single-quoted string switch (ch) { case '\'': state = STATE_ARGUMENT; break; default: curarg += ch; } break; case STATE_DOUBLEQUOTED: // Double-quoted string switch (ch) { case '"': state = STATE_ARGUMENT; break; case '\\': state = STATE_ESCAPE_DOUBLEQUOTED; break; default: curarg += ch; } break; case STATE_ESCAPE_OUTER: // '\' outside quotes curarg += ch; state = STATE_ARGUMENT; break; case STATE_ESCAPE_DOUBLEQUOTED: // '\' in double-quoted text if (ch != '"' && ch != '\\') curarg += '\\'; // keep '\' for everything but the quote and '\' itself curarg += ch; state = STATE_DOUBLEQUOTED; break; } } switch (state) // final state { case STATE_EATING_SPACES: return true; case STATE_ARGUMENT: args.push_back(curarg); return true; default: // ERROR to end in one of the other states return false; } } void RPCExecutor::request(const QString& command) { std::vector<std::string> args; if (!parseCommandLine(args, command.toStdString())) { emit reply(RPCConsole::CMD_ERROR, QString("Parse error: unbalanced ' or \"")); return; } if (args.empty()) return; // Nothing to do try { std::string strPrint; // Convert argument list to JSON objects in method-dependent way, // and pass it along with the method name to the dispatcher. json_spirit::Value result = tableRPC.execute( args[0], RPCConvertValues(args[0], std::vector<std::string>(args.begin() + 1, args.end()))); // Format result reply if (result.type() == json_spirit::null_type) strPrint = ""; else if (result.type() == json_spirit::str_type) strPrint = result.get_str(); else strPrint = write_string(result, true); emit reply(RPCConsole::CMD_REPLY, QString::fromStdString(strPrint)); } catch (json_spirit::Object& objError) { try // Nice formatting for standard-format error { int code = find_value(objError, "code").get_int(); std::string message = find_value(objError, "message").get_str(); emit reply(RPCConsole::CMD_ERROR, QString::fromStdString(message) + " (code " + QString::number(code) + ")"); } catch (std::runtime_error&) // raised when converting to invalid type, i.e. missing code or message { // Show raw JSON object emit reply(RPCConsole::CMD_ERROR, QString::fromStdString(write_string(json_spirit::Value(objError), false))); } } catch (std::exception& e) { emit reply(RPCConsole::CMD_ERROR, QString("Error: ") + QString::fromStdString(e.what())); } } RPCConsole::RPCConsole(QWidget* parent) : QDialog(parent), ui(new Ui::RPCConsole), clientModel(0), historyPtr(0), cachedNodeid(-1) { ui->setupUi(this); GUIUtil::restoreWindowGeometry("nRPCConsoleWindow", this->size(), this); #ifndef Q_OS_MAC ui->openDebugLogfileButton->setIcon(QIcon(":/icons/export")); #endif // Install event filter for up and down arrow ui->lineEdit->installEventFilter(this); ui->messagesWidget->installEventFilter(this); connect(ui->clearButton, SIGNAL(clicked()), this, SLOT(clear())); connect(ui->btnClearTrafficGraph, SIGNAL(clicked()), ui->trafficGraph, SLOT(clear())); // Wallet Repair Buttons connect(ui->btn_salvagewallet, SIGNAL(clicked()), this, SLOT(walletSalvage())); connect(ui->btn_rescan, SIGNAL(clicked()), this, SLOT(walletRescan())); connect(ui->btn_zapwallettxes1, SIGNAL(clicked()), this, SLOT(walletZaptxes1())); connect(ui->btn_zapwallettxes2, SIGNAL(clicked()), this, SLOT(walletZaptxes2())); connect(ui->btn_upgradewallet, SIGNAL(clicked()), this, SLOT(walletUpgrade())); connect(ui->btn_reindex, SIGNAL(clicked()), this, SLOT(walletReindex())); // set library version labels ui->openSSLVersion->setText(SSLeay_version(SSLEAY_VERSION)); #ifdef ENABLE_WALLET ui->berkeleyDBVersion->setText(DbEnv::version(0, 0, 0)); ui->wallet_path->setText(QString::fromStdString(GetDataDir().string() + QDir::separator().toLatin1() + GetArg("-wallet", "wallet.dat"))); #else ui->label_berkeleyDBVersion->hide(); ui->berkeleyDBVersion->hide(); #endif startExecutor(); setTrafficGraphRange(INITIAL_TRAFFIC_GRAPH_MINS); ui->peerHeading->setText(tr("Select a peer to view detailed information.")); clear(); } RPCConsole::~RPCConsole() { GUIUtil::saveWindowGeometry("nRPCConsoleWindow", this); emit stopExecutor(); delete ui; } bool RPCConsole::eventFilter(QObject* obj, QEvent* event) { if (event->type() == QEvent::KeyPress) // Special key handling { QKeyEvent* keyevt = static_cast<QKeyEvent*>(event); int key = keyevt->key(); Qt::KeyboardModifiers mod = keyevt->modifiers(); switch (key) { case Qt::Key_Up: if (obj == ui->lineEdit) { browseHistory(-1); return true; } break; case Qt::Key_Down: if (obj == ui->lineEdit) { browseHistory(1); return true; } break; case Qt::Key_PageUp: /* pass paging keys to messages widget */ case Qt::Key_PageDown: if (obj == ui->lineEdit) { QApplication::postEvent(ui->messagesWidget, new QKeyEvent(*keyevt)); return true; } break; default: // Typing in messages widget brings focus to line edit, and redirects key there // Exclude most combinations and keys that emit no text, except paste shortcuts if (obj == ui->messagesWidget && ((!mod && !keyevt->text().isEmpty() && key != Qt::Key_Tab) || ((mod & Qt::ControlModifier) && key == Qt::Key_V) || ((mod & Qt::ShiftModifier) && key == Qt::Key_Insert))) { ui->lineEdit->setFocus(); QApplication::postEvent(ui->lineEdit, new QKeyEvent(*keyevt)); return true; } } } return QDialog::eventFilter(obj, event); } void RPCConsole::setClientModel(ClientModel* model) { clientModel = model; ui->trafficGraph->setClientModel(model); if (model) { // Keep up to date with client setNumConnections(model->getNumConnections()); connect(model, SIGNAL(numConnectionsChanged(int)), this, SLOT(setNumConnections(int))); setNumBlocks(model->getNumBlocks()); connect(model, SIGNAL(numBlocksChanged(int)), this, SLOT(setNumBlocks(int))); setMasternodeCount(model->getMasternodeCountString()); connect(model, SIGNAL(strMasternodesChanged(QString)), this, SLOT(setMasternodeCount(QString))); updateTrafficStats(model->getTotalBytesRecv(), model->getTotalBytesSent()); connect(model, SIGNAL(bytesChanged(quint64, quint64)), this, SLOT(updateTrafficStats(quint64, quint64))); // set up peer table ui->peerWidget->setModel(model->getPeerTableModel()); ui->peerWidget->verticalHeader()->hide(); ui->peerWidget->setEditTriggers(QAbstractItemView::NoEditTriggers); ui->peerWidget->setSelectionBehavior(QAbstractItemView::SelectRows); ui->peerWidget->setSelectionMode(QAbstractItemView::SingleSelection); ui->peerWidget->setColumnWidth(PeerTableModel::Address, ADDRESS_COLUMN_WIDTH); ui->peerWidget->setColumnWidth(PeerTableModel::Subversion, SUBVERSION_COLUMN_WIDTH); ui->peerWidget->setColumnWidth(PeerTableModel::Ping, PING_COLUMN_WIDTH); // connect the peerWidget selection model to our peerSelected() handler connect(ui->peerWidget->selectionModel(), SIGNAL(selectionChanged(const QItemSelection&, const QItemSelection&)), this, SLOT(peerSelected(const QItemSelection&, const QItemSelection&))); connect(model->getPeerTableModel(), SIGNAL(layoutChanged()), this, SLOT(peerLayoutChanged())); // Provide initial values ui->clientVersion->setText(model->formatFullVersion()); ui->clientName->setText(model->clientName()); ui->buildDate->setText(model->formatBuildDate()); ui->startupTime->setText(model->formatClientStartupTime()); ui->networkName->setText(QString::fromStdString(Params().NetworkIDString())); } } static QString categoryClass(int category) { switch (category) { case RPCConsole::CMD_REQUEST: return "cmd-request"; break; case RPCConsole::CMD_REPLY: return "cmd-reply"; break; case RPCConsole::CMD_ERROR: return "cmd-error"; break; default: return "misc"; } } /** Restart wallet with "-salvagewallet" */ void RPCConsole::walletSalvage() { buildParameterlist(SALVAGEWALLET); } /** Restart wallet with "-rescan" */ void RPCConsole::walletRescan() { buildParameterlist(RESCAN); } /** Restart wallet with "-zapwallettxes=1" */ void RPCConsole::walletZaptxes1() { buildParameterlist(ZAPTXES1); } /** Restart wallet with "-zapwallettxes=2" */ void RPCConsole::walletZaptxes2() { buildParameterlist(ZAPTXES2); } /** Restart wallet with "-upgradewallet" */ void RPCConsole::walletUpgrade() { buildParameterlist(UPGRADEWALLET); } /** Restart wallet with "-reindex" */ void RPCConsole::walletReindex() { buildParameterlist(REINDEX); } /** Build command-line parameter list for restart */ void RPCConsole::buildParameterlist(QString arg) { // Get command-line arguments and remove the application name QStringList args = QApplication::arguments(); args.removeFirst(); // Remove existing repair-options args.removeAll(SALVAGEWALLET); args.removeAll(RESCAN); args.removeAll(ZAPTXES1); args.removeAll(ZAPTXES2); args.removeAll(UPGRADEWALLET); args.removeAll(REINDEX); // Append repair parameter to command line. args.append(arg); // Send command-line arguments to BitcoinGUI::handleRestart() emit handleRestart(args); } void RPCConsole::clear() { ui->messagesWidget->clear(); history.clear(); historyPtr = 0; ui->lineEdit->clear(); ui->lineEdit->setFocus(); // Add smoothly scaled icon images. // (when using width/height on an img, Qt uses nearest instead of linear interpolation) for (int i = 0; ICON_MAPPING[i].url; ++i) { ui->messagesWidget->document()->addResource( QTextDocument::ImageResource, QUrl(ICON_MAPPING[i].url), QImage(ICON_MAPPING[i].source).scaled(ICON_SIZE, Qt::IgnoreAspectRatio, Qt::SmoothTransformation)); } // Set default style sheet ui->messagesWidget->document()->setDefaultStyleSheet( "table { }" "td.time { color: #808080; padding-top: 3px; } " "td.message { font-family: Courier, Courier New, Lucida Console, monospace; font-size: 12px; } " // Todo: Remove fixed font-size "td.cmd-request { color: #006060; } " "td.cmd-error { color: red; } " "b { color: #006060; } "); message(CMD_REPLY, (tr("Welcome to the HERB RPC console.") + "<br>" + tr("Use up and down arrows to navigate history, and <b>Ctrl-L</b> to clear screen.") + "<br>" + tr("Type <b>help</b> for an overview of available commands.")), true); } void RPCConsole::reject() { // Ignore escape keypress if this is not a seperate window if (windowType() != Qt::Widget) QDialog::reject(); } void RPCConsole::message(int category, const QString& message, bool html) { QTime time = QTime::currentTime(); QString timeString = time.toString(); QString out; out += "<table><tr><td class=\"time\" width=\"65\">" + timeString + "</td>"; out += "<td class=\"icon\" width=\"32\"><img src=\"" + categoryClass(category) + "\"></td>"; out += "<td class=\"message " + categoryClass(category) + "\" valign=\"middle\">"; if (html) out += message; else out += GUIUtil::HtmlEscape(message, true); out += "</td></tr></table>"; ui->messagesWidget->append(out); } void RPCConsole::setNumConnections(int count) { if (!clientModel) return; QString connections = QString::number(count) + " ("; connections += tr("In:") + " " + QString::number(clientModel->getNumConnections(CONNECTIONS_IN)) + " / "; connections += tr("Out:") + " " + QString::number(clientModel->getNumConnections(CONNECTIONS_OUT)) + ")"; ui->numberOfConnections->setText(connections); } void RPCConsole::setNumBlocks(int count) { ui->numberOfBlocks->setText(QString::number(count)); if (clientModel) ui->lastBlockTime->setText(clientModel->getLastBlockDate().toString()); } void RPCConsole::setMasternodeCount(const QString& strMasternodes) { ui->masternodeCount->setText(strMasternodes); } void RPCConsole::on_lineEdit_returnPressed() { QString cmd = ui->lineEdit->text(); ui->lineEdit->clear(); if (!cmd.isEmpty()) { message(CMD_REQUEST, cmd); emit cmdRequest(cmd); // Remove command, if already in history history.removeOne(cmd); // Append command to history history.append(cmd); // Enforce maximum history size while (history.size() > CONSOLE_HISTORY) history.removeFirst(); // Set pointer to end of history historyPtr = history.size(); // Scroll console view to end scrollToEnd(); } } void RPCConsole::browseHistory(int offset) { historyPtr += offset; if (historyPtr < 0) historyPtr = 0; if (historyPtr > history.size()) historyPtr = history.size(); QString cmd; if (historyPtr < history.size()) cmd = history.at(historyPtr); ui->lineEdit->setText(cmd); } void RPCConsole::startExecutor() { QThread* thread = new QThread; RPCExecutor* executor = new RPCExecutor(); executor->moveToThread(thread); // Replies from executor object must go to this object connect(executor, SIGNAL(reply(int, QString)), this, SLOT(message(int, QString))); // Requests from this object must go to executor connect(this, SIGNAL(cmdRequest(QString)), executor, SLOT(request(QString))); // On stopExecutor signal // - queue executor for deletion (in execution thread) // - quit the Qt event loop in the execution thread connect(this, SIGNAL(stopExecutor()), executor, SLOT(deleteLater())); connect(this, SIGNAL(stopExecutor()), thread, SLOT(quit())); // Queue the thread for deletion (in this thread) when it is finished connect(thread, SIGNAL(finished()), thread, SLOT(deleteLater())); // Default implementation of QThread::run() simply spins up an event loop in the thread, // which is what we want. thread->start(); } void RPCConsole::on_tabWidget_currentChanged(int index) { if (ui->tabWidget->widget(index) == ui->tab_console) { ui->lineEdit->setFocus(); } } void RPCConsole::on_openDebugLogfileButton_clicked() { GUIUtil::openDebugLogfile(); } void RPCConsole::scrollToEnd() { QScrollBar* scrollbar = ui->messagesWidget->verticalScrollBar(); scrollbar->setValue(scrollbar->maximum()); } void RPCConsole::on_sldGraphRange_valueChanged(int value) { const int multiplier = 5; // each position on the slider represents 5 min int mins = value * multiplier; setTrafficGraphRange(mins); } QString RPCConsole::FormatBytes(quint64 bytes) { if (bytes < 1024) return QString(tr("%1 B")).arg(bytes); if (bytes < 1024 * 1024) return QString(tr("%1 KB")).arg(bytes / 1024); if (bytes < 1024 * 1024 * 1024) return QString(tr("%1 MB")).arg(bytes / 1024 / 1024); return QString(tr("%1 GB")).arg(bytes / 1024 / 1024 / 1024); } void RPCConsole::setTrafficGraphRange(int mins) { ui->trafficGraph->setGraphRangeMins(mins); ui->lblGraphRange->setText(GUIUtil::formatDurationStr(mins * 60)); } void RPCConsole::updateTrafficStats(quint64 totalBytesIn, quint64 totalBytesOut) { ui->lblBytesIn->setText(FormatBytes(totalBytesIn)); ui->lblBytesOut->setText(FormatBytes(totalBytesOut)); } void RPCConsole::showInfo() { ui->tabWidget->setCurrentIndex(0); show(); } void RPCConsole::showConsole() { ui->tabWidget->setCurrentIndex(1); show(); } void RPCConsole::showNetwork() { ui->tabWidget->setCurrentIndex(2); show(); } void RPCConsole::showPeers() { ui->tabWidget->setCurrentIndex(3); show(); } void RPCConsole::showRepair() { ui->tabWidget->setCurrentIndex(4); show(); } void RPCConsole::showConfEditor() { GUIUtil::openConfigfile(); } void RPCConsole::showMNConfEditor() { GUIUtil::openMNConfigfile(); } void RPCConsole::peerSelected(const QItemSelection& selected, const QItemSelection& deselected) { Q_UNUSED(deselected); if (!clientModel || selected.indexes().isEmpty()) return; const CNodeCombinedStats* stats = clientModel->getPeerTableModel()->getNodeStats(selected.indexes().first().row()); if (stats) updateNodeDetail(stats); } void RPCConsole::peerLayoutChanged() { if (!clientModel) return; const CNodeCombinedStats* stats = NULL; bool fUnselect = false; bool fReselect = false; if (cachedNodeid == -1) // no node selected yet return; // find the currently selected row int selectedRow; QModelIndexList selectedModelIndex = ui->peerWidget->selectionModel()->selectedIndexes(); if (selectedModelIndex.isEmpty()) selectedRow = -1; else selectedRow = selectedModelIndex.first().row(); // check if our detail node has a row in the table (it may not necessarily // be at selectedRow since its position can change after a layout change) int detailNodeRow = clientModel->getPeerTableModel()->getRowByNodeId(cachedNodeid); if (detailNodeRow < 0) { // detail node dissapeared from table (node disconnected) fUnselect = true; cachedNodeid = -1; ui->peerHeading->setText(tr("Select a peer to view detailed information.")); } else { if (detailNodeRow != selectedRow) { // detail node moved position fUnselect = true; fReselect = true; } // get fresh stats on the detail node. stats = clientModel->getPeerTableModel()->getNodeStats(detailNodeRow); } if (fUnselect && selectedRow >= 0) { ui->peerWidget->selectionModel()->select(QItemSelection(selectedModelIndex.first(), selectedModelIndex.last()), QItemSelectionModel::Deselect); } if (fReselect) { ui->peerWidget->selectRow(detailNodeRow); } if (stats) updateNodeDetail(stats); } void RPCConsole::updateNodeDetail(const CNodeCombinedStats* stats) { // Update cached nodeid cachedNodeid = stats->nodeStats.nodeid; // update the detail ui with latest node information QString peerAddrDetails(QString::fromStdString(stats->nodeStats.addrName)); if (!stats->nodeStats.addrLocal.empty()) peerAddrDetails += "<br />" + tr("via %1").arg(QString::fromStdString(stats->nodeStats.addrLocal)); ui->peerHeading->setText(peerAddrDetails); ui->peerServices->setText(GUIUtil::formatServicesStr(stats->nodeStats.nServices)); ui->peerLastSend->setText(stats->nodeStats.nLastSend ? GUIUtil::formatDurationStr(GetTime() - stats->nodeStats.nLastSend) : tr("never")); ui->peerLastRecv->setText(stats->nodeStats.nLastRecv ? GUIUtil::formatDurationStr(GetTime() - stats->nodeStats.nLastRecv) : tr("never")); ui->peerBytesSent->setText(FormatBytes(stats->nodeStats.nSendBytes)); ui->peerBytesRecv->setText(FormatBytes(stats->nodeStats.nRecvBytes)); ui->peerConnTime->setText(GUIUtil::formatDurationStr(GetTime() - stats->nodeStats.nTimeConnected)); ui->peerPingTime->setText(GUIUtil::formatPingTime(stats->nodeStats.dPingTime)); ui->peerVersion->setText(QString("%1").arg(stats->nodeStats.nVersion)); ui->peerSubversion->setText(QString::fromStdString(stats->nodeStats.cleanSubVer)); ui->peerDirection->setText(stats->nodeStats.fInbound ? tr("Inbound") : tr("Outbound")); ui->peerHeight->setText(QString("%1").arg(stats->nodeStats.nStartingHeight)); // This check fails for example if the lock was busy and // nodeStateStats couldn't be fetched. if (stats->fNodeStateStatsAvailable) { // Ban score is init to 0 ui->peerBanScore->setText(QString("%1").arg(stats->nodeStateStats.nMisbehavior)); // Sync height is init to -1 if (stats->nodeStateStats.nSyncHeight > -1) ui->peerSyncHeight->setText(QString("%1").arg(stats->nodeStateStats.nSyncHeight)); else ui->peerSyncHeight->setText(tr("Unknown")); } else { ui->peerBanScore->setText(tr("Fetching...")); ui->peerSyncHeight->setText(tr("Fetching...")); } ui->detailWidget->show(); } void RPCConsole::resizeEvent(QResizeEvent* event) { QWidget::resizeEvent(event); } void RPCConsole::showEvent(QShowEvent* event) { QWidget::showEvent(event); if (!clientModel) return; // start PeerTableModel auto refresh clientModel->getPeerTableModel()->startAutoRefresh(); } void RPCConsole::hideEvent(QHideEvent* event) { QWidget::hideEvent(event); if (!clientModel) return; // stop PeerTableModel auto refresh clientModel->getPeerTableModel()->stopAutoRefresh(); } void RPCConsole::showBackups() { GUIUtil::showBackups(); }
/* Copyright (C) 2015-present The DotCpp Authors. This file is part of .C++, a native C++ implementation of popular .NET class library APIs developed to facilitate code reuse between C# and C++. http://github.com/dotcpp/dotcpp (source) http://dotcpp.org (documentation) 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. */ #pragma once namespace dot { /// All classes with reference semantics should derive from this type. /// It works with ptr to provide an emulation of reference semantics in C++. class reference_counter { private: // FIELDS /// Reference count for intrusive pointer. std::atomic<unsigned int> reference_count_ = 0; public: // DESTRUCTOR /// Virtual destructor to ensure that destructor /// of the derived type is called by ptr. virtual ~reference_counter() = default; public: // METHODS /// Increment reference count. void increment_reference_count() { ++reference_count_; } /// Decrement reference count, deletes if decremented count is zero. void decrement_reference_count() { if (!--reference_count_) { delete this; } } protected: // CONSTRUCTORS /// Prevent construction on stack. reference_counter() = default; private: // CONSTRUCTORS /// Prevent copying object instead of copying pointer. reference_counter(const reference_counter&) = delete; private: // OPERATORS /// Prevent assignment of object instead of assignment of pointer. reference_counter& operator=(const reference_counter& rhs) = delete; }; }
/** THIS IS AN AUTOMATICALLY GENERATED FILE. * DO NOT MODIFY BY HAND!! * * Generated by zcm-gen **/ #include <zcm/zcm_coretypes.h> #ifndef __craebot_leds_t_hpp__ #define __craebot_leds_t_hpp__ namespace craebot { class leds_t { public: int64_t utime; int8_t debris; int8_t spot; int8_t dock; int8_t check; uint8_t power[2]; public: /** * Destructs a message properly if anything inherits from it */ virtual ~leds_t() {} /** * Encode a message into binary form. * * @param buf The output buffer. * @param offset Encoding starts at thie byte offset into @p buf. * @param maxlen Maximum number of bytes to write. This should generally be * equal to getEncodedSize(). * @return The number of bytes encoded, or <0 on error. */ inline int encode(void* buf, uint32_t offset, uint32_t maxlen) const; /** * Check how many bytes are required to encode this message. */ inline uint32_t getEncodedSize() const; /** * Decode a message from binary form into this instance. * * @param buf The buffer containing the encoded message. * @param offset The byte offset into @p buf where the encoded message starts. * @param maxlen The maximum number of bytes to reqad while decoding. * @return The number of bytes decoded, or <0 if an error occured. */ inline int decode(const void* buf, uint32_t offset, uint32_t maxlen); /** * Retrieve the 64-bit fingerprint identifying the structure of the message. * Note that the fingerprint is the same for all instances of the same * message type, and is a fingerprint on the message type definition, not on * the message contents. */ inline static int64_t getHash(); /** * Returns "leds_t" */ inline static const char* getTypeName(); // ZCM support functions. Users should not call these inline int _encodeNoHash(void* buf, uint32_t offset, uint32_t maxlen) const; inline uint32_t _getEncodedSizeNoHash() const; inline int _decodeNoHash(const void* buf, uint32_t offset, uint32_t maxlen); inline static uint64_t _computeHash(const __zcm_hash_ptr* p); }; int leds_t::encode(void* buf, uint32_t offset, uint32_t maxlen) const { uint32_t pos = 0; int thislen; int64_t hash = (int64_t)getHash(); thislen = __int64_t_encode_array(buf, offset + pos, maxlen - pos, &hash, 1); if(thislen < 0) return thislen; else pos += thislen; thislen = this->_encodeNoHash(buf, offset + pos, maxlen - pos); if (thislen < 0) return thislen; else pos += thislen; return pos; } int leds_t::decode(const void* buf, uint32_t offset, uint32_t maxlen) { uint32_t pos = 0; int thislen; int64_t msg_hash; thislen = __int64_t_decode_array(buf, offset + pos, maxlen - pos, &msg_hash, 1); if (thislen < 0) return thislen; else pos += thislen; if (msg_hash != getHash()) return -1; thislen = this->_decodeNoHash(buf, offset + pos, maxlen - pos); if (thislen < 0) return thislen; else pos += thislen; return pos; } uint32_t leds_t::getEncodedSize() const { return 8 + _getEncodedSizeNoHash(); } int64_t leds_t::getHash() { static int64_t hash = _computeHash(NULL); return hash; } const char* leds_t::getTypeName() { return "leds_t"; } int leds_t::_encodeNoHash(void* buf, uint32_t offset, uint32_t maxlen) const { uint32_t pos = 0; int thislen; thislen = __int64_t_encode_array(buf, offset + pos, maxlen - pos, &this->utime, 1); if(thislen < 0) return thislen; else pos += thislen; thislen = __boolean_encode_array(buf, offset + pos, maxlen - pos, &this->debris, 1); if(thislen < 0) return thislen; else pos += thislen; thislen = __boolean_encode_array(buf, offset + pos, maxlen - pos, &this->spot, 1); if(thislen < 0) return thislen; else pos += thislen; thislen = __boolean_encode_array(buf, offset + pos, maxlen - pos, &this->dock, 1); if(thislen < 0) return thislen; else pos += thislen; thislen = __boolean_encode_array(buf, offset + pos, maxlen - pos, &this->check, 1); if(thislen < 0) return thislen; else pos += thislen; thislen = __byte_encode_array(buf, offset + pos, maxlen - pos, &this->power[0], 2); if(thislen < 0) return thislen; else pos += thislen; return pos; } int leds_t::_decodeNoHash(const void* buf, uint32_t offset, uint32_t maxlen) { uint32_t pos = 0; int thislen; thislen = __int64_t_decode_array(buf, offset + pos, maxlen - pos, &this->utime, 1); if(thislen < 0) return thislen; else pos += thislen; thislen = __boolean_decode_array(buf, offset + pos, maxlen - pos, &this->debris, 1); if(thislen < 0) return thislen; else pos += thislen; thislen = __boolean_decode_array(buf, offset + pos, maxlen - pos, &this->spot, 1); if(thislen < 0) return thislen; else pos += thislen; thislen = __boolean_decode_array(buf, offset + pos, maxlen - pos, &this->dock, 1); if(thislen < 0) return thislen; else pos += thislen; thislen = __boolean_decode_array(buf, offset + pos, maxlen - pos, &this->check, 1); if(thislen < 0) return thislen; else pos += thislen; thislen = __byte_decode_array(buf, offset + pos, maxlen - pos, &this->power[0], 2); if(thislen < 0) return thislen; else pos += thislen; return pos; } uint32_t leds_t::_getEncodedSizeNoHash() const { uint32_t enc_size = 0; enc_size += __int64_t_encoded_array_size(NULL, 1); enc_size += __boolean_encoded_array_size(NULL, 1); enc_size += __boolean_encoded_array_size(NULL, 1); enc_size += __boolean_encoded_array_size(NULL, 1); enc_size += __boolean_encoded_array_size(NULL, 1); enc_size += __byte_encoded_array_size(NULL, 2); return enc_size; } uint64_t leds_t::_computeHash(const __zcm_hash_ptr*) { uint64_t hash = (uint64_t)0x8a7ae099135d4af6LL; return (hash<<1) + ((hash>>63)&1); } } #endif
// Copyright (c) 2011 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "ppapi/cpp/private/var_private.h" #include "ppapi/c/dev/ppb_memory_dev.h" #include "ppapi/c/dev/ppb_var_deprecated.h" #include "ppapi/cpp/instance_handle.h" #include "ppapi/cpp/private/instance_private.h" #include "ppapi/cpp/logging.h" #include "ppapi/cpp/module_impl.h" #include "ppapi/cpp/dev/scriptable_object_deprecated.h" namespace pp { namespace { template <> const char* interface_name<PPB_Var_Deprecated>() { return PPB_VAR_DEPRECATED_INTERFACE; } } // namespace using namespace deprecated; VarPrivate::VarPrivate(const InstanceHandle& instance, ScriptableObject* object) { if (has_interface<PPB_Var_Deprecated>()) { var_ = get_interface<PPB_Var_Deprecated>()->CreateObject( instance.pp_instance(), object->GetClass(), object); } else { var_.type = PP_VARTYPE_NULL; var_.padding = 0; } is_managed_ = true; } ScriptableObject* VarPrivate::AsScriptableObject() const { if (!is_object()) { PP_NOTREACHED(); } else if (has_interface<PPB_Var_Deprecated>()) { void* object = NULL; if (get_interface<PPB_Var_Deprecated>()->IsInstanceOf( var_, ScriptableObject::GetClass(), &object)) { return reinterpret_cast<ScriptableObject*>(object); } } return NULL; } bool VarPrivate::HasProperty(const Var& name, Var* exception) const { if (!has_interface<PPB_Var_Deprecated>()) return false; return get_interface<PPB_Var_Deprecated>()->HasProperty( var_, name.pp_var(), OutException(exception).get()); } bool VarPrivate::HasMethod(const Var& name, Var* exception) const { if (!has_interface<PPB_Var_Deprecated>()) return false; return get_interface<PPB_Var_Deprecated>()->HasMethod( var_, name.pp_var(), OutException(exception).get()); } VarPrivate VarPrivate::GetProperty(const Var& name, Var* exception) const { if (!has_interface<PPB_Var_Deprecated>()) return Var(); return Var(PassRef(), get_interface<PPB_Var_Deprecated>()->GetProperty( var_, name.pp_var(), OutException(exception).get())); } void VarPrivate::GetAllPropertyNames(std::vector<Var>* properties, Var* exception) const { if (!has_interface<PPB_Var_Deprecated>()) return; PP_Var* props = NULL; uint32_t prop_count = 0; get_interface<PPB_Var_Deprecated>()->GetAllPropertyNames( var_, &prop_count, &props, OutException(exception).get()); if (!prop_count) return; properties->resize(prop_count); for (uint32_t i = 0; i < prop_count; ++i) { Var temp(PassRef(), props[i]); (*properties)[i] = temp; } const PPB_Memory_Dev* memory_if = static_cast<const PPB_Memory_Dev*>( pp::Module::Get()->GetBrowserInterface(PPB_MEMORY_DEV_INTERFACE)); memory_if->MemFree(props); } void VarPrivate::SetProperty(const Var& name, const Var& value, Var* exception) { if (!has_interface<PPB_Var_Deprecated>()) return; get_interface<PPB_Var_Deprecated>()->SetProperty( var_, name.pp_var(), value.pp_var(), OutException(exception).get()); } void VarPrivate::RemoveProperty(const Var& name, Var* exception) { if (!has_interface<PPB_Var_Deprecated>()) return; get_interface<PPB_Var_Deprecated>()->RemoveProperty( var_, name.pp_var(), OutException(exception).get()); } VarPrivate VarPrivate::Call(const Var& method_name, uint32_t argc, Var* argv, Var* exception) { if (!has_interface<PPB_Var_Deprecated>()) return Var(); if (argc > 0) { std::vector<PP_Var> args; args.reserve(argc); for (size_t i = 0; i < argc; i++) args.push_back(argv[i].pp_var()); return Var(PassRef(), get_interface<PPB_Var_Deprecated>()->Call( var_, method_name.pp_var(), argc, &args[0], OutException(exception).get())); } else { // Don't try to get the address of a vector if it's empty. return Var(PassRef(), get_interface<PPB_Var_Deprecated>()->Call( var_, method_name.pp_var(), 0, NULL, OutException(exception).get())); } } VarPrivate VarPrivate::Construct(uint32_t argc, Var* argv, Var* exception) const { if (!has_interface<PPB_Var_Deprecated>()) return Var(); if (argc > 0) { std::vector<PP_Var> args; args.reserve(argc); for (size_t i = 0; i < argc; i++) args.push_back(argv[i].pp_var()); return Var(PassRef(), get_interface<PPB_Var_Deprecated>()->Construct( var_, argc, &args[0], OutException(exception).get())); } else { // Don't try to get the address of a vector if it's empty. return Var(PassRef(), get_interface<PPB_Var_Deprecated>()->Construct( var_, 0, NULL, OutException(exception).get())); } } VarPrivate VarPrivate::Call(const Var& method_name, Var* exception) { if (!has_interface<PPB_Var_Deprecated>()) return Var(); return Var(PassRef(), get_interface<PPB_Var_Deprecated>()->Call( var_, method_name.pp_var(), 0, NULL, OutException(exception).get())); } VarPrivate VarPrivate::Call(const Var& method_name, const Var& arg1, Var* exception) { if (!has_interface<PPB_Var_Deprecated>()) return Var(); PP_Var args[1] = {arg1.pp_var()}; return Var(PassRef(), get_interface<PPB_Var_Deprecated>()->Call( var_, method_name.pp_var(), 1, args, OutException(exception).get())); } VarPrivate VarPrivate::Call(const Var& method_name, const Var& arg1, const Var& arg2, Var* exception) { if (!has_interface<PPB_Var_Deprecated>()) return Var(); PP_Var args[2] = {arg1.pp_var(), arg2.pp_var()}; return Var(PassRef(), get_interface<PPB_Var_Deprecated>()->Call( var_, method_name.pp_var(), 2, args, OutException(exception).get())); } VarPrivate VarPrivate::Call(const Var& method_name, const Var& arg1, const Var& arg2, const Var& arg3, Var* exception) { if (!has_interface<PPB_Var_Deprecated>()) return Var(); PP_Var args[3] = {arg1.pp_var(), arg2.pp_var(), arg3.pp_var()}; return Var(PassRef(), get_interface<PPB_Var_Deprecated>()->Call( var_, method_name.pp_var(), 3, args, OutException(exception).get())); } VarPrivate VarPrivate::Call(const Var& method_name, const Var& arg1, const Var& arg2, const Var& arg3, const Var& arg4, Var* exception) { if (!has_interface<PPB_Var_Deprecated>()) return Var(); PP_Var args[4] = {arg1.pp_var(), arg2.pp_var(), arg3.pp_var(), arg4.pp_var()}; return Var(PassRef(), get_interface<PPB_Var_Deprecated>()->Call( var_, method_name.pp_var(), 4, args, OutException(exception).get())); } } // namespace pp
// Copyright (c) 1994-2006 Sun Microsystems Inc. // 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. // // - Redistribution in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the // distribution. // // - Neither the name of Sun Microsystems or the names of contributors may // be used to endorse or promote products derived from this software without // specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS // FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE // COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, // INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES // (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR // SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) // HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, // STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED // OF THE POSSIBILITY OF SUCH DAMAGE. // The original source code covered by the above license above has been // modified significantly by Google Inc. // Copyright 2012 the V8 project authors. All rights reserved. #include "src/codegen/arm/assembler-arm.h" #if V8_TARGET_ARCH_ARM #include "src/base/bits.h" #include "src/base/cpu.h" #include "src/base/overflowing-math.h" #include "src/codegen/arm/assembler-arm-inl.h" #include "src/codegen/assembler-inl.h" #include "src/codegen/machine-type.h" #include "src/codegen/macro-assembler.h" #include "src/codegen/string-constants.h" #include "src/deoptimizer/deoptimizer.h" #include "src/objects/objects-inl.h" namespace v8 { namespace internal { static const unsigned kArmv6 = 0u; static const unsigned kArmv7 = kArmv6 | (1u << ARMv7); static const unsigned kArmv7WithSudiv = kArmv7 | (1u << ARMv7_SUDIV); static const unsigned kArmv8 = kArmv7WithSudiv | (1u << ARMv8); static unsigned CpuFeaturesFromCommandLine() { unsigned result; if (strcmp(FLAG_arm_arch, "armv8") == 0) { result = kArmv8; } else if (strcmp(FLAG_arm_arch, "armv7+sudiv") == 0) { result = kArmv7WithSudiv; } else if (strcmp(FLAG_arm_arch, "armv7") == 0) { result = kArmv7; } else if (strcmp(FLAG_arm_arch, "armv6") == 0) { result = kArmv6; } else { fprintf(stderr, "Error: unrecognised value for --arm-arch ('%s').\n", FLAG_arm_arch); fprintf(stderr, "Supported values are: armv8\n" " armv7+sudiv\n" " armv7\n" " armv6\n"); FATAL("arm-arch"); } // If any of the old (deprecated) flags are specified, print a warning, but // otherwise try to respect them for now. // TODO(jbramley): When all the old bots have been updated, remove this. if (FLAG_enable_armv7.has_value || FLAG_enable_vfp3.has_value || FLAG_enable_32dregs.has_value || FLAG_enable_neon.has_value || FLAG_enable_sudiv.has_value || FLAG_enable_armv8.has_value) { // As an approximation of the old behaviour, set the default values from the // arm_arch setting, then apply the flags over the top. bool enable_armv7 = (result & (1u << ARMv7)) != 0; bool enable_vfp3 = (result & (1u << ARMv7)) != 0; bool enable_32dregs = (result & (1u << ARMv7)) != 0; bool enable_neon = (result & (1u << ARMv7)) != 0; bool enable_sudiv = (result & (1u << ARMv7_SUDIV)) != 0; bool enable_armv8 = (result & (1u << ARMv8)) != 0; if (FLAG_enable_armv7.has_value) { fprintf(stderr, "Warning: --enable_armv7 is deprecated. " "Use --arm_arch instead.\n"); enable_armv7 = FLAG_enable_armv7.value; } if (FLAG_enable_vfp3.has_value) { fprintf(stderr, "Warning: --enable_vfp3 is deprecated. " "Use --arm_arch instead.\n"); enable_vfp3 = FLAG_enable_vfp3.value; } if (FLAG_enable_32dregs.has_value) { fprintf(stderr, "Warning: --enable_32dregs is deprecated. " "Use --arm_arch instead.\n"); enable_32dregs = FLAG_enable_32dregs.value; } if (FLAG_enable_neon.has_value) { fprintf(stderr, "Warning: --enable_neon is deprecated. " "Use --arm_arch instead.\n"); enable_neon = FLAG_enable_neon.value; } if (FLAG_enable_sudiv.has_value) { fprintf(stderr, "Warning: --enable_sudiv is deprecated. " "Use --arm_arch instead.\n"); enable_sudiv = FLAG_enable_sudiv.value; } if (FLAG_enable_armv8.has_value) { fprintf(stderr, "Warning: --enable_armv8 is deprecated. " "Use --arm_arch instead.\n"); enable_armv8 = FLAG_enable_armv8.value; } // Emulate the old implications. if (enable_armv8) { enable_vfp3 = true; enable_neon = true; enable_32dregs = true; enable_sudiv = true; } // Select the best available configuration. if (enable_armv7 && enable_vfp3 && enable_32dregs && enable_neon) { if (enable_sudiv) { if (enable_armv8) { result = kArmv8; } else { result = kArmv7WithSudiv; } } else { result = kArmv7; } } else { result = kArmv6; } } return result; } // Get the CPU features enabled by the build. // For cross compilation the preprocessor symbols such as // CAN_USE_ARMV7_INSTRUCTIONS and CAN_USE_VFP3_INSTRUCTIONS can be used to // enable ARMv7 and VFPv3 instructions when building the snapshot. However, // these flags should be consistent with a supported ARM configuration: // "armv6": ARMv6 + VFPv2 // "armv7": ARMv7 + VFPv3-D32 + NEON // "armv7+sudiv": ARMv7 + VFPv4-D32 + NEON + SUDIV // "armv8": ARMv8 (+ all of the above) static constexpr unsigned CpuFeaturesFromCompiler() { // TODO(jbramley): Once the build flags are simplified, these tests should // also be simplified. // Check *architectural* implications. #if defined(CAN_USE_ARMV8_INSTRUCTIONS) && !defined(CAN_USE_ARMV7_INSTRUCTIONS) #error "CAN_USE_ARMV8_INSTRUCTIONS should imply CAN_USE_ARMV7_INSTRUCTIONS" #endif #if defined(CAN_USE_ARMV8_INSTRUCTIONS) && !defined(CAN_USE_SUDIV) #error "CAN_USE_ARMV8_INSTRUCTIONS should imply CAN_USE_SUDIV" #endif #if defined(CAN_USE_ARMV7_INSTRUCTIONS) != defined(CAN_USE_VFP3_INSTRUCTIONS) // V8 requires VFP, and all ARMv7 devices with VFP have VFPv3. Similarly, // VFPv3 isn't available before ARMv7. #error "CAN_USE_ARMV7_INSTRUCTIONS should match CAN_USE_VFP3_INSTRUCTIONS" #endif #if defined(CAN_USE_NEON) && !defined(CAN_USE_ARMV7_INSTRUCTIONS) #error "CAN_USE_NEON should imply CAN_USE_ARMV7_INSTRUCTIONS" #endif // Find compiler-implied features. #if defined(CAN_USE_ARMV8_INSTRUCTIONS) && \ defined(CAN_USE_ARMV7_INSTRUCTIONS) && defined(CAN_USE_SUDIV) && \ defined(CAN_USE_NEON) && defined(CAN_USE_VFP3_INSTRUCTIONS) return kArmv8; #elif defined(CAN_USE_ARMV7_INSTRUCTIONS) && defined(CAN_USE_SUDIV) && \ defined(CAN_USE_NEON) && defined(CAN_USE_VFP3_INSTRUCTIONS) return kArmv7WithSudiv; #elif defined(CAN_USE_ARMV7_INSTRUCTIONS) && defined(CAN_USE_NEON) && \ defined(CAN_USE_VFP3_INSTRUCTIONS) return kArmv7; #else return kArmv6; #endif } bool CpuFeatures::SupportsWasmSimd128() { return IsSupported(NEON); } void CpuFeatures::ProbeImpl(bool cross_compile) { dcache_line_size_ = 64; unsigned command_line = CpuFeaturesFromCommandLine(); // Only use statically determined features for cross compile (snapshot). if (cross_compile) { supported_ |= command_line & CpuFeaturesFromCompiler(); return; } #ifndef __arm__ // For the simulator build, use whatever the flags specify. supported_ |= command_line; #else // __arm__ // Probe for additional features at runtime. base::CPU cpu; // Runtime detection is slightly fuzzy, and some inferences are necessary. unsigned runtime = kArmv6; // NEON and VFPv3 imply at least ARMv7-A. if (cpu.has_neon() && cpu.has_vfp3_d32()) { DCHECK(cpu.has_vfp3()); runtime |= kArmv7; if (cpu.has_idiva()) { runtime |= kArmv7WithSudiv; if (cpu.architecture() >= 8) { runtime |= kArmv8; } } } // Use the best of the features found by CPU detection and those inferred from // the build system. In both cases, restrict available features using the // command-line. Note that the command-line flags are very permissive (kArmv8) // by default. supported_ |= command_line & CpuFeaturesFromCompiler(); supported_ |= command_line & runtime; // Additional tuning options. // ARM Cortex-A9 and Cortex-A5 have 32 byte cachelines. if (cpu.implementer() == base::CPU::kArm && (cpu.part() == base::CPU::kArmCortexA5 || cpu.part() == base::CPU::kArmCortexA9)) { dcache_line_size_ = 32; } #endif DCHECK_IMPLIES(IsSupported(ARMv7_SUDIV), IsSupported(ARMv7)); DCHECK_IMPLIES(IsSupported(ARMv8), IsSupported(ARMv7_SUDIV)); // Set a static value on whether Simd is supported. // This variable is only used for certain archs to query SupportWasmSimd128() // at runtime in builtins using an extern ref. Other callers should use // CpuFeatures::SupportWasmSimd128(). CpuFeatures::supports_wasm_simd_128_ = CpuFeatures::SupportsWasmSimd128(); } void CpuFeatures::PrintTarget() { const char* arm_arch = nullptr; const char* arm_target_type = ""; const char* arm_no_probe = ""; const char* arm_fpu = ""; const char* arm_thumb = ""; const char* arm_float_abi = nullptr; #if !defined __arm__ arm_target_type = " simulator"; #endif #if defined ARM_TEST_NO_FEATURE_PROBE arm_no_probe = " noprobe"; #endif #if defined CAN_USE_ARMV8_INSTRUCTIONS arm_arch = "arm v8"; #elif defined CAN_USE_ARMV7_INSTRUCTIONS arm_arch = "arm v7"; #else arm_arch = "arm v6"; #endif #if defined CAN_USE_NEON arm_fpu = " neon"; #elif defined CAN_USE_VFP3_INSTRUCTIONS #if defined CAN_USE_VFP32DREGS arm_fpu = " vfp3"; #else arm_fpu = " vfp3-d16"; #endif #else arm_fpu = " vfp2"; #endif #ifdef __arm__ arm_float_abi = base::OS::ArmUsingHardFloat() ? "hard" : "softfp"; #elif USE_EABI_HARDFLOAT arm_float_abi = "hard"; #else arm_float_abi = "softfp"; #endif #if defined __arm__ && (defined __thumb__) || (defined __thumb2__) arm_thumb = " thumb"; #endif printf("target%s%s %s%s%s %s\n", arm_target_type, arm_no_probe, arm_arch, arm_fpu, arm_thumb, arm_float_abi); } void CpuFeatures::PrintFeatures() { printf("ARMv8=%d ARMv7=%d VFPv3=%d VFP32DREGS=%d NEON=%d SUDIV=%d", CpuFeatures::IsSupported(ARMv8), CpuFeatures::IsSupported(ARMv7), CpuFeatures::IsSupported(VFPv3), CpuFeatures::IsSupported(VFP32DREGS), CpuFeatures::IsSupported(NEON), CpuFeatures::IsSupported(SUDIV)); #ifdef __arm__ bool eabi_hardfloat = base::OS::ArmUsingHardFloat(); #elif USE_EABI_HARDFLOAT bool eabi_hardfloat = true; #else bool eabi_hardfloat = false; #endif printf(" USE_EABI_HARDFLOAT=%d\n", eabi_hardfloat); } // ----------------------------------------------------------------------------- // Implementation of RelocInfo // static const int RelocInfo::kApplyMask = RelocInfo::ModeMask(RelocInfo::RELATIVE_CODE_TARGET); bool RelocInfo::IsCodedSpecially() { // The deserializer needs to know whether a pointer is specially coded.  Being // specially coded on ARM means that it is a movw/movt instruction. We don't // generate those for relocatable pointers. return false; } bool RelocInfo::IsInConstantPool() { return Assembler::is_constant_pool_load(pc_); } uint32_t RelocInfo::wasm_call_tag() const { DCHECK(rmode_ == WASM_CALL || rmode_ == WASM_STUB_CALL); return static_cast<uint32_t>( Assembler::target_address_at(pc_, constant_pool_)); } // ----------------------------------------------------------------------------- // Implementation of Operand and MemOperand // See assembler-arm-inl.h for inlined constructors Operand::Operand(Handle<HeapObject> handle) { rm_ = no_reg; value_.immediate = static_cast<intptr_t>(handle.address()); rmode_ = RelocInfo::FULL_EMBEDDED_OBJECT; } Operand::Operand(Register rm, ShiftOp shift_op, int shift_imm) { DCHECK(is_uint5(shift_imm)); rm_ = rm; rs_ = no_reg; shift_op_ = shift_op; shift_imm_ = shift_imm & 31; if ((shift_op == ROR) && (shift_imm == 0)) { // ROR #0 is functionally equivalent to LSL #0 and this allow us to encode // RRX as ROR #0 (See below). shift_op = LSL; } else if (shift_op == RRX) { // encoded as ROR with shift_imm == 0 DCHECK_EQ(shift_imm, 0); shift_op_ = ROR; shift_imm_ = 0; } } Operand::Operand(Register rm, ShiftOp shift_op, Register rs) { DCHECK(shift_op != RRX); rm_ = rm; rs_ = no_reg; shift_op_ = shift_op; rs_ = rs; } Operand Operand::EmbeddedNumber(double value) { int32_t smi; if (DoubleToSmiInteger(value, &smi)) return Operand(Smi::FromInt(smi)); Operand result(0, RelocInfo::FULL_EMBEDDED_OBJECT); result.is_heap_object_request_ = true; result.value_.heap_object_request = HeapObjectRequest(value); return result; } Operand Operand::EmbeddedStringConstant(const StringConstantBase* str) { Operand result(0, RelocInfo::FULL_EMBEDDED_OBJECT); result.is_heap_object_request_ = true; result.value_.heap_object_request = HeapObjectRequest(str); return result; } MemOperand::MemOperand(Register rn, int32_t offset, AddrMode am) : rn_(rn), rm_(no_reg), offset_(offset), am_(am) { // Accesses below the stack pointer are not safe, and are prohibited by the // ABI. We can check obvious violations here. if (rn == sp) { if (am == Offset) DCHECK_LE(0, offset); if (am == NegOffset) DCHECK_GE(0, offset); } } MemOperand::MemOperand(Register rn, Register rm, AddrMode am) : rn_(rn), rm_(rm), shift_op_(LSL), shift_imm_(0), am_(am) {} MemOperand::MemOperand(Register rn, Register rm, ShiftOp shift_op, int shift_imm, AddrMode am) : rn_(rn), rm_(rm), shift_op_(shift_op), shift_imm_(shift_imm & 31), am_(am) { DCHECK(is_uint5(shift_imm)); } NeonMemOperand::NeonMemOperand(Register rn, AddrMode am, int align) : rn_(rn), rm_(am == Offset ? pc : sp) { DCHECK((am == Offset) || (am == PostIndex)); SetAlignment(align); } NeonMemOperand::NeonMemOperand(Register rn, Register rm, int align) : rn_(rn), rm_(rm) { SetAlignment(align); } void NeonMemOperand::SetAlignment(int align) { switch (align) { case 0: align_ = 0; break; case 64: align_ = 1; break; case 128: align_ = 2; break; case 256: align_ = 3; break; default: UNREACHABLE(); } } void Assembler::AllocateAndInstallRequestedHeapObjects(Isolate* isolate) { DCHECK_IMPLIES(isolate == nullptr, heap_object_requests_.empty()); for (auto& request : heap_object_requests_) { Handle<HeapObject> object; switch (request.kind()) { case HeapObjectRequest::kHeapNumber: object = isolate->factory()->NewHeapNumber<AllocationType::kOld>( request.heap_number()); break; case HeapObjectRequest::kStringConstant: { const StringConstantBase* str = request.string(); CHECK_NOT_NULL(str); object = str->AllocateStringConstant(isolate); break; } } Address pc = reinterpret_cast<Address>(buffer_start_) + request.offset(); Memory<Address>(constant_pool_entry_address(pc, 0 /* unused */)) = object.address(); } } // ----------------------------------------------------------------------------- // Specific instructions, constants, and masks. // str(r, MemOperand(sp, 4, NegPreIndex), al) instruction (aka push(r)) // register r is not encoded. const Instr kPushRegPattern = al | B26 | 4 | NegPreIndex | sp.code() * B16; // ldr(r, MemOperand(sp, 4, PostIndex), al) instruction (aka pop(r)) // register r is not encoded. const Instr kPopRegPattern = al | B26 | L | 4 | PostIndex | sp.code() * B16; // ldr rd, [pc, #offset] const Instr kLdrPCImmedMask = 15 * B24 | 7 * B20 | 15 * B16; const Instr kLdrPCImmedPattern = 5 * B24 | L | pc.code() * B16; // Pc-relative call or jump to a signed imm24 offset. // bl pc + #offset // b pc + #offset const Instr kBOrBlPCImmedMask = 0xE * B24; const Instr kBOrBlPCImmedPattern = 0xA * B24; // vldr dd, [pc, #offset] const Instr kVldrDPCMask = 15 * B24 | 3 * B20 | 15 * B16 | 15 * B8; const Instr kVldrDPCPattern = 13 * B24 | L | pc.code() * B16 | 11 * B8; // blxcc rm const Instr kBlxRegMask = 15 * B24 | 15 * B20 | 15 * B16 | 15 * B12 | 15 * B8 | 15 * B4; const Instr kBlxRegPattern = B24 | B21 | 15 * B16 | 15 * B12 | 15 * B8 | BLX; const Instr kBlxIp = al | kBlxRegPattern | ip.code(); const Instr kMovMvnMask = 0x6D * B21 | 0xF * B16; const Instr kMovMvnPattern = 0xD * B21; const Instr kMovMvnFlip = B22; const Instr kMovLeaveCCMask = 0xDFF * B16; const Instr kMovLeaveCCPattern = 0x1A0 * B16; const Instr kMovwPattern = 0x30 * B20; const Instr kMovtPattern = 0x34 * B20; const Instr kMovwLeaveCCFlip = 0x5 * B21; const Instr kMovImmedMask = 0x7F * B21; const Instr kMovImmedPattern = 0x1D * B21; const Instr kOrrImmedMask = 0x7F * B21; const Instr kOrrImmedPattern = 0x1C * B21; const Instr kCmpCmnMask = 0xDD * B20 | 0xF * B12; const Instr kCmpCmnPattern = 0x15 * B20; const Instr kCmpCmnFlip = B21; const Instr kAddSubFlip = 0x6 * B21; const Instr kAndBicFlip = 0xE * B21; // A mask for the Rd register for push, pop, ldr, str instructions. const Instr kLdrRegFpOffsetPattern = al | B26 | L | Offset | fp.code() * B16; const Instr kStrRegFpOffsetPattern = al | B26 | Offset | fp.code() * B16; const Instr kLdrRegFpNegOffsetPattern = al | B26 | L | NegOffset | fp.code() * B16; const Instr kStrRegFpNegOffsetPattern = al | B26 | NegOffset | fp.code() * B16; const Instr kLdrStrInstrTypeMask = 0xFFFF0000; Assembler::Assembler(const AssemblerOptions& options, std::unique_ptr<AssemblerBuffer> buffer) : AssemblerBase(options, std::move(buffer)), pending_32_bit_constants_(), scratch_register_list_({ip}) { reloc_info_writer.Reposition(buffer_start_ + buffer_->size(), pc_); constant_pool_deadline_ = kMaxInt; const_pool_blocked_nesting_ = 0; no_const_pool_before_ = 0; first_const_pool_32_use_ = -1; last_bound_pos_ = 0; if (CpuFeatures::IsSupported(VFP32DREGS)) { // Register objects tend to be abstracted and survive between scopes, so // it's awkward to use CpuFeatures::VFP32DREGS with CpuFeatureScope. To make // its use consistent with other features, we always enable it if we can. EnableCpuFeature(VFP32DREGS); // Make sure we pick two D registers which alias a Q register. This way, we // can use a Q as a scratch if NEON is supported. scratch_vfp_register_list_ = d14.ToVfpRegList() | d15.ToVfpRegList(); } else { // When VFP32DREGS is not supported, d15 become allocatable. Therefore we // cannot use it as a scratch. scratch_vfp_register_list_ = d14.ToVfpRegList(); } } Assembler::~Assembler() { DCHECK_EQ(const_pool_blocked_nesting_, 0); DCHECK_EQ(first_const_pool_32_use_, -1); } void Assembler::GetCode(Isolate* isolate, CodeDesc* desc, SafepointTableBuilder* safepoint_table_builder, int handler_table_offset) { // As a crutch to avoid having to add manual Align calls wherever we use a // raw workflow to create Code objects (mostly in tests), add another Align // call here. It does no harm - the end of the Code object is aligned to the // (larger) kCodeAlignment anyways. // TODO(jgruber): Consider moving responsibility for proper alignment to // metadata table builders (safepoint, handler, constant pool, code // comments). DataAlign(Code::kMetadataAlignment); // Emit constant pool if necessary. CheckConstPool(true, false); DCHECK(pending_32_bit_constants_.empty()); int code_comments_size = WriteCodeComments(); AllocateAndInstallRequestedHeapObjects(isolate); // Set up code descriptor. // TODO(jgruber): Reconsider how these offsets and sizes are maintained up to // this point to make CodeDesc initialization less fiddly. static constexpr int kConstantPoolSize = 0; const int instruction_size = pc_offset(); const int code_comments_offset = instruction_size - code_comments_size; const int constant_pool_offset = code_comments_offset - kConstantPoolSize; const int handler_table_offset2 = (handler_table_offset == kNoHandlerTable) ? constant_pool_offset : handler_table_offset; const int safepoint_table_offset = (safepoint_table_builder == kNoSafepointTable) ? handler_table_offset2 : safepoint_table_builder->safepoint_table_offset(); const int reloc_info_offset = static_cast<int>(reloc_info_writer.pos() - buffer_->start()); CodeDesc::Initialize(desc, this, safepoint_table_offset, handler_table_offset2, constant_pool_offset, code_comments_offset, reloc_info_offset); } void Assembler::Align(int m) { DCHECK(m >= 4 && base::bits::IsPowerOfTwo(m)); DCHECK_EQ(pc_offset() & (kInstrSize - 1), 0); while ((pc_offset() & (m - 1)) != 0) { nop(); } } void Assembler::CodeTargetAlign() { // Preferred alignment of jump targets on some ARM chips. Align(8); } Condition Assembler::GetCondition(Instr instr) { return Instruction::ConditionField(instr); } bool Assembler::IsLdrRegisterImmediate(Instr instr) { return (instr & (B27 | B26 | B25 | B22 | B20)) == (B26 | B20); } bool Assembler::IsVldrDRegisterImmediate(Instr instr) { return (instr & (15 * B24 | 3 * B20 | 15 * B8)) == (13 * B24 | B20 | 11 * B8); } int Assembler::GetLdrRegisterImmediateOffset(Instr instr) { DCHECK(IsLdrRegisterImmediate(instr)); bool positive = (instr & B23) == B23; int offset = instr & kOff12Mask; // Zero extended offset. return positive ? offset : -offset; } int Assembler::GetVldrDRegisterImmediateOffset(Instr instr) { DCHECK(IsVldrDRegisterImmediate(instr)); bool positive = (instr & B23) == B23; int offset = instr & kOff8Mask; // Zero extended offset. offset <<= 2; return positive ? offset : -offset; } Instr Assembler::SetLdrRegisterImmediateOffset(Instr instr, int offset) { DCHECK(IsLdrRegisterImmediate(instr)); bool positive = offset >= 0; if (!positive) offset = -offset; DCHECK(is_uint12(offset)); // Set bit indicating whether the offset should be added. instr = (instr & ~B23) | (positive ? B23 : 0); // Set the actual offset. return (instr & ~kOff12Mask) | offset; } Instr Assembler::SetVldrDRegisterImmediateOffset(Instr instr, int offset) { DCHECK(IsVldrDRegisterImmediate(instr)); DCHECK((offset & ~3) == offset); // Must be 64-bit aligned. bool positive = offset >= 0; if (!positive) offset = -offset; DCHECK(is_uint10(offset)); // Set bit indicating whether the offset should be added. instr = (instr & ~B23) | (positive ? B23 : 0); // Set the actual offset. Its bottom 2 bits are zero. return (instr & ~kOff8Mask) | (offset >> 2); } bool Assembler::IsStrRegisterImmediate(Instr instr) { return (instr & (B27 | B26 | B25 | B22 | B20)) == B26; } Instr Assembler::SetStrRegisterImmediateOffset(Instr instr, int offset) { DCHECK(IsStrRegisterImmediate(instr)); bool positive = offset >= 0; if (!positive) offset = -offset; DCHECK(is_uint12(offset)); // Set bit indicating whether the offset should be added. instr = (instr & ~B23) | (positive ? B23 : 0); // Set the actual offset. return (instr & ~kOff12Mask) | offset; } bool Assembler::IsAddRegisterImmediate(Instr instr) { return (instr & (B27 | B26 | B25 | B24 | B23 | B22 | B21)) == (B25 | B23); } Instr Assembler::SetAddRegisterImmediateOffset(Instr instr, int offset) { DCHECK(IsAddRegisterImmediate(instr)); DCHECK_GE(offset, 0); DCHECK(is_uint12(offset)); // Set the offset. return (instr & ~kOff12Mask) | offset; } Register Assembler::GetRd(Instr instr) { return Register::from_code(Instruction::RdValue(instr)); } Register Assembler::GetRn(Instr instr) { return Register::from_code(Instruction::RnValue(instr)); } Register Assembler::GetRm(Instr instr) { return Register::from_code(Instruction::RmValue(instr)); } bool Assembler::IsPush(Instr instr) { return ((instr & ~kRdMask) == kPushRegPattern); } bool Assembler::IsPop(Instr instr) { return ((instr & ~kRdMask) == kPopRegPattern); } bool Assembler::IsStrRegFpOffset(Instr instr) { return ((instr & kLdrStrInstrTypeMask) == kStrRegFpOffsetPattern); } bool Assembler::IsLdrRegFpOffset(Instr instr) { return ((instr & kLdrStrInstrTypeMask) == kLdrRegFpOffsetPattern); } bool Assembler::IsStrRegFpNegOffset(Instr instr) { return ((instr & kLdrStrInstrTypeMask) == kStrRegFpNegOffsetPattern); } bool Assembler::IsLdrRegFpNegOffset(Instr instr) { return ((instr & kLdrStrInstrTypeMask) == kLdrRegFpNegOffsetPattern); } bool Assembler::IsLdrPcImmediateOffset(Instr instr) { // Check the instruction is indeed a // ldr<cond> <Rd>, [pc +/- offset_12]. return (instr & kLdrPCImmedMask) == kLdrPCImmedPattern; } bool Assembler::IsBOrBlPcImmediateOffset(Instr instr) { return (instr & kBOrBlPCImmedMask) == kBOrBlPCImmedPattern; } bool Assembler::IsVldrDPcImmediateOffset(Instr instr) { // Check the instruction is indeed a // vldr<cond> <Dd>, [pc +/- offset_10]. return (instr & kVldrDPCMask) == kVldrDPCPattern; } bool Assembler::IsBlxReg(Instr instr) { // Check the instruction is indeed a // blxcc <Rm> return (instr & kBlxRegMask) == kBlxRegPattern; } bool Assembler::IsBlxIp(Instr instr) { // Check the instruction is indeed a // blx ip return instr == kBlxIp; } bool Assembler::IsTstImmediate(Instr instr) { return (instr & (B27 | B26 | I | kOpCodeMask | S | kRdMask)) == (I | TST | S); } bool Assembler::IsCmpRegister(Instr instr) { return (instr & (B27 | B26 | I | kOpCodeMask | S | kRdMask | B4)) == (CMP | S); } bool Assembler::IsCmpImmediate(Instr instr) { return (instr & (B27 | B26 | I | kOpCodeMask | S | kRdMask)) == (I | CMP | S); } Register Assembler::GetCmpImmediateRegister(Instr instr) { DCHECK(IsCmpImmediate(instr)); return GetRn(instr); } int Assembler::GetCmpImmediateRawImmediate(Instr instr) { DCHECK(IsCmpImmediate(instr)); return instr & kOff12Mask; } // Labels refer to positions in the (to be) generated code. // There are bound, linked, and unused labels. // // Bound labels refer to known positions in the already // generated code. pos() is the position the label refers to. // // Linked labels refer to unknown positions in the code // to be generated; pos() is the position of the last // instruction using the label. // // The linked labels form a link chain by making the branch offset // in the instruction steam to point to the previous branch // instruction using the same label. // // The link chain is terminated by a branch offset pointing to the // same position. int Assembler::target_at(int pos) { Instr instr = instr_at(pos); if (is_uint24(instr)) { // Emitted link to a label, not part of a branch. return instr; } DCHECK_EQ(5 * B25, instr & 7 * B25); // b, bl, or blx imm24 int imm26 = ((instr & kImm24Mask) << 8) >> 6; if ((Instruction::ConditionField(instr) == kSpecialCondition) && ((instr & B24) != 0)) { // blx uses bit 24 to encode bit 2 of imm26 imm26 += 2; } return pos + Instruction::kPcLoadDelta + imm26; } void Assembler::target_at_put(int pos, int target_pos) { Instr instr = instr_at(pos); if (is_uint24(instr)) { DCHECK(target_pos == pos || target_pos >= 0); // Emitted link to a label, not part of a branch. // Load the position of the label relative to the generated code object // pointer in a register. // The existing code must be a single 24-bit label chain link, followed by // nops encoding the destination register. See mov_label_offset. // Extract the destination register from the first nop instructions. Register dst = Register::from_code(Instruction::RmValue(instr_at(pos + kInstrSize))); // In addition to the 24-bit label chain link, we expect to find one nop for // ARMv7 and above, or two nops for ARMv6. See mov_label_offset. DCHECK(IsNop(instr_at(pos + kInstrSize), dst.code())); if (!CpuFeatures::IsSupported(ARMv7)) { DCHECK(IsNop(instr_at(pos + 2 * kInstrSize), dst.code())); } // Here are the instructions we need to emit: // For ARMv7: target24 => target16_1:target16_0 // movw dst, #target16_0 // movt dst, #target16_1 // For ARMv6: target24 => target8_2:target8_1:target8_0 // mov dst, #target8_0 // orr dst, dst, #target8_1 << 8 // orr dst, dst, #target8_2 << 16 uint32_t target24 = target_pos + (Code::kHeaderSize - kHeapObjectTag); CHECK(is_uint24(target24)); if (is_uint8(target24)) { // If the target fits in a byte then only patch with a mov // instruction. PatchingAssembler patcher( options(), reinterpret_cast<byte*>(buffer_start_ + pos), 1); patcher.mov(dst, Operand(target24)); } else { uint16_t target16_0 = target24 & kImm16Mask; uint16_t target16_1 = target24 >> 16; if (CpuFeatures::IsSupported(ARMv7)) { // Patch with movw/movt. if (target16_1 == 0) { PatchingAssembler patcher( options(), reinterpret_cast<byte*>(buffer_start_ + pos), 1); CpuFeatureScope scope(&patcher, ARMv7); patcher.movw(dst, target16_0); } else { PatchingAssembler patcher( options(), reinterpret_cast<byte*>(buffer_start_ + pos), 2); CpuFeatureScope scope(&patcher, ARMv7); patcher.movw(dst, target16_0); patcher.movt(dst, target16_1); } } else { // Patch with a sequence of mov/orr/orr instructions. uint8_t target8_0 = target16_0 & kImm8Mask; uint8_t target8_1 = target16_0 >> 8; uint8_t target8_2 = target16_1 & kImm8Mask; if (target8_2 == 0) { PatchingAssembler patcher( options(), reinterpret_cast<byte*>(buffer_start_ + pos), 2); patcher.mov(dst, Operand(target8_0)); patcher.orr(dst, dst, Operand(target8_1 << 8)); } else { PatchingAssembler patcher( options(), reinterpret_cast<byte*>(buffer_start_ + pos), 3); patcher.mov(dst, Operand(target8_0)); patcher.orr(dst, dst, Operand(target8_1 << 8)); patcher.orr(dst, dst, Operand(target8_2 << 16)); } } } return; } int imm26 = target_pos - (pos + Instruction::kPcLoadDelta); DCHECK_EQ(5 * B25, instr & 7 * B25); // b, bl, or blx imm24 if (Instruction::ConditionField(instr) == kSpecialCondition) { // blx uses bit 24 to encode bit 2 of imm26 DCHECK_EQ(0, imm26 & 1); instr = (instr & ~(B24 | kImm24Mask)) | ((imm26 & 2) >> 1) * B24; } else { DCHECK_EQ(0, imm26 & 3); instr &= ~kImm24Mask; } int imm24 = imm26 >> 2; CHECK(is_int24(imm24)); instr_at_put(pos, instr | (imm24 & kImm24Mask)); } void Assembler::print(const Label* L) { if (L->is_unused()) { PrintF("unused label\n"); } else if (L->is_bound()) { PrintF("bound label to %d\n", L->pos()); } else if (L->is_linked()) { Label l; l.link_to(L->pos()); PrintF("unbound label"); while (l.is_linked()) { PrintF("@ %d ", l.pos()); Instr instr = instr_at(l.pos()); if ((instr & ~kImm24Mask) == 0) { PrintF("value\n"); } else { DCHECK_EQ(instr & 7 * B25, 5 * B25); // b, bl, or blx Condition cond = Instruction::ConditionField(instr); const char* b; const char* c; if (cond == kSpecialCondition) { b = "blx"; c = ""; } else { if ((instr & B24) != 0) b = "bl"; else b = "b"; switch (cond) { case eq: c = "eq"; break; case ne: c = "ne"; break; case hs: c = "hs"; break; case lo: c = "lo"; break; case mi: c = "mi"; break; case pl: c = "pl"; break; case vs: c = "vs"; break; case vc: c = "vc"; break; case hi: c = "hi"; break; case ls: c = "ls"; break; case ge: c = "ge"; break; case lt: c = "lt"; break; case gt: c = "gt"; break; case le: c = "le"; break; case al: c = ""; break; default: c = ""; UNREACHABLE(); } } PrintF("%s%s\n", b, c); } next(&l); } } else { PrintF("label in inconsistent state (pos = %d)\n", L->pos_); } } void Assembler::bind_to(Label* L, int pos) { DCHECK(0 <= pos && pos <= pc_offset()); // must have a valid binding position while (L->is_linked()) { int fixup_pos = L->pos(); next(L); // call next before overwriting link with target at fixup_pos target_at_put(fixup_pos, pos); } L->bind_to(pos); // Keep track of the last bound label so we don't eliminate any instructions // before a bound label. if (pos > last_bound_pos_) last_bound_pos_ = pos; } void Assembler::bind(Label* L) { DCHECK(!L->is_bound()); // label can only be bound once bind_to(L, pc_offset()); } void Assembler::next(Label* L) { DCHECK(L->is_linked()); int link = target_at(L->pos()); if (link == L->pos()) { // Branch target points to the same instruction. This is the end of the link // chain. L->Unuse(); } else { DCHECK_GE(link, 0); L->link_to(link); } } namespace { // Low-level code emission routines depending on the addressing mode. // If this returns true then you have to use the rotate_imm and immed_8 // that it returns, because it may have already changed the instruction // to match them! bool FitsShifter(uint32_t imm32, uint32_t* rotate_imm, uint32_t* immed_8, Instr* instr) { // imm32 must be unsigned. { // 32-bit immediates can be encoded as: // (8-bit value, 2*N bit left rotation) // e.g. 0xab00 can be encoded as 0xab shifted left by 8 == 2*4, i.e. // (0xab, 4) // // Check three categories which cover all possible shifter fits: // 1. 0x000000FF: The value is already 8-bit (no shifting necessary), // 2. 0x000FF000: The 8-bit value is somewhere in the middle of the 32-bit // value, and // 3. 0xF000000F: The 8-bit value is split over the beginning and end of // the 32-bit value. // For 0x000000FF. if (imm32 <= 0xFF) { *rotate_imm = 0; *immed_8 = imm32; return true; } // For 0x000FF000, count trailing zeros and shift down to 0x000000FF. Note // that we have to round the trailing zeros down to the nearest multiple of // two, since we can only encode shifts of 2*N. Note also that we know that // imm32 isn't zero, since we already checked if it's less than 0xFF. int half_trailing_zeros = base::bits::CountTrailingZerosNonZero(imm32) / 2; uint32_t imm8 = imm32 >> (half_trailing_zeros * 2); if (imm8 <= 0xFF) { DCHECK_GT(half_trailing_zeros, 0); // Rotating right by trailing_zeros is equivalent to rotating left by // 32 - trailing_zeros. We return rotate_right / 2, so calculate // (32 - trailing_zeros)/2 == 16 - trailing_zeros/2. *rotate_imm = (16 - half_trailing_zeros); *immed_8 = imm8; return true; } // For 0xF000000F, rotate by 16 to get 0x000FF000 and continue as if it // were that case. uint32_t imm32_rot16 = base::bits::RotateLeft32(imm32, 16); half_trailing_zeros = base::bits::CountTrailingZerosNonZero(imm32_rot16) / 2; imm8 = imm32_rot16 >> (half_trailing_zeros * 2); if (imm8 <= 0xFF) { // We've rotated left by 2*8, so we can't have more than that many // trailing zeroes. DCHECK_LT(half_trailing_zeros, 8); // We've already rotated by 2*8, before calculating trailing_zeros/2, // so we need (32 - (16 + trailing_zeros))/2 == 8 - trailing_zeros/2. *rotate_imm = 8 - half_trailing_zeros; *immed_8 = imm8; return true; } } // If the opcode is one with a complementary version and the complementary // immediate fits, change the opcode. if (instr != nullptr) { if ((*instr & kMovMvnMask) == kMovMvnPattern) { if (FitsShifter(~imm32, rotate_imm, immed_8, nullptr)) { *instr ^= kMovMvnFlip; return true; } else if ((*instr & kMovLeaveCCMask) == kMovLeaveCCPattern) { if (CpuFeatures::IsSupported(ARMv7)) { if (imm32 < 0x10000) { *instr ^= kMovwLeaveCCFlip; *instr |= Assembler::EncodeMovwImmediate(imm32); *rotate_imm = *immed_8 = 0; // Not used for movw. return true; } } } } else if ((*instr & kCmpCmnMask) == kCmpCmnPattern) { if (FitsShifter(-static_cast<int>(imm32), rotate_imm, immed_8, nullptr)) { *instr ^= kCmpCmnFlip; return true; } } else { Instr alu_insn = (*instr & kALUMask); if (alu_insn == ADD || alu_insn == SUB) { if (FitsShifter(-static_cast<int>(imm32), rotate_imm, immed_8, nullptr)) { *instr ^= kAddSubFlip; return true; } } else if (alu_insn == AND || alu_insn == BIC) { if (FitsShifter(~imm32, rotate_imm, immed_8, nullptr)) { *instr ^= kAndBicFlip; return true; } } } } return false; } // We have to use the temporary register for things that can be relocated even // if they can be encoded in the ARM's 12 bits of immediate-offset instruction // space. There is no guarantee that the relocated location can be similarly // encoded. bool MustOutputRelocInfo(RelocInfo::Mode rmode, const Assembler* assembler) { if (RelocInfo::IsOnlyForSerializer(rmode)) { if (assembler->predictable_code_size()) return true; return assembler->options().record_reloc_info_for_serialization; } else if (RelocInfo::IsNoInfo(rmode)) { return false; } return true; } bool UseMovImmediateLoad(const Operand& x, const Assembler* assembler) { DCHECK_NOT_NULL(assembler); if (x.MustOutputRelocInfo(assembler)) { // Prefer constant pool if data is likely to be patched. return false; } else { // Otherwise, use immediate load if movw / movt is available. return CpuFeatures::IsSupported(ARMv7); } } } // namespace bool Operand::MustOutputRelocInfo(const Assembler* assembler) const { return v8::internal::MustOutputRelocInfo(rmode_, assembler); } int Operand::InstructionsRequired(const Assembler* assembler, Instr instr) const { DCHECK_NOT_NULL(assembler); if (rm_.is_valid()) return 1; uint32_t dummy1, dummy2; if (MustOutputRelocInfo(assembler) || !FitsShifter(immediate(), &dummy1, &dummy2, &instr)) { // The immediate operand cannot be encoded as a shifter operand, or use of // constant pool is required. First account for the instructions required // for the constant pool or immediate load int instructions; if (UseMovImmediateLoad(*this, assembler)) { DCHECK(CpuFeatures::IsSupported(ARMv7)); // A movw / movt immediate load. instructions = 2; } else { // A small constant pool load. instructions = 1; } if ((instr & ~kCondMask) != 13 * B21) { // mov, S not set // For a mov or mvn instruction which doesn't set the condition // code, the constant pool or immediate load is enough, otherwise we need // to account for the actual instruction being requested. instructions += 1; } return instructions; } else { // No use of constant pool and the immediate operand can be encoded as a // shifter operand. return 1; } } void Assembler::Move32BitImmediate(Register rd, const Operand& x, Condition cond) { if (UseMovImmediateLoad(x, this)) { CpuFeatureScope scope(this, ARMv7); // UseMovImmediateLoad should return false when we need to output // relocation info, since we prefer the constant pool for values that // can be patched. DCHECK(!x.MustOutputRelocInfo(this)); UseScratchRegisterScope temps(this); // Re-use the destination register as a scratch if possible. Register target = rd != pc && rd != sp ? rd : temps.Acquire(); uint32_t imm32 = static_cast<uint32_t>(x.immediate()); movw(target, imm32 & 0xFFFF, cond); movt(target, imm32 >> 16, cond); if (target.code() != rd.code()) { mov(rd, target, LeaveCC, cond); } } else { int32_t immediate; if (x.IsHeapObjectRequest()) { RequestHeapObject(x.heap_object_request()); immediate = 0; } else { immediate = x.immediate(); } ConstantPoolAddEntry(pc_offset(), x.rmode_, immediate); ldr_pcrel(rd, 0, cond); } } void Assembler::AddrMode1(Instr instr, Register rd, Register rn, const Operand& x) { CheckBuffer(); uint32_t opcode = instr & kOpCodeMask; bool set_flags = (instr & S) != 0; DCHECK((opcode == ADC) || (opcode == ADD) || (opcode == AND) || (opcode == BIC) || (opcode == EOR) || (opcode == ORR) || (opcode == RSB) || (opcode == RSC) || (opcode == SBC) || (opcode == SUB) || (opcode == CMN) || (opcode == CMP) || (opcode == TEQ) || (opcode == TST) || (opcode == MOV) || (opcode == MVN)); // For comparison instructions, rd is not defined. DCHECK(rd.is_valid() || (opcode == CMN) || (opcode == CMP) || (opcode == TEQ) || (opcode == TST)); // For move instructions, rn is not defined. DCHECK(rn.is_valid() || (opcode == MOV) || (opcode == MVN)); DCHECK(rd.is_valid() || rn.is_valid()); DCHECK_EQ(instr & ~(kCondMask | kOpCodeMask | S), 0); if (!AddrMode1TryEncodeOperand(&instr, x)) { DCHECK(x.IsImmediate()); // Upon failure to encode, the opcode should not have changed. DCHECK(opcode == (instr & kOpCodeMask)); UseScratchRegisterScope temps(this); Condition cond = Instruction::ConditionField(instr); if ((opcode == MOV) && !set_flags) { // Generate a sequence of mov instructions or a load from the constant // pool only for a MOV instruction which does not set the flags. DCHECK(!rn.is_valid()); Move32BitImmediate(rd, x, cond); } else if ((opcode == ADD) && !set_flags && (rd == rn) && !temps.CanAcquire()) { // Split the operation into a sequence of additions if we cannot use a // scratch register. In this case, we cannot re-use rn and the assembler // does not have any scratch registers to spare. uint32_t imm = x.immediate(); do { // The immediate encoding format is composed of 8 bits of data and 4 // bits encoding a rotation. Each of the 16 possible rotations accounts // for a rotation by an even number. // 4 bits -> 16 rotations possible // -> 16 rotations of 2 bits each fits in a 32-bit value. // This means that finding the even number of trailing zeroes of the // immediate allows us to more efficiently split it: int trailing_zeroes = base::bits::CountTrailingZeros(imm) & ~1u; uint32_t mask = (0xFF << trailing_zeroes); add(rd, rd, Operand(imm & mask), LeaveCC, cond); imm = imm & ~mask; } while (!ImmediateFitsAddrMode1Instruction(imm)); add(rd, rd, Operand(imm), LeaveCC, cond); } else { // The immediate operand cannot be encoded as a shifter operand, so load // it first to a scratch register and change the original instruction to // use it. // Re-use the destination register if possible. Register scratch = (rd.is_valid() && rd != rn && rd != pc && rd != sp) ? rd : temps.Acquire(); mov(scratch, x, LeaveCC, cond); AddrMode1(instr, rd, rn, Operand(scratch)); } return; } if (!rd.is_valid()) { // Emit a comparison instruction. emit(instr | rn.code() * B16); } else if (!rn.is_valid()) { // Emit a move instruction. If the operand is a register-shifted register, // then prevent the destination from being PC as this is unpredictable. DCHECK(!x.IsRegisterShiftedRegister() || rd != pc); emit(instr | rd.code() * B12); } else { emit(instr | rn.code() * B16 | rd.code() * B12); } if (rn == pc || x.rm_ == pc) { // Block constant pool emission for one instruction after reading pc. BlockConstPoolFor(1); } } bool Assembler::AddrMode1TryEncodeOperand(Instr* instr, const Operand& x) { if (x.IsImmediate()) { // Immediate. uint32_t rotate_imm; uint32_t immed_8; if (x.MustOutputRelocInfo(this) || !FitsShifter(x.immediate(), &rotate_imm, &immed_8, instr)) { // Let the caller handle generating multiple instructions. return false; } *instr |= I | rotate_imm * B8 | immed_8; } else if (x.IsImmediateShiftedRegister()) { *instr |= x.shift_imm_ * B7 | x.shift_op_ | x.rm_.code(); } else { DCHECK(x.IsRegisterShiftedRegister()); // It is unpredictable to use the PC in this case. DCHECK(x.rm_ != pc && x.rs_ != pc); *instr |= x.rs_.code() * B8 | x.shift_op_ | B4 | x.rm_.code(); } return true; } void Assembler::AddrMode2(Instr instr, Register rd, const MemOperand& x) { DCHECK((instr & ~(kCondMask | B | L)) == B26); // This method does not handle pc-relative addresses. ldr_pcrel() should be // used instead. DCHECK(x.rn_ != pc); int am = x.am_; if (!x.rm_.is_valid()) { // Immediate offset. int offset_12 = x.offset_; if (offset_12 < 0) { offset_12 = -offset_12; am ^= U; } if (!is_uint12(offset_12)) { // Immediate offset cannot be encoded, load it first to a scratch // register. UseScratchRegisterScope temps(this); // Allow re-using rd for load instructions if possible. bool is_load = (instr & L) == L; Register scratch = (is_load && rd != x.rn_ && rd != pc && rd != sp) ? rd : temps.Acquire(); mov(scratch, Operand(x.offset_), LeaveCC, Instruction::ConditionField(instr)); AddrMode2(instr, rd, MemOperand(x.rn_, scratch, x.am_)); return; } DCHECK_GE(offset_12, 0); // no masking needed instr |= offset_12; } else { // Register offset (shift_imm_ and shift_op_ are 0) or scaled // register offset the constructors make sure than both shift_imm_ // and shift_op_ are initialized. DCHECK(x.rm_ != pc); instr |= B25 | x.shift_imm_ * B7 | x.shift_op_ | x.rm_.code(); } DCHECK((am & (P | W)) == P || x.rn_ != pc); // no pc base with writeback emit(instr | am | x.rn_.code() * B16 | rd.code() * B12); } void Assembler::AddrMode3(Instr instr, Register rd, const MemOperand& x) { DCHECK((instr & ~(kCondMask | L | S6 | H)) == (B4 | B7)); DCHECK(x.rn_.is_valid()); // This method does not handle pc-relative addresses. ldr_pcrel() should be // used instead. DCHECK(x.rn_ != pc); int am = x.am_; bool is_load = (instr & L) == L; if (!x.rm_.is_valid()) { // Immediate offset. int offset_8 = x.offset_; if (offset_8 < 0) { offset_8 = -offset_8; am ^= U; } if (!is_uint8(offset_8)) { // Immediate offset cannot be encoded, load it first to a scratch // register. UseScratchRegisterScope temps(this); // Allow re-using rd for load instructions if possible. Register scratch = (is_load && rd != x.rn_ && rd != pc && rd != sp) ? rd : temps.Acquire(); mov(scratch, Operand(x.offset_), LeaveCC, Instruction::ConditionField(instr)); AddrMode3(instr, rd, MemOperand(x.rn_, scratch, x.am_)); return; } DCHECK_GE(offset_8, 0); // no masking needed instr |= B | (offset_8 >> 4) * B8 | (offset_8 & 0xF); } else if (x.shift_imm_ != 0) { // Scaled register offsets are not supported, compute the offset separately // to a scratch register. UseScratchRegisterScope temps(this); // Allow re-using rd for load instructions if possible. Register scratch = (is_load && rd != x.rn_ && rd != pc && rd != sp) ? rd : temps.Acquire(); mov(scratch, Operand(x.rm_, x.shift_op_, x.shift_imm_), LeaveCC, Instruction::ConditionField(instr)); AddrMode3(instr, rd, MemOperand(x.rn_, scratch, x.am_)); return; } else { // Register offset. DCHECK((am & (P | W)) == P || x.rm_ != pc); // no pc index with writeback instr |= x.rm_.code(); } DCHECK((am & (P | W)) == P || x.rn_ != pc); // no pc base with writeback emit(instr | am | x.rn_.code() * B16 | rd.code() * B12); } void Assembler::AddrMode4(Instr instr, Register rn, RegList rl) { DCHECK((instr & ~(kCondMask | P | U | W | L)) == B27); DCHECK(!rl.is_empty()); DCHECK(rn != pc); emit(instr | rn.code() * B16 | rl.bits()); } void Assembler::AddrMode5(Instr instr, CRegister crd, const MemOperand& x) { // Unindexed addressing is not encoded by this function. DCHECK_EQ((B27 | B26), (instr & ~(kCondMask | kCoprocessorMask | P | U | N | W | L))); DCHECK(x.rn_.is_valid() && !x.rm_.is_valid()); int am = x.am_; int offset_8 = x.offset_; DCHECK_EQ(offset_8 & 3, 0); // offset must be an aligned word offset offset_8 >>= 2; if (offset_8 < 0) { offset_8 = -offset_8; am ^= U; } DCHECK(is_uint8(offset_8)); // unsigned word offset must fit in a byte DCHECK((am & (P | W)) == P || x.rn_ != pc); // no pc base with writeback // Post-indexed addressing requires W == 1; different than in AddrMode2/3. if ((am & P) == 0) am |= W; DCHECK_GE(offset_8, 0); // no masking needed emit(instr | am | x.rn_.code() * B16 | crd.code() * B12 | offset_8); } int Assembler::branch_offset(Label* L) { int target_pos; if (L->is_bound()) { target_pos = L->pos(); } else { if (L->is_linked()) { // Point to previous instruction that uses the link. target_pos = L->pos(); } else { // First entry of the link chain points to itself. target_pos = pc_offset(); } L->link_to(pc_offset()); } // Block the emission of the constant pool, since the branch instruction must // be emitted at the pc offset recorded by the label. if (!is_const_pool_blocked()) BlockConstPoolFor(1); return target_pos - (pc_offset() + Instruction::kPcLoadDelta); } // Branch instructions. void Assembler::b(int branch_offset, Condition cond, RelocInfo::Mode rmode) { if (!RelocInfo::IsNoInfo(rmode)) RecordRelocInfo(rmode); DCHECK_EQ(branch_offset & 3, 0); int imm24 = branch_offset >> 2; const bool b_imm_check = is_int24(imm24); CHECK(b_imm_check); emit(cond | B27 | B25 | (imm24 & kImm24Mask)); if (cond == al) { // Dead code is a good location to emit the constant pool. CheckConstPool(false, false); } } void Assembler::bl(int branch_offset, Condition cond, RelocInfo::Mode rmode) { if (!RelocInfo::IsNoInfo(rmode)) RecordRelocInfo(rmode); DCHECK_EQ(branch_offset & 3, 0); int imm24 = branch_offset >> 2; const bool bl_imm_check = is_int24(imm24); CHECK(bl_imm_check); emit(cond | B27 | B25 | B24 | (imm24 & kImm24Mask)); } void Assembler::blx(int branch_offset) { DCHECK_EQ(branch_offset & 1, 0); int h = ((branch_offset & 2) >> 1) * B24; int imm24 = branch_offset >> 2; const bool blx_imm_check = is_int24(imm24); CHECK(blx_imm_check); emit(kSpecialCondition | B27 | B25 | h | (imm24 & kImm24Mask)); } void Assembler::blx(Register target, Condition cond) { DCHECK(target != pc); emit(cond | B24 | B21 | 15 * B16 | 15 * B12 | 15 * B8 | BLX | target.code()); } void Assembler::bx(Register target, Condition cond) { DCHECK(target != pc); // use of pc is actually allowed, but discouraged emit(cond | B24 | B21 | 15 * B16 | 15 * B12 | 15 * B8 | BX | target.code()); } void Assembler::b(Label* L, Condition cond) { CheckBuffer(); b(branch_offset(L), cond); } void Assembler::bl(Label* L, Condition cond) { CheckBuffer(); bl(branch_offset(L), cond); } void Assembler::blx(Label* L) { CheckBuffer(); blx(branch_offset(L)); } // Data-processing instructions. void Assembler::and_(Register dst, Register src1, const Operand& src2, SBit s, Condition cond) { AddrMode1(cond | AND | s, dst, src1, src2); } void Assembler::and_(Register dst, Register src1, Register src2, SBit s, Condition cond) { and_(dst, src1, Operand(src2), s, cond); } void Assembler::eor(Register dst, Register src1, const Operand& src2, SBit s, Condition cond) { AddrMode1(cond | EOR | s, dst, src1, src2); } void Assembler::eor(Register dst, Register src1, Register src2, SBit s, Condition cond) { AddrMode1(cond | EOR | s, dst, src1, Operand(src2)); } void Assembler::sub(Register dst, Register src1, const Operand& src2, SBit s, Condition cond) { AddrMode1(cond | SUB | s, dst, src1, src2); } void Assembler::sub(Register dst, Register src1, Register src2, SBit s, Condition cond) { sub(dst, src1, Operand(src2), s, cond); } void Assembler::rsb(Register dst, Register src1, const Operand& src2, SBit s, Condition cond) { AddrMode1(cond | RSB | s, dst, src1, src2); } void Assembler::add(Register dst, Register src1, const Operand& src2, SBit s, Condition cond) { AddrMode1(cond | ADD | s, dst, src1, src2); } void Assembler::add(Register dst, Register src1, Register src2, SBit s, Condition cond) { add(dst, src1, Operand(src2), s, cond); } void Assembler::adc(Register dst, Register src1, const Operand& src2, SBit s, Condition cond) { AddrMode1(cond | ADC | s, dst, src1, src2); } void Assembler::sbc(Register dst, Register src1, const Operand& src2, SBit s, Condition cond) { AddrMode1(cond | SBC | s, dst, src1, src2); } void Assembler::rsc(Register dst, Register src1, const Operand& src2, SBit s, Condition cond) { AddrMode1(cond | RSC | s, dst, src1, src2); } void Assembler::tst(Register src1, const Operand& src2, Condition cond) { AddrMode1(cond | TST | S, no_reg, src1, src2); } void Assembler::tst(Register src1, Register src2, Condition cond) { tst(src1, Operand(src2), cond); } void Assembler::teq(Register src1, const Operand& src2, Condition cond) { AddrMode1(cond | TEQ | S, no_reg, src1, src2); } void Assembler::cmp(Register src1, const Operand& src2, Condition cond) { AddrMode1(cond | CMP | S, no_reg, src1, src2); } void Assembler::cmp(Register src1, Register src2, Condition cond) { cmp(src1, Operand(src2), cond); } void Assembler::cmp_raw_immediate(Register src, int raw_immediate, Condition cond) { DCHECK(is_uint12(raw_immediate)); emit(cond | I | CMP | S | src.code() << 16 | raw_immediate); } void Assembler::cmn(Register src1, const Operand& src2, Condition cond) { AddrMode1(cond | CMN | S, no_reg, src1, src2); } void Assembler::orr(Register dst, Register src1, const Operand& src2, SBit s, Condition cond) { AddrMode1(cond | ORR | s, dst, src1, src2); } void Assembler::orr(Register dst, Register src1, Register src2, SBit s, Condition cond) { orr(dst, src1, Operand(src2), s, cond); } void Assembler::mov(Register dst, const Operand& src, SBit s, Condition cond) { // Don't allow nop instructions in the form mov rn, rn to be generated using // the mov instruction. They must be generated using nop(int/NopMarkerTypes). DCHECK(!(src.IsRegister() && src.rm() == dst && s == LeaveCC && cond == al)); AddrMode1(cond | MOV | s, dst, no_reg, src); } void Assembler::mov(Register dst, Register src, SBit s, Condition cond) { mov(dst, Operand(src), s, cond); } void Assembler::mov_label_offset(Register dst, Label* label) { if (label->is_bound()) { mov(dst, Operand(label->pos() + (Code::kHeaderSize - kHeapObjectTag))); } else { // Emit the link to the label in the code stream followed by extra nop // instructions. // If the label is not linked, then start a new link chain by linking it to // itself, emitting pc_offset(). int link = label->is_linked() ? label->pos() : pc_offset(); label->link_to(pc_offset()); // When the label is bound, these instructions will be patched with a // sequence of movw/movt or mov/orr/orr instructions. They will load the // destination register with the position of the label from the beginning // of the code. // // The link will be extracted from the first instruction and the destination // register from the second. // For ARMv7: // link // mov dst, dst // For ARMv6: // link // mov dst, dst // mov dst, dst // // When the label gets bound: target_at extracts the link and target_at_put // patches the instructions. CHECK(is_uint24(link)); BlockConstPoolScope block_const_pool(this); emit(link); nop(dst.code()); if (!CpuFeatures::IsSupported(ARMv7)) { nop(dst.code()); } } } void Assembler::movw(Register reg, uint32_t immediate, Condition cond) { DCHECK(IsEnabled(ARMv7)); emit(cond | 0x30 * B20 | reg.code() * B12 | EncodeMovwImmediate(immediate)); } void Assembler::movt(Register reg, uint32_t immediate, Condition cond) { DCHECK(IsEnabled(ARMv7)); emit(cond | 0x34 * B20 | reg.code() * B12 | EncodeMovwImmediate(immediate)); } void Assembler::bic(Register dst, Register src1, const Operand& src2, SBit s, Condition cond) { AddrMode1(cond | BIC | s, dst, src1, src2); } void Assembler::mvn(Register dst, const Operand& src, SBit s, Condition cond) { AddrMode1(cond | MVN | s, dst, no_reg, src); } void Assembler::asr(Register dst, Register src1, const Operand& src2, SBit s, Condition cond) { if (src2.IsRegister()) { mov(dst, Operand(src1, ASR, src2.rm()), s, cond); } else { mov(dst, Operand(src1, ASR, src2.immediate()), s, cond); } } void Assembler::lsl(Register dst, Register src1, const Operand& src2, SBit s, Condition cond) { if (src2.IsRegister()) { mov(dst, Operand(src1, LSL, src2.rm()), s, cond); } else { mov(dst, Operand(src1, LSL, src2.immediate()), s, cond); } } void Assembler::lsr(Register dst, Register src1, const Operand& src2, SBit s, Condition cond) { if (src2.IsRegister()) { mov(dst, Operand(src1, LSR, src2.rm()), s, cond); } else { mov(dst, Operand(src1, LSR, src2.immediate()), s, cond); } } // Multiply instructions. void Assembler::mla(Register dst, Register src1, Register src2, Register srcA, SBit s, Condition cond) { DCHECK(dst != pc && src1 != pc && src2 != pc && srcA != pc); emit(cond | A | s | dst.code() * B16 | srcA.code() * B12 | src2.code() * B8 | B7 | B4 | src1.code()); } void Assembler::mls(Register dst, Register src1, Register src2, Register srcA, Condition cond) { DCHECK(dst != pc && src1 != pc && src2 != pc && srcA != pc); DCHECK(IsEnabled(ARMv7)); emit(cond | B22 | B21 | dst.code() * B16 | srcA.code() * B12 | src2.code() * B8 | B7 | B4 | src1.code()); } void Assembler::sdiv(Register dst, Register src1, Register src2, Condition cond) { DCHECK(dst != pc && src1 != pc && src2 != pc); DCHECK(IsEnabled(SUDIV)); emit(cond | B26 | B25 | B24 | B20 | dst.code() * B16 | 0xF * B12 | src2.code() * B8 | B4 | src1.code()); } void Assembler::udiv(Register dst, Register src1, Register src2, Condition cond) { DCHECK(dst != pc && src1 != pc && src2 != pc); DCHECK(IsEnabled(SUDIV)); emit(cond | B26 | B25 | B24 | B21 | B20 | dst.code() * B16 | 0xF * B12 | src2.code() * B8 | B4 | src1.code()); } void Assembler::mul(Register dst, Register src1, Register src2, SBit s, Condition cond) { DCHECK(dst != pc && src1 != pc && src2 != pc); // dst goes in bits 16-19 for this instruction! emit(cond | s | dst.code() * B16 | src2.code() * B8 | B7 | B4 | src1.code()); } void Assembler::smmla(Register dst, Register src1, Register src2, Register srcA, Condition cond) { DCHECK(dst != pc && src1 != pc && src2 != pc && srcA != pc); emit(cond | B26 | B25 | B24 | B22 | B20 | dst.code() * B16 | srcA.code() * B12 | src2.code() * B8 | B4 | src1.code()); } void Assembler::smmul(Register dst, Register src1, Register src2, Condition cond) { DCHECK(dst != pc && src1 != pc && src2 != pc); emit(cond | B26 | B25 | B24 | B22 | B20 | dst.code() * B16 | 0xF * B12 | src2.code() * B8 | B4 | src1.code()); } void Assembler::smlal(Register dstL, Register dstH, Register src1, Register src2, SBit s, Condition cond) { DCHECK(dstL != pc && dstH != pc && src1 != pc && src2 != pc); DCHECK(dstL != dstH); emit(cond | B23 | B22 | A | s | dstH.code() * B16 | dstL.code() * B12 | src2.code() * B8 | B7 | B4 | src1.code()); } void Assembler::smull(Register dstL, Register dstH, Register src1, Register src2, SBit s, Condition cond) { DCHECK(dstL != pc && dstH != pc && src1 != pc && src2 != pc); DCHECK(dstL != dstH); emit(cond | B23 | B22 | s | dstH.code() * B16 | dstL.code() * B12 | src2.code() * B8 | B7 | B4 | src1.code()); } void Assembler::umlal(Register dstL, Register dstH, Register src1, Register src2, SBit s, Condition cond) { DCHECK(dstL != pc && dstH != pc && src1 != pc && src2 != pc); DCHECK(dstL != dstH); emit(cond | B23 | A | s | dstH.code() * B16 | dstL.code() * B12 | src2.code() * B8 | B7 | B4 | src1.code()); } void Assembler::umull(Register dstL, Register dstH, Register src1, Register src2, SBit s, Condition cond) { DCHECK(dstL != pc && dstH != pc && src1 != pc && src2 != pc); DCHECK(dstL != dstH); emit(cond | B23 | s | dstH.code() * B16 | dstL.code() * B12 | src2.code() * B8 | B7 | B4 | src1.code()); } // Miscellaneous arithmetic instructions. void Assembler::clz(Register dst, Register src, Condition cond) { DCHECK(dst != pc && src != pc); emit(cond | B24 | B22 | B21 | 15 * B16 | dst.code() * B12 | 15 * B8 | CLZ | src.code()); } // Saturating instructions. // Unsigned saturate. void Assembler::usat(Register dst, int satpos, const Operand& src, Condition cond) { DCHECK(dst != pc && src.rm_ != pc); DCHECK((satpos >= 0) && (satpos <= 31)); DCHECK(src.IsImmediateShiftedRegister()); DCHECK((src.shift_op_ == ASR) || (src.shift_op_ == LSL)); int sh = 0; if (src.shift_op_ == ASR) { sh = 1; } emit(cond | 0x6 * B24 | 0xE * B20 | satpos * B16 | dst.code() * B12 | src.shift_imm_ * B7 | sh * B6 | 0x1 * B4 | src.rm_.code()); } // Bitfield manipulation instructions. // Unsigned bit field extract. // Extracts #width adjacent bits from position #lsb in a register, and // writes them to the low bits of a destination register. // ubfx dst, src, #lsb, #width void Assembler::ubfx(Register dst, Register src, int lsb, int width, Condition cond) { DCHECK(IsEnabled(ARMv7)); DCHECK(dst != pc && src != pc); DCHECK((lsb >= 0) && (lsb <= 31)); DCHECK((width >= 1) && (width <= (32 - lsb))); emit(cond | 0xF * B23 | B22 | B21 | (width - 1) * B16 | dst.code() * B12 | lsb * B7 | B6 | B4 | src.code()); } // Signed bit field extract. // Extracts #width adjacent bits from position #lsb in a register, and // writes them to the low bits of a destination register. The extracted // value is sign extended to fill the destination register. // sbfx dst, src, #lsb, #width void Assembler::sbfx(Register dst, Register src, int lsb, int width, Condition cond) { DCHECK(IsEnabled(ARMv7)); DCHECK(dst != pc && src != pc); DCHECK((lsb >= 0) && (lsb <= 31)); DCHECK((width >= 1) && (width <= (32 - lsb))); emit(cond | 0xF * B23 | B21 | (width - 1) * B16 | dst.code() * B12 | lsb * B7 | B6 | B4 | src.code()); } // Bit field clear. // Sets #width adjacent bits at position #lsb in the destination register // to zero, preserving the value of the other bits. // bfc dst, #lsb, #width void Assembler::bfc(Register dst, int lsb, int width, Condition cond) { DCHECK(IsEnabled(ARMv7)); DCHECK(dst != pc); DCHECK((lsb >= 0) && (lsb <= 31)); DCHECK((width >= 1) && (width <= (32 - lsb))); int msb = lsb + width - 1; emit(cond | 0x1F * B22 | msb * B16 | dst.code() * B12 | lsb * B7 | B4 | 0xF); } // Bit field insert. // Inserts #width adjacent bits from the low bits of the source register // into position #lsb of the destination register. // bfi dst, src, #lsb, #width void Assembler::bfi(Register dst, Register src, int lsb, int width, Condition cond) { DCHECK(IsEnabled(ARMv7)); DCHECK(dst != pc && src != pc); DCHECK((lsb >= 0) && (lsb <= 31)); DCHECK((width >= 1) && (width <= (32 - lsb))); int msb = lsb + width - 1; emit(cond | 0x1F * B22 | msb * B16 | dst.code() * B12 | lsb * B7 | B4 | src.code()); } void Assembler::pkhbt(Register dst, Register src1, const Operand& src2, Condition cond) { // Instruction details available in ARM DDI 0406C.b, A8.8.125. // cond(31-28) | 01101000(27-20) | Rn(19-16) | // Rd(15-12) | imm5(11-7) | 0(6) | 01(5-4) | Rm(3-0) DCHECK(dst != pc); DCHECK(src1 != pc); DCHECK(src2.IsImmediateShiftedRegister()); DCHECK(src2.rm() != pc); DCHECK((src2.shift_imm_ >= 0) && (src2.shift_imm_ <= 31)); DCHECK(src2.shift_op() == LSL); emit(cond | 0x68 * B20 | src1.code() * B16 | dst.code() * B12 | src2.shift_imm_ * B7 | B4 | src2.rm().code()); } void Assembler::pkhtb(Register dst, Register src1, const Operand& src2, Condition cond) { // Instruction details available in ARM DDI 0406C.b, A8.8.125. // cond(31-28) | 01101000(27-20) | Rn(19-16) | // Rd(15-12) | imm5(11-7) | 1(6) | 01(5-4) | Rm(3-0) DCHECK(dst != pc); DCHECK(src1 != pc); DCHECK(src2.IsImmediateShiftedRegister()); DCHECK(src2.rm() != pc); DCHECK((src2.shift_imm_ >= 1) && (src2.shift_imm_ <= 32)); DCHECK(src2.shift_op() == ASR); int asr = (src2.shift_imm_ == 32) ? 0 : src2.shift_imm_; emit(cond | 0x68 * B20 | src1.code() * B16 | dst.code() * B12 | asr * B7 | B6 | B4 | src2.rm().code()); } void Assembler::sxtb(Register dst, Register src, int rotate, Condition cond) { // Instruction details available in ARM DDI 0406C.b, A8.8.233. // cond(31-28) | 01101010(27-20) | 1111(19-16) | // Rd(15-12) | rotate(11-10) | 00(9-8)| 0111(7-4) | Rm(3-0) DCHECK(dst != pc); DCHECK(src != pc); DCHECK(rotate == 0 || rotate == 8 || rotate == 16 || rotate == 24); emit(cond | 0x6A * B20 | 0xF * B16 | dst.code() * B12 | ((rotate >> 1) & 0xC) * B8 | 7 * B4 | src.code()); } void Assembler::sxtab(Register dst, Register src1, Register src2, int rotate, Condition cond) { // Instruction details available in ARM DDI 0406C.b, A8.8.233. // cond(31-28) | 01101010(27-20) | Rn(19-16) | // Rd(15-12) | rotate(11-10) | 00(9-8)| 0111(7-4) | Rm(3-0) DCHECK(dst != pc); DCHECK(src1 != pc); DCHECK(src2 != pc); DCHECK(rotate == 0 || rotate == 8 || rotate == 16 || rotate == 24); emit(cond | 0x6A * B20 | src1.code() * B16 | dst.code() * B12 | ((rotate >> 1) & 0xC) * B8 | 7 * B4 | src2.code()); } void Assembler::sxth(Register dst, Register src, int rotate, Condition cond) { // Instruction details available in ARM DDI 0406C.b, A8.8.235. // cond(31-28) | 01101011(27-20) | 1111(19-16) | // Rd(15-12) | rotate(11-10) | 00(9-8)| 0111(7-4) | Rm(3-0) DCHECK(dst != pc); DCHECK(src != pc); DCHECK(rotate == 0 || rotate == 8 || rotate == 16 || rotate == 24); emit(cond | 0x6B * B20 | 0xF * B16 | dst.code() * B12 | ((rotate >> 1) & 0xC) * B8 | 7 * B4 | src.code()); } void Assembler::sxtah(Register dst, Register src1, Register src2, int rotate, Condition cond) { // Instruction details available in ARM DDI 0406C.b, A8.8.235. // cond(31-28) | 01101011(27-20) | Rn(19-16) | // Rd(15-12) | rotate(11-10) | 00(9-8)| 0111(7-4) | Rm(3-0) DCHECK(dst != pc); DCHECK(src1 != pc); DCHECK(src2 != pc); DCHECK(rotate == 0 || rotate == 8 || rotate == 16 || rotate == 24); emit(cond | 0x6B * B20 | src1.code() * B16 | dst.code() * B12 | ((rotate >> 1) & 0xC) * B8 | 7 * B4 | src2.code()); } void Assembler::uxtb(Register dst, Register src, int rotate, Condition cond) { // Instruction details available in ARM DDI 0406C.b, A8.8.274. // cond(31-28) | 01101110(27-20) | 1111(19-16) | // Rd(15-12) | rotate(11-10) | 00(9-8)| 0111(7-4) | Rm(3-0) DCHECK(dst != pc); DCHECK(src != pc); DCHECK(rotate == 0 || rotate == 8 || rotate == 16 || rotate == 24); emit(cond | 0x6E * B20 | 0xF * B16 | dst.code() * B12 | ((rotate >> 1) & 0xC) * B8 | 7 * B4 | src.code()); } void Assembler::uxtab(Register dst, Register src1, Register src2, int rotate, Condition cond) { // Instruction details available in ARM DDI 0406C.b, A8.8.271. // cond(31-28) | 01101110(27-20) | Rn(19-16) | // Rd(15-12) | rotate(11-10) | 00(9-8)| 0111(7-4) | Rm(3-0) DCHECK(dst != pc); DCHECK(src1 != pc); DCHECK(src2 != pc); DCHECK(rotate == 0 || rotate == 8 || rotate == 16 || rotate == 24); emit(cond | 0x6E * B20 | src1.code() * B16 | dst.code() * B12 | ((rotate >> 1) & 0xC) * B8 | 7 * B4 | src2.code()); } void Assembler::uxtb16(Register dst, Register src, int rotate, Condition cond) { // Instruction details available in ARM DDI 0406C.b, A8.8.275. // cond(31-28) | 01101100(27-20) | 1111(19-16) | // Rd(15-12) | rotate(11-10) | 00(9-8)| 0111(7-4) | Rm(3-0) DCHECK(dst != pc); DCHECK(src != pc); DCHECK(rotate == 0 || rotate == 8 || rotate == 16 || rotate == 24); emit(cond | 0x6C * B20 | 0xF * B16 | dst.code() * B12 | ((rotate >> 1) & 0xC) * B8 | 7 * B4 | src.code()); } void Assembler::uxth(Register dst, Register src, int rotate, Condition cond) { // Instruction details available in ARM DDI 0406C.b, A8.8.276. // cond(31-28) | 01101111(27-20) | 1111(19-16) | // Rd(15-12) | rotate(11-10) | 00(9-8)| 0111(7-4) | Rm(3-0) DCHECK(dst != pc); DCHECK(src != pc); DCHECK(rotate == 0 || rotate == 8 || rotate == 16 || rotate == 24); emit(cond | 0x6F * B20 | 0xF * B16 | dst.code() * B12 | ((rotate >> 1) & 0xC) * B8 | 7 * B4 | src.code()); } void Assembler::uxtah(Register dst, Register src1, Register src2, int rotate, Condition cond) { // Instruction details available in ARM DDI 0406C.b, A8.8.273. // cond(31-28) | 01101111(27-20) | Rn(19-16) | // Rd(15-12) | rotate(11-10) | 00(9-8)| 0111(7-4) | Rm(3-0) DCHECK(dst != pc); DCHECK(src1 != pc); DCHECK(src2 != pc); DCHECK(rotate == 0 || rotate == 8 || rotate == 16 || rotate == 24); emit(cond | 0x6F * B20 | src1.code() * B16 | dst.code() * B12 | ((rotate >> 1) & 0xC) * B8 | 7 * B4 | src2.code()); } void Assembler::rbit(Register dst, Register src, Condition cond) { // Instruction details available in ARM DDI 0406C.b, A8.8.144. // cond(31-28) | 011011111111(27-16) | Rd(15-12) | 11110011(11-4) | Rm(3-0) DCHECK(IsEnabled(ARMv7)); DCHECK(dst != pc); DCHECK(src != pc); emit(cond | 0x6FF * B16 | dst.code() * B12 | 0xF3 * B4 | src.code()); } void Assembler::rev(Register dst, Register src, Condition cond) { // Instruction details available in ARM DDI 0406C.b, A8.8.144. // cond(31-28) | 011010111111(27-16) | Rd(15-12) | 11110011(11-4) | Rm(3-0) DCHECK(dst != pc); DCHECK(src != pc); emit(cond | 0x6BF * B16 | dst.code() * B12 | 0xF3 * B4 | src.code()); } // Status register access instructions. void Assembler::mrs(Register dst, SRegister s, Condition cond) { DCHECK(dst != pc); emit(cond | B24 | s | 15 * B16 | dst.code() * B12); } void Assembler::msr(SRegisterFieldMask fields, const Operand& src, Condition cond) { DCHECK_NE(fields & 0x000F0000, 0); // At least one field must be set. DCHECK(((fields & 0xFFF0FFFF) == CPSR) || ((fields & 0xFFF0FFFF) == SPSR)); Instr instr; if (src.IsImmediate()) { // Immediate. uint32_t rotate_imm; uint32_t immed_8; if (src.MustOutputRelocInfo(this) || !FitsShifter(src.immediate(), &rotate_imm, &immed_8, nullptr)) { UseScratchRegisterScope temps(this); Register scratch = temps.Acquire(); // Immediate operand cannot be encoded, load it first to a scratch // register. Move32BitImmediate(scratch, src); msr(fields, Operand(scratch), cond); return; } instr = I | rotate_imm * B8 | immed_8; } else { DCHECK(src.IsRegister()); // Only rm is allowed. instr = src.rm_.code(); } emit(cond | instr | B24 | B21 | fields | 15 * B12); } // Load/Store instructions. void Assembler::ldr(Register dst, const MemOperand& src, Condition cond) { AddrMode2(cond | B26 | L, dst, src); } void Assembler::str(Register src, const MemOperand& dst, Condition cond) { AddrMode2(cond | B26, src, dst); } void Assembler::ldrb(Register dst, const MemOperand& src, Condition cond) { AddrMode2(cond | B26 | B | L, dst, src); } void Assembler::strb(Register src, const MemOperand& dst, Condition cond) { AddrMode2(cond | B26 | B, src, dst); } void Assembler::ldrh(Register dst, const MemOperand& src, Condition cond) { AddrMode3(cond | L | B7 | H | B4, dst, src); } void Assembler::strh(Register src, const MemOperand& dst, Condition cond) { AddrMode3(cond | B7 | H | B4, src, dst); } void Assembler::ldrsb(Register dst, const MemOperand& src, Condition cond) { AddrMode3(cond | L | B7 | S6 | B4, dst, src); } void Assembler::ldrsh(Register dst, const MemOperand& src, Condition cond) { AddrMode3(cond | L | B7 | S6 | H | B4, dst, src); } void Assembler::ldrd(Register dst1, Register dst2, const MemOperand& src, Condition cond) { DCHECK(src.rm() == no_reg); DCHECK(dst1 != lr); // r14. DCHECK_EQ(0, dst1.code() % 2); DCHECK_EQ(dst1.code() + 1, dst2.code()); AddrMode3(cond | B7 | B6 | B4, dst1, src); } void Assembler::strd(Register src1, Register src2, const MemOperand& dst, Condition cond) { DCHECK(dst.rm() == no_reg); DCHECK(src1 != lr); // r14. DCHECK_EQ(0, src1.code() % 2); DCHECK_EQ(src1.code() + 1, src2.code()); AddrMode3(cond | B7 | B6 | B5 | B4, src1, dst); } void Assembler::ldr_pcrel(Register dst, int imm12, Condition cond) { AddrMode am = Offset; if (imm12 < 0) { imm12 = -imm12; am = NegOffset; } DCHECK(is_uint12(imm12)); emit(cond | B26 | am | L | pc.code() * B16 | dst.code() * B12 | imm12); } // Load/Store exclusive instructions. void Assembler::ldrex(Register dst, Register src, Condition cond) { // Instruction details available in ARM DDI 0406C.b, A8.8.75. // cond(31-28) | 00011001(27-20) | Rn(19-16) | Rt(15-12) | 111110011111(11-0) DCHECK(dst != pc); DCHECK(src != pc); emit(cond | B24 | B23 | B20 | src.code() * B16 | dst.code() * B12 | 0xF9F); } void Assembler::strex(Register src1, Register src2, Register dst, Condition cond) { // Instruction details available in ARM DDI 0406C.b, A8.8.212. // cond(31-28) | 00011000(27-20) | Rn(19-16) | Rd(15-12) | 11111001(11-4) | // Rt(3-0) DCHECK(dst != pc); DCHECK(src1 != pc); DCHECK(src2 != pc); DCHECK(src1 != dst); DCHECK(src1 != src2); emit(cond | B24 | B23 | dst.code() * B16 | src1.code() * B12 | 0xF9 * B4 | src2.code()); } void Assembler::ldrexb(Register dst, Register src, Condition cond) { // Instruction details available in ARM DDI 0406C.b, A8.8.76. // cond(31-28) | 00011101(27-20) | Rn(19-16) | Rt(15-12) | 111110011111(11-0) DCHECK(dst != pc); DCHECK(src != pc); emit(cond | B24 | B23 | B22 | B20 | src.code() * B16 | dst.code() * B12 | 0xF9F); } void Assembler::strexb(Register src1, Register src2, Register dst, Condition cond) { // Instruction details available in ARM DDI 0406C.b, A8.8.213. // cond(31-28) | 00011100(27-20) | Rn(19-16) | Rd(15-12) | 11111001(11-4) | // Rt(3-0) DCHECK(dst != pc); DCHECK(src1 != pc); DCHECK(src2 != pc); DCHECK(src1 != dst); DCHECK(src1 != src2); emit(cond | B24 | B23 | B22 | dst.code() * B16 | src1.code() * B12 | 0xF9 * B4 | src2.code()); } void Assembler::ldrexh(Register dst, Register src, Condition cond) { // Instruction details available in ARM DDI 0406C.b, A8.8.78. // cond(31-28) | 00011111(27-20) | Rn(19-16) | Rt(15-12) | 111110011111(11-0) DCHECK(dst != pc); DCHECK(src != pc); emit(cond | B24 | B23 | B22 | B21 | B20 | src.code() * B16 | dst.code() * B12 | 0xF9F); } void Assembler::strexh(Register src1, Register src2, Register dst, Condition cond) { // Instruction details available in ARM DDI 0406C.b, A8.8.215. // cond(31-28) | 00011110(27-20) | Rn(19-16) | Rd(15-12) | 11111001(11-4) | // Rt(3-0) DCHECK(dst != pc); DCHECK(src1 != pc); DCHECK(src2 != pc); DCHECK(src1 != dst); DCHECK(src1 != src2); emit(cond | B24 | B23 | B22 | B21 | dst.code() * B16 | src1.code() * B12 | 0xF9 * B4 | src2.code()); } void Assembler::ldrexd(Register dst1, Register dst2, Register src, Condition cond) { // cond(31-28) | 00011011(27-20) | Rn(19-16) | Rt(15-12) | 111110011111(11-0) DCHECK(dst1 != lr); // r14. // The pair of destination registers is restricted to being an even-numbered // register and the odd-numbered register that immediately follows it. DCHECK_EQ(0, dst1.code() % 2); DCHECK_EQ(dst1.code() + 1, dst2.code()); emit(cond | B24 | B23 | B21 | B20 | src.code() * B16 | dst1.code() * B12 | 0xF9F); } void Assembler::strexd(Register res, Register src1, Register src2, Register dst, Condition cond) { // cond(31-28) | 00011010(27-20) | Rn(19-16) | Rt(15-12) | 111110011111(11-0) DCHECK(src1 != lr); // r14. // The pair of source registers is restricted to being an even-numbered // register and the odd-numbered register that immediately follows it. DCHECK_EQ(0, src1.code() % 2); DCHECK_EQ(src1.code() + 1, src2.code()); emit(cond | B24 | B23 | B21 | dst.code() * B16 | res.code() * B12 | 0xF9 * B4 | src1.code()); } // Preload instructions. void Assembler::pld(const MemOperand& address) { // Instruction details available in ARM DDI 0406C.b, A8.8.128. // 1111(31-28) | 0111(27-24) | U(23) | R(22) | 01(21-20) | Rn(19-16) | // 1111(15-12) | imm5(11-07) | type(6-5) | 0(4)| Rm(3-0) | DCHECK(address.rm() == no_reg); DCHECK(address.am() == Offset); int U = B23; int offset = address.offset(); if (offset < 0) { offset = -offset; U = 0; } DCHECK_LT(offset, 4096); emit(kSpecialCondition | B26 | B24 | U | B22 | B20 | address.rn().code() * B16 | 0xF * B12 | offset); } // Load/Store multiple instructions. void Assembler::ldm(BlockAddrMode am, Register base, RegList dst, Condition cond) { // ABI stack constraint: ldmxx base, {..sp..} base != sp is not restartable. DCHECK(base == sp || !dst.has(sp)); AddrMode4(cond | B27 | am | L, base, dst); // Emit the constant pool after a function return implemented by ldm ..{..pc}. if (cond == al && dst.has(pc)) { // There is a slight chance that the ldm instruction was actually a call, // in which case it would be wrong to return into the constant pool; we // recognize this case by checking if the emission of the pool was blocked // at the pc of the ldm instruction by a mov lr, pc instruction; if this is // the case, we emit a jump over the pool. CheckConstPool(true, no_const_pool_before_ == pc_offset() - kInstrSize); } } void Assembler::stm(BlockAddrMode am, Register base, RegList src, Condition cond) { AddrMode4(cond | B27 | am, base, src); } // Exception-generating instructions and debugging support. // Stops with a non-negative code less than kNumOfWatchedStops support // enabling/disabling and a counter feature. See simulator-arm.h . void Assembler::stop(Condition cond, int32_t code) { #ifndef __arm__ DCHECK_GE(code, kDefaultStopCode); { BlockConstPoolScope block_const_pool(this); if (code >= 0) { svc(kStopCode + code, cond); } else { svc(kStopCode + kMaxStopCode, cond); } } #else // def __arm__ if (cond != al) { Label skip; b(&skip, NegateCondition(cond)); bkpt(0); bind(&skip); } else { bkpt(0); } #endif // def __arm__ } void Assembler::bkpt(uint32_t imm16) { DCHECK(is_uint16(imm16)); emit(al | B24 | B21 | (imm16 >> 4) * B8 | BKPT | (imm16 & 0xF)); } void Assembler::svc(uint32_t imm24, Condition cond) { CHECK(is_uint24(imm24)); emit(cond | 15 * B24 | imm24); } void Assembler::dmb(BarrierOption option) { if (CpuFeatures::IsSupported(ARMv7)) { // Details available in ARM DDI 0406C.b, A8-378. emit(kSpecialCondition | 0x57FF * B12 | 5 * B4 | option); } else { // Details available in ARM DDI 0406C.b, B3-1750. // CP15DMB: CRn=c7, opc1=0, CRm=c10, opc2=5, Rt is ignored. mcr(p15, 0, r0, cr7, cr10, 5); } } void Assembler::dsb(BarrierOption option) { if (CpuFeatures::IsSupported(ARMv7)) { // Details available in ARM DDI 0406C.b, A8-380. emit(kSpecialCondition | 0x57FF * B12 | 4 * B4 | option); } else { // Details available in ARM DDI 0406C.b, B3-1750. // CP15DSB: CRn=c7, opc1=0, CRm=c10, opc2=4, Rt is ignored. mcr(p15, 0, r0, cr7, cr10, 4); } } void Assembler::isb(BarrierOption option) { if (CpuFeatures::IsSupported(ARMv7)) { // Details available in ARM DDI 0406C.b, A8-389. emit(kSpecialCondition | 0x57FF * B12 | 6 * B4 | option); } else { // Details available in ARM DDI 0406C.b, B3-1750. // CP15ISB: CRn=c7, opc1=0, CRm=c5, opc2=4, Rt is ignored. mcr(p15, 0, r0, cr7, cr5, 4); } } void Assembler::csdb() { // Details available in Arm Cache Speculation Side-channels white paper, // version 1.1, page 4. emit(0xE320F014); } // Coprocessor instructions. void Assembler::cdp(Coprocessor coproc, int opcode_1, CRegister crd, CRegister crn, CRegister crm, int opcode_2, Condition cond) { DCHECK(is_uint4(opcode_1) && is_uint3(opcode_2)); emit(cond | B27 | B26 | B25 | (opcode_1 & 15) * B20 | crn.code() * B16 | crd.code() * B12 | coproc * B8 | (opcode_2 & 7) * B5 | crm.code()); } void Assembler::cdp2(Coprocessor coproc, int opcode_1, CRegister crd, CRegister crn, CRegister crm, int opcode_2) { cdp(coproc, opcode_1, crd, crn, crm, opcode_2, kSpecialCondition); } void Assembler::mcr(Coprocessor coproc, int opcode_1, Register rd, CRegister crn, CRegister crm, int opcode_2, Condition cond) { DCHECK(is_uint3(opcode_1) && is_uint3(opcode_2)); emit(cond | B27 | B26 | B25 | (opcode_1 & 7) * B21 | crn.code() * B16 | rd.code() * B12 | coproc * B8 | (opcode_2 & 7) * B5 | B4 | crm.code()); } void Assembler::mcr2(Coprocessor coproc, int opcode_1, Register rd, CRegister crn, CRegister crm, int opcode_2) { mcr(coproc, opcode_1, rd, crn, crm, opcode_2, kSpecialCondition); } void Assembler::mrc(Coprocessor coproc, int opcode_1, Register rd, CRegister crn, CRegister crm, int opcode_2, Condition cond) { DCHECK(is_uint3(opcode_1) && is_uint3(opcode_2)); emit(cond | B27 | B26 | B25 | (opcode_1 & 7) * B21 | L | crn.code() * B16 | rd.code() * B12 | coproc * B8 | (opcode_2 & 7) * B5 | B4 | crm.code()); } void Assembler::mrc2(Coprocessor coproc, int opcode_1, Register rd, CRegister crn, CRegister crm, int opcode_2) { mrc(coproc, opcode_1, rd, crn, crm, opcode_2, kSpecialCondition); } void Assembler::ldc(Coprocessor coproc, CRegister crd, const MemOperand& src, LFlag l, Condition cond) { AddrMode5(cond | B27 | B26 | l | L | coproc * B8, crd, src); } void Assembler::ldc(Coprocessor coproc, CRegister crd, Register rn, int option, LFlag l, Condition cond) { // Unindexed addressing. DCHECK(is_uint8(option)); emit(cond | B27 | B26 | U | l | L | rn.code() * B16 | crd.code() * B12 | coproc * B8 | (option & 255)); } void Assembler::ldc2(Coprocessor coproc, CRegister crd, const MemOperand& src, LFlag l) { ldc(coproc, crd, src, l, kSpecialCondition); } void Assembler::ldc2(Coprocessor coproc, CRegister crd, Register rn, int option, LFlag l) { ldc(coproc, crd, rn, option, l, kSpecialCondition); } // Support for VFP. void Assembler::vldr(const DwVfpRegister dst, const Register base, int offset, const Condition cond) { // Ddst = MEM(Rbase + offset). // Instruction details available in ARM DDI 0406C.b, A8-924. // cond(31-28) | 1101(27-24)| U(23) | D(22) | 01(21-20) | Rbase(19-16) | // Vd(15-12) | 1011(11-8) | offset DCHECK(VfpRegisterIsAvailable(dst)); int u = 1; if (offset < 0) { CHECK_NE(offset, kMinInt); offset = -offset; u = 0; } int vd, d; dst.split_code(&vd, &d); DCHECK_GE(offset, 0); if ((offset % 4) == 0 && (offset / 4) < 256) { emit(cond | 0xD * B24 | u * B23 | d * B22 | B20 | base.code() * B16 | vd * B12 | 0xB * B8 | ((offset / 4) & 255)); } else { UseScratchRegisterScope temps(this); Register scratch = temps.Acquire(); // Larger offsets must be handled by computing the correct address in a // scratch register. DCHECK(base != scratch); if (u == 1) { add(scratch, base, Operand(offset)); } else { sub(scratch, base, Operand(offset)); } emit(cond | 0xD * B24 | d * B22 | B20 | scratch.code() * B16 | vd * B12 | 0xB * B8); } } void Assembler::vldr(const DwVfpRegister dst, const MemOperand& operand, const Condition cond) { DCHECK(VfpRegisterIsAvailable(dst)); DCHECK(operand.am_ == Offset); if (operand.rm().is_valid()) { UseScratchRegisterScope temps(this); Register scratch = temps.Acquire(); add(scratch, operand.rn(), Operand(operand.rm(), operand.shift_op_, operand.shift_imm_)); vldr(dst, scratch, 0, cond); } else { vldr(dst, operand.rn(), operand.offset(), cond); } } void Assembler::vldr(const SwVfpRegister dst, const Register base, int offset, const Condition cond) { // Sdst = MEM(Rbase + offset). // Instruction details available in ARM DDI 0406A, A8-628. // cond(31-28) | 1101(27-24)| U001(23-20) | Rbase(19-16) | // Vdst(15-12) | 1010(11-8) | offset int u = 1; if (offset < 0) { offset = -offset; u = 0; } int sd, d; dst.split_code(&sd, &d); DCHECK_GE(offset, 0); if ((offset % 4) == 0 && (offset / 4) < 256) { emit(cond | u * B23 | d * B22 | 0xD1 * B20 | base.code() * B16 | sd * B12 | 0xA * B8 | ((offset / 4) & 255)); } else { // Larger offsets must be handled by computing the correct address in a // scratch register. UseScratchRegisterScope temps(this); Register scratch = temps.Acquire(); DCHECK(base != scratch); if (u == 1) { add(scratch, base, Operand(offset)); } else { sub(scratch, base, Operand(offset)); } emit(cond | d * B22 | 0xD1 * B20 | scratch.code() * B16 | sd * B12 | 0xA * B8); } } void Assembler::vldr(const SwVfpRegister dst, const MemOperand& operand, const Condition cond) { DCHECK(operand.am_ == Offset); if (operand.rm().is_valid()) { UseScratchRegisterScope temps(this); Register scratch = temps.Acquire(); add(scratch, operand.rn(), Operand(operand.rm(), operand.shift_op_, operand.shift_imm_)); vldr(dst, scratch, 0, cond); } else { vldr(dst, operand.rn(), operand.offset(), cond); } } void Assembler::vstr(const DwVfpRegister src, const Register base, int offset, const Condition cond) { // MEM(Rbase + offset) = Dsrc. // Instruction details available in ARM DDI 0406C.b, A8-1082. // cond(31-28) | 1101(27-24)| U(23) | D(22) | 00(21-20) | Rbase(19-16) | // Vd(15-12) | 1011(11-8) | (offset/4) DCHECK(VfpRegisterIsAvailable(src)); int u = 1; if (offset < 0) { CHECK_NE(offset, kMinInt); offset = -offset; u = 0; } DCHECK_GE(offset, 0); int vd, d; src.split_code(&vd, &d); if ((offset % 4) == 0 && (offset / 4) < 256) { emit(cond | 0xD * B24 | u * B23 | d * B22 | base.code() * B16 | vd * B12 | 0xB * B8 | ((offset / 4) & 255)); } else { // Larger offsets must be handled by computing the correct address in the a // scratch register. UseScratchRegisterScope temps(this); Register scratch = temps.Acquire(); DCHECK(base != scratch); if (u == 1) { add(scratch, base, Operand(offset)); } else { sub(scratch, base, Operand(offset)); } emit(cond | 0xD * B24 | d * B22 | scratch.code() * B16 | vd * B12 | 0xB * B8); } } void Assembler::vstr(const DwVfpRegister src, const MemOperand& operand, const Condition cond) { DCHECK(VfpRegisterIsAvailable(src)); DCHECK(operand.am_ == Offset); if (operand.rm().is_valid()) { UseScratchRegisterScope temps(this); Register scratch = temps.Acquire(); add(scratch, operand.rn(), Operand(operand.rm(), operand.shift_op_, operand.shift_imm_)); vstr(src, scratch, 0, cond); } else { vstr(src, operand.rn(), operand.offset(), cond); } } void Assembler::vstr(const SwVfpRegister src, const Register base, int offset, const Condition cond) { // MEM(Rbase + offset) = SSrc. // Instruction details available in ARM DDI 0406A, A8-786. // cond(31-28) | 1101(27-24)| U000(23-20) | Rbase(19-16) | // Vdst(15-12) | 1010(11-8) | (offset/4) int u = 1; if (offset < 0) { CHECK_NE(offset, kMinInt); offset = -offset; u = 0; } int sd, d; src.split_code(&sd, &d); DCHECK_GE(offset, 0); if ((offset % 4) == 0 && (offset / 4) < 256) { emit(cond | u * B23 | d * B22 | 0xD0 * B20 | base.code() * B16 | sd * B12 | 0xA * B8 | ((offset / 4) & 255)); } else { // Larger offsets must be handled by computing the correct address in a // scratch register. UseScratchRegisterScope temps(this); Register scratch = temps.Acquire(); DCHECK(base != scratch); if (u == 1) { add(scratch, base, Operand(offset)); } else { sub(scratch, base, Operand(offset)); } emit(cond | d * B22 | 0xD0 * B20 | scratch.code() * B16 | sd * B12 | 0xA * B8); } } void Assembler::vstr(const SwVfpRegister src, const MemOperand& operand, const Condition cond) { DCHECK(operand.am_ == Offset); if (operand.rm().is_valid()) { UseScratchRegisterScope temps(this); Register scratch = temps.Acquire(); add(scratch, operand.rn(), Operand(operand.rm(), operand.shift_op_, operand.shift_imm_)); vstr(src, scratch, 0, cond); } else { vstr(src, operand.rn(), operand.offset(), cond); } } void Assembler::vldm(BlockAddrMode am, Register base, DwVfpRegister first, DwVfpRegister last, Condition cond) { // Instruction details available in ARM DDI 0406C.b, A8-922. // cond(31-28) | 110(27-25)| PUDW1(24-20) | Rbase(19-16) | // first(15-12) | 1011(11-8) | (count * 2) DCHECK_LE(first.code(), last.code()); DCHECK(VfpRegisterIsAvailable(last)); DCHECK(am == ia || am == ia_w || am == db_w); DCHECK(base != pc); int sd, d; first.split_code(&sd, &d); int count = last.code() - first.code() + 1; DCHECK_LE(count, 16); emit(cond | B27 | B26 | am | d * B22 | B20 | base.code() * B16 | sd * B12 | 0xB * B8 | count * 2); } void Assembler::vstm(BlockAddrMode am, Register base, DwVfpRegister first, DwVfpRegister last, Condition cond) { // Instruction details available in ARM DDI 0406C.b, A8-1080. // cond(31-28) | 110(27-25)| PUDW0(24-20) | Rbase(19-16) | // first(15-12) | 1011(11-8) | (count * 2) DCHECK_LE(first.code(), last.code()); DCHECK(VfpRegisterIsAvailable(last)); DCHECK(am == ia || am == ia_w || am == db_w); DCHECK(base != pc); int sd, d; first.split_code(&sd, &d); int count = last.code() - first.code() + 1; DCHECK_LE(count, 16); emit(cond | B27 | B26 | am | d * B22 | base.code() * B16 | sd * B12 | 0xB * B8 | count * 2); } void Assembler::vldm(BlockAddrMode am, Register base, SwVfpRegister first, SwVfpRegister last, Condition cond) { // Instruction details available in ARM DDI 0406A, A8-626. // cond(31-28) | 110(27-25)| PUDW1(24-20) | Rbase(19-16) | // first(15-12) | 1010(11-8) | (count/2) DCHECK_LE(first.code(), last.code()); DCHECK(am == ia || am == ia_w || am == db_w); DCHECK(base != pc); int sd, d; first.split_code(&sd, &d); int count = last.code() - first.code() + 1; emit(cond | B27 | B26 | am | d * B22 | B20 | base.code() * B16 | sd * B12 | 0xA * B8 | count); } void Assembler::vstm(BlockAddrMode am, Register base, SwVfpRegister first, SwVfpRegister last, Condition cond) { // Instruction details available in ARM DDI 0406A, A8-784. // cond(31-28) | 110(27-25)| PUDW0(24-20) | Rbase(19-16) | // first(15-12) | 1011(11-8) | (count/2) DCHECK_LE(first.code(), last.code()); DCHECK(am == ia || am == ia_w || am == db_w); DCHECK(base != pc); int sd, d; first.split_code(&sd, &d); int count = last.code() - first.code() + 1; emit(cond | B27 | B26 | am | d * B22 | base.code() * B16 | sd * B12 | 0xA * B8 | count); } static void DoubleAsTwoUInt32(base::Double d, uint32_t* lo, uint32_t* hi) { uint64_t i = d.AsUint64(); *lo = i & 0xFFFFFFFF; *hi = i >> 32; } static void WriteVmovIntImmEncoding(uint8_t imm, uint32_t* encoding) { // Integer promotion from uint8_t to int makes these all okay. *encoding = ((imm & 0x80) << (24 - 7)); // a *encoding |= ((imm & 0x70) << (16 - 4)); // bcd *encoding |= (imm & 0x0f); // efgh } // This checks if imm can be encoded into an immediate for vmov. // See Table A7-15 in ARM DDI 0406C.d. // Currently only supports the first row and op=0 && cmode=1110. static bool FitsVmovIntImm(uint64_t imm, uint32_t* encoding, uint8_t* cmode) { uint32_t lo = imm & 0xFFFFFFFF; uint32_t hi = imm >> 32; if ((lo == hi && ((lo & 0xffffff00) == 0))) { WriteVmovIntImmEncoding(imm & 0xff, encoding); *cmode = 0; return true; } else if ((lo == hi) && ((lo & 0xffff) == (lo >> 16)) && ((lo & 0xff) == (lo >> 24))) { // Check that all bytes in imm are the same. WriteVmovIntImmEncoding(imm & 0xff, encoding); *cmode = 0xe; return true; } return false; } void Assembler::vmov(const DwVfpRegister dst, uint64_t imm) { uint32_t enc; uint8_t cmode; uint8_t op = 0; if (CpuFeatures::IsSupported(NEON) && FitsVmovIntImm(imm, &enc, &cmode)) { CpuFeatureScope scope(this, NEON); // Instruction details available in ARM DDI 0406C.b, A8-937. // 001i1(27-23) | D(22) | 000(21-19) | imm3(18-16) | Vd(15-12) | cmode(11-8) // | 0(7) | 0(6) | op(5) | 4(1) | imm4(3-0) int vd, d; dst.split_code(&vd, &d); emit(kSpecialCondition | 0x05 * B23 | d * B22 | vd * B12 | cmode * B8 | op * B5 | 0x1 * B4 | enc); } else { UNIMPLEMENTED(); } } void Assembler::vmov(const QwNeonRegister dst, uint64_t imm) { uint32_t enc; uint8_t cmode; uint8_t op = 0; if (CpuFeatures::IsSupported(NEON) && FitsVmovIntImm(imm, &enc, &cmode)) { CpuFeatureScope scope(this, NEON); // Instruction details available in ARM DDI 0406C.b, A8-937. // 001i1(27-23) | D(22) | 000(21-19) | imm3(18-16) | Vd(15-12) | cmode(11-8) // | 0(7) | Q(6) | op(5) | 4(1) | imm4(3-0) int vd, d; dst.split_code(&vd, &d); emit(kSpecialCondition | 0x05 * B23 | d * B22 | vd * B12 | cmode * B8 | 0x1 * B6 | op * B5 | 0x1 * B4 | enc); } else { UNIMPLEMENTED(); } } // Only works for little endian floating point formats. // We don't support VFP on the mixed endian floating point platform. static bool FitsVmovFPImmediate(base::Double d, uint32_t* encoding) { // VMOV can accept an immediate of the form: // // +/- m * 2^(-n) where 16 <= m <= 31 and 0 <= n <= 7 // // The immediate is encoded using an 8-bit quantity, comprised of two // 4-bit fields. For an 8-bit immediate of the form: // // [abcdefgh] // // where a is the MSB and h is the LSB, an immediate 64-bit double can be // created of the form: // // [aBbbbbbb,bbcdefgh,00000000,00000000, // 00000000,00000000,00000000,00000000] // // where B = ~b. // uint32_t lo, hi; DoubleAsTwoUInt32(d, &lo, &hi); // The most obvious constraint is the long block of zeroes. if ((lo != 0) || ((hi & 0xFFFF) != 0)) { return false; } // Bits 61:54 must be all clear or all set. if (((hi & 0x3FC00000) != 0) && ((hi & 0x3FC00000) != 0x3FC00000)) { return false; } // Bit 62 must be NOT bit 61. if (((hi ^ (hi << 1)) & (0x40000000)) == 0) { return false; } // Create the encoded immediate in the form: // [00000000,0000abcd,00000000,0000efgh] *encoding = (hi >> 16) & 0xF; // Low nybble. *encoding |= (hi >> 4) & 0x70000; // Low three bits of the high nybble. *encoding |= (hi >> 12) & 0x80000; // Top bit of the high nybble. return true; } void Assembler::vmov(const SwVfpRegister dst, Float32 imm) { uint32_t enc; if (CpuFeatures::IsSupported(VFPv3) && FitsVmovFPImmediate(base::Double(imm.get_scalar()), &enc)) { CpuFeatureScope scope(this, VFPv3); // The float can be encoded in the instruction. // // Sd = immediate // Instruction details available in ARM DDI 0406C.b, A8-936. // cond(31-28) | 11101(27-23) | D(22) | 11(21-20) | imm4H(19-16) | // Vd(15-12) | 101(11-9) | sz=0(8) | imm4L(3-0) int vd, d; dst.split_code(&vd, &d); emit(al | 0x1D * B23 | d * B22 | 0x3 * B20 | vd * B12 | 0x5 * B9 | enc); } else { UseScratchRegisterScope temps(this); Register scratch = temps.Acquire(); mov(scratch, Operand(imm.get_bits())); vmov(dst, scratch); } } void Assembler::vmov(const DwVfpRegister dst, base::Double imm, const Register extra_scratch) { DCHECK(VfpRegisterIsAvailable(dst)); uint32_t enc; if (CpuFeatures::IsSupported(VFPv3) && FitsVmovFPImmediate(imm, &enc)) { CpuFeatureScope scope(this, VFPv3); // The double can be encoded in the instruction. // // Dd = immediate // Instruction details available in ARM DDI 0406C.b, A8-936. // cond(31-28) | 11101(27-23) | D(22) | 11(21-20) | imm4H(19-16) | // Vd(15-12) | 101(11-9) | sz=1(8) | imm4L(3-0) int vd, d; dst.split_code(&vd, &d); emit(al | 0x1D * B23 | d * B22 | 0x3 * B20 | vd * B12 | 0x5 * B9 | B8 | enc); } else { // Synthesise the double from ARM immediates. uint32_t lo, hi; DoubleAsTwoUInt32(imm, &lo, &hi); UseScratchRegisterScope temps(this); Register scratch = temps.Acquire(); if (lo == hi) { // Move the low and high parts of the double to a D register in one // instruction. mov(scratch, Operand(lo)); vmov(dst, scratch, scratch); } else if (extra_scratch == no_reg) { // We only have one spare scratch register. mov(scratch, Operand(lo)); vmov(NeonS32, dst, 0, scratch); if (((lo & 0xFFFF) == (hi & 0xFFFF)) && CpuFeatures::IsSupported(ARMv7)) { CpuFeatureScope scope(this, ARMv7); movt(scratch, hi >> 16); } else { mov(scratch, Operand(hi)); } vmov(NeonS32, dst, 1, scratch); } else { // Move the low and high parts of the double to a D register in one // instruction. mov(scratch, Operand(lo)); mov(extra_scratch, Operand(hi)); vmov(dst, scratch, extra_scratch); } } } void Assembler::vmov(const SwVfpRegister dst, const SwVfpRegister src, const Condition cond) { // Sd = Sm // Instruction details available in ARM DDI 0406B, A8-642. int sd, d, sm, m; dst.split_code(&sd, &d); src.split_code(&sm, &m); emit(cond | 0xE * B24 | d * B22 | 0xB * B20 | sd * B12 | 0xA * B8 | B6 | m * B5 | sm); } void Assembler::vmov(const DwVfpRegister dst, const DwVfpRegister src, const Condition cond) { // Dd = Dm // Instruction details available in ARM DDI 0406C.b, A8-938. // cond(31-28) | 11101(27-23) | D(22) | 11(21-20) | 0000(19-16) | Vd(15-12) | // 101(11-9) | sz=1(8) | 0(7) | 1(6) | M(5) | 0(4) | Vm(3-0) DCHECK(VfpRegisterIsAvailable(dst)); DCHECK(VfpRegisterIsAvailable(src)); int vd, d; dst.split_code(&vd, &d); int vm, m; src.split_code(&vm, &m); emit(cond | 0x1D * B23 | d * B22 | 0x3 * B20 | vd * B12 | 0x5 * B9 | B8 | B6 | m * B5 | vm); } void Assembler::vmov(const DwVfpRegister dst, const Register src1, const Register src2, const Condition cond) { // Dm = <Rt,Rt2>. // Instruction details available in ARM DDI 0406C.b, A8-948. // cond(31-28) | 1100(27-24)| 010(23-21) | op=0(20) | Rt2(19-16) | // Rt(15-12) | 1011(11-8) | 00(7-6) | M(5) | 1(4) | Vm DCHECK(VfpRegisterIsAvailable(dst)); DCHECK(src1 != pc && src2 != pc); int vm, m; dst.split_code(&vm, &m); emit(cond | 0xC * B24 | B22 | src2.code() * B16 | src1.code() * B12 | 0xB * B8 | m * B5 | B4 | vm); } void Assembler::vmov(const Register dst1, const Register dst2, const DwVfpRegister src, const Condition cond) { // <Rt,Rt2> = Dm. // Instruction details available in ARM DDI 0406C.b, A8-948. // cond(31-28) | 1100(27-24)| 010(23-21) | op=1(20) | Rt2(19-16) | // Rt(15-12) | 1011(11-8) | 00(7-6) | M(5) | 1(4) | Vm DCHECK(VfpRegisterIsAvailable(src)); DCHECK(dst1 != pc && dst2 != pc); int vm, m; src.split_code(&vm, &m); emit(cond | 0xC * B24 | B22 | B20 | dst2.code() * B16 | dst1.code() * B12 | 0xB * B8 | m * B5 | B4 | vm); } void Assembler::vmov(const SwVfpRegister dst, const Register src, const Condition cond) { // Sn = Rt. // Instruction details available in ARM DDI 0406A, A8-642. // cond(31-28) | 1110(27-24)| 000(23-21) | op=0(20) | Vn(19-16) | // Rt(15-12) | 1010(11-8) | N(7)=0 | 00(6-5) | 1(4) | 0000(3-0) DCHECK(src != pc); int sn, n; dst.split_code(&sn, &n); emit(cond | 0xE * B24 | sn * B16 | src.code() * B12 | 0xA * B8 | n * B7 | B4); } void Assembler::vmov(const Register dst, const SwVfpRegister src, const Condition cond) { // Rt = Sn. // Instruction details available in ARM DDI 0406A, A8-642. // cond(31-28) | 1110(27-24)| 000(23-21) | op=1(20) | Vn(19-16) | // Rt(15-12) | 1010(11-8) | N(7)=0 | 00(6-5) | 1(4) | 0000(3-0) DCHECK(dst != pc); int sn, n; src.split_code(&sn, &n); emit(cond | 0xE * B24 | B20 | sn * B16 | dst.code() * B12 | 0xA * B8 | n * B7 | B4); } // Type of data to read from or write to VFP register. // Used as specifier in generic vcvt instruction. enum VFPType { S32, U32, F32, F64 }; static bool IsSignedVFPType(VFPType type) { switch (type) { case S32: return true; case U32: return false; default: UNREACHABLE(); } } static bool IsIntegerVFPType(VFPType type) { switch (type) { case S32: case U32: return true; case F32: case F64: return false; default: UNREACHABLE(); } } static bool IsDoubleVFPType(VFPType type) { switch (type) { case F32: return false; case F64: return true; default: UNREACHABLE(); } } // Split five bit reg_code based on size of reg_type. // 32-bit register codes are Vm:M // 64-bit register codes are M:Vm // where Vm is four bits, and M is a single bit. static void SplitRegCode(VFPType reg_type, int reg_code, int* vm, int* m) { DCHECK((reg_code >= 0) && (reg_code <= 31)); if (IsIntegerVFPType(reg_type) || !IsDoubleVFPType(reg_type)) { SwVfpRegister::split_code(reg_code, vm, m); } else { DwVfpRegister::split_code(reg_code, vm, m); } } // Encode vcvt.src_type.dst_type instruction. static Instr EncodeVCVT(const VFPType dst_type, const int dst_code, const VFPType src_type, const int src_code, VFPConversionMode mode, const Condition cond) { DCHECK(src_type != dst_type); int D, Vd, M, Vm; SplitRegCode(src_type, src_code, &Vm, &M); SplitRegCode(dst_type, dst_code, &Vd, &D); if (IsIntegerVFPType(dst_type) || IsIntegerVFPType(src_type)) { // Conversion between IEEE floating point and 32-bit integer. // Instruction details available in ARM DDI 0406B, A8.6.295. // cond(31-28) | 11101(27-23)| D(22) | 11(21-20) | 1(19) | opc2(18-16) | // Vd(15-12) | 101(11-9) | sz(8) | op(7) | 1(6) | M(5) | 0(4) | Vm(3-0) DCHECK(!IsIntegerVFPType(dst_type) || !IsIntegerVFPType(src_type)); int sz, opc2, op; if (IsIntegerVFPType(dst_type)) { opc2 = IsSignedVFPType(dst_type) ? 0x5 : 0x4; sz = IsDoubleVFPType(src_type) ? 0x1 : 0x0; op = mode; } else { DCHECK(IsIntegerVFPType(src_type)); opc2 = 0x0; sz = IsDoubleVFPType(dst_type) ? 0x1 : 0x0; op = IsSignedVFPType(src_type) ? 0x1 : 0x0; } return (cond | 0xE * B24 | B23 | D * B22 | 0x3 * B20 | B19 | opc2 * B16 | Vd * B12 | 0x5 * B9 | sz * B8 | op * B7 | B6 | M * B5 | Vm); } else { // Conversion between IEEE double and single precision. // Instruction details available in ARM DDI 0406B, A8.6.298. // cond(31-28) | 11101(27-23)| D(22) | 11(21-20) | 0111(19-16) | // Vd(15-12) | 101(11-9) | sz(8) | 1(7) | 1(6) | M(5) | 0(4) | Vm(3-0) int sz = IsDoubleVFPType(src_type) ? 0x1 : 0x0; return (cond | 0xE * B24 | B23 | D * B22 | 0x3 * B20 | 0x7 * B16 | Vd * B12 | 0x5 * B9 | sz * B8 | B7 | B6 | M * B5 | Vm); } } void Assembler::vcvt_f64_s32(const DwVfpRegister dst, const SwVfpRegister src, VFPConversionMode mode, const Condition cond) { DCHECK(VfpRegisterIsAvailable(dst)); emit(EncodeVCVT(F64, dst.code(), S32, src.code(), mode, cond)); } void Assembler::vcvt_f32_s32(const SwVfpRegister dst, const SwVfpRegister src, VFPConversionMode mode, const Condition cond) { emit(EncodeVCVT(F32, dst.code(), S32, src.code(), mode, cond)); } void Assembler::vcvt_f64_u32(const DwVfpRegister dst, const SwVfpRegister src, VFPConversionMode mode, const Condition cond) { DCHECK(VfpRegisterIsAvailable(dst)); emit(EncodeVCVT(F64, dst.code(), U32, src.code(), mode, cond)); } void Assembler::vcvt_f32_u32(const SwVfpRegister dst, const SwVfpRegister src, VFPConversionMode mode, const Condition cond) { emit(EncodeVCVT(F32, dst.code(), U32, src.code(), mode, cond)); } void Assembler::vcvt_s32_f32(const SwVfpRegister dst, const SwVfpRegister src, VFPConversionMode mode, const Condition cond) { emit(EncodeVCVT(S32, dst.code(), F32, src.code(), mode, cond)); } void Assembler::vcvt_u32_f32(const SwVfpRegister dst, const SwVfpRegister src, VFPConversionMode mode, const Condition cond) { emit(EncodeVCVT(U32, dst.code(), F32, src.code(), mode, cond)); } void Assembler::vcvt_s32_f64(const SwVfpRegister dst, const DwVfpRegister src, VFPConversionMode mode, const Condition cond) { DCHECK(VfpRegisterIsAvailable(src)); emit(EncodeVCVT(S32, dst.code(), F64, src.code(), mode, cond)); } void Assembler::vcvt_u32_f64(const SwVfpRegister dst, const DwVfpRegister src, VFPConversionMode mode, const Condition cond) { DCHECK(VfpRegisterIsAvailable(src)); emit(EncodeVCVT(U32, dst.code(), F64, src.code(), mode, cond)); } void Assembler::vcvt_f64_f32(const DwVfpRegister dst, const SwVfpRegister src, VFPConversionMode mode, const Condition cond) { DCHECK(VfpRegisterIsAvailable(dst)); emit(EncodeVCVT(F64, dst.code(), F32, src.code(), mode, cond)); } void Assembler::vcvt_f32_f64(const SwVfpRegister dst, const DwVfpRegister src, VFPConversionMode mode, const Condition cond) { DCHECK(VfpRegisterIsAvailable(src)); emit(EncodeVCVT(F32, dst.code(), F64, src.code(), mode, cond)); } void Assembler::vcvt_f64_s32(const DwVfpRegister dst, int fraction_bits, const Condition cond) { // Instruction details available in ARM DDI 0406C.b, A8-874. // cond(31-28) | 11101(27-23) | D(22) | 11(21-20) | 1010(19-16) | Vd(15-12) | // 101(11-9) | sf=1(8) | sx=1(7) | 1(6) | i(5) | 0(4) | imm4(3-0) DCHECK(IsEnabled(VFPv3)); DCHECK(VfpRegisterIsAvailable(dst)); DCHECK(fraction_bits > 0 && fraction_bits <= 32); int vd, d; dst.split_code(&vd, &d); int imm5 = 32 - fraction_bits; int i = imm5 & 1; int imm4 = (imm5 >> 1) & 0xF; emit(cond | 0xE * B24 | B23 | d * B22 | 0x3 * B20 | B19 | 0x2 * B16 | vd * B12 | 0x5 * B9 | B8 | B7 | B6 | i * B5 | imm4); } void Assembler::vneg(const DwVfpRegister dst, const DwVfpRegister src, const Condition cond) { // Instruction details available in ARM DDI 0406C.b, A8-968. // cond(31-28) | 11101(27-23) | D(22) | 11(21-20) | 0001(19-16) | Vd(15-12) | // 101(11-9) | sz=1(8) | 0(7) | 1(6) | M(5) | 0(4) | Vm(3-0) DCHECK(VfpRegisterIsAvailable(dst)); DCHECK(VfpRegisterIsAvailable(src)); int vd, d; dst.split_code(&vd, &d); int vm, m; src.split_code(&vm, &m); emit(cond | 0x1D * B23 | d * B22 | 0x3 * B20 | B16 | vd * B12 | 0x5 * B9 | B8 | B6 | m * B5 | vm); } void Assembler::vneg(const SwVfpRegister dst, const SwVfpRegister src, const Condition cond) { // Instruction details available in ARM DDI 0406C.b, A8-968. // cond(31-28) | 11101(27-23) | D(22) | 11(21-20) | 0001(19-16) | Vd(15-12) | // 101(11-9) | sz=0(8) | 0(7) | 1(6) | M(5) | 0(4) | Vm(3-0) int vd, d; dst.split_code(&vd, &d); int vm, m; src.split_code(&vm, &m); emit(cond | 0x1D * B23 | d * B22 | 0x3 * B20 | B16 | vd * B12 | 0x5 * B9 | B6 | m * B5 | vm); } void Assembler::vabs(const DwVfpRegister dst, const DwVfpRegister src, const Condition cond) { // Instruction details available in ARM DDI 0406C.b, A8-524. // cond(31-28) | 11101(27-23) | D(22) | 11(21-20) | 0000(19-16) | Vd(15-12) | // 101(11-9) | sz=1(8) | 1(7) | 1(6) | M(5) | 0(4) | Vm(3-0) DCHECK(VfpRegisterIsAvailable(dst)); DCHECK(VfpRegisterIsAvailable(src)); int vd, d; dst.split_code(&vd, &d); int vm, m; src.split_code(&vm, &m); emit(cond | 0x1D * B23 | d * B22 | 0x3 * B20 | vd * B12 | 0x5 * B9 | B8 | B7 | B6 | m * B5 | vm); } void Assembler::vabs(const SwVfpRegister dst, const SwVfpRegister src, const Condition cond) { // Instruction details available in ARM DDI 0406C.b, A8-524. // cond(31-28) | 11101(27-23) | D(22) | 11(21-20) | 0000(19-16) | Vd(15-12) | // 101(11-9) | sz=0(8) | 1(7) | 1(6) | M(5) | 0(4) | Vm(3-0) int vd, d; dst.split_code(&vd, &d); int vm, m; src.split_code(&vm, &m); emit(cond | 0x1D * B23 | d * B22 | 0x3 * B20 | vd * B12 | 0x5 * B9 | B7 | B6 | m * B5 | vm); } void Assembler::vadd(const DwVfpRegister dst, const DwVfpRegister src1, const DwVfpRegister src2, const Condition cond) { // Dd = vadd(Dn, Dm) double precision floating point addition. // Dd = D:Vd; Dm=M:Vm; Dn=N:Vm. // Instruction details available in ARM DDI 0406C.b, A8-830. // cond(31-28) | 11100(27-23)| D(22) | 11(21-20) | Vn(19-16) | // Vd(15-12) | 101(11-9) | sz=1(8) | N(7) | 0(6) | M(5) | 0(4) | Vm(3-0) DCHECK(VfpRegisterIsAvailable(dst)); DCHECK(VfpRegisterIsAvailable(src1)); DCHECK(VfpRegisterIsAvailable(src2)); int vd, d; dst.split_code(&vd, &d); int vn, n; src1.split_code(&vn, &n); int vm, m; src2.split_code(&vm, &m); emit(cond | 0x1C * B23 | d * B22 | 0x3 * B20 | vn * B16 | vd * B12 | 0x5 * B9 | B8 | n * B7 | m * B5 | vm); } void Assembler::vadd(const SwVfpRegister dst, const SwVfpRegister src1, const SwVfpRegister src2, const Condition cond) { // Sd = vadd(Sn, Sm) single precision floating point addition. // Sd = D:Vd; Sm=M:Vm; Sn=N:Vm. // Instruction details available in ARM DDI 0406C.b, A8-830. // cond(31-28) | 11100(27-23)| D(22) | 11(21-20) | Vn(19-16) | // Vd(15-12) | 101(11-9) | sz=0(8) | N(7) | 0(6) | M(5) | 0(4) | Vm(3-0) int vd, d; dst.split_code(&vd, &d); int vn, n; src1.split_code(&vn, &n); int vm, m; src2.split_code(&vm, &m); emit(cond | 0x1C * B23 | d * B22 | 0x3 * B20 | vn * B16 | vd * B12 | 0x5 * B9 | n * B7 | m * B5 | vm); } void Assembler::vsub(const DwVfpRegister dst, const DwVfpRegister src1, const DwVfpRegister src2, const Condition cond) { // Dd = vsub(Dn, Dm) double precision floating point subtraction. // Dd = D:Vd; Dm=M:Vm; Dn=N:Vm. // Instruction details available in ARM DDI 0406C.b, A8-1086. // cond(31-28) | 11100(27-23)| D(22) | 11(21-20) | Vn(19-16) | // Vd(15-12) | 101(11-9) | sz=1(8) | N(7) | 1(6) | M(5) | 0(4) | Vm(3-0) DCHECK(VfpRegisterIsAvailable(dst)); DCHECK(VfpRegisterIsAvailable(src1)); DCHECK(VfpRegisterIsAvailable(src2)); int vd, d; dst.split_code(&vd, &d); int vn, n; src1.split_code(&vn, &n); int vm, m; src2.split_code(&vm, &m); emit(cond | 0x1C * B23 | d * B22 | 0x3 * B20 | vn * B16 | vd * B12 | 0x5 * B9 | B8 | n * B7 | B6 | m * B5 | vm); } void Assembler::vsub(const SwVfpRegister dst, const SwVfpRegister src1, const SwVfpRegister src2, const Condition cond) { // Sd = vsub(Sn, Sm) single precision floating point subtraction. // Sd = D:Vd; Sm=M:Vm; Sn=N:Vm. // Instruction details available in ARM DDI 0406C.b, A8-1086. // cond(31-28) | 11100(27-23)| D(22) | 11(21-20) | Vn(19-16) | // Vd(15-12) | 101(11-9) | sz=0(8) | N(7) | 1(6) | M(5) | 0(4) | Vm(3-0) int vd, d; dst.split_code(&vd, &d); int vn, n; src1.split_code(&vn, &n); int vm, m; src2.split_code(&vm, &m); emit(cond | 0x1C * B23 | d * B22 | 0x3 * B20 | vn * B16 | vd * B12 | 0x5 * B9 | n * B7 | B6 | m * B5 | vm); } void Assembler::vmul(const DwVfpRegister dst, const DwVfpRegister src1, const DwVfpRegister src2, const Condition cond) { // Dd = vmul(Dn, Dm) double precision floating point multiplication. // Dd = D:Vd; Dm=M:Vm; Dn=N:Vm. // Instruction details available in ARM DDI 0406C.b, A8-960. // cond(31-28) | 11100(27-23)| D(22) | 10(21-20) | Vn(19-16) | // Vd(15-12) | 101(11-9) | sz=1(8) | N(7) | 0(6) | M(5) | 0(4) | Vm(3-0) DCHECK(VfpRegisterIsAvailable(dst)); DCHECK(VfpRegisterIsAvailable(src1)); DCHECK(VfpRegisterIsAvailable(src2)); int vd, d; dst.split_code(&vd, &d); int vn, n; src1.split_code(&vn, &n); int vm, m; src2.split_code(&vm, &m); emit(cond | 0x1C * B23 | d * B22 | 0x2 * B20 | vn * B16 | vd * B12 | 0x5 * B9 | B8 | n * B7 | m * B5 | vm); } void Assembler::vmul(const SwVfpRegister dst, const SwVfpRegister src1, const SwVfpRegister src2, const Condition cond) { // Sd = vmul(Sn, Sm) single precision floating point multiplication. // Sd = D:Vd; Sm=M:Vm; Sn=N:Vm. // Instruction details available in ARM DDI 0406C.b, A8-960. // cond(31-28) | 11100(27-23)| D(22) | 10(21-20) | Vn(19-16) | // Vd(15-12) | 101(11-9) | sz=0(8) | N(7) | 0(6) | M(5) | 0(4) | Vm(3-0) int vd, d; dst.split_code(&vd, &d); int vn, n; src1.split_code(&vn, &n); int vm, m; src2.split_code(&vm, &m); emit(cond | 0x1C * B23 | d * B22 | 0x2 * B20 | vn * B16 | vd * B12 | 0x5 * B9 | n * B7 | m * B5 | vm); } void Assembler::vmla(const DwVfpRegister dst, const DwVfpRegister src1, const DwVfpRegister src2, const Condition cond) { // Instruction details available in ARM DDI 0406C.b, A8-932. // cond(31-28) | 11100(27-23) | D(22) | 00(21-20) | Vn(19-16) | // Vd(15-12) | 101(11-9) | sz=1(8) | N(7) | op=0(6) | M(5) | 0(4) | Vm(3-0) DCHECK(VfpRegisterIsAvailable(dst)); DCHECK(VfpRegisterIsAvailable(src1)); DCHECK(VfpRegisterIsAvailable(src2)); int vd, d; dst.split_code(&vd, &d); int vn, n; src1.split_code(&vn, &n); int vm, m; src2.split_code(&vm, &m); emit(cond | 0x1C * B23 | d * B22 | vn * B16 | vd * B12 | 0x5 * B9 | B8 | n * B7 | m * B5 | vm); } void Assembler::vmla(const SwVfpRegister dst, const SwVfpRegister src1, const SwVfpRegister src2, const Condition cond) { // Instruction details available in ARM DDI 0406C.b, A8-932. // cond(31-28) | 11100(27-23) | D(22) | 00(21-20) | Vn(19-16) | // Vd(15-12) | 101(11-9) | sz=0(8) | N(7) | op=0(6) | M(5) | 0(4) | Vm(3-0) int vd, d; dst.split_code(&vd, &d); int vn, n; src1.split_code(&vn, &n); int vm, m; src2.split_code(&vm, &m); emit(cond | 0x1C * B23 | d * B22 | vn * B16 | vd * B12 | 0x5 * B9 | n * B7 | m * B5 | vm); } void Assembler::vmls(const DwVfpRegister dst, const DwVfpRegister src1, const DwVfpRegister src2, const Condition cond) { // Instruction details available in ARM DDI 0406C.b, A8-932. // cond(31-28) | 11100(27-23) | D(22) | 00(21-20) | Vn(19-16) | // Vd(15-12) | 101(11-9) | sz=1(8) | N(7) | op=1(6) | M(5) | 0(4) | Vm(3-0) DCHECK(VfpRegisterIsAvailable(dst)); DCHECK(VfpRegisterIsAvailable(src1)); DCHECK(VfpRegisterIsAvailable(src2)); int vd, d; dst.split_code(&vd, &d); int vn, n; src1.split_code(&vn, &n); int vm, m; src2.split_code(&vm, &m); emit(cond | 0x1C * B23 | d * B22 | vn * B16 | vd * B12 | 0x5 * B9 | B8 | n * B7 | B6 | m * B5 | vm); } void Assembler::vmls(const SwVfpRegister dst, const SwVfpRegister src1, const SwVfpRegister src2, const Condition cond) { // Instruction details available in ARM DDI 0406C.b, A8-932. // cond(31-28) | 11100(27-23) | D(22) | 00(21-20) | Vn(19-16) | // Vd(15-12) | 101(11-9) | sz=0(8) | N(7) | op=1(6) | M(5) | 0(4) | Vm(3-0) int vd, d; dst.split_code(&vd, &d); int vn, n; src1.split_code(&vn, &n); int vm, m; src2.split_code(&vm, &m); emit(cond | 0x1C * B23 | d * B22 | vn * B16 | vd * B12 | 0x5 * B9 | n * B7 | B6 | m * B5 | vm); } void Assembler::vdiv(const DwVfpRegister dst, const DwVfpRegister src1, const DwVfpRegister src2, const Condition cond) { // Dd = vdiv(Dn, Dm) double precision floating point division. // Dd = D:Vd; Dm=M:Vm; Dn=N:Vm. // Instruction details available in ARM DDI 0406C.b, A8-882. // cond(31-28) | 11101(27-23)| D(22) | 00(21-20) | Vn(19-16) | // Vd(15-12) | 101(11-9) | sz=1(8) | N(7) | 0(6) | M(5) | 0(4) | Vm(3-0) DCHECK(VfpRegisterIsAvailable(dst)); DCHECK(VfpRegisterIsAvailable(src1)); DCHECK(VfpRegisterIsAvailable(src2)); int vd, d; dst.split_code(&vd, &d); int vn, n; src1.split_code(&vn, &n); int vm, m; src2.split_code(&vm, &m); emit(cond | 0x1D * B23 | d * B22 | vn * B16 | vd * B12 | 0x5 * B9 | B8 | n * B7 | m * B5 | vm); } void Assembler::vdiv(const SwVfpRegister dst, const SwVfpRegister src1, const SwVfpRegister src2, const Condition cond) { // Sd = vdiv(Sn, Sm) single precision floating point division. // Sd = D:Vd; Sm=M:Vm; Sn=N:Vm. // Instruction details available in ARM DDI 0406C.b, A8-882. // cond(31-28) | 11101(27-23)| D(22) | 00(21-20) | Vn(19-16) | // Vd(15-12) | 101(11-9) | sz=0(8) | N(7) | 0(6) | M(5) | 0(4) | Vm(3-0) int vd, d; dst.split_code(&vd, &d); int vn, n; src1.split_code(&vn, &n); int vm, m; src2.split_code(&vm, &m); emit(cond | 0x1D * B23 | d * B22 | vn * B16 | vd * B12 | 0x5 * B9 | n * B7 | m * B5 | vm); } void Assembler::vcmp(const DwVfpRegister src1, const DwVfpRegister src2, const Condition cond) { // vcmp(Dd, Dm) double precision floating point comparison. // Instruction details available in ARM DDI 0406C.b, A8-864. // cond(31-28) | 11101(27-23)| D(22) | 11(21-20) | 0100(19-16) | // Vd(15-12) | 101(11-9) | sz=1(8) | E=0(7) | 1(6) | M(5) | 0(4) | Vm(3-0) DCHECK(VfpRegisterIsAvailable(src1)); DCHECK(VfpRegisterIsAvailable(src2)); int vd, d; src1.split_code(&vd, &d); int vm, m; src2.split_code(&vm, &m); emit(cond | 0x1D * B23 | d * B22 | 0x3 * B20 | 0x4 * B16 | vd * B12 | 0x5 * B9 | B8 | B6 | m * B5 | vm); } void Assembler::vcmp(const SwVfpRegister src1, const SwVfpRegister src2, const Condition cond) { // vcmp(Sd, Sm) single precision floating point comparison. // Instruction details available in ARM DDI 0406C.b, A8-864. // cond(31-28) | 11101(27-23)| D(22) | 11(21-20) | 0100(19-16) | // Vd(15-12) | 101(11-9) | sz=0(8) | E=0(7) | 1(6) | M(5) | 0(4) | Vm(3-0) int vd, d; src1.split_code(&vd, &d); int vm, m; src2.split_code(&vm, &m); emit(cond | 0x1D * B23 | d * B22 | 0x3 * B20 | 0x4 * B16 | vd * B12 | 0x5 * B9 | B6 | m * B5 | vm); } void Assembler::vcmp(const DwVfpRegister src1, const double src2, const Condition cond) { // vcmp(Dd, #0.0) double precision floating point comparison. // Instruction details available in ARM DDI 0406C.b, A8-864. // cond(31-28) | 11101(27-23)| D(22) | 11(21-20) | 0101(19-16) | // Vd(15-12) | 101(11-9) | sz=1(8) | E=0(7) | 1(6) | 0(5) | 0(4) | 0000(3-0) DCHECK(VfpRegisterIsAvailable(src1)); DCHECK_EQ(src2, 0.0); int vd, d; src1.split_code(&vd, &d); emit(cond | 0x1D * B23 | d * B22 | 0x3 * B20 | 0x5 * B16 | vd * B12 | 0x5 * B9 | B8 | B6); } void Assembler::vcmp(const SwVfpRegister src1, const float src2, const Condition cond) { // vcmp(Sd, #0.0) single precision floating point comparison. // Instruction details available in ARM DDI 0406C.b, A8-864. // cond(31-28) | 11101(27-23)| D(22) | 11(21-20) | 0101(19-16) | // Vd(15-12) | 101(11-9) | sz=0(8) | E=0(7) | 1(6) | 0(5) | 0(4) | 0000(3-0) DCHECK_EQ(src2, 0.0); int vd, d; src1.split_code(&vd, &d); emit(cond | 0x1D * B23 | d * B22 | 0x3 * B20 | 0x5 * B16 | vd * B12 | 0x5 * B9 | B6); } void Assembler::vmaxnm(const DwVfpRegister dst, const DwVfpRegister src1, const DwVfpRegister src2) { // kSpecialCondition(31-28) | 11101(27-23) | D(22) | 00(21-20) | Vn(19-16) | // Vd(15-12) | 101(11-9) | sz=1(8) | N(7) | 0(6) | M(5) | 0(4) | Vm(3-0) DCHECK(IsEnabled(ARMv8)); int vd, d; dst.split_code(&vd, &d); int vn, n; src1.split_code(&vn, &n); int vm, m; src2.split_code(&vm, &m); emit(kSpecialCondition | 0x1D * B23 | d * B22 | vn * B16 | vd * B12 | 0x5 * B9 | B8 | n * B7 | m * B5 | vm); } void Assembler::vmaxnm(const SwVfpRegister dst, const SwVfpRegister src1, const SwVfpRegister src2) { // kSpecialCondition(31-28) | 11101(27-23) | D(22) | 00(21-20) | Vn(19-16) | // Vd(15-12) | 101(11-9) | sz=0(8) | N(7) | 0(6) | M(5) | 0(4) | Vm(3-0) DCHECK(IsEnabled(ARMv8)); int vd, d; dst.split_code(&vd, &d); int vn, n; src1.split_code(&vn, &n); int vm, m; src2.split_code(&vm, &m); emit(kSpecialCondition | 0x1D * B23 | d * B22 | vn * B16 | vd * B12 | 0x5 * B9 | n * B7 | m * B5 | vm); } void Assembler::vminnm(const DwVfpRegister dst, const DwVfpRegister src1, const DwVfpRegister src2) { // kSpecialCondition(31-28) | 11101(27-23) | D(22) | 00(21-20) | Vn(19-16) | // Vd(15-12) | 101(11-9) | sz=1(8) | N(7) | 1(6) | M(5) | 0(4) | Vm(3-0) DCHECK(IsEnabled(ARMv8)); int vd, d; dst.split_code(&vd, &d); int vn, n; src1.split_code(&vn, &n); int vm, m; src2.split_code(&vm, &m); emit(kSpecialCondition | 0x1D * B23 | d * B22 | vn * B16 | vd * B12 | 0x5 * B9 | B8 | n * B7 | B6 | m * B5 | vm); } void Assembler::vminnm(const SwVfpRegister dst, const SwVfpRegister src1, const SwVfpRegister src2) { // kSpecialCondition(31-28) | 11101(27-23) | D(22) | 00(21-20) | Vn(19-16) | // Vd(15-12) | 101(11-9) | sz=0(8) | N(7) | 1(6) | M(5) | 0(4) | Vm(3-0) DCHECK(IsEnabled(ARMv8)); int vd, d; dst.split_code(&vd, &d); int vn, n; src1.split_code(&vn, &n); int vm, m; src2.split_code(&vm, &m); emit(kSpecialCondition | 0x1D * B23 | d * B22 | vn * B16 | vd * B12 | 0x5 * B9 | n * B7 | B6 | m * B5 | vm); } void Assembler::vsel(Condition cond, const DwVfpRegister dst, const DwVfpRegister src1, const DwVfpRegister src2) { // cond=kSpecialCondition(31-28) | 11100(27-23) | D(22) | // vsel_cond=XX(21-20) | Vn(19-16) | Vd(15-12) | 101(11-9) | sz=1(8) | N(7) | // 0(6) | M(5) | 0(4) | Vm(3-0) DCHECK(IsEnabled(ARMv8)); int vd, d; dst.split_code(&vd, &d); int vn, n; src1.split_code(&vn, &n); int vm, m; src2.split_code(&vm, &m); int sz = 1; // VSEL has a special (restricted) condition encoding. // eq(0b0000)... -> 0b00 // ge(0b1010)... -> 0b10 // gt(0b1100)... -> 0b11 // vs(0b0110)... -> 0b01 // No other conditions are supported. int vsel_cond = (cond >> 30) & 0x3; if ((cond != eq) && (cond != ge) && (cond != gt) && (cond != vs)) { // We can implement some other conditions by swapping the inputs. DCHECK((cond == ne) | (cond == lt) | (cond == le) | (cond == vc)); std::swap(vn, vm); std::swap(n, m); } emit(kSpecialCondition | 0x1C * B23 | d * B22 | vsel_cond * B20 | vn * B16 | vd * B12 | 0x5 * B9 | sz * B8 | n * B7 | m * B5 | vm); } void Assembler::vsel(Condition cond, const SwVfpRegister dst, const SwVfpRegister src1, const SwVfpRegister src2) { // cond=kSpecialCondition(31-28) | 11100(27-23) | D(22) | // vsel_cond=XX(21-20) | Vn(19-16) | Vd(15-12) | 101(11-9) | sz=0(8) | N(7) | // 0(6) | M(5) | 0(4) | Vm(3-0) DCHECK(IsEnabled(ARMv8)); int vd, d; dst.split_code(&vd, &d); int vn, n; src1.split_code(&vn, &n); int vm, m; src2.split_code(&vm, &m); int sz = 0; // VSEL has a special (restricted) condition encoding. // eq(0b0000)... -> 0b00 // ge(0b1010)... -> 0b10 // gt(0b1100)... -> 0b11 // vs(0b0110)... -> 0b01 // No other conditions are supported. int vsel_cond = (cond >> 30) & 0x3; if ((cond != eq) && (cond != ge) && (cond != gt) && (cond != vs)) { // We can implement some other conditions by swapping the inputs. DCHECK((cond == ne) | (cond == lt) | (cond == le) | (cond == vc)); std::swap(vn, vm); std::swap(n, m); } emit(kSpecialCondition | 0x1C * B23 | d * B22 | vsel_cond * B20 | vn * B16 | vd * B12 | 0x5 * B9 | sz * B8 | n * B7 | m * B5 | vm); } void Assembler::vsqrt(const DwVfpRegister dst, const DwVfpRegister src, const Condition cond) { // Instruction details available in ARM DDI 0406C.b, A8-1058. // cond(31-28) | 11101(27-23)| D(22) | 11(21-20) | 0001(19-16) | // Vd(15-12) | 101(11-9) | sz=1(8) | 11(7-6) | M(5) | 0(4) | Vm(3-0) DCHECK(VfpRegisterIsAvailable(dst)); DCHECK(VfpRegisterIsAvailable(src)); int vd, d; dst.split_code(&vd, &d); int vm, m; src.split_code(&vm, &m); emit(cond | 0x1D * B23 | d * B22 | 0x3 * B20 | B16 | vd * B12 | 0x5 * B9 | B8 | 0x3 * B6 | m * B5 | vm); } void Assembler::vsqrt(const SwVfpRegister dst, const SwVfpRegister src, const Condition cond) { // Instruction details available in ARM DDI 0406C.b, A8-1058. // cond(31-28) | 11101(27-23)| D(22) | 11(21-20) | 0001(19-16) | // Vd(15-12) | 101(11-9) | sz=0(8) | 11(7-6) | M(5) | 0(4) | Vm(3-0) int vd, d; dst.split_code(&vd, &d); int vm, m; src.split_code(&vm, &m); emit(cond | 0x1D * B23 | d * B22 | 0x3 * B20 | B16 | vd * B12 | 0x5 * B9 | 0x3 * B6 | m * B5 | vm); } void Assembler::vmsr(Register dst, Condition cond) { // Instruction details available in ARM DDI 0406A, A8-652. // cond(31-28) | 1110 (27-24) | 1110(23-20)| 0001 (19-16) | // Rt(15-12) | 1010 (11-8) | 0(7) | 00 (6-5) | 1(4) | 0000(3-0) emit(cond | 0xE * B24 | 0xE * B20 | B16 | dst.code() * B12 | 0xA * B8 | B4); } void Assembler::vmrs(Register dst, Condition cond) { // Instruction details available in ARM DDI 0406A, A8-652. // cond(31-28) | 1110 (27-24) | 1111(23-20)| 0001 (19-16) | // Rt(15-12) | 1010 (11-8) | 0(7) | 00 (6-5) | 1(4) | 0000(3-0) emit(cond | 0xE * B24 | 0xF * B20 | B16 | dst.code() * B12 | 0xA * B8 | B4); } void Assembler::vrinta(const SwVfpRegister dst, const SwVfpRegister src) { // cond=kSpecialCondition(31-28) | 11101(27-23)| D(22) | 11(21-20) | // 10(19-18) | RM=00(17-16) | Vd(15-12) | 101(11-9) | sz=0(8) | 01(7-6) | // M(5) | 0(4) | Vm(3-0) DCHECK(IsEnabled(ARMv8)); int vd, d; dst.split_code(&vd, &d); int vm, m; src.split_code(&vm, &m); emit(kSpecialCondition | 0x1D * B23 | d * B22 | 0x3 * B20 | B19 | vd * B12 | 0x5 * B9 | B6 | m * B5 | vm); } void Assembler::vrinta(const DwVfpRegister dst, const DwVfpRegister src) { // cond=kSpecialCondition(31-28) | 11101(27-23)| D(22) | 11(21-20) | // 10(19-18) | RM=00(17-16) | Vd(15-12) | 101(11-9) | sz=1(8) | 01(7-6) | // M(5) | 0(4) | Vm(3-0) DCHECK(IsEnabled(ARMv8)); int vd, d; dst.split_code(&vd, &d); int vm, m; src.split_code(&vm, &m); emit(kSpecialCondition | 0x1D * B23 | d * B22 | 0x3 * B20 | B19 | vd * B12 | 0x5 * B9 | B8 | B6 | m * B5 | vm); } void Assembler::vrintn(const SwVfpRegister dst, const SwVfpRegister src) { // cond=kSpecialCondition(31-28) | 11101(27-23)| D(22) | 11(21-20) | // 10(19-18) | RM=01(17-16) | Vd(15-12) | 101(11-9) | sz=0(8) | 01(7-6) | // M(5) | 0(4) | Vm(3-0) DCHECK(IsEnabled(ARMv8)); int vd, d; dst.split_code(&vd, &d); int vm, m; src.split_code(&vm, &m); emit(kSpecialCondition | 0x1D * B23 | d * B22 | 0x3 * B20 | B19 | 0x1 * B16 | vd * B12 | 0x5 * B9 | B6 | m * B5 | vm); } void Assembler::vrintn(const DwVfpRegister dst, const DwVfpRegister src) { // cond=kSpecialCondition(31-28) | 11101(27-23)| D(22) | 11(21-20) | // 10(19-18) | RM=01(17-16) | Vd(15-12) | 101(11-9) | sz=1(8) | 01(7-6) | // M(5) | 0(4) | Vm(3-0) DCHECK(IsEnabled(ARMv8)); int vd, d; dst.split_code(&vd, &d); int vm, m; src.split_code(&vm, &m); emit(kSpecialCondition | 0x1D * B23 | d * B22 | 0x3 * B20 | B19 | 0x1 * B16 | vd * B12 | 0x5 * B9 | B8 | B6 | m * B5 | vm); } void Assembler::vrintp(const SwVfpRegister dst, const SwVfpRegister src) { // cond=kSpecialCondition(31-28) | 11101(27-23)| D(22) | 11(21-20) | // 10(19-18) | RM=10(17-16) | Vd(15-12) | 101(11-9) | sz=0(8) | 01(7-6) | // M(5) | 0(4) | Vm(3-0) DCHECK(IsEnabled(ARMv8)); int vd, d; dst.split_code(&vd, &d); int vm, m; src.split_code(&vm, &m); emit(kSpecialCondition | 0x1D * B23 | d * B22 | 0x3 * B20 | B19 | 0x2 * B16 | vd * B12 | 0x5 * B9 | B6 | m * B5 | vm); } void Assembler::vrintp(const DwVfpRegister dst, const DwVfpRegister src) { // cond=kSpecialCondition(31-28) | 11101(27-23)| D(22) | 11(21-20) | // 10(19-18) | RM=10(17-16) | Vd(15-12) | 101(11-9) | sz=1(8) | 01(7-6) | // M(5) | 0(4) | Vm(3-0) DCHECK(IsEnabled(ARMv8)); int vd, d; dst.split_code(&vd, &d); int vm, m; src.split_code(&vm, &m); emit(kSpecialCondition | 0x1D * B23 | d * B22 | 0x3 * B20 | B19 | 0x2 * B16 | vd * B12 | 0x5 * B9 | B8 | B6 | m * B5 | vm); } void Assembler::vrintm(const SwVfpRegister dst, const SwVfpRegister src) { // cond=kSpecialCondition(31-28) | 11101(27-23)| D(22) | 11(21-20) | // 10(19-18) | RM=11(17-16) | Vd(15-12) | 101(11-9) | sz=0(8) | 01(7-6) | // M(5) | 0(4) | Vm(3-0) DCHECK(IsEnabled(ARMv8)); int vd, d; dst.split_code(&vd, &d); int vm, m; src.split_code(&vm, &m); emit(kSpecialCondition | 0x1D * B23 | d * B22 | 0x3 * B20 | B19 | 0x3 * B16 | vd * B12 | 0x5 * B9 | B6 | m * B5 | vm); } void Assembler::vrintm(const DwVfpRegister dst, const DwVfpRegister src) { // cond=kSpecialCondition(31-28) | 11101(27-23)| D(22) | 11(21-20) | // 10(19-18) | RM=11(17-16) | Vd(15-12) | 101(11-9) | sz=1(8) | 01(7-6) | // M(5) | 0(4) | Vm(3-0) DCHECK(IsEnabled(ARMv8)); int vd, d; dst.split_code(&vd, &d); int vm, m; src.split_code(&vm, &m); emit(kSpecialCondition | 0x1D * B23 | d * B22 | 0x3 * B20 | B19 | 0x3 * B16 | vd * B12 | 0x5 * B9 | B8 | B6 | m * B5 | vm); } void Assembler::vrintz(const SwVfpRegister dst, const SwVfpRegister src, const Condition cond) { // cond(31-28) | 11101(27-23)| D(22) | 11(21-20) | 011(19-17) | 0(16) | // Vd(15-12) | 101(11-9) | sz=0(8) | op=1(7) | 1(6) | M(5) | 0(4) | Vm(3-0) DCHECK(IsEnabled(ARMv8)); int vd, d; dst.split_code(&vd, &d); int vm, m; src.split_code(&vm, &m); emit(cond | 0x1D * B23 | d * B22 | 0x3 * B20 | 0x3 * B17 | vd * B12 | 0x5 * B9 | B7 | B6 | m * B5 | vm); } void Assembler::vrintz(const DwVfpRegister dst, const DwVfpRegister src, const Condition cond) { // cond(31-28) | 11101(27-23)| D(22) | 11(21-20) | 011(19-17) | 0(16) | // Vd(15-12) | 101(11-9) | sz=1(8) | op=1(7) | 1(6) | M(5) | 0(4) | Vm(3-0) DCHECK(IsEnabled(ARMv8)); int vd, d; dst.split_code(&vd, &d); int vm, m; src.split_code(&vm, &m); emit(cond | 0x1D * B23 | d * B22 | 0x3 * B20 | 0x3 * B17 | vd * B12 | 0x5 * B9 | B8 | B7 | B6 | m * B5 | vm); } // Support for NEON. void Assembler::vld1(NeonSize size, const NeonListOperand& dst, const NeonMemOperand& src) { // Instruction details available in ARM DDI 0406C.b, A8.8.320. // 1111(31-28) | 01000(27-23) | D(22) | 10(21-20) | Rn(19-16) | // Vd(15-12) | type(11-8) | size(7-6) | align(5-4) | Rm(3-0) DCHECK(IsEnabled(NEON)); int vd, d; dst.base().split_code(&vd, &d); emit(0xFU * B28 | 4 * B24 | d * B22 | 2 * B20 | src.rn().code() * B16 | vd * B12 | dst.type() * B8 | size * B6 | src.align() * B4 | src.rm().code()); } // vld1s(ingle element to one lane). void Assembler::vld1s(NeonSize size, const NeonListOperand& dst, uint8_t index, const NeonMemOperand& src) { // Instruction details available in ARM DDI 0406C.b, A8.8.322. // 1111(31-28) | 01001(27-23) | D(22) | 10(21-20) | Rn(19-16) | // Vd(15-12) | size(11-10) | index_align(7-4) | Rm(3-0) // See vld1 (single element to all lanes) if size == 0x3, implemented as // vld1r(eplicate). DCHECK_NE(size, 0x3); // Check for valid lane indices. DCHECK_GT(1 << (3 - size), index); // Specifying alignment not supported, use standard alignment. uint8_t index_align = index << (size + 1); DCHECK(IsEnabled(NEON)); int vd, d; dst.base().split_code(&vd, &d); emit(0xFU * B28 | 4 * B24 | 1 * B23 | d * B22 | 2 * B20 | src.rn().code() * B16 | vd * B12 | size * B10 | index_align * B4 | src.rm().code()); } // vld1r(eplicate) void Assembler::vld1r(NeonSize size, const NeonListOperand& dst, const NeonMemOperand& src) { DCHECK(IsEnabled(NEON)); int vd, d; dst.base().split_code(&vd, &d); emit(0xFU * B28 | 4 * B24 | 1 * B23 | d * B22 | 2 * B20 | src.rn().code() * B16 | vd * B12 | 0xC * B8 | size * B6 | dst.length() * B5 | src.rm().code()); } void Assembler::vst1(NeonSize size, const NeonListOperand& src, const NeonMemOperand& dst) { // Instruction details available in ARM DDI 0406C.b, A8.8.404. // 1111(31-28) | 01000(27-23) | D(22) | 00(21-20) | Rn(19-16) | // Vd(15-12) | type(11-8) | size(7-6) | align(5-4) | Rm(3-0) DCHECK(IsEnabled(NEON)); int vd, d; src.base().split_code(&vd, &d); emit(0xFU * B28 | 4 * B24 | d * B22 | dst.rn().code() * B16 | vd * B12 | src.type() * B8 | size * B6 | dst.align() * B4 | dst.rm().code()); } void Assembler::vst1s(NeonSize size, const NeonListOperand& src, uint8_t index, const NeonMemOperand& dst) { // Instruction details available in ARM DDI 0487F.b F6.1.236. // 1111(31-28) | 01001(27-23) | D(22) | 00(21-20) | Rn(19-16) | // Vd(15-12) | size(11-10) | 00(9-8) | index_align(7-4) | Rm(3-0) DCHECK(IsEnabled(NEON)); DCHECK_NE(size, 0x3); DCHECK_GT(1 << (3 - size), index); // Specifying alignment not supported, use standard alignment. uint8_t index_align = index << (size + 1); int vd, d; src.base().split_code(&vd, &d); emit(0xFU * B28 | 9 * B23 | d * B22 | dst.rn().code() * B16 | vd * B12 | size * B10 | index_align * B4 | dst.rm().code()); } void Assembler::vmovl(NeonDataType dt, QwNeonRegister dst, DwVfpRegister src) { // Instruction details available in ARM DDI 0406C.b, A8.8.346. // 1111(31-28) | 001(27-25) | U(24) | 1(23) | D(22) | imm3(21-19) | // 000(18-16) | Vd(15-12) | 101000(11-6) | M(5) | 1(4) | Vm(3-0) DCHECK(IsEnabled(NEON)); int vd, d; dst.split_code(&vd, &d); int vm, m; src.split_code(&vm, &m); int U = NeonU(dt); int imm3 = 1 << NeonSz(dt); emit(0xFU * B28 | B25 | U * B24 | B23 | d * B22 | imm3 * B19 | vd * B12 | 0xA * B8 | m * B5 | B4 | vm); } void Assembler::vqmovn(NeonDataType dst_dt, NeonDataType src_dt, DwVfpRegister dst, QwNeonRegister src) { // Instruction details available in ARM DDI 0406C.b, A8.8.1004. // vqmovn.<type><size> Dd, Qm. ARM vector narrowing move with saturation. // vqmovun.<type><size> Dd, Qm. Same as above, but produces unsigned results. DCHECK(IsEnabled(NEON)); DCHECK_IMPLIES(NeonU(src_dt), NeonU(dst_dt)); int vd, d; dst.split_code(&vd, &d); int vm, m; src.split_code(&vm, &m); int size = NeonSz(dst_dt); DCHECK_NE(3, size); int op = NeonU(src_dt) ? 0b11 : NeonU(dst_dt) ? 0b01 : 0b10; emit(0x1E7U * B23 | d * B22 | 0x3 * B20 | size * B18 | 0x2 * B16 | vd * B12 | 0x2 * B8 | op * B6 | m * B5 | vm); } static int EncodeScalar(NeonDataType dt, int index) { int opc1_opc2 = 0; DCHECK_LE(0, index); switch (dt) { case NeonS8: case NeonU8: DCHECK_GT(8, index); opc1_opc2 = 0x8 | index; break; case NeonS16: case NeonU16: DCHECK_GT(4, index); opc1_opc2 = 0x1 | (index << 1); break; case NeonS32: case NeonU32: DCHECK_GT(2, index); opc1_opc2 = index << 2; break; default: UNREACHABLE(); } return (opc1_opc2 >> 2) * B21 | (opc1_opc2 & 0x3) * B5; } void Assembler::vmov(NeonDataType dt, DwVfpRegister dst, int index, Register src) { // Instruction details available in ARM DDI 0406C.b, A8.8.940. // vmov ARM core register to scalar. DCHECK(dt == NeonS32 || dt == NeonU32 || IsEnabled(NEON)); int vd, d; dst.split_code(&vd, &d); int opc1_opc2 = EncodeScalar(dt, index); emit(0xEEu * B24 | vd * B16 | src.code() * B12 | 0xB * B8 | d * B7 | B4 | opc1_opc2); } void Assembler::vmov(NeonDataType dt, Register dst, DwVfpRegister src, int index) { // Instruction details available in ARM DDI 0406C.b, A8.8.942. // vmov Arm scalar to core register. DCHECK(dt == NeonS32 || dt == NeonU32 || IsEnabled(NEON)); int vn, n; src.split_code(&vn, &n); int opc1_opc2 = EncodeScalar(dt, index); // NeonS32 and NeonU32 both encoded as u = 0. int u = NeonDataTypeToSize(dt) == Neon32 ? 0 : NeonU(dt); emit(0xEEu * B24 | u * B23 | B20 | vn * B16 | dst.code() * B12 | 0xB * B8 | n * B7 | B4 | opc1_opc2); } void Assembler::vmov(QwNeonRegister dst, QwNeonRegister src) { // Instruction details available in ARM DDI 0406C.b, A8-938. // vmov is encoded as vorr. vorr(dst, src, src); } void Assembler::vdup(NeonSize size, QwNeonRegister dst, Register src) { DCHECK(IsEnabled(NEON)); // Instruction details available in ARM DDI 0406C.b, A8-886. int B = 0, E = 0; switch (size) { case Neon8: B = 1; break; case Neon16: E = 1; break; case Neon32: break; default: UNREACHABLE(); } int vd, d; dst.split_code(&vd, &d); emit(al | 0x1D * B23 | B * B22 | B21 | vd * B16 | src.code() * B12 | 0xB * B8 | d * B7 | E * B5 | B4); } enum NeonRegType { NEON_D, NEON_Q }; void NeonSplitCode(NeonRegType type, int code, int* vm, int* m, int* encoding) { if (type == NEON_D) { DwVfpRegister::split_code(code, vm, m); } else { DCHECK_EQ(type, NEON_Q); QwNeonRegister::split_code(code, vm, m); *encoding |= B6; } } static Instr EncodeNeonDupOp(NeonSize size, NeonRegType reg_type, int dst_code, DwVfpRegister src, int index) { DCHECK_NE(Neon64, size); int sz = static_cast<int>(size); DCHECK_LE(0, index); DCHECK_GT(kSimd128Size / (1 << sz), index); int imm4 = (1 << sz) | ((index << (sz + 1)) & 0xF); int qbit = 0; int vd, d; NeonSplitCode(reg_type, dst_code, &vd, &d, &qbit); int vm, m; src.split_code(&vm, &m); return 0x1E7U * B23 | d * B22 | 0x3 * B20 | imm4 * B16 | vd * B12 | 0x18 * B7 | qbit | m * B5 | vm; } void Assembler::vdup(NeonSize size, DwVfpRegister dst, DwVfpRegister src, int index) { DCHECK(IsEnabled(NEON)); // Instruction details available in ARM DDI 0406C.b, A8-884. emit(EncodeNeonDupOp(size, NEON_D, dst.code(), src, index)); } void Assembler::vdup(NeonSize size, QwNeonRegister dst, DwVfpRegister src, int index) { // Instruction details available in ARM DDI 0406C.b, A8-884. DCHECK(IsEnabled(NEON)); emit(EncodeNeonDupOp(size, NEON_Q, dst.code(), src, index)); } // Encode NEON vcvt.src_type.dst_type instruction. static Instr EncodeNeonVCVT(VFPType dst_type, QwNeonRegister dst, VFPType src_type, QwNeonRegister src) { DCHECK(src_type != dst_type); DCHECK(src_type == F32 || dst_type == F32); // Instruction details available in ARM DDI 0406C.b, A8.8.868. int vd, d; dst.split_code(&vd, &d); int vm, m; src.split_code(&vm, &m); int op = 0; if (src_type == F32) { DCHECK(dst_type == S32 || dst_type == U32); op = dst_type == U32 ? 3 : 2; } else { DCHECK(src_type == S32 || src_type == U32); op = src_type == U32 ? 1 : 0; } return 0x1E7U * B23 | d * B22 | 0x3B * B16 | vd * B12 | 0x3 * B9 | op * B7 | B6 | m * B5 | vm; } void Assembler::vcvt_f32_s32(QwNeonRegister dst, QwNeonRegister src) { DCHECK(IsEnabled(NEON)); DCHECK(VfpRegisterIsAvailable(dst)); DCHECK(VfpRegisterIsAvailable(src)); emit(EncodeNeonVCVT(F32, dst, S32, src)); } void Assembler::vcvt_f32_u32(QwNeonRegister dst, QwNeonRegister src) { DCHECK(IsEnabled(NEON)); DCHECK(VfpRegisterIsAvailable(dst)); DCHECK(VfpRegisterIsAvailable(src)); emit(EncodeNeonVCVT(F32, dst, U32, src)); } void Assembler::vcvt_s32_f32(QwNeonRegister dst, QwNeonRegister src) { DCHECK(IsEnabled(NEON)); DCHECK(VfpRegisterIsAvailable(dst)); DCHECK(VfpRegisterIsAvailable(src)); emit(EncodeNeonVCVT(S32, dst, F32, src)); } void Assembler::vcvt_u32_f32(QwNeonRegister dst, QwNeonRegister src) { DCHECK(IsEnabled(NEON)); DCHECK(VfpRegisterIsAvailable(dst)); DCHECK(VfpRegisterIsAvailable(src)); emit(EncodeNeonVCVT(U32, dst, F32, src)); } enum UnaryOp { VMVN, VSWP, VABS, VABSF, VNEG, VNEGF, VRINTM, VRINTN, VRINTP, VRINTZ, VZIP, VUZP, VREV16, VREV32, VREV64, VTRN, VRECPE, VRSQRTE, VPADAL_S, VPADAL_U, VPADDL_S, VPADDL_U, VCEQ0, VCLT0, VCNT }; // Encoding helper for "Advanced SIMD two registers misc" decode group. See ARM // DDI 0487F.b, F4-4228. static Instr EncodeNeonUnaryOp(UnaryOp op, NeonRegType reg_type, NeonSize size, int dst_code, int src_code) { int op_encoding = 0; switch (op) { case VMVN: DCHECK_EQ(Neon8, size); // size == 0 for vmvn op_encoding = B10 | 0x3 * B7; break; case VSWP: DCHECK_EQ(Neon8, size); // size == 0 for vswp op_encoding = B17; break; case VABS: op_encoding = B16 | 0x6 * B7; break; case VABSF: DCHECK_EQ(Neon32, size); op_encoding = B16 | B10 | 0x6 * B7; break; case VNEG: op_encoding = B16 | 0x7 * B7; break; case VNEGF: DCHECK_EQ(Neon32, size); op_encoding = B16 | B10 | 0x7 * B7; break; case VRINTM: op_encoding = B17 | 0xD * B7; break; case VRINTN: op_encoding = B17 | 0x8 * B7; break; case VRINTP: op_encoding = B17 | 0xF * B7; break; case VRINTZ: op_encoding = B17 | 0xB * B7; break; case VZIP: op_encoding = 0x2 * B16 | 0x3 * B7; break; case VUZP: op_encoding = 0x2 * B16 | 0x2 * B7; break; case VREV16: op_encoding = 0x2 * B7; break; case VREV32: op_encoding = 0x1 * B7; break; case VREV64: // op_encoding is 0; break; case VTRN: op_encoding = 0x2 * B16 | B7; break; case VRECPE: // Only support floating point. op_encoding = 0x3 * B16 | 0xA * B7; break; case VRSQRTE: // Only support floating point. op_encoding = 0x3 * B16 | 0xB * B7; break; case VPADAL_S: op_encoding = 0xC * B7; break; case VPADAL_U: op_encoding = 0xD * B7; break; case VPADDL_S: op_encoding = 0x4 * B7; break; case VPADDL_U: op_encoding = 0x5 * B7; break; case VCEQ0: // Only support integers. op_encoding = 0x1 * B16 | 0x2 * B7; break; case VCLT0: // Only support signed integers. op_encoding = 0x1 * B16 | 0x4 * B7; break; case VCNT: op_encoding = 0xA * B7; break; } int vd, d; NeonSplitCode(reg_type, dst_code, &vd, &d, &op_encoding); int vm, m; NeonSplitCode(reg_type, src_code, &vm, &m, &op_encoding); return 0x1E7U * B23 | d * B22 | 0x3 * B20 | size * B18 | vd * B12 | m * B5 | vm | op_encoding; } void Assembler::vmvn(QwNeonRegister dst, QwNeonRegister src) { // Qd = vmvn(Qn, Qm) SIMD bitwise negate. // Instruction details available in ARM DDI 0406C.b, A8-966. DCHECK(IsEnabled(NEON)); emit(EncodeNeonUnaryOp(VMVN, NEON_Q, Neon8, dst.code(), src.code())); } void Assembler::vswp(DwVfpRegister dst, DwVfpRegister src) { DCHECK(IsEnabled(NEON)); // Dd = vswp(Dn, Dm) SIMD d-register swap. // Instruction details available in ARM DDI 0406C.b, A8.8.418. DCHECK(IsEnabled(NEON)); emit(EncodeNeonUnaryOp(VSWP, NEON_D, Neon8, dst.code(), src.code())); } void Assembler::vswp(QwNeonRegister dst, QwNeonRegister src) { // Qd = vswp(Qn, Qm) SIMD q-register swap. // Instruction details available in ARM DDI 0406C.b, A8.8.418. DCHECK(IsEnabled(NEON)); emit(EncodeNeonUnaryOp(VSWP, NEON_Q, Neon8, dst.code(), src.code())); } void Assembler::vabs(QwNeonRegister dst, QwNeonRegister src) { // Qd = vabs.f<size>(Qn, Qm) SIMD floating point absolute value. // Instruction details available in ARM DDI 0406C.b, A8.8.824. DCHECK(IsEnabled(NEON)); emit(EncodeNeonUnaryOp(VABSF, NEON_Q, Neon32, dst.code(), src.code())); } void Assembler::vabs(NeonSize size, QwNeonRegister dst, QwNeonRegister src) { // Qd = vabs.s<size>(Qn, Qm) SIMD integer absolute value. // Instruction details available in ARM DDI 0406C.b, A8.8.824. DCHECK(IsEnabled(NEON)); emit(EncodeNeonUnaryOp(VABS, NEON_Q, size, dst.code(), src.code())); } void Assembler::vneg(QwNeonRegister dst, QwNeonRegister src) { // Qd = vabs.f<size>(Qn, Qm) SIMD floating point negate. // Instruction details available in ARM DDI 0406C.b, A8.8.968. DCHECK(IsEnabled(NEON)); emit(EncodeNeonUnaryOp(VNEGF, NEON_Q, Neon32, dst.code(), src.code())); } void Assembler::vneg(NeonSize size, QwNeonRegister dst, QwNeonRegister src) { // Qd = vabs.s<size>(Qn, Qm) SIMD integer negate. // Instruction details available in ARM DDI 0406C.b, A8.8.968. DCHECK(IsEnabled(NEON)); emit(EncodeNeonUnaryOp(VNEG, NEON_Q, size, dst.code(), src.code())); } enum BinaryBitwiseOp { VAND, VBIC, VBIF, VBIT, VBSL, VEOR, VORR, VORN }; static Instr EncodeNeonBinaryBitwiseOp(BinaryBitwiseOp op, NeonRegType reg_type, int dst_code, int src_code1, int src_code2) { int op_encoding = 0; switch (op) { case VBIC: op_encoding = 0x1 * B20; break; case VBIF: op_encoding = B24 | 0x3 * B20; break; case VBIT: op_encoding = B24 | 0x2 * B20; break; case VBSL: op_encoding = B24 | 0x1 * B20; break; case VEOR: op_encoding = B24; break; case VORR: op_encoding = 0x2 * B20; break; case VORN: op_encoding = 0x3 * B20; break; case VAND: // op_encoding is 0. break; default: UNREACHABLE(); } int vd, d; NeonSplitCode(reg_type, dst_code, &vd, &d, &op_encoding); int vn, n; NeonSplitCode(reg_type, src_code1, &vn, &n, &op_encoding); int vm, m; NeonSplitCode(reg_type, src_code2, &vm, &m, &op_encoding); return 0x1E4U * B23 | op_encoding | d * B22 | vn * B16 | vd * B12 | B8 | n * B7 | m * B5 | B4 | vm; } void Assembler::vand(QwNeonRegister dst, QwNeonRegister src1, QwNeonRegister src2) { // Qd = vand(Qn, Qm) SIMD AND. // Instruction details available in ARM DDI 0406C.b, A8.8.836. DCHECK(IsEnabled(NEON)); emit(EncodeNeonBinaryBitwiseOp(VAND, NEON_Q, dst.code(), src1.code(), src2.code())); } void Assembler::vbic(QwNeonRegister dst, QwNeonRegister src1, QwNeonRegister src2) { // Qd = vbic(Qn, Qm) SIMD AND. // Instruction details available in ARM DDI 0406C.b, A8-840. DCHECK(IsEnabled(NEON)); emit(EncodeNeonBinaryBitwiseOp(VBIC, NEON_Q, dst.code(), src1.code(), src2.code())); } void Assembler::vbsl(QwNeonRegister dst, QwNeonRegister src1, QwNeonRegister src2) { // Qd = vbsl(Qn, Qm) SIMD bitwise select. // Instruction details available in ARM DDI 0406C.b, A8-844. DCHECK(IsEnabled(NEON)); emit(EncodeNeonBinaryBitwiseOp(VBSL, NEON_Q, dst.code(), src1.code(), src2.code())); } void Assembler::veor(DwVfpRegister dst, DwVfpRegister src1, DwVfpRegister src2) { // Dd = veor(Dn, Dm) SIMD exclusive OR. // Instruction details available in ARM DDI 0406C.b, A8.8.888. DCHECK(IsEnabled(NEON)); emit(EncodeNeonBinaryBitwiseOp(VEOR, NEON_D, dst.code(), src1.code(), src2.code())); } void Assembler::veor(QwNeonRegister dst, QwNeonRegister src1, QwNeonRegister src2) { // Qd = veor(Qn, Qm) SIMD exclusive OR. // Instruction details available in ARM DDI 0406C.b, A8.8.888. DCHECK(IsEnabled(NEON)); emit(EncodeNeonBinaryBitwiseOp(VEOR, NEON_Q, dst.code(), src1.code(), src2.code())); } void Assembler::vorr(QwNeonRegister dst, QwNeonRegister src1, QwNeonRegister src2) { // Qd = vorr(Qn, Qm) SIMD OR. // Instruction details available in ARM DDI 0406C.b, A8.8.976. DCHECK(IsEnabled(NEON)); emit(EncodeNeonBinaryBitwiseOp(VORR, NEON_Q, dst.code(), src1.code(), src2.code())); } void Assembler::vorn(QwNeonRegister dst, QwNeonRegister src1, QwNeonRegister src2) { // Qd = vorn(Qn, Qm) SIMD OR NOT. // Instruction details available in ARM DDI 0406C.d, A8.8.359. DCHECK(IsEnabled(NEON)); emit(EncodeNeonBinaryBitwiseOp(VORN, NEON_Q, dst.code(), src1.code(), src2.code())); } enum FPBinOp { VADDF, VSUBF, VMULF, VMINF, VMAXF, VRECPS, VRSQRTS, VCEQF, VCGEF, VCGTF }; static Instr EncodeNeonBinOp(FPBinOp op, QwNeonRegister dst, QwNeonRegister src1, QwNeonRegister src2) { int op_encoding = 0; switch (op) { case VADDF: op_encoding = 0xD * B8; break; case VSUBF: op_encoding = B21 | 0xD * B8; break; case VMULF: op_encoding = B24 | 0xD * B8 | B4; break; case VMINF: op_encoding = B21 | 0xF * B8; break; case VMAXF: op_encoding = 0xF * B8; break; case VRECPS: op_encoding = 0xF * B8 | B4; break; case VRSQRTS: op_encoding = B21 | 0xF * B8 | B4; break; case VCEQF: op_encoding = 0xE * B8; break; case VCGEF: op_encoding = B24 | 0xE * B8; break; case VCGTF: op_encoding = B24 | B21 | 0xE * B8; break; default: UNREACHABLE(); } int vd, d; dst.split_code(&vd, &d); int vn, n; src1.split_code(&vn, &n); int vm, m; src2.split_code(&vm, &m); return 0x1E4U * B23 | d * B22 | vn * B16 | vd * B12 | n * B7 | B6 | m * B5 | vm | op_encoding; } enum IntegerBinOp { VADD, VQADD, VSUB, VQSUB, VMUL, VMIN, VMAX, VTST, VCEQ, VCGE, VCGT, VRHADD, VQRDMULH }; static Instr EncodeNeonBinOp(IntegerBinOp op, NeonDataType dt, QwNeonRegister dst, QwNeonRegister src1, QwNeonRegister src2) { int op_encoding = 0; switch (op) { case VADD: op_encoding = 0x8 * B8; break; case VQADD: op_encoding = B4; break; case VSUB: op_encoding = B24 | 0x8 * B8; break; case VQSUB: op_encoding = 0x2 * B8 | B4; break; case VMUL: op_encoding = 0x9 * B8 | B4; break; case VMIN: op_encoding = 0x6 * B8 | B4; break; case VMAX: op_encoding = 0x6 * B8; break; case VTST: op_encoding = 0x8 * B8 | B4; break; case VCEQ: op_encoding = B24 | 0x8 * B8 | B4; break; case VCGE: op_encoding = 0x3 * B8 | B4; break; case VCGT: op_encoding = 0x3 * B8; break; case VRHADD: op_encoding = B8; break; case VQRDMULH: op_encoding = B24 | 0xB * B8; break; default: UNREACHABLE(); } int vd, d; dst.split_code(&vd, &d); int vn, n; src1.split_code(&vn, &n); int vm, m; src2.split_code(&vm, &m); int size = NeonSz(dt); int u = NeonU(dt); return 0x1E4U * B23 | u * B24 | d * B22 | size * B20 | vn * B16 | vd * B12 | n * B7 | B6 | m * B5 | vm | op_encoding; } static Instr EncodeNeonBinOp(IntegerBinOp op, NeonSize size, QwNeonRegister dst, QwNeonRegister src1, QwNeonRegister src2) { // Map NeonSize values to the signed values in NeonDataType, so the U bit // will be 0. return EncodeNeonBinOp(op, static_cast<NeonDataType>(size), dst, src1, src2); } void Assembler::vadd(QwNeonRegister dst, QwNeonRegister src1, QwNeonRegister src2) { DCHECK(IsEnabled(NEON)); // Qd = vadd(Qn, Qm) SIMD floating point addition. // Instruction details available in ARM DDI 0406C.b, A8-830. emit(EncodeNeonBinOp(VADDF, dst, src1, src2)); } void Assembler::vadd(NeonSize size, QwNeonRegister dst, QwNeonRegister src1, QwNeonRegister src2) { DCHECK(IsEnabled(NEON)); // Qd = vadd(Qn, Qm) SIMD integer addition. // Instruction details available in ARM DDI 0406C.b, A8-828. emit(EncodeNeonBinOp(VADD, size, dst, src1, src2)); } void Assembler::vqadd(NeonDataType dt, QwNeonRegister dst, QwNeonRegister src1, QwNeonRegister src2) { DCHECK(IsEnabled(NEON)); // Qd = vqadd(Qn, Qm) SIMD integer saturating addition. // Instruction details available in ARM DDI 0406C.b, A8-996. emit(EncodeNeonBinOp(VQADD, dt, dst, src1, src2)); } void Assembler::vsub(QwNeonRegister dst, QwNeonRegister src1, QwNeonRegister src2) { DCHECK(IsEnabled(NEON)); // Qd = vsub(Qn, Qm) SIMD floating point subtraction. // Instruction details available in ARM DDI 0406C.b, A8-1086. emit(EncodeNeonBinOp(VSUBF, dst, src1, src2)); } void Assembler::vsub(NeonSize size, QwNeonRegister dst, QwNeonRegister src1, QwNeonRegister src2) { DCHECK(IsEnabled(NEON)); // Qd = vsub(Qn, Qm) SIMD integer subtraction. // Instruction details available in ARM DDI 0406C.b, A8-1084. emit(EncodeNeonBinOp(VSUB, size, dst, src1, src2)); } void Assembler::vqsub(NeonDataType dt, QwNeonRegister dst, QwNeonRegister src1, QwNeonRegister src2) { DCHECK(IsEnabled(NEON)); // Qd = vqsub(Qn, Qm) SIMD integer saturating subtraction. // Instruction details available in ARM DDI 0406C.b, A8-1020. emit(EncodeNeonBinOp(VQSUB, dt, dst, src1, src2)); } void Assembler::vmlal(NeonDataType dt, QwNeonRegister dst, DwVfpRegister src1, DwVfpRegister src2) { DCHECK(IsEnabled(NEON)); // Qd = vmlal(Dn, Dm) Vector Multiply Accumulate Long (integer) // Instruction details available in ARM DDI 0406C.b, A8-931. int vd, d; dst.split_code(&vd, &d); int vn, n; src1.split_code(&vn, &n); int vm, m; src2.split_code(&vm, &m); int size = NeonSz(dt); int u = NeonU(dt); if (!u) UNIMPLEMENTED(); DCHECK_NE(size, 3); // SEE "Related encodings" emit(0xFU * B28 | B25 | u * B24 | B23 | d * B22 | size * B20 | vn * B16 | vd * B12 | 0x8 * B8 | n * B7 | m * B5 | vm); } void Assembler::vmul(QwNeonRegister dst, QwNeonRegister src1, QwNeonRegister src2) { DCHECK(IsEnabled(NEON)); // Qd = vadd(Qn, Qm) SIMD floating point multiply. // Instruction details available in ARM DDI 0406C.b, A8-958. emit(EncodeNeonBinOp(VMULF, dst, src1, src2)); } void Assembler::vmul(NeonSize size, QwNeonRegister dst, QwNeonRegister src1, QwNeonRegister src2) { DCHECK(IsEnabled(NEON)); // Qd = vadd(Qn, Qm) SIMD integer multiply. // Instruction details available in ARM DDI 0406C.b, A8-960. emit(EncodeNeonBinOp(VMUL, size, dst, src1, src2)); } void Assembler::vmull(NeonDataType dt, QwNeonRegister dst, DwVfpRegister src1, DwVfpRegister src2) { DCHECK(IsEnabled(NEON)); // Qd = vmull(Dn, Dm) Vector Multiply Long (integer). // Instruction details available in ARM DDI 0406C.b, A8-960. int vd, d; dst.split_code(&vd, &d); int vn, n; src1.split_code(&vn, &n); int vm, m; src2.split_code(&vm, &m); int size = NeonSz(dt); int u = NeonU(dt); emit(0xFU * B28 | B25 | u * B24 | B23 | d * B22 | size * B20 | vn * B16 | vd * B12 | 0xC * B8 | n * B7 | m * B5 | vm); } void Assembler::vmin(QwNeonRegister dst, QwNeonRegister src1, QwNeonRegister src2) { DCHECK(IsEnabled(NEON)); // Qd = vmin(Qn, Qm) SIMD floating point MIN. // Instruction details available in ARM DDI 0406C.b, A8-928. emit(EncodeNeonBinOp(VMINF, dst, src1, src2)); } void Assembler::vmin(NeonDataType dt, QwNeonRegister dst, QwNeonRegister src1, QwNeonRegister src2) { DCHECK(IsEnabled(NEON)); // Qd = vmin(Qn, Qm) SIMD integer MIN. // Instruction details available in ARM DDI 0406C.b, A8-926. emit(EncodeNeonBinOp(VMIN, dt, dst, src1, src2)); } void Assembler::vmax(QwNeonRegister dst, QwNeonRegister src1, QwNeonRegister src2) { DCHECK(IsEnabled(NEON)); // Qd = vmax(Qn, Qm) SIMD floating point MAX. // Instruction details available in ARM DDI 0406C.b, A8-928. emit(EncodeNeonBinOp(VMAXF, dst, src1, src2)); } void Assembler::vmax(NeonDataType dt, QwNeonRegister dst, QwNeonRegister src1, QwNeonRegister src2) { DCHECK(IsEnabled(NEON)); // Qd = vmax(Qn, Qm) SIMD integer MAX. // Instruction details available in ARM DDI 0406C.b, A8-926. emit(EncodeNeonBinOp(VMAX, dt, dst, src1, src2)); } enum NeonShiftOp { VSHL, VSHR, VSLI, VSRI, VSRA }; static Instr EncodeNeonShiftRegisterOp(NeonShiftOp op, NeonDataType dt, NeonRegType reg_type, int dst_code, int src_code, int shift_code) { DCHECK_EQ(op, VSHL); int op_encoding = 0; int vd, d; NeonSplitCode(reg_type, dst_code, &vd, &d, &op_encoding); int vm, m; NeonSplitCode(reg_type, src_code, &vm, &m, &op_encoding); int vn, n; NeonSplitCode(reg_type, shift_code, &vn, &n, &op_encoding); int size = NeonSz(dt); int u = NeonU(dt); return 0x1E4U * B23 | u * B24 | d * B22 | size * B20 | vn * B16 | vd * B12 | 0x4 * B8 | n * B7 | m * B5 | vm | op_encoding; } static Instr EncodeNeonShiftOp(NeonShiftOp op, NeonSize size, bool is_unsigned, NeonRegType reg_type, int dst_code, int src_code, int shift) { int size_in_bits = kBitsPerByte << static_cast<int>(size); int op_encoding = 0, imm6 = 0, L = 0; switch (op) { case VSHL: { DCHECK(shift >= 0 && size_in_bits > shift); imm6 = size_in_bits + shift; op_encoding = 0x5 * B8; break; } case VSHR: { DCHECK(shift > 0 && size_in_bits >= shift); imm6 = 2 * size_in_bits - shift; if (is_unsigned) op_encoding |= B24; break; } case VSLI: { DCHECK(shift >= 0 && size_in_bits > shift); imm6 = size_in_bits + shift; op_encoding = B24 | 0x5 * B8; break; } case VSRI: { DCHECK(shift > 0 && size_in_bits >= shift); imm6 = 2 * size_in_bits - shift; op_encoding = B24 | 0x4 * B8; break; } case VSRA: { DCHECK(shift > 0 && size_in_bits >= shift); imm6 = 2 * size_in_bits - shift; op_encoding = B8; if (is_unsigned) op_encoding |= B24; break; } default: UNREACHABLE(); } L = imm6 >> 6; imm6 &= 0x3F; int vd, d; NeonSplitCode(reg_type, dst_code, &vd, &d, &op_encoding); int vm, m; NeonSplitCode(reg_type, src_code, &vm, &m, &op_encoding); return 0x1E5U * B23 | d * B22 | imm6 * B16 | vd * B12 | L * B7 | m * B5 | B4 | vm | op_encoding; } void Assembler::vshl(NeonDataType dt, QwNeonRegister dst, QwNeonRegister src, int shift) { DCHECK(IsEnabled(NEON)); // Qd = vshl(Qm, bits) SIMD shift left immediate. // Instruction details available in ARM DDI 0406C.b, A8-1046. emit(EncodeNeonShiftOp(VSHL, NeonDataTypeToSize(dt), false, NEON_Q, dst.code(), src.code(), shift)); } void Assembler::vshl(NeonDataType dt, QwNeonRegister dst, QwNeonRegister src, QwNeonRegister shift) { DCHECK(IsEnabled(NEON)); // Qd = vshl(Qm, Qn) SIMD shift left Register. // Instruction details available in ARM DDI 0487A.a, F8-3340.. emit(EncodeNeonShiftRegisterOp(VSHL, dt, NEON_Q, dst.code(), src.code(), shift.code())); } void Assembler::vshr(NeonDataType dt, DwVfpRegister dst, DwVfpRegister src, int shift) { DCHECK(IsEnabled(NEON)); // Dd = vshr(Dm, bits) SIMD shift right immediate. // Instruction details available in ARM DDI 0406C.b, A8-1052. emit(EncodeNeonShiftOp(VSHR, NeonDataTypeToSize(dt), NeonU(dt), NEON_D, dst.code(), src.code(), shift)); } void Assembler::vshr(NeonDataType dt, QwNeonRegister dst, QwNeonRegister src, int shift) { DCHECK(IsEnabled(NEON)); // Qd = vshr(Qm, bits) SIMD shift right immediate. // Instruction details available in ARM DDI 0406C.b, A8-1052. emit(EncodeNeonShiftOp(VSHR, NeonDataTypeToSize(dt), NeonU(dt), NEON_Q, dst.code(), src.code(), shift)); } void Assembler::vsli(NeonSize size, DwVfpRegister dst, DwVfpRegister src, int shift) { DCHECK(IsEnabled(NEON)); // Dd = vsli(Dm, bits) SIMD shift left and insert. // Instruction details available in ARM DDI 0406C.b, A8-1056. emit(EncodeNeonShiftOp(VSLI, size, false, NEON_D, dst.code(), src.code(), shift)); } void Assembler::vsri(NeonSize size, DwVfpRegister dst, DwVfpRegister src, int shift) { DCHECK(IsEnabled(NEON)); // Dd = vsri(Dm, bits) SIMD shift right and insert. // Instruction details available in ARM DDI 0406C.b, A8-1062. emit(EncodeNeonShiftOp(VSRI, size, false, NEON_D, dst.code(), src.code(), shift)); } void Assembler::vsra(NeonDataType dt, DwVfpRegister dst, DwVfpRegister src, int imm) { DCHECK(IsEnabled(NEON)); // Dd = vsra(Dm, imm) SIMD shift right and accumulate. // Instruction details available in ARM DDI 0487F.b, F6-5569. emit(EncodeNeonShiftOp(VSRA, NeonDataTypeToSize(dt), NeonU(dt), NEON_D, dst.code(), src.code(), imm)); } void Assembler::vrecpe(QwNeonRegister dst, QwNeonRegister src) { DCHECK(IsEnabled(NEON)); // Qd = vrecpe(Qm) SIMD reciprocal estimate. // Instruction details available in ARM DDI 0406C.b, A8-1024. emit(EncodeNeonUnaryOp(VRECPE, NEON_Q, Neon32, dst.code(), src.code())); } void Assembler::vrsqrte(QwNeonRegister dst, QwNeonRegister src) { DCHECK(IsEnabled(NEON)); // Qd = vrsqrte(Qm) SIMD reciprocal square root estimate. // Instruction details available in ARM DDI 0406C.b, A8-1038. emit(EncodeNeonUnaryOp(VRSQRTE, NEON_Q, Neon32, dst.code(), src.code())); } void Assembler::vrecps(QwNeonRegister dst, QwNeonRegister src1, QwNeonRegister src2) { DCHECK(IsEnabled(NEON)); // Qd = vrecps(Qn, Qm) SIMD reciprocal refinement step. // Instruction details available in ARM DDI 0406C.b, A8-1026. emit(EncodeNeonBinOp(VRECPS, dst, src1, src2)); } void Assembler::vrsqrts(QwNeonRegister dst, QwNeonRegister src1, QwNeonRegister src2) { DCHECK(IsEnabled(NEON)); // Qd = vrsqrts(Qn, Qm) SIMD reciprocal square root refinement step. // Instruction details available in ARM DDI 0406C.b, A8-1040. emit(EncodeNeonBinOp(VRSQRTS, dst, src1, src2)); } enum NeonPairwiseOp { VPADD, VPMIN, VPMAX }; static Instr EncodeNeonPairwiseOp(NeonPairwiseOp op, NeonDataType dt, DwVfpRegister dst, DwVfpRegister src1, DwVfpRegister src2) { int op_encoding = 0; switch (op) { case VPADD: op_encoding = 0xB * B8 | B4; break; case VPMIN: op_encoding = 0xA * B8 | B4; break; case VPMAX: op_encoding = 0xA * B8; break; default: UNREACHABLE(); } int vd, d; dst.split_code(&vd, &d); int vn, n; src1.split_code(&vn, &n); int vm, m; src2.split_code(&vm, &m); int size = NeonSz(dt); int u = NeonU(dt); return 0x1E4U * B23 | u * B24 | d * B22 | size * B20 | vn * B16 | vd * B12 | n * B7 | m * B5 | vm | op_encoding; } void Assembler::vpadd(DwVfpRegister dst, DwVfpRegister src1, DwVfpRegister src2) { DCHECK(IsEnabled(NEON)); // Dd = vpadd(Dn, Dm) SIMD floating point pairwise ADD. // Instruction details available in ARM DDI 0406C.b, A8-982. int vd, d; dst.split_code(&vd, &d); int vn, n; src1.split_code(&vn, &n); int vm, m; src2.split_code(&vm, &m); emit(0x1E6U * B23 | d * B22 | vn * B16 | vd * B12 | 0xD * B8 | n * B7 | m * B5 | vm); } void Assembler::vpadd(NeonSize size, DwVfpRegister dst, DwVfpRegister src1, DwVfpRegister src2) { DCHECK(IsEnabled(NEON)); // Dd = vpadd(Dn, Dm) SIMD integer pairwise ADD. // Instruction details available in ARM DDI 0406C.b, A8-980. emit(EncodeNeonPairwiseOp(VPADD, NeonSizeToDataType(size), dst, src1, src2)); } void Assembler::vpmin(NeonDataType dt, DwVfpRegister dst, DwVfpRegister src1, DwVfpRegister src2) { DCHECK(IsEnabled(NEON)); // Dd = vpmin(Dn, Dm) SIMD integer pairwise MIN. // Instruction details available in ARM DDI 0406C.b, A8-986. emit(EncodeNeonPairwiseOp(VPMIN, dt, dst, src1, src2)); } void Assembler::vpmax(NeonDataType dt, DwVfpRegister dst, DwVfpRegister src1, DwVfpRegister src2) { DCHECK(IsEnabled(NEON)); // Dd = vpmax(Dn, Dm) SIMD integer pairwise MAX. // Instruction details available in ARM DDI 0406C.b, A8-986. emit(EncodeNeonPairwiseOp(VPMAX, dt, dst, src1, src2)); } void Assembler::vrintm(NeonDataType dt, const QwNeonRegister dst, const QwNeonRegister src) { // SIMD vector round floating-point to integer towards -Infinity. // See ARM DDI 0487F.b, F6-5493. DCHECK(IsEnabled(ARMv8)); emit(EncodeNeonUnaryOp(VRINTM, NEON_Q, NeonSize(dt), dst.code(), src.code())); } void Assembler::vrintn(NeonDataType dt, const QwNeonRegister dst, const QwNeonRegister src) { // SIMD vector round floating-point to integer to Nearest. // See ARM DDI 0487F.b, F6-5497. DCHECK(IsEnabled(ARMv8)); emit(EncodeNeonUnaryOp(VRINTN, NEON_Q, NeonSize(dt), dst.code(), src.code())); } void Assembler::vrintp(NeonDataType dt, const QwNeonRegister dst, const QwNeonRegister src) { // SIMD vector round floating-point to integer towards +Infinity. // See ARM DDI 0487F.b, F6-5501. DCHECK(IsEnabled(ARMv8)); emit(EncodeNeonUnaryOp(VRINTP, NEON_Q, NeonSize(dt), dst.code(), src.code())); } void Assembler::vrintz(NeonDataType dt, const QwNeonRegister dst, const QwNeonRegister src) { // SIMD vector round floating-point to integer towards Zero. // See ARM DDI 0487F.b, F6-5511. DCHECK(IsEnabled(ARMv8)); emit(EncodeNeonUnaryOp(VRINTZ, NEON_Q, NeonSize(dt), dst.code(), src.code())); } void Assembler::vtst(NeonSize size, QwNeonRegister dst, QwNeonRegister src1, QwNeonRegister src2) { DCHECK(IsEnabled(NEON)); // Qd = vtst(Qn, Qm) SIMD test integer operands. // Instruction details available in ARM DDI 0406C.b, A8-1098. emit(EncodeNeonBinOp(VTST, size, dst, src1, src2)); } void Assembler::vceq(QwNeonRegister dst, QwNeonRegister src1, QwNeonRegister src2) { DCHECK(IsEnabled(NEON)); // Qd = vceq(Qn, Qm) SIMD floating point compare equal. // Instruction details available in ARM DDI 0406C.b, A8-844. emit(EncodeNeonBinOp(VCEQF, dst, src1, src2)); } void Assembler::vceq(NeonSize size, QwNeonRegister dst, QwNeonRegister src1, QwNeonRegister src2) { DCHECK(IsEnabled(NEON)); // Qd = vceq(Qn, Qm) SIMD integer compare equal. // Instruction details available in ARM DDI 0406C.b, A8-844. emit(EncodeNeonBinOp(VCEQ, size, dst, src1, src2)); } void Assembler::vceq(NeonSize size, QwNeonRegister dst, QwNeonRegister src1, int value) { DCHECK(IsEnabled(NEON)); DCHECK_EQ(0, value); // Qd = vceq(Qn, Qm, #0) Vector Compare Equal to Zero. // Instruction details available in ARM DDI 0406C.d, A8-847. emit(EncodeNeonUnaryOp(VCEQ0, NEON_Q, size, dst.code(), src1.code())); } void Assembler::vcge(QwNeonRegister dst, QwNeonRegister src1, QwNeonRegister src2) { DCHECK(IsEnabled(NEON)); // Qd = vcge(Qn, Qm) SIMD floating point compare greater or equal. // Instruction details available in ARM DDI 0406C.b, A8-848. emit(EncodeNeonBinOp(VCGEF, dst, src1, src2)); } void Assembler::vcge(NeonDataType dt, QwNeonRegister dst, QwNeonRegister src1, QwNeonRegister src2) { DCHECK(IsEnabled(NEON)); // Qd = vcge(Qn, Qm) SIMD integer compare greater or equal. // Instruction details available in ARM DDI 0406C.b, A8-848. emit(EncodeNeonBinOp(VCGE, dt, dst, src1, src2)); } void Assembler::vcgt(QwNeonRegister dst, QwNeonRegister src1, QwNeonRegister src2) { DCHECK(IsEnabled(NEON)); // Qd = vcgt(Qn, Qm) SIMD floating point compare greater than. // Instruction details available in ARM DDI 0406C.b, A8-852. emit(EncodeNeonBinOp(VCGTF, dst, src1, src2)); } void Assembler::vcgt(NeonDataType dt, QwNeonRegister dst, QwNeonRegister src1, QwNeonRegister src2) { DCHECK(IsEnabled(NEON)); // Qd = vcgt(Qn, Qm) SIMD integer compare greater than. // Instruction details available in ARM DDI 0406C.b, A8-852. emit(EncodeNeonBinOp(VCGT, dt, dst, src1, src2)); } void Assembler::vclt(NeonSize size, QwNeonRegister dst, QwNeonRegister src, int value) { DCHECK(IsEnabled(NEON)); DCHECK_EQ(0, value); // vclt.<size>(Qn, Qm, #0) SIMD Vector Compare Less Than Zero. // Instruction details available in ARM DDI 0487F.b, F6-5072. emit(EncodeNeonUnaryOp(VCLT0, NEON_Q, size, dst.code(), src.code())); } void Assembler::vrhadd(NeonDataType dt, QwNeonRegister dst, QwNeonRegister src1, QwNeonRegister src2) { DCHECK(IsEnabled(NEON)); // Qd = vrhadd(Qn, Qm) SIMD integer rounding halving add. // Instruction details available in ARM DDI 0406C.b, A8-1030. emit(EncodeNeonBinOp(VRHADD, dt, dst, src1, src2)); } void Assembler::vext(QwNeonRegister dst, QwNeonRegister src1, QwNeonRegister src2, int bytes) { DCHECK(IsEnabled(NEON)); // Qd = vext(Qn, Qm) SIMD byte extract. // Instruction details available in ARM DDI 0406C.b, A8-890. int vd, d; dst.split_code(&vd, &d); int vn, n; src1.split_code(&vn, &n); int vm, m; src2.split_code(&vm, &m); DCHECK_GT(16, bytes); emit(0x1E5U * B23 | d * B22 | 0x3 * B20 | vn * B16 | vd * B12 | bytes * B8 | n * B7 | B6 | m * B5 | vm); } void Assembler::vzip(NeonSize size, DwVfpRegister src1, DwVfpRegister src2) { if (size == Neon32) { // vzip.32 Dd, Dm is a pseudo-op for vtrn.32 Dd, Dm. vtrn(size, src1, src2); } else { DCHECK(IsEnabled(NEON)); // vzip.<size>(Dn, Dm) SIMD zip (interleave). // Instruction details available in ARM DDI 0406C.b, A8-1102. emit(EncodeNeonUnaryOp(VZIP, NEON_D, size, src1.code(), src2.code())); } } void Assembler::vzip(NeonSize size, QwNeonRegister src1, QwNeonRegister src2) { DCHECK(IsEnabled(NEON)); // vzip.<size>(Qn, Qm) SIMD zip (interleave). // Instruction details available in ARM DDI 0406C.b, A8-1102. emit(EncodeNeonUnaryOp(VZIP, NEON_Q, size, src1.code(), src2.code())); } void Assembler::vuzp(NeonSize size, DwVfpRegister src1, DwVfpRegister src2) { if (size == Neon32) { // vuzp.32 Dd, Dm is a pseudo-op for vtrn.32 Dd, Dm. vtrn(size, src1, src2); } else { DCHECK(IsEnabled(NEON)); // vuzp.<size>(Dn, Dm) SIMD un-zip (de-interleave). // Instruction details available in ARM DDI 0406C.b, A8-1100. emit(EncodeNeonUnaryOp(VUZP, NEON_D, size, src1.code(), src2.code())); } } void Assembler::vuzp(NeonSize size, QwNeonRegister src1, QwNeonRegister src2) { DCHECK(IsEnabled(NEON)); // vuzp.<size>(Qn, Qm) SIMD un-zip (de-interleave). // Instruction details available in ARM DDI 0406C.b, A8-1100. emit(EncodeNeonUnaryOp(VUZP, NEON_Q, size, src1.code(), src2.code())); } void Assembler::vrev16(NeonSize size, QwNeonRegister dst, QwNeonRegister src) { DCHECK(IsEnabled(NEON)); // Qd = vrev16.<size>(Qm) SIMD element reverse. // Instruction details available in ARM DDI 0406C.b, A8-1028. emit(EncodeNeonUnaryOp(VREV16, NEON_Q, size, dst.code(), src.code())); } void Assembler::vrev32(NeonSize size, QwNeonRegister dst, QwNeonRegister src) { DCHECK(IsEnabled(NEON)); // Qd = vrev32.<size>(Qm) SIMD element reverse. // Instruction details available in ARM DDI 0406C.b, A8-1028. emit(EncodeNeonUnaryOp(VREV32, NEON_Q, size, dst.code(), src.code())); } void Assembler::vrev64(NeonSize size, QwNeonRegister dst, QwNeonRegister src) { DCHECK(IsEnabled(NEON)); // Qd = vrev64.<size>(Qm) SIMD element reverse. // Instruction details available in ARM DDI 0406C.b, A8-1028. emit(EncodeNeonUnaryOp(VREV64, NEON_Q, size, dst.code(), src.code())); } void Assembler::vtrn(NeonSize size, DwVfpRegister src1, DwVfpRegister src2) { DCHECK(IsEnabled(NEON)); // vtrn.<size>(Dn, Dm) SIMD element transpose. // Instruction details available in ARM DDI 0406C.b, A8-1096. emit(EncodeNeonUnaryOp(VTRN, NEON_D, size, src1.code(), src2.code())); } void Assembler::vtrn(NeonSize size, QwNeonRegister src1, QwNeonRegister src2) { DCHECK(IsEnabled(NEON)); // vtrn.<size>(Qn, Qm) SIMD element transpose. // Instruction details available in ARM DDI 0406C.b, A8-1096. emit(EncodeNeonUnaryOp(VTRN, NEON_Q, size, src1.code(), src2.code())); } void Assembler::vpadal(NeonDataType dt, QwNeonRegister dst, QwNeonRegister src) { DCHECK(IsEnabled(NEON)); // vpadal.<dt>(Qd, Qm) SIMD Vector Pairwise Add and Accumulate Long emit(EncodeNeonUnaryOp(NeonU(dt) ? VPADAL_U : VPADAL_S, NEON_Q, NeonDataTypeToSize(dt), dst.code(), src.code())); } void Assembler::vpaddl(NeonDataType dt, QwNeonRegister dst, QwNeonRegister src) { DCHECK(IsEnabled(NEON)); // vpaddl.<dt>(Qd, Qm) SIMD Vector Pairwise Add Long. emit(EncodeNeonUnaryOp(NeonU(dt) ? VPADDL_U : VPADDL_S, NEON_Q, NeonDataTypeToSize(dt), dst.code(), src.code())); } void Assembler::vqrdmulh(NeonDataType dt, QwNeonRegister dst, QwNeonRegister src1, QwNeonRegister src2) { DCHECK(IsEnabled(NEON)); DCHECK(dt == NeonS16 || dt == NeonS32); emit(EncodeNeonBinOp(VQRDMULH, dt, dst, src1, src2)); } void Assembler::vcnt(QwNeonRegister dst, QwNeonRegister src) { // Qd = vcnt(Qm) SIMD Vector Count Set Bits. // Instruction details available at ARM DDI 0487F.b, F6-5094. DCHECK(IsEnabled(NEON)); emit(EncodeNeonUnaryOp(VCNT, NEON_Q, Neon8, dst.code(), src.code())); } // Encode NEON vtbl / vtbx instruction. static Instr EncodeNeonVTB(DwVfpRegister dst, const NeonListOperand& list, DwVfpRegister index, bool vtbx) { // Dd = vtbl(table, Dm) SIMD vector permute, zero at out of range indices. // Instruction details available in ARM DDI 0406C.b, A8-1094. // Dd = vtbx(table, Dm) SIMD vector permute, skip out of range indices. // Instruction details available in ARM DDI 0406C.b, A8-1094. int vd, d; dst.split_code(&vd, &d); int vn, n; list.base().split_code(&vn, &n); int vm, m; index.split_code(&vm, &m); int op = vtbx ? 1 : 0; // vtbl = 0, vtbx = 1. return 0x1E7U * B23 | d * B22 | 0x3 * B20 | vn * B16 | vd * B12 | 0x2 * B10 | list.length() * B8 | n * B7 | op * B6 | m * B5 | vm; } void Assembler::vtbl(DwVfpRegister dst, const NeonListOperand& list, DwVfpRegister index) { DCHECK(IsEnabled(NEON)); emit(EncodeNeonVTB(dst, list, index, false)); } void Assembler::vtbx(DwVfpRegister dst, const NeonListOperand& list, DwVfpRegister index) { DCHECK(IsEnabled(NEON)); emit(EncodeNeonVTB(dst, list, index, true)); } // Pseudo instructions. void Assembler::nop(int type) { // ARMv6{K/T2} and v7 have an actual NOP instruction but it serializes // some of the CPU's pipeline and has to issue. Older ARM chips simply used // MOV Rx, Rx as NOP and it performs better even in newer CPUs. // We therefore use MOV Rx, Rx, even on newer CPUs, and use Rx to encode // a type. DCHECK(0 <= type && type <= 14); // mov pc, pc isn't a nop. emit(al | 13 * B21 | type * B12 | type); } void Assembler::pop() { add(sp, sp, Operand(kPointerSize)); } bool Assembler::IsMovT(Instr instr) { instr &= ~(((kNumberOfConditions - 1) << 28) | // Mask off conditions ((kNumRegisters - 1) * B12) | // mask out register EncodeMovwImmediate(0xFFFF)); // mask out immediate value return instr == kMovtPattern; } bool Assembler::IsMovW(Instr instr) { instr &= ~(((kNumberOfConditions - 1) << 28) | // Mask off conditions ((kNumRegisters - 1) * B12) | // mask out destination EncodeMovwImmediate(0xFFFF)); // mask out immediate value return instr == kMovwPattern; } Instr Assembler::GetMovTPattern() { return kMovtPattern; } Instr Assembler::GetMovWPattern() { return kMovwPattern; } Instr Assembler::EncodeMovwImmediate(uint32_t immediate) { DCHECK_LT(immediate, 0x10000); return ((immediate & 0xF000) << 4) | (immediate & 0xFFF); } Instr Assembler::PatchMovwImmediate(Instr instruction, uint32_t immediate) { instruction &= ~EncodeMovwImmediate(0xFFFF); return instruction | EncodeMovwImmediate(immediate); } int Assembler::DecodeShiftImm(Instr instr) { int rotate = Instruction::RotateValue(instr) * 2; int immed8 = Instruction::Immed8Value(instr); return base::bits::RotateRight32(immed8, rotate); } Instr Assembler::PatchShiftImm(Instr instr, int immed) { uint32_t rotate_imm = 0; uint32_t immed_8 = 0; bool immed_fits = FitsShifter(immed, &rotate_imm, &immed_8, nullptr); DCHECK(immed_fits); USE(immed_fits); return (instr & ~kOff12Mask) | (rotate_imm << 8) | immed_8; } bool Assembler::IsNop(Instr instr, int type) { DCHECK(0 <= type && type <= 14); // mov pc, pc isn't a nop. // Check for mov rx, rx where x = type. return instr == (al | 13 * B21 | type * B12 | type); } bool Assembler::IsMovImmed(Instr instr) { return (instr & kMovImmedMask) == kMovImmedPattern; } bool Assembler::IsOrrImmed(Instr instr) { return (instr & kOrrImmedMask) == kOrrImmedPattern; } // static bool Assembler::ImmediateFitsAddrMode1Instruction(int32_t imm32) { uint32_t dummy1; uint32_t dummy2; return FitsShifter(imm32, &dummy1, &dummy2, nullptr); } bool Assembler::ImmediateFitsAddrMode2Instruction(int32_t imm32) { return is_uint12(abs(imm32)); } // Debugging. void Assembler::RecordConstPool(int size) { // We only need this for debugger support, to correctly compute offsets in the // code. RecordRelocInfo(RelocInfo::CONST_POOL, static_cast<intptr_t>(size)); } void Assembler::GrowBuffer() { DCHECK_EQ(buffer_start_, buffer_->start()); // Compute new buffer size. int old_size = buffer_->size(); int new_size = std::min(2 * old_size, old_size + 1 * MB); // Some internal data structures overflow for very large buffers, // they must ensure that kMaximalBufferSize is not too large. if (new_size > kMaximalBufferSize) { V8::FatalProcessOutOfMemory(nullptr, "Assembler::GrowBuffer"); } // Set up new buffer. std::unique_ptr<AssemblerBuffer> new_buffer = buffer_->Grow(new_size); DCHECK_EQ(new_size, new_buffer->size()); byte* new_start = new_buffer->start(); // Copy the data. int pc_delta = new_start - buffer_start_; int rc_delta = (new_start + new_size) - (buffer_start_ + old_size); size_t reloc_size = (buffer_start_ + old_size) - reloc_info_writer.pos(); MemMove(new_start, buffer_start_, pc_offset()); byte* new_reloc_start = reinterpret_cast<byte*>( reinterpret_cast<Address>(reloc_info_writer.pos()) + rc_delta); MemMove(new_reloc_start, reloc_info_writer.pos(), reloc_size); // Switch buffers. buffer_ = std::move(new_buffer); buffer_start_ = new_start; pc_ = reinterpret_cast<byte*>(reinterpret_cast<Address>(pc_) + pc_delta); byte* new_last_pc = reinterpret_cast<byte*>( reinterpret_cast<Address>(reloc_info_writer.last_pc()) + pc_delta); reloc_info_writer.Reposition(new_reloc_start, new_last_pc); // None of our relocation types are pc relative pointing outside the code // buffer nor pc absolute pointing inside the code buffer, so there is no need // to relocate any emitted relocation entries. } void Assembler::db(uint8_t data) { // db is used to write raw data. The constant pool should be emitted or // blocked before using db. DCHECK(is_const_pool_blocked() || pending_32_bit_constants_.empty()); CheckBuffer(); *reinterpret_cast<uint8_t*>(pc_) = data; pc_ += sizeof(uint8_t); } void Assembler::dd(uint32_t data, RelocInfo::Mode rmode) { // dd is used to write raw data. The constant pool should be emitted or // blocked before using dd. DCHECK(is_const_pool_blocked() || pending_32_bit_constants_.empty()); CheckBuffer(); if (!RelocInfo::IsNoInfo(rmode)) { DCHECK(RelocInfo::IsDataEmbeddedObject(rmode) || RelocInfo::IsLiteralConstant(rmode)); RecordRelocInfo(rmode); } base::WriteUnalignedValue(reinterpret_cast<Address>(pc_), data); pc_ += sizeof(uint32_t); } void Assembler::dq(uint64_t value, RelocInfo::Mode rmode) { // dq is used to write raw data. The constant pool should be emitted or // blocked before using dq. DCHECK(is_const_pool_blocked() || pending_32_bit_constants_.empty()); CheckBuffer(); if (!RelocInfo::IsNoInfo(rmode)) { DCHECK(RelocInfo::IsDataEmbeddedObject(rmode) || RelocInfo::IsLiteralConstant(rmode)); RecordRelocInfo(rmode); } base::WriteUnalignedValue(reinterpret_cast<Address>(pc_), value); pc_ += sizeof(uint64_t); } void Assembler::RecordRelocInfo(RelocInfo::Mode rmode, intptr_t data) { if (!ShouldRecordRelocInfo(rmode)) return; DCHECK_GE(buffer_space(), kMaxRelocSize); // too late to grow buffer here RelocInfo rinfo(reinterpret_cast<Address>(pc_), rmode, data, Code()); reloc_info_writer.Write(&rinfo); } void Assembler::ConstantPoolAddEntry(int position, RelocInfo::Mode rmode, intptr_t value) { DCHECK(rmode != RelocInfo::CONST_POOL); // We can share CODE_TARGETs and embedded objects, but we must make sure we // only emit one reloc info for them (thus delta patching will apply the delta // only once). At the moment, we do not deduplicate heap object request which // are indicated by value == 0. bool sharing_ok = RelocInfo::IsShareableRelocMode(rmode) || (rmode == RelocInfo::CODE_TARGET && value != 0) || (RelocInfo::IsEmbeddedObjectMode(rmode) && value != 0); DCHECK_LT(pending_32_bit_constants_.size(), kMaxNumPending32Constants); if (first_const_pool_32_use_ < 0) { DCHECK(pending_32_bit_constants_.empty()); DCHECK_EQ(constant_pool_deadline_, kMaxInt); first_const_pool_32_use_ = position; constant_pool_deadline_ = position + kCheckPoolDeadline; } else { DCHECK(!pending_32_bit_constants_.empty()); } ConstantPoolEntry entry(position, value, sharing_ok, rmode); bool shared = false; if (sharing_ok) { // Merge the constant, if possible. for (size_t i = 0; i < pending_32_bit_constants_.size(); i++) { ConstantPoolEntry& current_entry = pending_32_bit_constants_[i]; if (!current_entry.sharing_ok()) continue; if (entry.value() == current_entry.value() && entry.rmode() == current_entry.rmode()) { entry.set_merged_index(i); shared = true; break; } } } pending_32_bit_constants_.emplace_back(entry); // Make sure the constant pool is not emitted in place of the next // instruction for which we just recorded relocation info. BlockConstPoolFor(1); // Emit relocation info. if (MustOutputRelocInfo(rmode, this) && !shared) { RecordRelocInfo(rmode); } } void Assembler::BlockConstPoolFor(int instructions) { int pc_limit = pc_offset() + instructions * kInstrSize; if (no_const_pool_before_ < pc_limit) { no_const_pool_before_ = pc_limit; } // If we're due a const pool check before the block finishes, move it to just // after the block. if (constant_pool_deadline_ < no_const_pool_before_) { // Make sure that the new deadline isn't too late (including a jump and the // constant pool marker). DCHECK_LE(no_const_pool_before_, first_const_pool_32_use_ + kMaxDistToIntPool); constant_pool_deadline_ = no_const_pool_before_; } } void Assembler::CheckConstPool(bool force_emit, bool require_jump) { // Some short sequence of instruction mustn't be broken up by constant pool // emission, such sequences are protected by calls to BlockConstPoolFor and // BlockConstPoolScope. if (is_const_pool_blocked()) { // Something is wrong if emission is forced and blocked at the same time. DCHECK(!force_emit); return; } // There is nothing to do if there are no pending constant pool entries. if (pending_32_bit_constants_.empty()) { // We should only fall into this case if we're either trying to forcing // emission or opportunistically checking after a jump. DCHECK(force_emit || !require_jump); return; } // We emit a constant pool when: // * requested to do so by parameter force_emit (e.g. after each function). // * the distance from the first instruction accessing the constant pool to // the first constant pool entry will exceed its limit the next time the // pool is checked. // * the instruction doesn't require a jump after itself to jump over the // constant pool, and we're getting close to running out of range. if (!force_emit) { DCHECK_NE(first_const_pool_32_use_, -1); int dist32 = pc_offset() - first_const_pool_32_use_; if (require_jump) { // We should only be on this path if we've exceeded our deadline. DCHECK_GE(dist32, kCheckPoolDeadline); } else if (dist32 < kCheckPoolDeadline / 2) { return; } } int size_after_marker = pending_32_bit_constants_.size() * kPointerSize; // Deduplicate constants. for (size_t i = 0; i < pending_32_bit_constants_.size(); i++) { ConstantPoolEntry& entry = pending_32_bit_constants_[i]; if (entry.is_merged()) size_after_marker -= kPointerSize; } // Check that the code buffer is large enough before emitting the constant // pool (include the jump over the pool and the constant pool marker and // the gap to the relocation information). int jump_instr = require_jump ? kInstrSize : 0; int size_up_to_marker = jump_instr + kInstrSize; int size = size_up_to_marker + size_after_marker; int needed_space = size + kGap; while (buffer_space() <= needed_space) GrowBuffer(); { ASM_CODE_COMMENT_STRING(this, "Constant Pool"); // Block recursive calls to CheckConstPool. BlockConstPoolScope block_const_pool(this); RecordConstPool(size); Label size_check; bind(&size_check); // Emit jump over constant pool if necessary. Label after_pool; if (require_jump) { b(&after_pool); } // Put down constant pool marker "Undefined instruction". // The data size helps disassembly know what to print. emit(kConstantPoolMarker | EncodeConstantPoolLength(size_after_marker / kPointerSize)); // The first entry in the constant pool should also be the first CHECK_EQ(first_const_pool_32_use_, pending_32_bit_constants_[0].position()); CHECK(!pending_32_bit_constants_[0].is_merged()); // Make sure we're not emitting the constant too late. CHECK_LE(pc_offset(), first_const_pool_32_use_ + kMaxDistToPcRelativeConstant); // Check that the code buffer is large enough before emitting the constant // pool (this includes the gap to the relocation information). int needed_space = pending_32_bit_constants_.size() * kPointerSize + kGap; while (buffer_space() <= needed_space) { GrowBuffer(); } // Emit 32-bit constant pool entries. for (size_t i = 0; i < pending_32_bit_constants_.size(); i++) { ConstantPoolEntry& entry = pending_32_bit_constants_[i]; Instr instr = instr_at(entry.position()); // 64-bit loads shouldn't get here. DCHECK(!IsVldrDPcImmediateOffset(instr)); DCHECK(!IsMovW(instr)); DCHECK(IsLdrPcImmediateOffset(instr) && GetLdrRegisterImmediateOffset(instr) == 0); int delta = pc_offset() - entry.position() - Instruction::kPcLoadDelta; DCHECK(is_uint12(delta)); // 0 is the smallest delta: // ldr rd, [pc, #0] // constant pool marker // data if (entry.is_merged()) { DCHECK(entry.sharing_ok()); ConstantPoolEntry& merged = pending_32_bit_constants_[entry.merged_index()]; DCHECK(entry.value() == merged.value()); DCHECK_LT(merged.position(), entry.position()); Instr merged_instr = instr_at(merged.position()); DCHECK(IsLdrPcImmediateOffset(merged_instr)); delta = GetLdrRegisterImmediateOffset(merged_instr); delta += merged.position() - entry.position(); } instr_at_put(entry.position(), SetLdrRegisterImmediateOffset(instr, delta)); if (!entry.is_merged()) { emit(entry.value()); } } pending_32_bit_constants_.clear(); first_const_pool_32_use_ = -1; DCHECK_EQ(size, SizeOfCodeGeneratedSince(&size_check)); if (after_pool.is_linked()) { bind(&after_pool); } } // Since a constant pool was just emitted, we don't need another check until // the next constant pool entry is added. constant_pool_deadline_ = kMaxInt; } PatchingAssembler::PatchingAssembler(const AssemblerOptions& options, byte* address, int instructions) : Assembler(options, ExternalAssemblerBuffer( address, instructions * kInstrSize + kGap)) { DCHECK_EQ(reloc_info_writer.pos(), buffer_start_ + buffer_->size()); } PatchingAssembler::~PatchingAssembler() { // Check that we don't have any pending constant pools. DCHECK(pending_32_bit_constants_.empty()); // Check that the code was patched as expected. DCHECK_EQ(pc_, buffer_start_ + buffer_->size() - kGap); DCHECK_EQ(reloc_info_writer.pos(), buffer_start_ + buffer_->size()); } void PatchingAssembler::Emit(Address addr) { emit(static_cast<Instr>(addr)); } void PatchingAssembler::PadWithNops() { DCHECK_LE(pc_, buffer_start_ + buffer_->size() - kGap); while (pc_ < buffer_start_ + buffer_->size() - kGap) { nop(); } } UseScratchRegisterScope::UseScratchRegisterScope(Assembler* assembler) : assembler_(assembler), old_available_(*assembler->GetScratchRegisterList()), old_available_vfp_(*assembler->GetScratchVfpRegisterList()) {} UseScratchRegisterScope::~UseScratchRegisterScope() { *assembler_->GetScratchRegisterList() = old_available_; *assembler_->GetScratchVfpRegisterList() = old_available_vfp_; } Register UseScratchRegisterScope::Acquire() { RegList* available = assembler_->GetScratchRegisterList(); DCHECK_NOT_NULL(available); return available->PopFirst(); } LoadStoreLaneParams::LoadStoreLaneParams(MachineRepresentation rep, uint8_t laneidx) { if (rep == MachineRepresentation::kWord8) { *this = LoadStoreLaneParams(laneidx, Neon8, 8); } else if (rep == MachineRepresentation::kWord16) { *this = LoadStoreLaneParams(laneidx, Neon16, 4); } else if (rep == MachineRepresentation::kWord32) { *this = LoadStoreLaneParams(laneidx, Neon32, 2); } else if (rep == MachineRepresentation::kWord64) { *this = LoadStoreLaneParams(laneidx, Neon64, 1); } else { UNREACHABLE(); } } } // namespace internal } // namespace v8 #endif // V8_TARGET_ARCH_ARM
/* * Copyright (C) 2010 Google Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following disclaimer * in the documentation and/or other materials provided with the * distribution. * * Neither the name of Google Inc. nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "config.h" #include "net/FileStream.h" #include "net/FileSystem.h" #include <wtf/text/WTFString.h> namespace net { FileStream::FileStream() : m_handle(invalidPlatformFileHandle) , m_bytesProcessed(0) , m_totalBytesToRead(0) { } FileStream::~FileStream() { close(); } long long FileStream::getSize(const String& path, double expectedModificationTime) { // Check the modification time for the possible file change. time_t modificationTime; if (!getFileModificationTime(path, modificationTime)) return -1; if (isValidFileTime(expectedModificationTime)) { if (static_cast<time_t>(expectedModificationTime) != modificationTime) return -1; } // Now get the file size. long long length; if (!getFileSize(path, length)) return -1; return length; } bool FileStream::openForRead(const String& path, long long offset, long long length) { if (isHandleValid(m_handle)) return true; // Open the file. m_handle = openFile(path, OpenForRead); if (!isHandleValid(m_handle)) return false; // Jump to the beginning position if the file has been sliced. if (offset > 0) { if (seekFile(m_handle, offset, SeekFromBeginning) < 0) return false; } m_totalBytesToRead = length; m_bytesProcessed = 0; return true; } bool FileStream::openForWrite(const String&) { // FIXME: to be implemented. return false; } void FileStream::close() { if (isHandleValid(m_handle)) { closeFile(m_handle); m_handle = invalidPlatformFileHandle; } } int FileStream::read(char* buffer, int bufferSize) { if (!isHandleValid(m_handle)) return -1; long long remaining = m_totalBytesToRead - m_bytesProcessed; int bytesToRead = (remaining < bufferSize) ? static_cast<int>(remaining) : bufferSize; int bytesRead = 0; if (bytesToRead > 0) bytesRead = readFromFile(m_handle, buffer, bytesToRead); if (bytesRead < 0) return -1; if (bytesRead > 0) m_bytesProcessed += bytesRead; return bytesRead; } int FileStream::write(const String&, long long, int) { // FIXME: to be implemented. return -1; } bool FileStream::truncate(long long) { // FIXME: to be implemented. return false; } } // namespace WebCore
/* * MPTrackUtilWine.cpp * ------------------- * Purpose: Wine utility functions. * Notes : (currently none) * Authors: OpenMPT Devs * The OpenMPT source code is released under the BSD license. Read LICENSE for more details. */ #include "stdafx.h" #include "MPTrackUtilWine.h" #include "Mptrack.h" #include "../common/misc_util.h" #include "../common/mptWine.h" OPENMPT_NAMESPACE_BEGIN namespace Util { namespace Wine { class CExecutePosixShellScriptProgressDialog : public CDialog { protected: mpt::Wine::Context & wine; std::string m_Title; std::string m_Status; bool m_bAbort; std::string m_script; FlagSet<mpt::Wine::ExecFlags> m_Flags; std::map<std::string, std::vector<char> > m_Filetree; mpt::Wine::ExecResult m_ExecResult; std::string m_ExceptionString; public: CExecutePosixShellScriptProgressDialog(mpt::Wine::Context & wine, std::string script, FlagSet<mpt::Wine::ExecFlags> flags, std::map<std::string, std::vector<char> > filetree, std::string title, std::string status, CWnd *parent = NULL); BOOL OnInitDialog(); void OnCancel(); afx_msg void OnButton1(); static mpt::Wine::ExecuteProgressResult ProgressCancelCallback(void *userdata); static void ProgressCallback(void *userdata); mpt::Wine::ExecuteProgressResult Progress(bool allowCancel); void MessageLoop(); mpt::Wine::ExecResult GetExecResult() const; std::string GetExceptionString() const; private: DECLARE_MESSAGE_MAP() }; BEGIN_MESSAGE_MAP(CExecutePosixShellScriptProgressDialog, CDialog) ON_COMMAND(IDC_BUTTON1, &CExecutePosixShellScriptProgressDialog::OnButton1) END_MESSAGE_MAP() CExecutePosixShellScriptProgressDialog::CExecutePosixShellScriptProgressDialog(mpt::Wine::Context & wine, std::string script, FlagSet<mpt::Wine::ExecFlags> flags, std::map<std::string, std::vector<char> > filetree, std::string title, std::string status, CWnd *parent) : CDialog(IDD_PROGRESS, parent) , wine(wine) , m_Title(title) , m_Status(status) , m_bAbort(false) , m_script(script) , m_Flags(flags) , m_Filetree(filetree) , m_ExecResult(mpt::Wine::ExecResult::Error()) { return; } void CExecutePosixShellScriptProgressDialog::OnCancel() { m_bAbort = true; } mpt::Wine::ExecuteProgressResult CExecutePosixShellScriptProgressDialog::ProgressCancelCallback(void *userdata) { return reinterpret_cast<CExecutePosixShellScriptProgressDialog*>(userdata)->Progress(true); } void CExecutePosixShellScriptProgressDialog::ProgressCallback(void *userdata) { reinterpret_cast<CExecutePosixShellScriptProgressDialog*>(userdata)->Progress(false); } void CExecutePosixShellScriptProgressDialog::MessageLoop() { MSG msg; while(::PeekMessage(&msg, NULL, 0, 0, PM_REMOVE)) { ::TranslateMessage(&msg); ::DispatchMessage(&msg); } } mpt::Wine::ExecResult CExecutePosixShellScriptProgressDialog::GetExecResult() const { return m_ExecResult; } std::string CExecutePosixShellScriptProgressDialog::GetExceptionString() const { return m_ExceptionString; } BOOL CExecutePosixShellScriptProgressDialog::OnInitDialog() { CDialog::OnInitDialog(); SetWindowText(mpt::ToCString(mpt::CharsetUTF8, m_Title)); SetDlgItemText(IDCANCEL, _T("Cancel")); SetWindowLong(::GetDlgItem(m_hWnd, IDC_PROGRESS1), GWL_STYLE, GetWindowLong(::GetDlgItem(m_hWnd, IDC_PROGRESS1), GWL_STYLE) | PBS_MARQUEE); ::SendMessage(::GetDlgItem(m_hWnd, IDC_PROGRESS1), PBM_SETMARQUEE, 1, 30); // 30 is Windows default, but Wine < 1.7.15 defaults to 0 PostMessage(WM_COMMAND, IDC_BUTTON1); return TRUE; } mpt::Wine::ExecuteProgressResult CExecutePosixShellScriptProgressDialog::Progress(bool allowCancel) { if(m_bAbort) { return mpt::Wine::ExecuteProgressAsyncCancel; } ::ShowWindow(::GetDlgItem(m_hWnd, IDCANCEL), allowCancel ? SW_SHOW : SW_HIDE); MessageLoop(); if(m_bAbort) { return mpt::Wine::ExecuteProgressAsyncCancel; } ::Sleep(10); return mpt::Wine::ExecuteProgressContinueWaiting; } void CExecutePosixShellScriptProgressDialog::OnButton1() { if(m_script.empty()) { EndDialog(IDCANCEL); return; } SetDlgItemText(IDC_TEXT1, mpt::ToCString(mpt::CharsetUTF8, m_Status)); MessageLoop(); if(m_bAbort) { EndDialog(IDCANCEL); return; } ::Sleep(10); try { m_ExecResult = wine.ExecutePosixShellScript(m_script, m_Flags, m_Filetree, m_Title, &ProgressCallback, &ProgressCancelCallback, this); } catch(const mpt::Wine::Exception &e) { m_ExceptionString = mpt::get_exception_text<std::string>(e); EndDialog(IDCANCEL); return; } MessageLoop(); if(m_bAbort) { EndDialog(IDCANCEL); return; } SetDlgItemText(IDC_TEXT1, _T("Done.")); ::ShowWindow(::GetDlgItem(m_hWnd, IDCANCEL), SW_HIDE); for(int i = 0; i < 10; ++i) { MessageLoop(); ::Sleep(10); } MessageLoop(); EndDialog(IDOK); } static void ProgressCallback(void * /*userdata*/ ) { MSG msg; while(::PeekMessage(&msg, NULL, 0, 0, PM_REMOVE)) { ::TranslateMessage(&msg); ::DispatchMessage(&msg); } ::Sleep(10); } static mpt::Wine::ExecuteProgressResult ProgressCancelCallback(void *userdata) { ProgressCallback(userdata); return mpt::Wine::ExecuteProgressContinueWaiting; } mpt::Wine::ExecResult ExecutePosixShellScript(mpt::Wine::Context & wine, std::string script, FlagSet<mpt::Wine::ExecFlags> flags, std::map<std::string, std::vector<char> > filetree, std::string title, std::string status) { if(flags[mpt::Wine::ExecFlagProgressWindow]) { CExecutePosixShellScriptProgressDialog dlg(wine, script, flags, filetree, title, status, theApp.GetMainWnd()); if(dlg.DoModal() != IDOK) { if(!dlg.GetExceptionString().empty()) { throw mpt::Wine::Exception(dlg.GetExceptionString()); } throw mpt::Wine::Exception("Canceled."); } return dlg.GetExecResult(); } else { return wine.ExecutePosixShellScript(script, flags, filetree, title, &ProgressCallback, &ProgressCancelCallback, nullptr); } } Dialog::Dialog(std::string title, bool terminal) : m_Terminal(terminal) , m_Title(title) { return; } std::string Dialog::Detect() const { std::string script; script += std::string() + "chmod u+x ./build/wine/dialog.sh" + "\n"; return script; } std::string Dialog::DialogVar() const { if(m_Terminal) { return "./build/wine/dialog.sh tui"; } else { return "./build/wine/dialog.sh gui"; } } std::string Dialog::Title() const { return m_Title; } std::string Dialog::Status(std::string text) const { return std::string() + DialogVar() + " --infobox \"" + Title() + "\" \"" + text + "\""; } std::string Dialog::MessageBox(std::string text) const { return std::string() + DialogVar() + " --msgbox \"" + Title() + "\" \"" + text + "\""; } std::string Dialog::YesNo(std::string text) const { return std::string() + DialogVar() + " --yesno \"" + Title() + "\" \"" + text + "\""; } std::string Dialog::TextBox(std::string text) const { return std::string() + DialogVar() + " --textbox \"" + Title() + "\" \"" + text + "\""; } std::string Dialog::Progress(std::string text) const { return std::string() + DialogVar() + " --gauge \"" + Title() + "\" \"" + text + "\""; } } // namespace Wine } // namespace Util OPENMPT_NAMESPACE_END
// Copyright (c) 2011-2014 The Bitcoin developers // Copyright (c) 2014-2015 The Dash developers //Copyright (c) 2015-2020 The PIVX developers //Copyright (c) 2020 The remita developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "transactiondesc.h" #include "bitcoinunits.h" #include "guiutil.h" #include "paymentserver.h" #include "transactionrecord.h" #include "base58.h" #include "db.h" #include "main.h" #include "script/script.h" #include "timedata.h" #include "guiinterface.h" #include "util.h" #include "wallet/wallet.h" #include <stdint.h> #include <string> QString TransactionDesc::FormatTxStatus(const CWalletTx& wtx) { AssertLockHeld(cs_main); if (!IsFinalTx(wtx, chainActive.Height() + 1)) { if (wtx.nLockTime < LOCKTIME_THRESHOLD) return tr("Open for %n more block(s)", "", wtx.nLockTime - chainActive.Height()); else return tr("Open until %1").arg(GUIUtil::dateTimeStr(wtx.nLockTime)); } else { const int signatures = wtx.GetTransactionLockSignatures(); QString strUsingIX = ""; bool fConflicted; const int nDepth = wtx.GetDepthAndMempool(fConflicted); if (nDepth < 0 || fConflicted) return tr("conflicted"); const bool isOffline = (GetAdjustedTime() - wtx.nTimeReceived > 2 * 60 && wtx.GetRequestCount() == 0); if (signatures >= 0) { if (signatures >= SWIFTTX_SIGNATURES_REQUIRED) { if (isOffline) return tr("%1/offline (verified via SwiftX)").arg(nDepth); else if (nDepth < 6) return tr("%1/confirmed (verified via SwiftX)").arg(nDepth); else return tr("%1 confirmations (verified via SwiftX)").arg(nDepth); } else { if (!wtx.IsTransactionLockTimedOut()) { if (isOffline) return tr("%1/offline (SwiftX verification in progress - %2 of %3 signatures)").arg(nDepth).arg(signatures).arg(SWIFTTX_SIGNATURES_TOTAL); else if (nDepth < 6) return tr("%1/confirmed (SwiftX verification in progress - %2 of %3 signatures )").arg(nDepth).arg(signatures).arg(SWIFTTX_SIGNATURES_TOTAL); else return tr("%1 confirmations (SwiftX verification in progress - %2 of %3 signatures)").arg(nDepth).arg(signatures).arg(SWIFTTX_SIGNATURES_TOTAL); } else { if (isOffline) return tr("%1/offline (SwiftX verification failed)").arg(nDepth); else if (nDepth < 6) return tr("%1/confirmed (SwiftX verification failed)").arg(nDepth); else return tr("%1 confirmations").arg(nDepth); } } } else { if (isOffline) return tr("%1/offline").arg(nDepth); else if (nDepth < 6) return tr("%1/unconfirmed").arg(nDepth); else return tr("%1 confirmations").arg(nDepth); } } } QString TransactionDesc::toHTML(CWallet* wallet, CWalletTx& wtx, TransactionRecord* rec, int unit) { QString strHTML; LOCK2(cs_main, wallet->cs_wallet); strHTML.reserve(4000); strHTML += "<html><font face='verdana, arial, helvetica, sans-serif'>"; CAmount nNet = rec->credit + rec->debit; strHTML += "<b>" + tr("Status") + ":</b> " + FormatTxStatus(wtx); int nRequests = wtx.GetRequestCount(); if (nRequests != -1) { if (nRequests == 0) strHTML += tr(", has not been successfully broadcast yet"); else if (nRequests > 0) strHTML += tr(", broadcast through %n node(s)", "", nRequests); } strHTML += "<br>"; strHTML += "<b>" + tr("Date") + ":</b> " + (rec->time ? GUIUtil::dateTimeStr(rec->time) : "") + "<br>"; // // From // if (wtx.IsCoinBase()) { strHTML += "<b>" + tr("Source") + ":</b> " + tr("Generated") + "<br>"; } else if (wtx.mapValue.count("from") && !wtx.mapValue["from"].empty()) { // Online transaction strHTML += "<b>" + tr("From") + ":</b> " + GUIUtil::HtmlEscape(wtx.mapValue["from"]) + "<br>"; } else { // Offline transaction if (nNet > 0) { // Credit if (CBitcoinAddress(rec->address).IsValid()) { CTxDestination address = CBitcoinAddress(rec->address).Get(); if (wallet->mapAddressBook.count(address)) { strHTML += "<b>" + tr("From") + ":</b> " + tr("unknown") + "<br>"; strHTML += "<b>" + tr("To") + ":</b> "; strHTML += GUIUtil::HtmlEscape(rec->address); QString addressOwned = (::IsMine(*wallet, address) == ISMINE_SPENDABLE) ? tr("own address") : tr("watch-only"); if (!wallet->mapAddressBook[address].name.empty()) strHTML += " (" + addressOwned + ", " + tr("label") + ": " + GUIUtil::HtmlEscape(wallet->mapAddressBook[address].name) + ")"; else strHTML += " (" + addressOwned + ")"; strHTML += "<br>"; } } } } // // To // if (wtx.mapValue.count("to") && !wtx.mapValue["to"].empty()) { // Online transaction std::string strAddress = wtx.mapValue["to"]; strHTML += "<b>" + tr("To") + ":</b> "; CTxDestination dest = CBitcoinAddress(strAddress).Get(); if (wallet->mapAddressBook.count(dest) && !wallet->mapAddressBook[dest].name.empty()) strHTML += GUIUtil::HtmlEscape(wallet->mapAddressBook[dest].name) + " "; strHTML += GUIUtil::HtmlEscape(strAddress) + "<br>"; } // // Amount // if (wtx.IsCoinBase() && rec->credit == 0) { // // Coinbase // CAmount nUnmatured = 0; for (const CTxOut& txout : wtx.vout) nUnmatured += wallet->GetCredit(txout, ISMINE_ALL); strHTML += "<b>" + tr("Credit") + ":</b> "; if (wtx.IsInMainChain()) strHTML += BitcoinUnits::formatHtmlWithUnit(unit, nUnmatured) + " (" + tr("matures in %n more block(s)", "", wtx.GetBlocksToMaturity()) + ")"; else strHTML += "(" + tr("not accepted") + ")"; strHTML += "<br>"; } else if (nNet > 0) { // // Credit // strHTML += "<b>" + tr("Credit") + ":</b> " + BitcoinUnits::formatHtmlWithUnit(unit, nNet) + "<br>"; } else { isminetype fAllFromMe = ISMINE_SPENDABLE; for (const CTxIn& txin : wtx.vin) { isminetype mine = wallet->IsMine(txin); if (fAllFromMe > mine) fAllFromMe = mine; } isminetype fAllToMe = ISMINE_SPENDABLE; for (const CTxOut& txout : wtx.vout) { isminetype mine = wallet->IsMine(txout); if (fAllToMe > mine) fAllToMe = mine; } if (fAllFromMe) { if (fAllFromMe == ISMINE_WATCH_ONLY) strHTML += "<b>" + tr("From") + ":</b> " + tr("watch-only") + "<br>"; // // Debit // for (const CTxOut& txout : wtx.vout) { // Ignore change isminetype toSelf = wallet->IsMine(txout); if ((toSelf == ISMINE_SPENDABLE) && (fAllFromMe == ISMINE_SPENDABLE)) continue; if (!wtx.mapValue.count("to") || wtx.mapValue["to"].empty()) { // Offline transaction CTxDestination address; if (ExtractDestination(txout.scriptPubKey, address)) { strHTML += "<b>" + tr("To") + ":</b> "; if (wallet->mapAddressBook.count(address) && !wallet->mapAddressBook[address].name.empty()) strHTML += GUIUtil::HtmlEscape(wallet->mapAddressBook[address].name) + " "; strHTML += GUIUtil::HtmlEscape(CBitcoinAddress(address).ToString()); if (toSelf == ISMINE_SPENDABLE) strHTML += " (own address)"; else if (toSelf == ISMINE_WATCH_ONLY) strHTML += " (watch-only)"; strHTML += "<br>"; } } strHTML += "<b>" + tr("Debit") + ":</b> " + BitcoinUnits::formatHtmlWithUnit(unit, -txout.nValue) + "<br>"; if (toSelf) strHTML += "<b>" + tr("Credit") + ":</b> " + BitcoinUnits::formatHtmlWithUnit(unit, txout.nValue) + "<br>"; } if (fAllToMe) { // Payment to self CAmount nChange = wtx.GetChange(); CAmount nValue = rec->credit - nChange; strHTML += "<b>" + tr("Total debit") + ":</b> " + BitcoinUnits::formatHtmlWithUnit(unit, -nValue) + "<br>"; strHTML += "<b>" + tr("Total credit") + ":</b> " + BitcoinUnits::formatHtmlWithUnit(unit, nValue) + "<br>"; } CAmount nTxFee = rec->debit - wtx.GetValueOut(); if (nTxFee > 0) strHTML += "<b>" + tr("Transaction fee") + ":</b> " + BitcoinUnits::formatHtmlWithUnit(unit, -nTxFee) + "<br>"; } else { // // Mixed debit transaction // for (const CTxIn& txin : wtx.vin) if (wallet->IsMine(txin)) strHTML += "<b>" + tr("Debit") + ":</b> " + BitcoinUnits::formatHtmlWithUnit(unit, -wallet->GetDebit(txin, ISMINE_ALL)) + "<br>"; for (const CTxOut& txout : wtx.vout) if (wallet->IsMine(txout)) strHTML += "<b>" + tr("Credit") + ":</b> " + BitcoinUnits::formatHtmlWithUnit(unit, wallet->GetCredit(txout, ISMINE_ALL)) + "<br>"; } } strHTML += "<b>" + tr("Net amount") + ":</b> " + BitcoinUnits::formatHtmlWithUnit(unit, nNet, true) + "<br>"; // // Message // if (wtx.mapValue.count("message") && !wtx.mapValue["message"].empty()) strHTML += "<br><b>" + tr("Message") + ":</b><br>" + GUIUtil::HtmlEscape(wtx.mapValue["message"], true) + "<br>"; if (wtx.mapValue.count("comment") && !wtx.mapValue["comment"].empty()) strHTML += "<br><b>" + tr("Comment") + ":</b><br>" + GUIUtil::HtmlEscape(wtx.mapValue["comment"], true) + "<br>"; strHTML += "<b>" + tr("Transaction ID") + ":</b> " + rec->getTxID() + "<br>"; strHTML += "<b>" + tr("Output index") + ":</b> " + QString::number(rec->getOutputIndex()) + "<br>"; // Message from normal remita:URI (remita:XyZ...?message=example) Q_FOREACH (const PAIRTYPE(std::string, std::string) & r, wtx.vOrderForm) if (r.first == "Message") strHTML += "<br><b>" + tr("Message") + ":</b><br>" + GUIUtil::HtmlEscape(r.second, true) + "<br>"; // // PaymentRequest info: // Q_FOREACH (const PAIRTYPE(std::string, std::string) & r, wtx.vOrderForm) { if (r.first == "PaymentRequest") { PaymentRequestPlus req; req.parse(QByteArray::fromRawData(r.second.data(), r.second.size())); QString merchant; if (req.getMerchant(PaymentServer::getCertStore(), merchant)) strHTML += "<b>" + tr("Merchant") + ":</b> " + GUIUtil::HtmlEscape(merchant) + "<br>"; } } if (wtx.IsCoinBase()) { //quint32 numBlocksToMaturity = Params().GetConsensus().nCoinbaseMaturity + 1; //strHTML += "<br>" + tr("Generated coins must mature %1 blocks before they can be spent. When you generated this block, it was broadcast to the network to be added to the block chain. If it fails to get into the chain, its state will change to \"not accepted\" and it won't be spendable. This may occasionally happen if another node generates a block within a few seconds of yours.").arg(QString::number(numBlocksToMaturity)) + "<br>"; } // // Debug view // if (!GetBoolArg("-shrinkdebugfile", g_logger->DefaultShrinkDebugFile())) { strHTML += "<hr><br>" + tr("Debug information") + "<br><br>"; for (const CTxIn& txin : wtx.vin) if (wallet->IsMine(txin)) strHTML += "<b>" + tr("Debit") + ":</b> " + BitcoinUnits::formatHtmlWithUnit(unit, -wallet->GetDebit(txin, ISMINE_ALL)) + "<br>"; for (const CTxOut& txout : wtx.vout) if (wallet->IsMine(txout)) strHTML += "<b>" + tr("Credit") + ":</b> " + BitcoinUnits::formatHtmlWithUnit(unit, wallet->GetCredit(txout, ISMINE_ALL)) + "<br>"; strHTML += "<br><b>" + tr("Transaction") + ":</b><br>"; strHTML += GUIUtil::HtmlEscape(wtx.ToString(), true); strHTML += "<br><b>" + tr("Inputs") + ":</b>"; strHTML += "<ul>"; for (const CTxIn& txin : wtx.vin) { COutPoint prevout = txin.prevout; CCoins prev; if (pcoinsTip->GetCoins(prevout.hash, prev)) { if (prevout.n < prev.vout.size()) { strHTML += "<li>"; const CTxOut& vout = prev.vout[prevout.n]; CTxDestination address; if (ExtractDestination(vout.scriptPubKey, address)) { if (wallet->mapAddressBook.count(address) && !wallet->mapAddressBook[address].name.empty()) strHTML += GUIUtil::HtmlEscape(wallet->mapAddressBook[address].name) + " "; strHTML += QString::fromStdString(CBitcoinAddress(address).ToString()); } strHTML = strHTML + " " + tr("Amount") + "=" + BitcoinUnits::formatHtmlWithUnit(unit, vout.nValue); strHTML = strHTML + " IsMine=" + (wallet->IsMine(vout) & ISMINE_SPENDABLE ? tr("true") : tr("false")); strHTML = strHTML + " IsWatchOnly=" + (wallet->IsMine(vout) & ISMINE_WATCH_ONLY ? tr("true") : tr("false")) + "</li>"; } } } strHTML += "</ul>"; } strHTML += "</font></html>"; return strHTML; }
/* Copyright 2017 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ #include "tensorflow/lite/kernels/internal/optimized/integer_ops/add.h" #include "tensorflow/lite/c/builtin_op_data.h" #include "tensorflow/lite/c/c_api_internal.h" #include "tensorflow/lite/kernels/internal/optimized/optimized_ops.h" #include "tensorflow/lite/kernels/internal/quantization_util.h" #include "tensorflow/lite/kernels/internal/reference/integer_ops/add.h" #include "tensorflow/lite/kernels/internal/reference/reference_ops.h" #include "tensorflow/lite/kernels/internal/tensor.h" #include "tensorflow/lite/kernels/kernel_util.h" #include "tensorflow/lite/kernels/op_macros.h" namespace tflite { namespace ops { namespace builtin { namespace add { // This file has three implementation of Add. enum KernelType { kReference, kGenericOptimized, // Neon-free kNeonOptimized, }; constexpr int kInputTensor1 = 0; constexpr int kInputTensor2 = 1; constexpr int kOutputTensor = 0; struct OpData { bool requires_broadcast; // These fields are used in both the general 8-bit -> 8bit quantized path, // and the special 16-bit -> 16bit quantized path int input1_shift; int input2_shift; int32 output_activation_min; int32 output_activation_max; // These fields are used only in the general 8-bit -> 8bit quantized path int32 input1_multiplier; int32 input2_multiplier; int32 output_multiplier; int output_shift; int left_shift; int32 input1_offset; int32 input2_offset; int32 output_offset; }; void* Init(TfLiteContext* context, const char* buffer, size_t length) { auto* data = new OpData; data->requires_broadcast = false; return data; } void Free(TfLiteContext* context, void* buffer) { delete reinterpret_cast<OpData*>(buffer); } TfLiteStatus Prepare(TfLiteContext* context, TfLiteNode* node) { auto* params = reinterpret_cast<TfLiteAddParams*>(node->builtin_data); OpData* data = reinterpret_cast<OpData*>(node->user_data); TF_LITE_ENSURE_EQ(context, NumInputs(node), 2); TF_LITE_ENSURE_EQ(context, NumOutputs(node), 1); const TfLiteTensor* input1 = GetInput(context, node, kInputTensor1); const TfLiteTensor* input2 = GetInput(context, node, kInputTensor2); TfLiteTensor* output = GetOutput(context, node, kOutputTensor); TF_LITE_ENSURE_EQ(context, input1->type, input2->type); output->type = input2->type; data->requires_broadcast = !HaveSameShapes(input1, input2); TfLiteIntArray* output_size = nullptr; if (data->requires_broadcast) { TF_LITE_ENSURE_OK(context, CalculateShapeForBroadcast( context, input1, input2, &output_size)); } else { output_size = TfLiteIntArrayCopy(input1->dims); } if (output->type == kTfLiteUInt8 || output->type == kTfLiteInt8) { // 8bit -> 8bit general quantized path, with general rescalings data->input1_offset = -input1->params.zero_point; data->input2_offset = -input2->params.zero_point; data->output_offset = output->params.zero_point; data->left_shift = 20; const double twice_max_input_scale = 2 * std::max(input1->params.scale, input2->params.scale); const double real_input1_multiplier = input1->params.scale / twice_max_input_scale; const double real_input2_multiplier = input2->params.scale / twice_max_input_scale; const double real_output_multiplier = twice_max_input_scale / ((1 << data->left_shift) * output->params.scale); QuantizeMultiplierSmallerThanOneExp( real_input1_multiplier, &data->input1_multiplier, &data->input1_shift); QuantizeMultiplierSmallerThanOneExp( real_input2_multiplier, &data->input2_multiplier, &data->input2_shift); QuantizeMultiplierSmallerThanOneExp( real_output_multiplier, &data->output_multiplier, &data->output_shift); if (output->type == kTfLiteUInt8) { CalculateActivationRangeUint8(params->activation, output, &data->output_activation_min, &data->output_activation_max); } else { CalculateActivationRangeInt8(params->activation, output, &data->output_activation_min, &data->output_activation_max); } } else if (output->type == kTfLiteInt16) { // 16bit -> 16bit special quantized path, supporting only a rather // narrow case of quantization parameters: zero_points must all be 0 // ("symmetric quantization") and scales must be power-of-two (which // we abbreviate as "POT" below). The intended use case for this path // is in LSTM cells, where, due to the constraints of implementing // some of the math in these LSTM cells in fixed-point arithmetic, // we need to have such symmetric, power-of-two quantization // (Fixed-point formats are inherently symmetric, power-of-two). TF_LITE_ENSURE_EQ(context, input1->params.zero_point, 0); TF_LITE_ENSURE_EQ(context, input2->params.zero_point, 0); TF_LITE_ENSURE_EQ(context, output->params.zero_point, 0); int input1_scale_log2_rounded; bool input1_scale_is_pot = CheckedLog2(input1->params.scale, &input1_scale_log2_rounded); TF_LITE_ENSURE(context, input1_scale_is_pot); int input2_scale_log2_rounded; bool input2_scale_is_pot = CheckedLog2(input2->params.scale, &input2_scale_log2_rounded); TF_LITE_ENSURE(context, input2_scale_is_pot); int output_scale_log2_rounded; bool output_scale_is_pot = CheckedLog2(output->params.scale, &output_scale_log2_rounded); TF_LITE_ENSURE(context, output_scale_is_pot); data->input1_shift = input1_scale_log2_rounded - output_scale_log2_rounded; data->input2_shift = input2_scale_log2_rounded - output_scale_log2_rounded; // Shifting of one input is supported. The graph quantization should ensure // that the other input matches the output. TF_LITE_ENSURE(context, data->input1_shift == 0 || data->input2_shift == 0); TF_LITE_ENSURE(context, data->input1_shift <= 0); TF_LITE_ENSURE(context, data->input2_shift <= 0); CalculateActivationRangeQuantized(context, params->activation, output, &data->output_activation_min, &data->output_activation_max); } return context->ResizeTensor(context, output, output_size); } template <KernelType kernel_type> void EvalAdd(TfLiteContext* context, TfLiteNode* node, TfLiteAddParams* params, const OpData* data, const TfLiteTensor* input1, const TfLiteTensor* input2, TfLiteTensor* output) { #define TF_LITE_ADD(type, opname, data_type) \ data_type output_activation_min, output_activation_max; \ CalculateActivationRange(params->activation, &output_activation_min, \ &output_activation_max); \ tflite::ArithmeticParams op_params; \ SetActivationParams(output_activation_min, output_activation_max, \ &op_params); \ type::opname(op_params, GetTensorShape(input1), \ GetTensorData<data_type>(input1), GetTensorShape(input2), \ GetTensorData<data_type>(input2), GetTensorShape(output), \ GetTensorData<data_type>(output)) if (output->type == kTfLiteInt32) { if (kernel_type == kReference) { if (data->requires_broadcast) { TF_LITE_ADD(reference_ops, BroadcastAdd4DSlow, int32_t); } else { TF_LITE_ADD(reference_ops, Add, int32_t); } } else { if (data->requires_broadcast) { TF_LITE_ADD(optimized_ops, BroadcastAdd4DSlow, int32_t); } else { TF_LITE_ADD(optimized_ops, Add, int32_t); } } } else if (output->type == kTfLiteFloat32) { if (kernel_type == kReference) { if (data->requires_broadcast) { TF_LITE_ADD(reference_ops, BroadcastAdd4DSlow, float); } else { TF_LITE_ADD(reference_ops, Add, float); } } else { if (data->requires_broadcast) { TF_LITE_ADD(optimized_ops, BroadcastAdd4DSlow, float); } else { TF_LITE_ADD(optimized_ops, Add, float); } } } #undef TF_LITE_ADD } template <KernelType kernel_type> TfLiteStatus EvalAddQuantized(TfLiteContext* context, TfLiteNode* node, TfLiteAddParams* params, const OpData* data, const TfLiteTensor* input1, const TfLiteTensor* input2, TfLiteTensor* output) { if (output->type == kTfLiteUInt8 || output->type == kTfLiteInt8) { tflite::ArithmeticParams op_params; op_params.left_shift = data->left_shift; op_params.input1_offset = data->input1_offset; op_params.input1_multiplier = data->input1_multiplier; op_params.input1_shift = data->input1_shift; op_params.input2_offset = data->input2_offset; op_params.input2_multiplier = data->input2_multiplier; op_params.input2_shift = data->input2_shift; op_params.output_offset = data->output_offset; op_params.output_multiplier = data->output_multiplier; op_params.output_shift = data->output_shift; SetActivationParams(data->output_activation_min, data->output_activation_max, &op_params); bool need_broadcast = optimized_ops::ProcessBroadcastShapes( GetTensorShape(input1), GetTensorShape(input2), &op_params); #define TF_LITE_ADD(type, opname, dtype) \ type::opname(op_params, GetTensorShape(input1), \ GetTensorData<dtype>(input1), GetTensorShape(input2), \ GetTensorData<dtype>(input2), GetTensorShape(output), \ GetTensorData<dtype>(output)); if (output->type == kTfLiteInt8) { if (kernel_type == kReference) { if (need_broadcast) { TF_LITE_ADD(reference_integer_ops, BroadcastAdd4DSlow, int8_t); } else { TF_LITE_ADD(reference_integer_ops, Add, int8_t); } } else { if (op_params.broadcast_category == BroadcastableOpCategory::kGenericBroadcast) { TF_LITE_ADD(reference_integer_ops, BroadcastAdd4DSlow, int8_t); } else if (need_broadcast) { TF_LITE_ADD(optimized_integer_ops, BroadcastAddFivefold, int8_t); } else { TF_LITE_ADD(optimized_integer_ops, Add, int8_t); } } } else { if (kernel_type == kReference) { if (need_broadcast) { TF_LITE_ADD(reference_ops, BroadcastAdd4DSlow, uint8_t); } else { TF_LITE_ADD(reference_ops, Add, uint8_t); } } else { if (op_params.broadcast_category == BroadcastableOpCategory::kGenericBroadcast) { TF_LITE_ADD(optimized_ops, BroadcastAdd4DSlow, uint8_t); } else if (need_broadcast) { TF_LITE_ADD(optimized_ops, BroadcastAddFivefold, uint8_t); } else { TF_LITE_ADD(optimized_ops, Add, uint8_t); } } } #undef TF_LITE_ADD } else if (output->type == kTfLiteInt16) { #define TF_LITE_ADD(type, opname) \ tflite::ArithmeticParams op_params; \ op_params.input1_shift = data->input1_shift; \ op_params.input2_shift = data->input2_shift; \ SetActivationParams(data->output_activation_min, \ data->output_activation_max, &op_params); \ type::opname(op_params, GetTensorShape(input1), \ GetTensorData<int16_t>(input1), GetTensorShape(input2), \ GetTensorData<int16_t>(input2), GetTensorShape(output), \ GetTensorData<int16_t>(output)) // The quantized version of Add doesn't support activations, so we // always use BroadcastAdd. if (kernel_type == kReference) { TF_LITE_ADD(reference_ops, Add); } else { TF_LITE_ADD(optimized_ops, Add); } #undef TF_LITE_ADD } return kTfLiteOk; } template <KernelType kernel_type> TfLiteStatus Eval(TfLiteContext* context, TfLiteNode* node) { auto* params = reinterpret_cast<TfLiteAddParams*>(node->builtin_data); OpData* data = reinterpret_cast<OpData*>(node->user_data); const TfLiteTensor* input1 = GetInput(context, node, kInputTensor1); const TfLiteTensor* input2 = GetInput(context, node, kInputTensor2); TfLiteTensor* output = GetOutput(context, node, kOutputTensor); if (output->type == kTfLiteFloat32 || output->type == kTfLiteInt32) { EvalAdd<kernel_type>(context, node, params, data, input1, input2, output); } else if (output->type == kTfLiteUInt8 || output->type == kTfLiteInt8 || output->type == kTfLiteInt16) { TF_LITE_ENSURE_OK(context, EvalAddQuantized<kernel_type>(context, node, params, data, input1, input2, output)); } else { context->ReportError(context, "Inputs and outputs not all float|uint8|int16 types."); return kTfLiteError; } return kTfLiteOk; } } // namespace add TfLiteRegistration* Register_ADD_REF() { static TfLiteRegistration r = {add::Init, add::Free, add::Prepare, add::Eval<add::kReference>}; return &r; } TfLiteRegistration* Register_ADD_GENERIC_OPT() { static TfLiteRegistration r = {add::Init, add::Free, add::Prepare, add::Eval<add::kGenericOptimized>}; return &r; } TfLiteRegistration* Register_ADD_NEON_OPT() { static TfLiteRegistration r = {add::Init, add::Free, add::Prepare, add::Eval<add::kNeonOptimized>}; return &r; } TfLiteRegistration* Register_ADD() { #ifdef USE_NEON return Register_ADD_NEON_OPT(); #else return Register_ADD_GENERIC_OPT(); #endif } } // namespace builtin } // namespace ops } // namespace tflite
//===--- FrontendTool.cpp - Swift Compiler Frontend -----------------------===// // // 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 // //===----------------------------------------------------------------------===// /// /// \file /// \brief This is the entry point to the swift -frontend functionality, which /// implements the core compiler functionality along with a number of additional /// tools for demonstration and testing purposes. /// /// This is separate from the rest of libFrontend to reduce the dependencies /// required by that library. /// //===----------------------------------------------------------------------===// #include "swift/FrontendTool/FrontendTool.h" #include "ImportedModules.h" #include "ReferenceDependencies.h" #include "TBD.h" #include "swift/Strings.h" #include "swift/Subsystems.h" #include "swift/AST/ASTScope.h" #include "swift/AST/DiagnosticsFrontend.h" #include "swift/AST/DiagnosticsSema.h" #include "swift/AST/IRGenOptions.h" #include "swift/AST/ASTMangler.h" #include "swift/AST/ReferencedNameTracker.h" #include "swift/AST/TypeRefinementContext.h" #include "swift/Basic/Dwarf.h" #include "swift/Basic/Edit.h" #include "swift/Basic/FileSystem.h" #include "swift/Basic/JSONSerialization.h" #include "swift/Basic/LLVMContext.h" #include "swift/Basic/SourceManager.h" #include "swift/Basic/Statistic.h" #include "swift/Basic/Timer.h" #include "swift/Basic/UUID.h" #include "swift/Frontend/DiagnosticVerifier.h" #include "swift/Frontend/Frontend.h" #include "swift/Frontend/PrintingDiagnosticConsumer.h" #include "swift/Frontend/SerializedDiagnosticConsumer.h" #include "swift/Immediate/Immediate.h" #include "swift/Option/Options.h" #include "swift/Migrator/FixitFilter.h" #include "swift/Migrator/Migrator.h" #include "swift/PrintAsObjC/PrintAsObjC.h" #include "swift/Serialization/SerializationOptions.h" #include "swift/SILOptimizer/PassManager/Passes.h" // FIXME: We're just using CompilerInstance::createOutputFile. // This API should be sunk down to LLVM. #include "clang/Frontend/CompilerInstance.h" #include "clang/APINotes/Types.h" #include "llvm/ADT/Statistic.h" #include "llvm/IR/LLVMContext.h" #include "llvm/IR/Module.h" #include "llvm/IR/ValueSymbolTable.h" #include "llvm/IRReader/IRReader.h" #include "llvm/Option/Option.h" #include "llvm/Option/OptTable.h" #include "llvm/Support/ErrorHandling.h" #include "llvm/Support/Path.h" #include "llvm/Support/raw_ostream.h" #include "llvm/Support/TargetSelect.h" #include "llvm/Support/Timer.h" #include "llvm/Target/TargetMachine.h" #include <memory> #include <unordered_set> #if !defined(_MSC_VER) && !defined(__MINGW32__) #include <unistd.h> #else #include <io.h> #endif using namespace swift; static std::string displayName(StringRef MainExecutablePath) { std::string Name = llvm::sys::path::stem(MainExecutablePath); Name += " -frontend"; return Name; } /// Emits a Make-style dependencies file. static bool emitMakeDependencies(DiagnosticEngine &diags, DependencyTracker &depTracker, const FrontendOptions &opts) { std::error_code EC; llvm::raw_fd_ostream out(opts.DependenciesFilePath, EC, llvm::sys::fs::F_None); if (out.has_error() || EC) { diags.diagnose(SourceLoc(), diag::error_opening_output, opts.DependenciesFilePath, EC.message()); out.clear_error(); return true; } // Declare a helper for escaping file names for use in Makefiles. llvm::SmallString<256> pathBuf; auto escape = [&](StringRef raw) -> StringRef { pathBuf.clear(); static const char badChars[] = " $#:\n"; size_t prev = 0; for (auto index = raw.find_first_of(badChars); index != StringRef::npos; index = raw.find_first_of(badChars, index+1)) { pathBuf.append(raw.slice(prev, index)); if (raw[index] == '$') pathBuf.push_back('$'); else pathBuf.push_back('\\'); prev = index; } pathBuf.append(raw.substr(prev)); return pathBuf; }; // FIXME: Xcode can't currently handle multiple targets in a single // dependency line. opts.forAllOutputPaths([&](StringRef targetName) { out << escape(targetName) << " :"; // First include all other files in the module. Make-style dependencies // need to be conservative! for (auto const &path : reversePathSortedFilenames(opts.InputFilenames)) out << ' ' << escape(path); // Then print dependencies we've picked up during compilation. for (auto const &path : reversePathSortedFilenames(depTracker.getDependencies())) out << ' ' << escape(path); out << '\n'; }); return false; } namespace { struct LoadedModuleTraceFormat { std::string Name; std::string Arch; std::vector<std::string> SwiftModules; }; } namespace swift { namespace json { template <> struct ObjectTraits<LoadedModuleTraceFormat> { static void mapping(Output &out, LoadedModuleTraceFormat &contents) { out.mapRequired("name", contents.Name); out.mapRequired("arch", contents.Arch); out.mapRequired("swiftmodules", contents.SwiftModules); } }; } } static bool emitLoadedModuleTrace(ASTContext &ctxt, DependencyTracker &depTracker, const FrontendOptions &opts) { std::error_code EC; llvm::raw_fd_ostream out(opts.LoadedModuleTracePath, EC, llvm::sys::fs::F_Append); if (out.has_error() || EC) { ctxt.Diags.diagnose(SourceLoc(), diag::error_opening_output, opts.LoadedModuleTracePath, EC.message()); out.clear_error(); return true; } llvm::SmallVector<std::string, 16> swiftModules; // Canonicalise all the paths by opening them. for (auto &dep : depTracker.getDependencies()) { llvm::SmallString<256> buffer; StringRef realPath; int FD; // FIXME: appropriate error handling if (llvm::sys::fs::openFileForRead(dep, FD, &buffer)) { // Couldn't open the file now, so let's just assume the old path was // canonical (enough). realPath = dep; } else { realPath = buffer.str(); // Not much we can do about failing to close. (void)close(FD); } // Decide if this is a swiftmodule based on the extension of the raw // dependency path, as the true file may have a different one. auto ext = llvm::sys::path::extension(dep); if (ext.startswith(".") && ext.drop_front() == SERIALIZED_MODULE_EXTENSION) { swiftModules.push_back(realPath); } } LoadedModuleTraceFormat trace = { /*name=*/opts.ModuleName, /*arch=*/ctxt.LangOpts.Target.getArchName(), /*swiftmodules=*/reversePathSortedFilenames(swiftModules)}; // raw_fd_ostream is unbuffered, and we may have multiple processes writing, // so first write the whole thing into memory and dump out that buffer to the // file. std::string stringBuffer; { llvm::raw_string_ostream memoryBuffer(stringBuffer); json::Output jsonOutput(memoryBuffer, /*PrettyPrint=*/false); json::jsonize(jsonOutput, trace, /*Required=*/true); } stringBuffer += "\n"; out << stringBuffer; return true; } /// Writes SIL out to the given file. static bool writeSIL(SILModule &SM, ModuleDecl *M, bool EmitVerboseSIL, StringRef OutputFilename, bool SortSIL) { std::error_code EC; llvm::raw_fd_ostream OS(OutputFilename, EC, llvm::sys::fs::F_None); if (EC) { M->getASTContext().Diags.diagnose(SourceLoc(), diag::error_opening_output, OutputFilename, EC.message()); return true; } SM.print(OS, EmitVerboseSIL, M, SortSIL); return false; } static bool printAsObjC(const std::string &outputPath, ModuleDecl *M, StringRef bridgingHeader, bool moduleIsPublic) { using namespace llvm::sys; clang::CompilerInstance Clang; std::string tmpFilePath; std::error_code EC; std::unique_ptr<llvm::raw_pwrite_stream> out = Clang.createOutputFile(outputPath, EC, /*Binary=*/false, /*RemoveFileOnSignal=*/true, /*BaseInput=*/"", path::extension(outputPath), /*UseTemporary=*/true, /*CreateMissingDirectories=*/false, /*ResultPathName=*/nullptr, &tmpFilePath); if (!out) { M->getASTContext().Diags.diagnose(SourceLoc(), diag::error_opening_output, tmpFilePath, EC.message()); return true; } auto requiredAccess = moduleIsPublic ? Accessibility::Public : Accessibility::Internal; bool hadError = printAsObjC(*out, M, bridgingHeader, requiredAccess); out->flush(); EC = swift::moveFileIfDifferent(tmpFilePath, outputPath); if (EC) { M->getASTContext().Diags.diagnose(SourceLoc(), diag::error_opening_output, outputPath, EC.message()); return true; } return hadError; } /// Returns the OutputKind for the given Action. static IRGenOutputKind getOutputKind(FrontendOptions::ActionType Action) { switch (Action) { case FrontendOptions::EmitIR: return IRGenOutputKind::LLVMAssembly; case FrontendOptions::EmitBC: return IRGenOutputKind::LLVMBitcode; case FrontendOptions::EmitAssembly: return IRGenOutputKind::NativeAssembly; case FrontendOptions::EmitObject: return IRGenOutputKind::ObjectFile; case FrontendOptions::Immediate: return IRGenOutputKind::Module; default: llvm_unreachable("Unknown ActionType which requires IRGen"); return IRGenOutputKind::ObjectFile; } } namespace { /// If there is an error with fixits it writes the fixits as edits in json /// format. class JSONFixitWriter : public DiagnosticConsumer, public migrator::FixitFilter { std::string FixitsOutputPath; std::unique_ptr<llvm::raw_ostream> OSPtr; bool FixitAll; std::vector<SingleEdit> AllEdits; public: JSONFixitWriter(std::string fixitsOutputPath, const DiagnosticOptions &DiagOpts) : FixitsOutputPath(fixitsOutputPath), FixitAll(DiagOpts.FixitCodeForAllDiagnostics) {} private: void handleDiagnostic(SourceManager &SM, SourceLoc Loc, DiagnosticKind Kind, StringRef FormatString, ArrayRef<DiagnosticArgument> FormatArgs, const DiagnosticInfo &Info) override { if (!(FixitAll || shouldTakeFixit(Kind, Info))) return; for (const auto &Fix : Info.FixIts) { AllEdits.push_back({SM, Fix.getRange(), Fix.getText()}); } } bool finishProcessing() override { std::error_code EC; std::unique_ptr<llvm::raw_fd_ostream> OS; OS.reset(new llvm::raw_fd_ostream(FixitsOutputPath, EC, llvm::sys::fs::F_None)); if (EC) { // Create a temporary diagnostics engine to print the error to stderr. SourceManager dummyMgr; DiagnosticEngine DE(dummyMgr); PrintingDiagnosticConsumer PDC; DE.addConsumer(PDC); DE.diagnose(SourceLoc(), diag::cannot_open_file, FixitsOutputPath, EC.message()); return true; } swift::writeEditsInJson(llvm::makeArrayRef(AllEdits), *OS); return false; } }; } // anonymous namespace // This is a separate function so that it shows up in stack traces. LLVM_ATTRIBUTE_NOINLINE static void debugFailWithAssertion() { // This assertion should always fail, per the user's request, and should // not be converted to llvm_unreachable. assert(0 && "This is an assertion!"); } // This is a separate function so that it shows up in stack traces. LLVM_ATTRIBUTE_NOINLINE static void debugFailWithCrash() { LLVM_BUILTIN_TRAP; } static void countStatsPostSema(UnifiedStatsReporter &Stats, CompilerInstance& Instance) { auto &C = Stats.getFrontendCounters(); C.NumSourceBuffers = Instance.getSourceMgr().getLLVMSourceMgr().getNumBuffers(); C.NumLinkLibraries = Instance.getLinkLibraries().size(); auto const &AST = Instance.getASTContext(); C.NumLoadedModules = AST.LoadedModules.size(); C.NumImportedExternalDefinitions = AST.ExternalDefinitions.size(); C.NumASTBytesAllocated = AST.getAllocator().getBytesAllocated(); if (auto *D = Instance.getDependencyTracker()) { C.NumDependencies = D->getDependencies().size(); } if (auto *R = Instance.getReferencedNameTracker()) { C.NumReferencedTopLevelNames = R->getTopLevelNames().size(); C.NumReferencedDynamicNames = R->getDynamicLookupNames().size(); C.NumReferencedMemberNames = R->getUsedMembers().size(); } if (auto *SF = Instance.getPrimarySourceFile()) { C.NumDecls = SF->Decls.size(); C.NumLocalTypeDecls = SF->LocalTypeDecls.size(); C.NumObjCMethods = SF->ObjCMethods.size(); C.NumInfixOperators = SF->InfixOperators.size(); C.NumPostfixOperators = SF->PostfixOperators.size(); C.NumPrefixOperators = SF->PrefixOperators.size(); C.NumPrecedenceGroups = SF->PrecedenceGroups.size(); C.NumUsedConformances = SF->getUsedConformances().size(); } } static void countStatsPostIRGen(UnifiedStatsReporter &Stats, const llvm::Module& Module) { auto &C = Stats.getFrontendCounters(); // FIXME: calculate these in constant time if possible. C.NumIRGlobals = Module.getGlobalList().size(); C.NumIRFunctions = Module.getFunctionList().size(); C.NumIRAliases = Module.getAliasList().size(); C.NumIRIFuncs = Module.getIFuncList().size(); C.NumIRNamedMetaData = Module.getNamedMDList().size(); C.NumIRValueSymbols = Module.getValueSymbolTable().size(); C.NumIRComdatSymbols = Module.getComdatSymbolTable().size(); for (auto const &Func : Module) { for (auto const &BB : Func) { C.NumIRBasicBlocks++; C.NumIRInsts += BB.size(); } } } static void countStatsPostSILGen(UnifiedStatsReporter &Stats, const SILModule& Module) { auto &C = Stats.getFrontendCounters(); // FIXME: calculate these in constant time, via the dense maps. C.NumSILGenFunctions = Module.getFunctionList().size(); C.NumSILGenVtables = Module.getVTableList().size(); C.NumSILGenWitnessTables = Module.getWitnessTableList().size(); C.NumSILGenDefaultWitnessTables = Module.getDefaultWitnessTableList().size(); C.NumSILGenGlobalVariables = Module.getSILGlobalList().size(); } static void countStatsPostSILOpt(UnifiedStatsReporter &Stats, const SILModule& Module) { auto &C = Stats.getFrontendCounters(); // FIXME: calculate these in constant time, via the dense maps. C.NumSILOptFunctions = Module.getFunctionList().size(); C.NumSILOptVtables = Module.getVTableList().size(); C.NumSILOptWitnessTables = Module.getWitnessTableList().size(); C.NumSILOptDefaultWitnessTables = Module.getDefaultWitnessTableList().size(); C.NumSILOptGlobalVariables = Module.getSILGlobalList().size(); } /// Performs the compile requested by the user. /// \param Instance Will be reset after performIRGeneration when the verifier /// mode is NoVerify and there were no errors. /// \returns true on error static bool performCompile(CompilerInstance &Instance, CompilerInvocation &Invocation, ArrayRef<const char *> Args, int &ReturnValue, FrontendObserver *observer, UnifiedStatsReporter *Stats) { FrontendOptions opts = Invocation.getFrontendOptions(); FrontendOptions::ActionType Action = opts.RequestedAction; // We've been asked to precompile a bridging header; we want to // avoid touching any other inputs and just parse, emit and exit. if (Action == FrontendOptions::EmitPCH) { auto clangImporter = static_cast<ClangImporter *>( Instance.getASTContext().getClangModuleLoader()); return clangImporter->emitBridgingPCH( Invocation.getInputFilenames()[0], opts.getSingleOutputFilename()); } IRGenOptions &IRGenOpts = Invocation.getIRGenOptions(); bool inputIsLLVMIr = Invocation.getInputKind() == InputFileKind::IFK_LLVM_IR; if (inputIsLLVMIr) { auto &LLVMContext = getGlobalLLVMContext(); // Load in bitcode file. assert(Invocation.getInputFilenames().size() == 1 && "We expect a single input for bitcode input!"); llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> FileBufOrErr = llvm::MemoryBuffer::getFileOrSTDIN(Invocation.getInputFilenames()[0]); if (!FileBufOrErr) { Instance.getASTContext().Diags.diagnose(SourceLoc(), diag::error_open_input_file, Invocation.getInputFilenames()[0], FileBufOrErr.getError().message()); return true; } llvm::MemoryBuffer *MainFile = FileBufOrErr.get().get(); llvm::SMDiagnostic Err; std::unique_ptr<llvm::Module> Module = llvm::parseIR( MainFile->getMemBufferRef(), Err, LLVMContext); if (!Module) { // TODO: Translate from the diagnostic info to the SourceManager location // if available. Instance.getASTContext().Diags.diagnose(SourceLoc(), diag::error_parse_input_file, Invocation.getInputFilenames()[0], Err.getMessage()); return true; } // TODO: remove once the frontend understands what action it should perform IRGenOpts.OutputKind = getOutputKind(Action); return performLLVM(IRGenOpts, Instance.getASTContext(), Module.get()); } ReferencedNameTracker nameTracker; bool shouldTrackReferences = !opts.ReferenceDependenciesFilePath.empty(); if (shouldTrackReferences) Instance.setReferencedNameTracker(&nameTracker); if (Action == FrontendOptions::Parse || Action == FrontendOptions::DumpParse || Action == FrontendOptions::DumpInterfaceHash || Action == FrontendOptions::EmitImportedModules) Instance.performParseOnly(); else Instance.performSema(); if (Action == FrontendOptions::Parse) return Instance.getASTContext().hadError(); if (observer) { observer->performedSemanticAnalysis(Instance); } if (Stats) { countStatsPostSema(*Stats, Instance); } FrontendOptions::DebugCrashMode CrashMode = opts.CrashMode; if (CrashMode == FrontendOptions::DebugCrashMode::AssertAfterParse) debugFailWithAssertion(); else if (CrashMode == FrontendOptions::DebugCrashMode::CrashAfterParse) debugFailWithCrash(); ASTContext &Context = Instance.getASTContext(); if (Invocation.getMigratorOptions().shouldRunMigrator()) { migrator::updateCodeAndEmitRemap(&Instance, Invocation); } if (Action == FrontendOptions::REPL) { runREPL(Instance, ProcessCmdLine(Args.begin(), Args.end()), Invocation.getParseStdlib()); return Context.hadError(); } SourceFile *PrimarySourceFile = Instance.getPrimarySourceFile(); // We've been told to dump the AST (either after parsing or type-checking, // which is already differentiated in CompilerInstance::performSema()), // so dump or print the main source file and return. if (Action == FrontendOptions::DumpParse || Action == FrontendOptions::DumpAST || Action == FrontendOptions::PrintAST || Action == FrontendOptions::DumpScopeMaps || Action == FrontendOptions::DumpTypeRefinementContexts || Action == FrontendOptions::DumpInterfaceHash) { SourceFile *SF = PrimarySourceFile; if (!SF) { SourceFileKind Kind = Invocation.getSourceFileKind(); SF = &Instance.getMainModule()->getMainSourceFile(Kind); } if (Action == FrontendOptions::PrintAST) SF->print(llvm::outs(), PrintOptions::printEverything()); else if (Action == FrontendOptions::DumpScopeMaps) { ASTScope &scope = SF->getScope(); if (opts.DumpScopeMapLocations.empty()) { scope.expandAll(); } else if (auto bufferID = SF->getBufferID()) { SourceManager &sourceMgr = Instance.getSourceMgr(); // Probe each of the locations, and dump what we find. for (auto lineColumn : opts.DumpScopeMapLocations) { SourceLoc loc = sourceMgr.getLocForLineCol(*bufferID, lineColumn.first, lineColumn.second); if (loc.isInvalid()) continue; llvm::errs() << "***Scope at " << lineColumn.first << ":" << lineColumn.second << "***\n"; auto locScope = scope.findInnermostEnclosingScope(loc); locScope->print(llvm::errs(), 0, false, false); // Dump the AST context, too. if (auto dc = locScope->getDeclContext()) { dc->printContext(llvm::errs()); } // Grab the local bindings introduced by this scope. auto localBindings = locScope->getLocalBindings(); if (!localBindings.empty()) { llvm::errs() << "Local bindings: "; interleave(localBindings.begin(), localBindings.end(), [&](ValueDecl *value) { llvm::errs() << value->getFullName(); }, [&]() { llvm::errs() << " "; }); llvm::errs() << "\n"; } } llvm::errs() << "***Complete scope map***\n"; } // Print the resulting map. scope.print(llvm::errs()); } else if (Action == FrontendOptions::DumpTypeRefinementContexts) SF->getTypeRefinementContext()->dump(llvm::errs(), Context.SourceMgr); else if (Action == FrontendOptions::DumpInterfaceHash) SF->dumpInterfaceHash(llvm::errs()); else SF->dump(); return Context.hadError(); } else if (Action == FrontendOptions::EmitImportedModules) { emitImportedModules(Context, Instance.getMainModule(), opts); return Context.hadError(); } // If we were asked to print Clang stats, do so. if (opts.PrintClangStats && Context.getClangModuleLoader()) Context.getClangModuleLoader()->printStatistics(); if (!opts.DependenciesFilePath.empty()) (void)emitMakeDependencies(Context.Diags, *Instance.getDependencyTracker(), opts); if (shouldTrackReferences) emitReferenceDependencies(Context.Diags, Instance.getPrimarySourceFile(), *Instance.getDependencyTracker(), opts); if (!opts.LoadedModuleTracePath.empty()) (void)emitLoadedModuleTrace(Context, *Instance.getDependencyTracker(), opts); if (Context.hadError()) return true; // FIXME: This is still a lousy approximation of whether the module file will // be externally consumed. bool moduleIsPublic = !Instance.getMainModule()->hasEntryPoint() && opts.ImplicitObjCHeaderPath.empty() && !Context.LangOpts.EnableAppExtensionRestrictions; // We've just been told to perform a typecheck, so we can return now. if (Action == FrontendOptions::Typecheck) { if (!opts.ObjCHeaderOutputPath.empty()) return printAsObjC(opts.ObjCHeaderOutputPath, Instance.getMainModule(), opts.ImplicitObjCHeaderPath, moduleIsPublic); return Context.hadError(); } if (Action == FrontendOptions::EmitTBD) { auto hasMultipleIRGenThreads = Invocation.getSILOptions().NumThreads > 1; return writeTBD(Instance.getMainModule(), hasMultipleIRGenThreads, opts.getSingleOutputFilename()); } assert(Action >= FrontendOptions::EmitSILGen && "All actions not requiring SILGen must have been handled!"); std::unique_ptr<SILModule> SM = Instance.takeSILModule(); if (!SM) { if (opts.PrimaryInput.hasValue() && opts.PrimaryInput.getValue().isFilename()) { FileUnit *PrimaryFile = PrimarySourceFile; if (!PrimaryFile) { auto Index = opts.PrimaryInput.getValue().Index; PrimaryFile = Instance.getMainModule()->getFiles()[Index]; } SM = performSILGeneration(*PrimaryFile, Invocation.getSILOptions(), None, opts.SILSerializeAll); } else { SM = performSILGeneration(Instance.getMainModule(), Invocation.getSILOptions(), opts.SILSerializeAll, true); } } if (observer) { observer->performedSILGeneration(*SM); } if (Stats) { countStatsPostSILGen(*Stats, *SM); } // We've been told to emit SIL after SILGen, so write it now. if (Action == FrontendOptions::EmitSILGen) { // If we are asked to link all, link all. if (Invocation.getSILOptions().LinkMode == SILOptions::LinkAll) performSILLinking(SM.get(), true); return writeSIL(*SM, Instance.getMainModule(), opts.EmitVerboseSIL, opts.getSingleOutputFilename(), opts.EmitSortedSIL); } if (Action == FrontendOptions::EmitSIBGen) { // If we are asked to link all, link all. if (Invocation.getSILOptions().LinkMode == SILOptions::LinkAll) performSILLinking(SM.get(), true); auto DC = PrimarySourceFile ? ModuleOrSourceFile(PrimarySourceFile) : Instance.getMainModule(); if (!opts.ModuleOutputPath.empty()) { SerializationOptions serializationOpts; serializationOpts.OutputPath = opts.ModuleOutputPath.c_str(); serializationOpts.SerializeAllSIL = true; serializationOpts.IsSIB = true; serialize(DC, serializationOpts, SM.get()); } return Context.hadError(); } // Perform "stable" optimizations that are invariant across compiler versions. if (!Invocation.getDiagnosticOptions().SkipDiagnosticPasses) { if (runSILDiagnosticPasses(*SM)) return true; if (observer) { observer->performedSILDiagnostics(*SM); } } else { // Even if we are not supposed to run the diagnostic passes, we still need // to run the ownership evaluator. if (runSILOwnershipEliminatorPass(*SM)) return true; } // Now if we are asked to link all, link all. if (Invocation.getSILOptions().LinkMode == SILOptions::LinkAll) performSILLinking(SM.get(), true); if (Invocation.getSILOptions().MergePartialModules) SM->linkAllFromCurrentModule(); { SharedTimer timer("SIL verification, pre-optimization"); SM->verify(); } // Perform SIL optimization passes if optimizations haven't been disabled. // These may change across compiler versions. { SharedTimer timer("SIL optimization"); if (Invocation.getSILOptions().Optimization > SILOptions::SILOptMode::None) { runSILOptPreparePasses(*SM); StringRef CustomPipelinePath = Invocation.getSILOptions().ExternalPassPipelineFilename; if (!CustomPipelinePath.empty()) { runSILOptimizationPassesWithFileSpecification(*SM, CustomPipelinePath); } else { runSILOptimizationPasses(*SM); } } else { runSILPassesForOnone(*SM); } } if (observer) { observer->performedSILOptimization(*SM); } if (Stats) { countStatsPostSILOpt(*Stats, *SM); } { SharedTimer timer("SIL verification, post-optimization"); SM->verify(); } // Gather instruction counts if we are asked to do so. if (SM->getOptions().PrintInstCounts) { performSILInstCount(&*SM); } // Get the main source file's private discriminator and attach it to // the compile unit's flags. if (PrimarySourceFile) { Identifier PD = PrimarySourceFile->getPrivateDiscriminator(); if (!PD.empty()) IRGenOpts.DWARFDebugFlags += (" -private-discriminator "+PD.str()).str(); } if (!opts.ObjCHeaderOutputPath.empty()) { (void)printAsObjC(opts.ObjCHeaderOutputPath, Instance.getMainModule(), opts.ImplicitObjCHeaderPath, moduleIsPublic); } if (Action == FrontendOptions::EmitSIB) { auto DC = PrimarySourceFile ? ModuleOrSourceFile(PrimarySourceFile) : Instance.getMainModule(); if (!opts.ModuleOutputPath.empty()) { SerializationOptions serializationOpts; serializationOpts.OutputPath = opts.ModuleOutputPath.c_str(); serializationOpts.SerializeAllSIL = true; serializationOpts.IsSIB = true; serialize(DC, serializationOpts, SM.get()); } return Context.hadError(); } if (!opts.ModuleOutputPath.empty() || !opts.ModuleDocOutputPath.empty()) { auto DC = PrimarySourceFile ? ModuleOrSourceFile(PrimarySourceFile) : Instance.getMainModule(); if (!opts.ModuleOutputPath.empty()) { SerializationOptions serializationOpts; serializationOpts.OutputPath = opts.ModuleOutputPath.c_str(); serializationOpts.DocOutputPath = opts.ModuleDocOutputPath.c_str(); serializationOpts.GroupInfoPath = opts.GroupInfoPath.c_str(); serializationOpts.SerializeAllSIL = opts.SILSerializeAll; if (opts.SerializeBridgingHeader) serializationOpts.ImportedHeader = opts.ImplicitObjCHeaderPath; serializationOpts.ModuleLinkName = opts.ModuleLinkName; serializationOpts.ExtraClangOptions = Invocation.getClangImporterOptions().ExtraArgs; serializationOpts.EnableNestedTypeLookupTable = opts.EnableSerializationNestedTypeLookupTable; if (!IRGenOpts.ForceLoadSymbolName.empty()) serializationOpts.AutolinkForceLoad = true; // Options contain information about the developer's computer, // so only serialize them if the module isn't going to be shipped to // the public. serializationOpts.SerializeOptionsForDebugging = !moduleIsPublic || opts.AlwaysSerializeDebuggingOptions; serialize(DC, serializationOpts, SM.get()); } if (Action == FrontendOptions::EmitModuleOnly) return Context.hadError(); } assert(Action >= FrontendOptions::EmitSIL && "All actions not requiring SILPasses must have been handled!"); // We've been told to write canonical SIL, so write it now. if (Action == FrontendOptions::EmitSIL) { return writeSIL(*SM, Instance.getMainModule(), opts.EmitVerboseSIL, opts.getSingleOutputFilename(), opts.EmitSortedSIL); } assert(Action >= FrontendOptions::Immediate && "All actions not requiring IRGen must have been handled!"); assert(Action != FrontendOptions::REPL && "REPL mode must be handled immediately after Instance->performSema()"); // Check if we had any errors; if we did, don't proceed to IRGen. if (Context.hadError()) return true; // Convert SIL to a lowered form suitable for IRGen. runSILLoweringPasses(*SM); // TODO: remove once the frontend understands what action it should perform IRGenOpts.OutputKind = getOutputKind(Action); if (Action == FrontendOptions::Immediate) { assert(!PrimarySourceFile && "-i doesn't work in -primary-file mode"); IRGenOpts.UseJIT = true; IRGenOpts.DebugInfoKind = IRGenDebugInfoKind::Normal; const ProcessCmdLine &CmdLine = ProcessCmdLine(opts.ImmediateArgv.begin(), opts.ImmediateArgv.end()); Instance.setSILModule(std::move(SM)); if (observer) { observer->aboutToRunImmediately(Instance); } ReturnValue = RunImmediately(Instance, CmdLine, IRGenOpts, Invocation.getSILOptions()); return Context.hadError(); } // FIXME: We shouldn't need to use the global context here, but // something is persisting across calls to performIRGeneration. auto &LLVMContext = getGlobalLLVMContext(); std::unique_ptr<llvm::Module> IRModule; llvm::GlobalVariable *HashGlobal; if (PrimarySourceFile) { IRModule = performIRGeneration(IRGenOpts, *PrimarySourceFile, std::move(SM), opts.getSingleOutputFilename(), LLVMContext, 0, &HashGlobal); } else { IRModule = performIRGeneration(IRGenOpts, Instance.getMainModule(), std::move(SM), opts.getSingleOutputFilename(), LLVMContext, &HashGlobal); } // Just because we had an AST error it doesn't mean we can't performLLVM. bool HadError = Instance.getASTContext().hadError(); // If the AST Context has no errors but no IRModule is available, // parallelIRGen happened correctly, since parallel IRGen produces multiple // modules. if (!IRModule) { return HadError; } if (Stats) { countStatsPostIRGen(*Stats, *IRModule); } if (opts.ValidateTBDAgainstIR) { auto hasMultipleIRGenThreads = Invocation.getSILOptions().NumThreads > 1; bool error; if (PrimarySourceFile) error = validateTBD(PrimarySourceFile, *IRModule, hasMultipleIRGenThreads); else error = validateTBD(Instance.getMainModule(), *IRModule, hasMultipleIRGenThreads); if (error) return true; } std::unique_ptr<llvm::TargetMachine> TargetMachine = createTargetMachine(IRGenOpts, Context); version::Version EffectiveLanguageVersion = Context.LangOpts.EffectiveLanguageVersion; // Free up some compiler resources now that we have an IRModule. Instance.freeContextAndSIL(); // Now that we have a single IR Module, hand it over to performLLVM. return performLLVM(IRGenOpts, &Instance.getDiags(), nullptr, HashGlobal, IRModule.get(), TargetMachine.get(), EffectiveLanguageVersion, opts.getSingleOutputFilename()) || HadError; } /// Returns true if an error occurred. static bool dumpAPI(ModuleDecl *Mod, StringRef OutDir) { using namespace llvm::sys; auto getOutPath = [&](SourceFile *SF) -> std::string { SmallString<256> Path = OutDir; StringRef Filename = SF->getFilename(); path::append(Path, path::filename(Filename)); return Path.str(); }; std::unordered_set<std::string> Filenames; auto dumpFile = [&](SourceFile *SF) -> bool { SmallString<512> TempBuf; llvm::raw_svector_ostream TempOS(TempBuf); PrintOptions PO = PrintOptions::printInterface(); PO.PrintOriginalSourceText = true; PO.Indent = 2; PO.PrintAccessibility = false; PO.SkipUnderscoredStdlibProtocols = true; SF->print(TempOS, PO); if (TempOS.str().trim().empty()) return false; // nothing to show. std::string OutPath = getOutPath(SF); bool WasInserted = Filenames.insert(OutPath).second; if (!WasInserted) { llvm::errs() << "multiple source files ended up with the same dump API " "filename to write to: " << OutPath << '\n'; return true; } std::error_code EC; llvm::raw_fd_ostream OS(OutPath, EC, fs::OpenFlags::F_RW); if (EC) { llvm::errs() << "error opening file '" << OutPath << "': " << EC.message() << '\n'; return true; } OS << TempOS.str(); return false; }; std::error_code EC = fs::create_directories(OutDir); if (EC) { llvm::errs() << "error creating directory '" << OutDir << "': " << EC.message() << '\n'; return true; } for (auto *FU : Mod->getFiles()) { if (auto *SF = dyn_cast<SourceFile>(FU)) if (dumpFile(SF)) return true; } return false; } int swift::performFrontend(ArrayRef<const char *> Args, const char *Argv0, void *MainAddr, FrontendObserver *observer) { llvm::InitializeAllTargets(); llvm::InitializeAllTargetMCs(); llvm::InitializeAllAsmPrinters(); llvm::InitializeAllAsmParsers(); PrintingDiagnosticConsumer PDC; // Hopefully we won't trigger any LLVM-level fatal errors, but if we do try // to route them through our usual textual diagnostics before crashing. // // Unfortunately it's not really safe to do anything else, since very // low-level operations in LLVM can trigger fatal errors. auto diagnoseFatalError = [&PDC](const std::string &reason, bool shouldCrash){ static const std::string *recursiveFatalError = nullptr; if (recursiveFatalError) { // Report the /original/ error through LLVM's default handler, not // whatever we encountered. llvm::remove_fatal_error_handler(); llvm::report_fatal_error(*recursiveFatalError, shouldCrash); } recursiveFatalError = &reason; SourceManager dummyMgr; PDC.handleDiagnostic(dummyMgr, SourceLoc(), DiagnosticKind::Error, "fatal error encountered during compilation; please " "file a bug report with your project and the crash " "log", {}, DiagnosticInfo()); PDC.handleDiagnostic(dummyMgr, SourceLoc(), DiagnosticKind::Note, reason, {}, DiagnosticInfo()); if (shouldCrash) abort(); }; llvm::ScopedFatalErrorHandler handler([](void *rawCallback, const std::string &reason, bool shouldCrash) { auto *callback = static_cast<decltype(&diagnoseFatalError)>(rawCallback); (*callback)(reason, shouldCrash); }, &diagnoseFatalError); std::unique_ptr<CompilerInstance> Instance = llvm::make_unique<CompilerInstance>(); Instance->addDiagnosticConsumer(&PDC); struct FinishDiagProcessingCheckRAII { bool CalledFinishDiagProcessing = false; ~FinishDiagProcessingCheckRAII() { assert(CalledFinishDiagProcessing && "returned from the function " "without calling finishDiagProcessing"); } } FinishDiagProcessingCheckRAII; auto finishDiagProcessing = [&](int retValue) -> int { FinishDiagProcessingCheckRAII.CalledFinishDiagProcessing = true; bool err = Instance->getDiags().finishProcessing(); return retValue ? retValue : err; }; if (Args.empty()) { Instance->getDiags().diagnose(SourceLoc(), diag::error_no_frontend_args); return finishDiagProcessing(1); } CompilerInvocation Invocation; std::string MainExecutablePath = llvm::sys::fs::getMainExecutable(Argv0, MainAddr); Invocation.setMainExecutablePath(MainExecutablePath); SmallString<128> workingDirectory; llvm::sys::fs::current_path(workingDirectory); // Parse arguments. if (Invocation.parseArgs(Args, Instance->getDiags(), workingDirectory)) { return finishDiagProcessing(1); } // Setting DWARF Version depend on platform IRGenOptions &IRGenOpts = Invocation.getIRGenOptions(); IRGenOpts.DWARFVersion = swift::DWARFVersion; // The compiler invocation is now fully configured; notify our observer. if (observer) { observer->parsedArgs(Invocation); } if (Invocation.getFrontendOptions().PrintHelp || Invocation.getFrontendOptions().PrintHelpHidden) { unsigned IncludedFlagsBitmask = options::FrontendOption; unsigned ExcludedFlagsBitmask = Invocation.getFrontendOptions().PrintHelpHidden ? 0 : llvm::opt::HelpHidden; std::unique_ptr<llvm::opt::OptTable> Options(createSwiftOptTable()); Options->PrintHelp(llvm::outs(), displayName(MainExecutablePath).c_str(), "Swift frontend", IncludedFlagsBitmask, ExcludedFlagsBitmask); return finishDiagProcessing(0); } if (Invocation.getFrontendOptions().RequestedAction == FrontendOptions::NoneAction) { Instance->getDiags().diagnose(SourceLoc(), diag::error_missing_frontend_action); return finishDiagProcessing(1); } // Because the serialized diagnostics consumer is initialized here, // diagnostics emitted above, within CompilerInvocation::parseArgs, are never // serialized. This is a non-issue because, in nearly all cases, frontend // arguments are generated by the driver, not directly by a user. The driver // is responsible for emitting diagnostics for its own errors. See SR-2683 // for details. std::unique_ptr<DiagnosticConsumer> SerializedConsumer; { const std::string &SerializedDiagnosticsPath = Invocation.getFrontendOptions().SerializedDiagnosticsPath; if (!SerializedDiagnosticsPath.empty()) { SerializedConsumer.reset( serialized_diagnostics::createConsumer(SerializedDiagnosticsPath)); Instance->addDiagnosticConsumer(SerializedConsumer.get()); } } std::unique_ptr<DiagnosticConsumer> FixitsConsumer; { const std::string &FixitsOutputPath = Invocation.getFrontendOptions().FixitsOutputPath; if (!FixitsOutputPath.empty()) { FixitsConsumer.reset(new JSONFixitWriter(FixitsOutputPath, Invocation.getDiagnosticOptions())); Instance->addDiagnosticConsumer(FixitsConsumer.get()); } } if (Invocation.getDiagnosticOptions().UseColor) PDC.forceColors(); if (Invocation.getFrontendOptions().DebugTimeCompilation) SharedTimer::enableCompilationTimers(); if (Invocation.getFrontendOptions().PrintStats) { llvm::EnableStatistics(); } const std::string &StatsOutputDir = Invocation.getFrontendOptions().StatsOutputDir; std::unique_ptr<UnifiedStatsReporter> StatsReporter; if (!StatsOutputDir.empty()) { auto &opts = Invocation.getFrontendOptions(); std::string TargetName = opts.ModuleName; if (opts.PrimaryInput.hasValue() && opts.PrimaryInput.getValue().isFilename()) { auto Index = opts.PrimaryInput.getValue().Index; TargetName += "."; TargetName += llvm::sys::path::filename(opts.InputFilenames[Index]); } StatsReporter = llvm::make_unique<UnifiedStatsReporter>("swift-frontend", TargetName, StatsOutputDir); } const DiagnosticOptions &diagOpts = Invocation.getDiagnosticOptions(); if (diagOpts.VerifyMode != DiagnosticOptions::NoVerify) { enableDiagnosticVerifier(Instance->getSourceMgr()); } DependencyTracker depTracker; if (!Invocation.getFrontendOptions().DependenciesFilePath.empty() || !Invocation.getFrontendOptions().ReferenceDependenciesFilePath.empty() || !Invocation.getFrontendOptions().LoadedModuleTracePath.empty()) { Instance->setDependencyTracker(&depTracker); } if (Instance->setup(Invocation)) { return finishDiagProcessing(1); } if (StatsReporter) { // Install stats-reporter somewhere visible for subsystems that // need to bump counters as they work, rather than measure // accumulated work on completion (mostly: TypeChecker). Instance->getASTContext().Stats = StatsReporter.get(); } // The compiler instance has been configured; notify our observer. if (observer) { observer->configuredCompiler(*Instance); } int ReturnValue = 0; bool HadError = performCompile(*Instance, Invocation, Args, ReturnValue, observer, StatsReporter.get()); if (!HadError) { Mangle::printManglingStats(); } if (!HadError && !Invocation.getFrontendOptions().DumpAPIPath.empty()) { HadError = dumpAPI(Instance->getMainModule(), Invocation.getFrontendOptions().DumpAPIPath); } if (diagOpts.VerifyMode != DiagnosticOptions::NoVerify) { HadError = verifyDiagnostics( Instance->getSourceMgr(), Instance->getInputBufferIDs(), diagOpts.VerifyMode == DiagnosticOptions::VerifyAndApplyFixes, diagOpts.VerifyIgnoreUnknown); DiagnosticEngine &diags = Instance->getDiags(); if (diags.hasFatalErrorOccurred() && !Invocation.getDiagnosticOptions().ShowDiagnosticsAfterFatalError) { diags.resetHadAnyError(); diags.diagnose(SourceLoc(), diag::verify_encountered_fatal); HadError = true; } } return finishDiagProcessing(HadError ? 1 : ReturnValue); } void FrontendObserver::parsedArgs(CompilerInvocation &invocation) {} void FrontendObserver::configuredCompiler(CompilerInstance &instance) {} void FrontendObserver::performedSemanticAnalysis(CompilerInstance &instance) {} void FrontendObserver::performedSILGeneration(SILModule &module) {} void FrontendObserver::performedSILDiagnostics(SILModule &module) {} void FrontendObserver::performedSILOptimization(SILModule &module) {} void FrontendObserver::aboutToRunImmediately(CompilerInstance &instance) {}
/*** * * Copyright (c) 1996-2001, Valve LLC. All rights reserved. * * This product contains software technology licensed from Id * Software, Inc. ("Id Technology"). Id Technology (c) 1996 Id Software, Inc. * All Rights Reserved. * * Use, distribution, and modification of this source code and/or resulting * object code is restricted to non-commercial enhancements to products from * Valve LLC. All other use, distribution, or modification is prohibited * without written permission from Valve LLC. * ****/ /* ===== h_cycler.cpp ======================================================== The Halflife Cycler Monsters */ #include "extdll.h" #include "util.h" #include "cbase.h" #include "monsters.h" #include "animation.h" #include "weapons.h" #include "player.h" #define TEMP_FOR_SCREEN_SHOTS #ifdef TEMP_FOR_SCREEN_SHOTS //=================================================== class CCycler : public CBaseMonster { public: void GenericCyclerSpawn(const char *szModel, Vector vecMin, Vector vecMax); virtual int ObjectCaps( void ) { return (CBaseEntity :: ObjectCaps() | FCAP_IMPULSE_USE); } int TakeDamage( entvars_t* pevInflictor, entvars_t* pevAttacker, float flDamage, int bitsDamageType ); void Spawn( void ); void Think( void ); //void Pain( float flDamage ); void Use ( CBaseEntity *pActivator, CBaseEntity *pCaller, USE_TYPE useType, float value ); // Don't treat as a live target virtual BOOL IsAlive( void ) { return FALSE; } virtual int Save( CSave &save ); virtual int Restore( CRestore &restore ); static TYPEDESCRIPTION m_SaveData[]; int m_animate; }; TYPEDESCRIPTION CCycler::m_SaveData[] = { DEFINE_FIELD( CCycler, m_animate, FIELD_INTEGER ), }; IMPLEMENT_SAVERESTORE( CCycler, CBaseMonster ); // // we should get rid of all the other cyclers and replace them with this. // class CGenericCycler : public CCycler { public: void Spawn( void ) { GenericCyclerSpawn( STRING(pev->model), Vector(-16, -16, 0), Vector(16, 16, 72) ); } }; LINK_ENTITY_TO_CLASS( cycler, CGenericCycler ); // Probe droid imported for tech demo compatibility // // PROBE DROID // class CCyclerProbe : public CCycler { public: void Spawn( void ); }; LINK_ENTITY_TO_CLASS( cycler_prdroid, CCyclerProbe ); void CCyclerProbe :: Spawn( void ) { pev->origin = pev->origin + Vector ( 0, 0, 16 ); GenericCyclerSpawn( "models/prdroid.mdl", Vector(-16,-16,-16), Vector(16,16,16)); } // Cycler member functions void CCycler :: GenericCyclerSpawn(const char *szModel, Vector vecMin, Vector vecMax) { if (!szModel || !*szModel) { ALERT(at_error, "cycler at %.0f %.0f %0.f missing modelname", pev->origin.x, pev->origin.y, pev->origin.z ); REMOVE_ENTITY(ENT(pev)); return; } pev->classname = MAKE_STRING("cycler"); PRECACHE_MODEL( szModel ); SET_MODEL(ENT(pev), szModel); CCycler::Spawn( ); UTIL_SetSize(pev, vecMin, vecMax); } void CCycler :: Spawn( ) { InitBoneControllers(); pev->solid = SOLID_SLIDEBOX; pev->movetype = MOVETYPE_NONE; pev->takedamage = DAMAGE_YES; pev->effects = 0; pev->health = 80000;// no cycler should die pev->yaw_speed = 5; pev->ideal_yaw = pev->angles.y; ChangeYaw( 360 ); m_flFrameRate = 75; m_flGroundSpeed = 0; pev->nextthink += 1.0; ResetSequenceInfo( ); if (pev->sequence != 0 || pev->frame != 0) { m_animate = 0; pev->framerate = 0; } else { m_animate = 1; } } // // cycler think // void CCycler :: Think( void ) { pev->nextthink = gpGlobals->time + 0.1; if (m_animate) { StudioFrameAdvance ( ); } if (m_fSequenceFinished && !m_fSequenceLoops) { // ResetSequenceInfo(); // hack to avoid reloading model every frame pev->animtime = gpGlobals->time; pev->framerate = 1.0; m_fSequenceFinished = FALSE; m_flLastEventCheck = gpGlobals->time; pev->frame = 0; if (!m_animate) pev->framerate = 0.0; // FIX: don't reset framerate } } // // CyclerUse - starts a rotation trend // void CCycler :: Use ( CBaseEntity *pActivator, CBaseEntity *pCaller, USE_TYPE useType, float value ) { m_animate = !m_animate; if (m_animate) pev->framerate = 1.0; else pev->framerate = 0.0; } // // CyclerPain , changes sequences when shot // //void CCycler :: Pain( float flDamage ) int CCycler :: TakeDamage( entvars_t* pevInflictor, entvars_t* pevAttacker, float flDamage, int bitsDamageType ) { if (m_animate) { pev->sequence++; ResetSequenceInfo( ); if (m_flFrameRate == 0.0) { pev->sequence = 0; ResetSequenceInfo( ); } pev->frame = 0; } else { pev->framerate = 1.0; StudioFrameAdvance ( 0.1 ); pev->framerate = 0; ALERT( at_console, "sequence: %d, frame %.0f\n", pev->sequence, pev->frame ); } return 0; } #endif class CCyclerSprite : public CBaseEntity { public: void Spawn( void ); void Think( void ); void Use( CBaseEntity *pActivator, CBaseEntity *pCaller, USE_TYPE useType, float value ); virtual int ObjectCaps( void ) { return (CBaseEntity :: ObjectCaps() | FCAP_DONT_SAVE | FCAP_IMPULSE_USE); } virtual int TakeDamage( entvars_t* pevInflictor, entvars_t* pevAttacker, float flDamage, int bitsDamageType ); void Animate( float frames ); virtual int Save( CSave &save ); virtual int Restore( CRestore &restore ); static TYPEDESCRIPTION m_SaveData[]; inline int ShouldAnimate( void ) { return m_animate && m_maxFrame > 1.0; } int m_animate; float m_lastTime; float m_maxFrame; }; LINK_ENTITY_TO_CLASS( cycler_sprite, CCyclerSprite ); TYPEDESCRIPTION CCyclerSprite::m_SaveData[] = { DEFINE_FIELD( CCyclerSprite, m_animate, FIELD_INTEGER ), DEFINE_FIELD( CCyclerSprite, m_lastTime, FIELD_TIME ), DEFINE_FIELD( CCyclerSprite, m_maxFrame, FIELD_FLOAT ), }; IMPLEMENT_SAVERESTORE( CCyclerSprite, CBaseEntity ); void CCyclerSprite::Spawn( void ) { pev->solid = SOLID_SLIDEBOX; pev->movetype = MOVETYPE_NONE; pev->takedamage = DAMAGE_YES; pev->effects = 0; pev->frame = 0; pev->nextthink = gpGlobals->time + 0.1; m_animate = 1; m_lastTime = gpGlobals->time; PRECACHE_MODEL( (char *)STRING(pev->model) ); SET_MODEL( ENT(pev), STRING(pev->model) ); m_maxFrame = (float) MODEL_FRAMES( pev->modelindex ) - 1; } void CCyclerSprite::Think( void ) { if ( ShouldAnimate() ) Animate( pev->framerate * (gpGlobals->time - m_lastTime) ); pev->nextthink = gpGlobals->time + 0.1; m_lastTime = gpGlobals->time; } void CCyclerSprite::Use( CBaseEntity *pActivator, CBaseEntity *pCaller, USE_TYPE useType, float value ) { m_animate = !m_animate; ALERT( at_console, "Sprite: %s\n", STRING(pev->model) ); } int CCyclerSprite::TakeDamage( entvars_t* pevInflictor, entvars_t* pevAttacker, float flDamage, int bitsDamageType ) { if ( m_maxFrame > 1.0 ) { Animate( 1.0 ); } return 1; } void CCyclerSprite::Animate( float frames ) { pev->frame += frames; if ( m_maxFrame > 0 ) pev->frame = fmod( pev->frame, m_maxFrame ); } class CWeaponCycler : public CBasePlayerWeapon { public: void Spawn( void ); int iItemSlot( void ) { return 1; } int GetItemInfo(ItemInfo *p) {return 0; } void PrimaryAttack( void ); void SecondaryAttack( void ); BOOL Deploy( void ); void Holster( int skiplocal = 0 ); int m_iszModel; int m_iModel; }; LINK_ENTITY_TO_CLASS( cycler_weapon, CWeaponCycler ); void CWeaponCycler::Spawn( ) { pev->solid = SOLID_SLIDEBOX; pev->movetype = MOVETYPE_NONE; PRECACHE_MODEL( (char *)STRING(pev->model) ); SET_MODEL( ENT(pev), STRING(pev->model) ); m_iszModel = pev->model; m_iModel = pev->modelindex; UTIL_SetOrigin( pev, pev->origin ); UTIL_SetSize(pev, Vector(-16, -16, 0), Vector(16, 16, 16)); SetTouch( &CWeaponCycler::DefaultTouch ); } BOOL CWeaponCycler::Deploy( ) { m_pPlayer->pev->viewmodel = m_iszModel; m_pPlayer->m_flNextAttack = UTIL_WeaponTimeBase() + 1.0; SendWeaponAnim( 0 ); m_iClip = 0; return TRUE; } void CWeaponCycler::Holster( int skiplocal /* = 0 */ ) { m_pPlayer->m_flNextAttack = UTIL_WeaponTimeBase() + 0.5; } void CWeaponCycler::PrimaryAttack() { SendWeaponAnim( pev->sequence ); m_flNextPrimaryAttack = gpGlobals->time + 0.3; } void CWeaponCycler::SecondaryAttack( void ) { float flFrameRate, flGroundSpeed; pev->sequence = (pev->sequence + 1) % 8; pev->modelindex = m_iModel; void *pmodel = GET_MODEL_PTR( ENT(pev) ); GetSequenceInfo( pmodel, pev, &flFrameRate, &flGroundSpeed ); pev->modelindex = 0; if (flFrameRate == 0.0) { pev->sequence = 0; } SendWeaponAnim( pev->sequence ); m_flNextSecondaryAttack = gpGlobals->time + 0.3; } // Flaming Wreakage class CWreckage : public CBaseMonster { int Save( CSave &save ); int Restore( CRestore &restore ); static TYPEDESCRIPTION m_SaveData[]; void Spawn( void ); void Precache( void ); void Think( void ); int m_flStartTime; }; TYPEDESCRIPTION CWreckage::m_SaveData[] = { DEFINE_FIELD( CWreckage, m_flStartTime, FIELD_TIME ), }; IMPLEMENT_SAVERESTORE( CWreckage, CBaseMonster ); LINK_ENTITY_TO_CLASS( cycler_wreckage, CWreckage ); void CWreckage::Spawn( void ) { pev->solid = SOLID_NOT; pev->movetype = MOVETYPE_NONE; pev->takedamage = 0; pev->effects = 0; pev->frame = 0; pev->nextthink = gpGlobals->time + 0.1; if (pev->model) { PRECACHE_MODEL( (char *)STRING(pev->model) ); SET_MODEL( ENT(pev), STRING(pev->model) ); } // pev->scale = 5.0; m_flStartTime = gpGlobals->time; } void CWreckage::Precache( ) { if ( pev->model ) PRECACHE_MODEL( (char *)STRING(pev->model) ); } void CWreckage::Think( void ) { StudioFrameAdvance( ); pev->nextthink = gpGlobals->time + 0.2; if (pev->dmgtime) { if (pev->dmgtime < gpGlobals->time) { UTIL_Remove( this ); return; } else if (RANDOM_FLOAT( 0, pev->dmgtime - m_flStartTime ) > pev->dmgtime - gpGlobals->time) { return; } } Vector VecSrc; VecSrc.x = RANDOM_FLOAT( pev->absmin.x, pev->absmax.x ); VecSrc.y = RANDOM_FLOAT( pev->absmin.y, pev->absmax.y ); VecSrc.z = RANDOM_FLOAT( pev->absmin.z, pev->absmax.z ); MESSAGE_BEGIN( MSG_PVS, SVC_TEMPENTITY, VecSrc ); WRITE_BYTE( TE_SMOKE ); WRITE_COORD( VecSrc.x ); WRITE_COORD( VecSrc.y ); WRITE_COORD( VecSrc.z ); WRITE_SHORT( g_sModelIndexSmoke ); WRITE_BYTE( RANDOM_LONG(0,49) + 50 ); // scale * 10 WRITE_BYTE( RANDOM_LONG(0, 3) + 8 ); // framerate MESSAGE_END(); }
// ARKSurvivalEvolved (329.9) SDK #ifdef _MSC_VER #pragma pack(push, 0x8) #endif #include "ARKSurvivalEvolved_EngramEntry_Ramp_Wood_parameters.hpp" namespace sdk { //--------------------------------------------------------------------------- //Functions //--------------------------------------------------------------------------- // Function EngramEntry_Ramp_Wood.EngramEntry_Ramp_Wood_C.ExecuteUbergraph_EngramEntry_Ramp_Wood // () // Parameters: // int EntryPoint (Parm, ZeroConstructor, IsPlainOldData) void UEngramEntry_Ramp_Wood_C::ExecuteUbergraph_EngramEntry_Ramp_Wood(int EntryPoint) { static auto fn = UObject::FindObject<UFunction>("Function EngramEntry_Ramp_Wood.EngramEntry_Ramp_Wood_C.ExecuteUbergraph_EngramEntry_Ramp_Wood"); UEngramEntry_Ramp_Wood_C_ExecuteUbergraph_EngramEntry_Ramp_Wood_Params params; params.EntryPoint = EntryPoint; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } } #ifdef _MSC_VER #pragma pack(pop) #endif
/** * Copyright (C) 2017 MongoDB Inc. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License, version 3, * as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * As a special exception, the copyright holders give permission to link the * code of portions of this program with the OpenSSL library under certain * conditions as described in each individual source file and distribute * linked combinations including the program with the OpenSSL library. You * must comply with the GNU Affero General Public License in all respects for * all of the code used other than as permitted herein. If you modify file(s) * with this exception, you may extend this exception to your version of the * file(s), but you are not obligated to do so. If you do not wish to do so, * delete this exception statement from your version. If you delete this * exception statement from all source files in the program, then also delete * it in the license file. */ #define MONGO_LOG_DEFAULT_COMPONENT ::mongo::logger::LogComponent::kNetwork #include "mongo/platform/basic.h" #include "mongo/transport/service_state_machine.h" #include "mongo/config.h" #include "mongo/db/client.h" #include "mongo/db/dbmessage.h" #include "mongo/db/stats/counters.h" #include "mongo/stdx/memory.h" #include "mongo/transport/message_compressor_manager.h" #include "mongo/transport/service_entry_point.h" #include "mongo/transport/service_executor_task_names.h" #include "mongo/transport/session.h" #include "mongo/transport/ticket.h" #include "mongo/transport/transport_layer.h" #include "mongo/util/assert_util.h" #include "mongo/util/concurrency/idle_thread_block.h" #include "mongo/util/concurrency/thread_name.h" #include "mongo/util/debug_util.h" #include "mongo/util/exit.h" #include "mongo/util/log.h" #include "mongo/util/net/message.h" #include "mongo/util/net/socket_exception.h" #include "mongo/util/net/thread_idle_callback.h" #include "mongo/util/quick_exit.h" namespace mongo { namespace { // Set up proper headers for formatting an exhaust request, if we need to bool setExhaustMessage(Message* m, const DbResponse& dbresponse) { MsgData::View header = dbresponse.response.header(); QueryResult::View qr = header.view2ptr(); long long cursorid = qr.getCursorId(); if (!cursorid) { return false; } invariant(dbresponse.exhaustNS.size() && dbresponse.exhaustNS[0]); auto ns = dbresponse.exhaustNS; // m->reset() will free this so we must cache a copy m->reset(); // Rebuild out the response. BufBuilder b(512); b.appendNum(static_cast<int>(0) /* size set later in setLen() */); b.appendNum(header.getId()); // message id b.appendNum(header.getResponseToMsgId()); // in response to b.appendNum(static_cast<int>(dbGetMore)); // opCode is OP_GET_MORE b.appendNum(static_cast<int>(0)); // Must be ZERO (reserved) b.appendStr(ns); // Namespace b.appendNum(static_cast<int>(0)); // ntoreturn b.appendNum(cursorid); // cursor id from the OP_REPLY MsgData::View(b.buf()).setLen(b.len()); m->setData(b.release()); return true; } } // namespace using transport::ServiceExecutor; using transport::TransportLayer; /* * This class wraps up the logic for swapping/unswapping the Client during runNext(). * * In debug builds this also ensures that only one thread is working on the SSM at once. */ class ServiceStateMachine::ThreadGuard { ThreadGuard(ThreadGuard&) = delete; ThreadGuard& operator=(ThreadGuard&) = delete; public: explicit ThreadGuard(ServiceStateMachine* ssm) : _ssm{ssm} { auto owned = _ssm->_owned.compareAndSwap(Ownership::kUnowned, Ownership::kOwned); if (owned == Ownership::kStatic) { dassert(haveClient()); dassert(Client::getCurrent() == _ssm->_dbClientPtr); _haveTakenOwnership = true; return; } #ifdef MONGO_CONFIG_DEBUG_BUILD invariant(owned == Ownership::kUnowned); _ssm->_owningThread.store(stdx::this_thread::get_id()); #endif // Set up the thread name auto oldThreadName = getThreadName(); if (oldThreadName != _ssm->_threadName) { _ssm->_oldThreadName = getThreadName().toString(); setThreadName(_ssm->_threadName); } // Swap the current Client so calls to cc() work as expected Client::setCurrent(std::move(_ssm->_dbClient)); _haveTakenOwnership = true; } // Constructing from a moved ThreadGuard invalidates the other thread guard. ThreadGuard(ThreadGuard&& other) : _ssm(other._ssm), _haveTakenOwnership(other._haveTakenOwnership) { other._haveTakenOwnership = false; } ThreadGuard& operator=(ThreadGuard&& other) { if (this != &other) { _ssm = other._ssm; _haveTakenOwnership = other._haveTakenOwnership; other._haveTakenOwnership = false; } return *this; }; ThreadGuard() = delete; ~ThreadGuard() { if (_haveTakenOwnership) release(); } explicit operator bool() const { #ifdef MONGO_CONFIG_DEBUG_BUILD if (_haveTakenOwnership) { invariant(_ssm->_owned.load() != Ownership::kUnowned); invariant(_ssm->_owningThread.load() == stdx::this_thread::get_id()); return true; } else { return false; } #else return _haveTakenOwnership; #endif } void markStaticOwnership() { dassert(static_cast<bool>(*this)); _ssm->_owned.store(Ownership::kStatic); } void release() { auto owned = _ssm->_owned.load(); #ifdef MONGO_CONFIG_DEBUG_BUILD dassert(_haveTakenOwnership); dassert(owned != Ownership::kUnowned); dassert(_ssm->_owningThread.load() == stdx::this_thread::get_id()); #endif if (owned != Ownership::kStatic) { if (haveClient()) { _ssm->_dbClient = Client::releaseCurrent(); } if (!_ssm->_oldThreadName.empty()) { setThreadName(_ssm->_oldThreadName); } } // If the session has ended, then it's unsafe to do anything but call the cleanup hook. if (_ssm->state() == State::Ended) { // The cleanup hook gets moved out of _ssm->_cleanupHook so that it can only be called // once. auto cleanupHook = std::move(_ssm->_cleanupHook); if (cleanupHook) cleanupHook(); // It's very important that the Guard returns here and that the SSM's state does not // get modified in any way after the cleanup hook is called. return; } _haveTakenOwnership = false; // If owned != Ownership::kOwned here then it can only equal Ownership::kStatic and we // should just return if (owned == Ownership::kOwned) { _ssm->_owned.store(Ownership::kUnowned); } } private: ServiceStateMachine* _ssm; bool _haveTakenOwnership = false; }; std::shared_ptr<ServiceStateMachine> ServiceStateMachine::create(ServiceContext* svcContext, transport::SessionHandle session, transport::Mode transportMode) { return std::make_shared<ServiceStateMachine>(svcContext, std::move(session), transportMode); } ServiceStateMachine::ServiceStateMachine(ServiceContext* svcContext, transport::SessionHandle session, transport::Mode transportMode) : _state{State::Created}, _sep{svcContext->getServiceEntryPoint()}, _transportMode(transportMode), _serviceContext(svcContext), _sessionHandle(session), _dbClient{svcContext->makeClient("conn", std::move(session))}, _dbClientPtr{_dbClient.get()}, _threadName{str::stream() << "conn" << _session()->id()} {} const transport::SessionHandle& ServiceStateMachine::_session() const { return _sessionHandle; } void ServiceStateMachine::_sourceMessage(ThreadGuard guard) { invariant(_inMessage.empty()); auto ticket = _session()->sourceMessage(&_inMessage); _state.store(State::SourceWait); guard.release(); if (_transportMode == transport::Mode::kSynchronous) { _sourceCallback([this](auto ticket) { MONGO_IDLE_THREAD_BLOCK; return _session()->getTransportLayer()->wait(std::move(ticket)); }(std::move(ticket))); } else if (_transportMode == transport::Mode::kAsynchronous) { _session()->getTransportLayer()->asyncWait( std::move(ticket), [this](Status status) { _sourceCallback(status); }); } } void ServiceStateMachine::_sinkMessage(ThreadGuard guard, Message toSink) { // Sink our response to the client auto ticket = _session()->sinkMessage(toSink); _state.store(State::SinkWait); guard.release(); if (_transportMode == transport::Mode::kSynchronous) { _sinkCallback(_session()->getTransportLayer()->wait(std::move(ticket))); } else if (_transportMode == transport::Mode::kAsynchronous) { _session()->getTransportLayer()->asyncWait( std::move(ticket), [this](Status status) { _sinkCallback(status); }); } } void ServiceStateMachine::_sourceCallback(Status status) { // The first thing to do is create a ThreadGuard which will take ownership of the SSM in this // thread. ThreadGuard guard(this); // Make sure we just called sourceMessage(); dassert(state() == State::SourceWait); auto remote = _session()->remote(); if (status.isOK()) { _state.store(State::Process); // Since we know that we're going to process a message, call scheduleNext() immediately // to schedule the call to processMessage() on the serviceExecutor (or just unwind the // stack) // If this callback doesn't own the ThreadGuard, then we're being called recursively, // and the executor shouldn't start a new thread to process the message - it can use this // one just after this returns. return _scheduleNextWithGuard(std::move(guard), ServiceExecutor::kMayRecurse, transport::ServiceExecutorTaskName::kSSMProcessMessage); } else if (ErrorCodes::isInterruption(status.code()) || ErrorCodes::isNetworkError(status.code())) { LOG(2) << "Session from " << remote << " encountered a network error during SourceMessage"; _state.store(State::EndSession); } else if (status == TransportLayer::TicketSessionClosedStatus) { // Our session may have been closed internally. LOG(2) << "Session from " << remote << " was closed internally during SourceMessage"; _state.store(State::EndSession); } else { log() << "Error receiving request from client: " << status << ". Ending connection from " << remote << " (connection id: " << _session()->id() << ")"; _state.store(State::EndSession); } // There was an error receiving a message from the client and we've already printed the error // so call runNextInGuard() to clean up the session without waiting. _runNextInGuard(std::move(guard)); } void ServiceStateMachine::_sinkCallback(Status status) { // The first thing to do is create a ThreadGuard which will take ownership of the SSM in this // thread. ThreadGuard guard(this); dassert(state() == State::SinkWait); // If there was an error sinking the message to the client, then we should print an error and // end the session. No need to unwind the stack, so this will runNextInGuard() and return. // // Otherwise, update the current state depending on whether we're in exhaust or not, and call // scheduleNext() to unwind the stack and do the next step. if (!status.isOK()) { log() << "Error sending response to client: " << status << ". Ending connection from " << _session()->remote() << " (connection id: " << _session()->id() << ")"; _state.store(State::EndSession); return _runNextInGuard(std::move(guard)); } else if (_inExhaust) { _state.store(State::Process); return _scheduleNextWithGuard(std::move(guard), ServiceExecutor::kDeferredTask | ServiceExecutor::kMayYieldBeforeSchedule, transport::ServiceExecutorTaskName::kSSMExhaustMessage); } else { _state.store(State::Source); return _scheduleNextWithGuard(std::move(guard), ServiceExecutor::kDeferredTask | ServiceExecutor::kMayYieldBeforeSchedule, transport::ServiceExecutorTaskName::kSSMSourceMessage); } } void ServiceStateMachine::_processMessage(ThreadGuard guard) { invariant(!_inMessage.empty()); auto& compressorMgr = MessageCompressorManager::forSession(_session()); _compressorId = boost::none; if (_inMessage.operation() == dbCompressed) { MessageCompressorId compressorId; auto swm = compressorMgr.decompressMessage(_inMessage, &compressorId); uassertStatusOK(swm.getStatus()); _inMessage = swm.getValue(); _compressorId = compressorId; } networkCounter.hitLogicalIn(_inMessage.size()); // Pass sourced Message to handler to generate response. auto opCtx = Client::getCurrent()->makeOperationContext(); // The handleRequest is implemented in a subclass for mongod/mongos and actually all the // database work for this request. DbResponse dbresponse = _sep->handleRequest(opCtx.get(), _inMessage); // opCtx must be destroyed here so that the operation cannot show // up in currentOp results after the response reaches the client opCtx.reset(); // Format our response, if we have one Message& toSink = dbresponse.response; if (!toSink.empty()) { invariant(!OpMsg::isFlagSet(_inMessage, OpMsg::kMoreToCome)); toSink.header().setId(nextMessageId()); toSink.header().setResponseToMsgId(_inMessage.header().getId()); // If this is an exhaust cursor, don't source more Messages if (dbresponse.exhaustNS.size() > 0 && setExhaustMessage(&_inMessage, dbresponse)) { _inExhaust = true; } else { _inExhaust = false; _inMessage.reset(); } networkCounter.hitLogicalOut(toSink.size()); if (_compressorId) { auto swm = compressorMgr.compressMessage(toSink, &_compressorId.value()); uassertStatusOK(swm.getStatus()); toSink = swm.getValue(); } _sinkMessage(std::move(guard), std::move(toSink)); } else { _state.store(State::Source); _inMessage.reset(); return _scheduleNextWithGuard(std::move(guard), ServiceExecutor::kDeferredTask, transport::ServiceExecutorTaskName::kSSMSourceMessage); } } void ServiceStateMachine::runNext() { return _runNextInGuard(ThreadGuard(this)); } void ServiceStateMachine::_runNextInGuard(ThreadGuard guard) { auto curState = state(); dassert(curState != State::Ended); // If this is the first run of the SSM, then update its state to Source if (curState == State::Created) { curState = State::Source; _state.store(curState); } // Make sure the current Client got set correctly dassert(Client::getCurrent() == _dbClientPtr); try { switch (curState) { case State::Source: _sourceMessage(std::move(guard)); break; case State::Process: _processMessage(std::move(guard)); break; case State::EndSession: _cleanupSession(std::move(guard)); break; default: MONGO_UNREACHABLE; } return; } catch (const DBException& e) { // must be right above std::exception to avoid catching subclasses log() << "DBException handling request, closing client connection: " << redact(e); } catch (const std::exception& e) { error() << "Uncaught std::exception: " << e.what() << ", terminating"; quickExit(EXIT_UNCAUGHT); } if (!guard) { guard = ThreadGuard(this); } _state.store(State::EndSession); _cleanupSession(std::move(guard)); } void ServiceStateMachine::start(Ownership ownershipModel) { _scheduleNextWithGuard(ThreadGuard(this), transport::ServiceExecutor::kEmptyFlags, transport::ServiceExecutorTaskName::kSSMStartSession, ownershipModel); } void ServiceStateMachine::_scheduleNextWithGuard(ThreadGuard guard, transport::ServiceExecutor::ScheduleFlags flags, transport::ServiceExecutorTaskName taskName, Ownership ownershipModel) { auto func = [ ssm = shared_from_this(), ownershipModel ] { ThreadGuard guard(ssm.get()); if (ownershipModel == Ownership::kStatic) guard.markStaticOwnership(); ssm->_runNextInGuard(std::move(guard)); }; guard.release(); Status status = _serviceContext->getServiceExecutor()->schedule(std::move(func), flags, taskName); if (status.isOK()) { return; } // We've had an error, reacquire the ThreadGuard and destroy the SSM ThreadGuard terminateGuard(this); // The service executor failed to schedule the task. This could for example be that we failed // to start a worker thread. Terminate this connection to leave the system in a valid state. _terminateAndLogIfError(status); _cleanupSession(std::move(terminateGuard)); } void ServiceStateMachine::terminate() { if (state() == State::Ended) return; _session()->getTransportLayer()->end(_session()); } void ServiceStateMachine::terminateIfTagsDontMatch(transport::Session::TagMask tags) { if (state() == State::Ended) return; auto sessionTags = _session()->getTags(); // If terminateIfTagsDontMatch gets called when we still are 'pending' where no tags have been // set, then skip the termination check. if ((sessionTags & tags) || (sessionTags & transport::Session::kPending)) { log() << "Skip closing connection for connection # " << _session()->id(); return; } terminate(); } void ServiceStateMachine::setCleanupHook(stdx::function<void()> hook) { invariant(state() == State::Created); _cleanupHook = std::move(hook); } ServiceStateMachine::State ServiceStateMachine::state() { return _state.load(); } void ServiceStateMachine::_terminateAndLogIfError(Status status) { if (!status.isOK()) { warning(logger::LogComponent::kExecutor) << "Terminating session due to error: " << status; terminate(); } } void ServiceStateMachine::_cleanupSession(ThreadGuard guard) { _state.store(State::Ended); _inMessage.reset(); // By ignoring the return value of Client::releaseCurrent() we destroy the session. // _dbClient is now nullptr and _dbClientPtr is invalid and should never be accessed. Client::releaseCurrent(); } } // namespace mongo
/* * Copyright (c) 2017-2018 ARM Limited. * * SPDX-License-Identifier: MIT * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to * deal in the Software without restriction, including without limitation the * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or * sell copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ #include "arm_compute/core/TensorShape.h" #include "arm_compute/core/Types.h" #include "arm_compute/runtime/CL/CLTensor.h" #include "arm_compute/runtime/CL/CLTensorAllocator.h" #include "arm_compute/runtime/CL/functions/CLActivationLayer.h" #include "tests/CL/CLAccessor.h" #include "tests/benchmark/fixtures/ActivationLayerFixture.h" #include "tests/datasets/system_tests/alexnet/AlexNetActivationLayerDataset.h" #include "tests/datasets/system_tests/googlenet/inceptionv1/GoogLeNetInceptionV1ActivationLayerDataset.h" #include "tests/datasets/system_tests/googlenet/inceptionv4/GoogLeNetInceptionV4ActivationLayerDataset.h" #include "tests/datasets/system_tests/lenet5/LeNet5ActivationLayerDataset.h" #include "tests/datasets/system_tests/mobilenet/MobileNetActivationLayerDataset.h" #include "tests/datasets/system_tests/squeezenet/SqueezeNetActivationLayerDataset.h" #include "tests/datasets/system_tests/vgg/vgg16/VGG16ActivationLayerDataset.h" #include "tests/datasets/system_tests/yolo/v2/YOLOV2ActivationLayerDataset.h" #include "tests/framework/Macros.h" #include "tests/framework/datasets/Datasets.h" #include "utils/TypePrinter.h" namespace arm_compute { namespace test { namespace benchmark { namespace { const auto data_types = framework::dataset::make("DataType", { DataType::F16, DataType::F32, DataType::QS8, DataType::QS16 }); const auto data_types_mobilenet = framework::dataset::make("DataType", { DataType::F16, DataType::F32, DataType::QS8, DataType::QS16, DataType::QASYMM8 }); } // namespace using CLActivationLayerFixture = ActivationLayerFixture<CLTensor, CLActivationLayer, CLAccessor>; TEST_SUITE(CL) REGISTER_FIXTURE_DATA_TEST_CASE(AlexNetActivationLayer, CLActivationLayerFixture, framework::DatasetMode::ALL, framework::dataset::combine(framework::dataset::combine(datasets::AlexNetActivationLayerDataset(), data_types), framework::dataset::make("Batches", 1))); REGISTER_FIXTURE_DATA_TEST_CASE(LeNet5ActivationLayer, CLActivationLayerFixture, framework::DatasetMode::ALL, framework::dataset::combine(framework::dataset::combine(datasets::LeNet5ActivationLayerDataset(), data_types), framework::dataset::make("Batches", 1))); REGISTER_FIXTURE_DATA_TEST_CASE(MobileNetActivationLayer, CLActivationLayerFixture, framework::DatasetMode::ALL, framework::dataset::combine(framework::dataset::combine(datasets::MobileNetActivationLayerDataset(), data_types_mobilenet), framework::dataset::make("Batches", 1))); REGISTER_FIXTURE_DATA_TEST_CASE(GoogLeNetInceptionV1ActivationLayer, CLActivationLayerFixture, framework::DatasetMode::ALL, framework::dataset::combine(framework::dataset::combine(datasets::GoogLeNetInceptionV1ActivationLayerDataset(), data_types), framework::dataset::make("Batches", 1))); REGISTER_FIXTURE_DATA_TEST_CASE(GoogLeNetInceptionV4ActivationLayer, CLActivationLayerFixture, framework::DatasetMode::ALL, framework::dataset::combine(framework::dataset::combine(datasets::GoogLeNetInceptionV4ActivationLayerDataset(), data_types), framework::dataset::make("Batches", 1))); REGISTER_FIXTURE_DATA_TEST_CASE(SqueezeNetActivationLayer, CLActivationLayerFixture, framework::DatasetMode::ALL, framework::dataset::combine(framework::dataset::combine(datasets::SqueezeNetActivationLayerDataset(), data_types), framework::dataset::make("Batches", 1))); REGISTER_FIXTURE_DATA_TEST_CASE(VGG16ActivationLayer, CLActivationLayerFixture, framework::DatasetMode::ALL, framework::dataset::combine(framework::dataset::combine(datasets::VGG16ActivationLayerDataset(), data_types), framework::dataset::make("Batches", 1))); REGISTER_FIXTURE_DATA_TEST_CASE(YOLOV2ActivationLayer, CLActivationLayerFixture, framework::DatasetMode::ALL, framework::dataset::combine(framework::dataset::combine(datasets::YOLOV2ActivationLayerDataset(), data_types), framework::dataset::make("Batches", 1))); TEST_SUITE(NIGHTLY) REGISTER_FIXTURE_DATA_TEST_CASE(AlexNetActivationLayer, CLActivationLayerFixture, framework::DatasetMode::NIGHTLY, framework::dataset::combine(framework::dataset::combine(datasets::AlexNetActivationLayerDataset(), data_types), framework::dataset::make("Batches", { 4, 8 }))); REGISTER_FIXTURE_DATA_TEST_CASE(LeNet5ActivationLayer, CLActivationLayerFixture, framework::DatasetMode::NIGHTLY, framework::dataset::combine(framework::dataset::combine(datasets::LeNet5ActivationLayerDataset(), data_types), framework::dataset::make("Batches", { 4, 8 }))); REGISTER_FIXTURE_DATA_TEST_CASE(MobileNetActivationLayer, CLActivationLayerFixture, framework::DatasetMode::NIGHTLY, framework::dataset::combine(framework::dataset::combine(datasets::MobileNetActivationLayerDataset(), data_types_mobilenet), framework::dataset::make("Batches", { 4, 8 }))); REGISTER_FIXTURE_DATA_TEST_CASE(GoogLeNetInceptionV1ActivationLayer, CLActivationLayerFixture, framework::DatasetMode::NIGHTLY, framework::dataset::combine(framework::dataset::combine(datasets::GoogLeNetInceptionV1ActivationLayerDataset(), data_types), framework::dataset::make("Batches", { 4, 8 }))); REGISTER_FIXTURE_DATA_TEST_CASE(GoogLeNetInceptionV4ActivationLayer, CLActivationLayerFixture, framework::DatasetMode::NIGHTLY, framework::dataset::combine(framework::dataset::combine(datasets::GoogLeNetInceptionV4ActivationLayerDataset(), data_types), framework::dataset::make("Batches", { 4, 8 }))); REGISTER_FIXTURE_DATA_TEST_CASE(SqueezeNetActivationLayer, CLActivationLayerFixture, framework::DatasetMode::NIGHTLY, framework::dataset::combine(framework::dataset::combine(datasets::SqueezeNetActivationLayerDataset(), data_types), framework::dataset::make("Batches", { 4, 8 }))); REGISTER_FIXTURE_DATA_TEST_CASE(VGG16ActivationLayer, CLActivationLayerFixture, framework::DatasetMode::NIGHTLY, framework::dataset::combine(framework::dataset::combine(datasets::VGG16ActivationLayerDataset(), data_types), framework::dataset::make("Batches", { 4, 8 }))); REGISTER_FIXTURE_DATA_TEST_CASE(YOLOV2ActivationLayer, CLActivationLayerFixture, framework::DatasetMode::NIGHTLY, framework::dataset::combine(framework::dataset::combine(datasets::YOLOV2ActivationLayerDataset(), data_types), framework::dataset::make("Batches", { 4, 8 }))); TEST_SUITE_END() TEST_SUITE_END() } // namespace benchmark } // namespace test } // namespace arm_compute
// Licensed to the Apache Software Foundation (ASF) under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information // regarding copyright ownership. The ASF licenses this file // to you under the Apache License, Version 2.0 (the // "License"); you may not use this file except in compliance // with the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, // software distributed under the License is distributed on an // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. #include "kudu/subprocess/subprocess_proxy.h" #include <cstdint> #include <memory> #include <string> #include <utility> #include <vector> #include <gflags/gflags_declare.h> #include <gtest/gtest.h> #include "kudu/gutil/casts.h" #include "kudu/gutil/ref_counted.h" #include "kudu/gutil/strings/substitute.h" #include "kudu/subprocess/echo_subprocess.h" #include "kudu/subprocess/subprocess.pb.h" #include "kudu/util/env.h" #include "kudu/util/metrics.h" #include "kudu/util/path_util.h" #include "kudu/util/status.h" #include "kudu/util/test_macros.h" #include "kudu/util/test_util.h" DECLARE_int32(subprocess_timeout_secs); METRIC_DECLARE_histogram(echo_subprocess_inbound_queue_length); METRIC_DECLARE_histogram(echo_subprocess_outbound_queue_length); METRIC_DECLARE_histogram(echo_subprocess_inbound_queue_time_ms); METRIC_DECLARE_histogram(echo_subprocess_outbound_queue_time_ms); METRIC_DECLARE_histogram(echo_subprocess_execution_time_ms); METRIC_DECLARE_histogram(echo_server_outbound_queue_size_bytes); METRIC_DECLARE_histogram(echo_server_inbound_queue_size_bytes); METRIC_DECLARE_histogram(echo_server_outbound_queue_time_ms); METRIC_DECLARE_histogram(echo_server_inbound_queue_time_ms); using std::unique_ptr; using std::string; using std::vector; using strings::Substitute; namespace kudu { namespace subprocess { class EchoSubprocessTest : public KuduTest { public: EchoSubprocessTest() : metric_entity_(METRIC_ENTITY_server.Instantiate(&metric_registry_, "subprocess_proxy-test")) {} void SetUp() override { KuduTest::SetUp(); ASSERT_OK(ResetEchoSubprocess()); } Status ResetEchoSubprocess() { string exe; RETURN_NOT_OK(env_->GetExecutablePath(&exe)); const string bin_dir = DirName(exe); string java_home; RETURN_NOT_OK(FindHomeDir("java", bin_dir, &java_home)); vector<string> argv = { Substitute("$0/bin/java", java_home), "-cp", Substitute("$0/kudu-subprocess.jar", bin_dir), "org.apache.kudu.subprocess.echo.EchoSubprocessMain" }; echo_subprocess_.reset(new EchoSubprocess(std::move(argv), metric_entity_)); return echo_subprocess_->Start(); } protected: MetricRegistry metric_registry_; scoped_refptr<MetricEntity> metric_entity_; unique_ptr<EchoSubprocess> echo_subprocess_; }; #define GET_HIST(metric_entity, metric_name) \ down_cast<Histogram*>((metric_entity)->FindOrNull(METRIC_##metric_name).get()); TEST_F(EchoSubprocessTest, TestBasicSubprocessMetrics) { const string kMessage = "don't catch you slippin' now"; const int64_t kSleepMs = 1000; EchoRequestPB req; req.set_data(kMessage); req.set_sleep_ms(kSleepMs); EchoResponsePB resp; ASSERT_OK(echo_subprocess_->Execute(req, &resp)); ASSERT_EQ(kMessage, resp.data()); // There shouldn't have anything in the subprocess queues. Histogram* in_len_hist = GET_HIST(metric_entity_, echo_subprocess_inbound_queue_length); ASSERT_EQ(1, in_len_hist->TotalCount()); ASSERT_EQ(0, in_len_hist->MaxValueForTests()); Histogram* out_len_hist = GET_HIST(metric_entity_, echo_subprocess_outbound_queue_length); ASSERT_EQ(1, out_len_hist->TotalCount()); ASSERT_EQ(0, out_len_hist->MaxValueForTests()); // We should have some non-negative queue times. Histogram* out_hist = GET_HIST(metric_entity_, echo_subprocess_outbound_queue_time_ms); ASSERT_EQ(1, out_hist->TotalCount()); ASSERT_LE(0, out_hist->MaxValueForTests()); Histogram* in_hist = GET_HIST(metric_entity_, echo_subprocess_inbound_queue_time_ms); ASSERT_EQ(1, in_hist->TotalCount()); ASSERT_LE(0, in_hist->MaxValueForTests()); // There shouldn't have anything bytes the server queues when we enqueue. Histogram* server_in_size_hist = GET_HIST(metric_entity_, echo_server_inbound_queue_size_bytes); ASSERT_EQ(1, server_in_size_hist->TotalCount()); ASSERT_EQ(0, server_in_size_hist->MaxValueForTests()); Histogram* server_out_size_hist = GET_HIST(metric_entity_, echo_server_outbound_queue_size_bytes); ASSERT_EQ(1, server_out_size_hist->TotalCount()); ASSERT_EQ(0, server_out_size_hist->MaxValueForTests()); // We should have some non-negative queue times on the server side too. Histogram* server_out_hist = GET_HIST(metric_entity_, echo_server_outbound_queue_time_ms); ASSERT_EQ(1, server_out_hist->TotalCount()); ASSERT_LE(0, server_out_hist->MaxValueForTests()); Histogram* server_in_hist = GET_HIST(metric_entity_, echo_server_inbound_queue_time_ms); ASSERT_EQ(1, server_in_hist->TotalCount()); ASSERT_LE(0, server_in_hist->MaxValueForTests()); // The execution should've taken at least our sleep time. Histogram* exec_hist = GET_HIST(metric_entity_, echo_subprocess_execution_time_ms); ASSERT_EQ(1, exec_hist->TotalCount()); ASSERT_LT(kSleepMs, exec_hist->MaxValueForTests()); } // Test that we'll still report metrics when we recieve them from the // subprocess, even if the call itself failed. TEST_F(EchoSubprocessTest, TestSubprocessMetricsOnError) { // Set things up so we'll time out. FLAGS_subprocess_timeout_secs = 1; const int64_t kSleepMs = 2000; ASSERT_OK(ResetEchoSubprocess()); EchoRequestPB req; req.set_data("garbage!"); req.set_sleep_ms(kSleepMs); EchoResponsePB resp; Status s = echo_subprocess_->Execute(req, &resp); ASSERT_TRUE(s.IsTimedOut()) << s.ToString(); // Immediately following our call, we won't have any metrics from the subprocess. Histogram* exec_hist = GET_HIST(metric_entity_, echo_subprocess_execution_time_ms); Histogram* out_len_hist = GET_HIST(metric_entity_, echo_subprocess_outbound_queue_length); Histogram* in_len_hist = GET_HIST(metric_entity_, echo_subprocess_inbound_queue_length); Histogram* sp_out_hist = GET_HIST(metric_entity_, echo_subprocess_outbound_queue_time_ms); Histogram* sp_in_hist = GET_HIST(metric_entity_, echo_subprocess_inbound_queue_time_ms); Histogram* server_out_time_hist = GET_HIST(metric_entity_, echo_server_outbound_queue_time_ms); Histogram* server_out_size_hist = GET_HIST(metric_entity_, echo_server_outbound_queue_size_bytes); Histogram* server_in_time_hist = GET_HIST(metric_entity_, echo_server_inbound_queue_time_ms); Histogram* server_in_size_hist = GET_HIST(metric_entity_, echo_server_inbound_queue_size_bytes); ASSERT_EQ(0, exec_hist->TotalCount()); ASSERT_EQ(0, out_len_hist->TotalCount()); ASSERT_EQ(0, in_len_hist->TotalCount()); ASSERT_EQ(0, sp_out_hist->TotalCount()); ASSERT_EQ(0, sp_in_hist->TotalCount()); // We'll have sent the request from the server and not received the response. // Our metrics should reflect that. ASSERT_EQ(1, server_out_time_hist->TotalCount()); ASSERT_EQ(1, server_out_size_hist->TotalCount()); ASSERT_EQ(0, server_in_time_hist->TotalCount()); ASSERT_EQ(0, server_in_size_hist->TotalCount()); // Eventually the subprocess will return our call, and we'll see some // metrics. ASSERT_EVENTUALLY([&] { ASSERT_EQ(1, exec_hist->TotalCount()); ASSERT_LT(kSleepMs, exec_hist->MaxValueForTests()); ASSERT_EQ(1, out_len_hist->TotalCount()); ASSERT_EQ(1, in_len_hist->TotalCount()); ASSERT_EQ(1, sp_out_hist->TotalCount()); ASSERT_EQ(1, sp_in_hist->TotalCount()); ASSERT_EQ(1, server_out_time_hist->TotalCount()); ASSERT_EQ(1, server_in_time_hist->TotalCount()); ASSERT_EQ(1, server_out_size_hist->TotalCount()); ASSERT_EQ(1, server_in_size_hist->TotalCount()); }); } #undef GET_HIST } // namespace subprocess } // namespace kudu
////////////////////////////////////////////////////////////////////////////// // // (C) Copyright Ion Gaztanaga 2006-2012. Distributed under the Boost // Software License, Version 1.0. (See accompanying file // LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // // See http://www.boost.org/libs/interprocess for documentation. // ////////////////////////////////////////////////////////////////////////////// //[doc_anonymous_mutexB #include <boost/interprocess/shared_memory_object.hpp> #include <boost/interprocess/mapped_region.hpp> #include <boost/interprocess/sync/scoped_lock.hpp> #include "doc_anonymous_mutex_shared_data.hpp" #include <iostream> #include <cstdio> using namespace boost::interprocess; int main () { //Remove shared memory on destruction struct shm_remove { ~shm_remove(){ shared_memory_object::remove("MySharedMemory"); } } remover; //<- (void)remover; //-> //Open the shared memory object. shared_memory_object shm (open_only //only create ,"MySharedMemory" //name ,read_write //read-write mode ); //Map the whole shared memory in this process mapped_region region (shm //What to map ,read_write //Map it as read-write ); //Get the address of the mapped region void * addr = region.get_address(); //Construct the shared structure in memory shared_memory_log * data = static_cast<shared_memory_log*>(addr); //Write some logs for(int i = 0; i < 100; ++i){ //Lock the mutex scoped_lock<interprocess_mutex> lock(data->mutex); std::sprintf(data->items[(data->current_line++) % shared_memory_log::NumItems] ,"%s_%d", "process_a", i); if(i == (shared_memory_log::NumItems-1)) data->end_b = true; //Mutex is released here } //Wait until the other process ends while(1){ scoped_lock<interprocess_mutex> lock(data->mutex); if(data->end_a) break; } return 0; } //]
// Copyright 2013 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. // From ppb_tcp_socket.idl modified Thu Jun 20 16:36:53 2013. #include "ppapi/c/pp_completion_callback.h" #include "ppapi/c/pp_errors.h" #include "ppapi/c/ppb_tcp_socket.h" #include "ppapi/shared_impl/tracked_callback.h" #include "ppapi/thunk/enter.h" #include "ppapi/thunk/ppb_instance_api.h" #include "ppapi/thunk/ppb_tcp_socket_api.h" #include "ppapi/thunk/resource_creation_api.h" #include "ppapi/thunk/thunk.h" namespace ppapi { namespace thunk { namespace { PP_Resource Create(PP_Instance instance) { VLOG(4) << "PPB_TCPSocket::Create()"; EnterResourceCreation enter(instance); if (enter.failed()) return 0; return enter.functions()->CreateTCPSocket(instance); } PP_Bool IsTCPSocket(PP_Resource resource) { VLOG(4) << "PPB_TCPSocket::IsTCPSocket()"; EnterResource<PPB_TCPSocket_API> enter(resource, false); return PP_FromBool(enter.succeeded()); } int32_t Connect(PP_Resource tcp_socket, PP_Resource addr, struct PP_CompletionCallback callback) { VLOG(4) << "PPB_TCPSocket::Connect()"; EnterResource<PPB_TCPSocket_API> enter(tcp_socket, callback, true); if (enter.failed()) return enter.retval(); return enter.SetResult(enter.object()->Connect(addr, enter.callback())); } PP_Resource GetLocalAddress(PP_Resource tcp_socket) { VLOG(4) << "PPB_TCPSocket::GetLocalAddress()"; EnterResource<PPB_TCPSocket_API> enter(tcp_socket, true); if (enter.failed()) return 0; return enter.object()->GetLocalAddress(); } PP_Resource GetRemoteAddress(PP_Resource tcp_socket) { VLOG(4) << "PPB_TCPSocket::GetRemoteAddress()"; EnterResource<PPB_TCPSocket_API> enter(tcp_socket, true); if (enter.failed()) return 0; return enter.object()->GetRemoteAddress(); } int32_t Read(PP_Resource tcp_socket, char* buffer, int32_t bytes_to_read, struct PP_CompletionCallback callback) { VLOG(4) << "PPB_TCPSocket::Read()"; EnterResource<PPB_TCPSocket_API> enter(tcp_socket, callback, true); if (enter.failed()) return enter.retval(); return enter.SetResult(enter.object()->Read(buffer, bytes_to_read, enter.callback())); } int32_t Write(PP_Resource tcp_socket, const char* buffer, int32_t bytes_to_write, struct PP_CompletionCallback callback) { VLOG(4) << "PPB_TCPSocket::Write()"; EnterResource<PPB_TCPSocket_API> enter(tcp_socket, callback, true); if (enter.failed()) return enter.retval(); return enter.SetResult(enter.object()->Write(buffer, bytes_to_write, enter.callback())); } void Close(PP_Resource tcp_socket) { VLOG(4) << "PPB_TCPSocket::Close()"; EnterResource<PPB_TCPSocket_API> enter(tcp_socket, true); if (enter.failed()) return; enter.object()->Close(); } int32_t SetOption(PP_Resource tcp_socket, PP_TCPSocket_Option name, struct PP_Var value, struct PP_CompletionCallback callback) { VLOG(4) << "PPB_TCPSocket::SetOption()"; EnterResource<PPB_TCPSocket_API> enter(tcp_socket, callback, true); if (enter.failed()) return enter.retval(); return enter.SetResult(enter.object()->SetOption(name, value, enter.callback())); } const PPB_TCPSocket_1_0 g_ppb_tcpsocket_thunk_1_0 = { &Create, &IsTCPSocket, &Connect, &GetLocalAddress, &GetRemoteAddress, &Read, &Write, &Close, &SetOption }; } // namespace const PPB_TCPSocket_1_0* GetPPB_TCPSocket_1_0_Thunk() { return &g_ppb_tcpsocket_thunk_1_0; } } // namespace thunk } // namespace ppapi
/* * Copyright (c) 2003, 2010, Oracle and/or its affiliates. All rights reserved. * Copyright 2008, 2009 Red Hat, Inc. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. * * This code 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 * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. * */ #ifndef CPU_ZERO_VM_CPPINTERPRETERGENERATOR_ZERO_HPP #define CPU_ZERO_VM_CPPINTERPRETERGENERATOR_ZERO_HPP protected: MacroAssembler* assembler() const { return _masm; } protected: address generate_entry(address entry_point) { ZeroEntry *entry = (ZeroEntry *) assembler()->pc(); assembler()->advance(sizeof(ZeroEntry)); entry->set_entry_point(entry_point); return (address) entry; } #endif // CPU_ZERO_VM_CPPINTERPRETERGENERATOR_ZERO_HPP
#include <vector> #include <iostream> #include <climits> #include <algorithm> #include <queue> #include <stack> #include <map> #include <math.h> using namespace std; #define ll long long #define ld long double #define fora(i, start, end) for(int i=start;i<end;i++) #define forb(i, start, end) for(int i=end;i>=start;i--) const double pi=acos(-1.0); const double eps=1e-11; const int mod = 1e9+7; #define mod(n,k) ( ( ((n) % (k)) + (k) ) % (k)) class Solution { public: bool isSubsequence(string s, string t) { int index = 0; for(int i=0;i<t.size();i++) { if(t[i] == s[index]) { index++; } } return index == s.size(); } }; int main() { Solution s; vector<int> c { 4,5,6,7,0,2,1,3 }; string str = "axc"; string t = "ahbgdc"; bool result = s.isSubsequence(str, t); cout<<result<<endl; }
// Licensed to the Apache Software Foundation (ASF) under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information // regarding copyright ownership. The ASF licenses this file // to you under the Apache License, Version 2.0 (the // "License"); you may not use this file except in compliance // with the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, // software distributed under the License is distributed on an // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. #include "exec/olap_scan_node.h" #include <gtest/gtest.h> #include <stdio.h> #include <stdlib.h> #include <iostream> #include <vector> #include "exec/text_converter.hpp" #include "exprs/binary_predicate.h" #include "exprs/in_predicate.h" #include "exprs/int_literal.h" #include "gen_cpp/PlanNodes_types.h" #include "gen_cpp/Types_types.h" #include "runtime/descriptors.h" #include "runtime/exec_env.h" #include "runtime/primitive_type.h" #include "runtime/row_batch.h" #include "runtime/runtime_state.h" #include "runtime/string_value.h" #include "runtime/tuple_row.h" #include "util/cpu_info.h" #include "util/debug_util.h" #include "util/runtime_profile.h" namespace doris { class OlapScanNodeTest : public ::testing::Test { public: OlapScanNodeTest() : _runtime_stat("test") {} virtual void SetUp() { TUniqueId fragment_id; TQueryOptions query_options; query_options.disable_codegen = true; ExecEnv* exec_env = new ExecEnv(); _runtime_stat.init(fragment_id, query_options, "test", exec_env); TDescriptorTable t_desc_table; // table descriptors TTableDescriptor t_table_desc; t_table_desc.id = 0; t_table_desc.tableType = TTableType::OLAP_TABLE; t_table_desc.numCols = 0; t_table_desc.numClusteringCols = 0; t_table_desc.olapTable.tableName = ""; t_table_desc.tableName = ""; t_table_desc.dbName = ""; t_table_desc.__isset.mysqlTable = true; t_desc_table.tableDescriptors.push_back(t_table_desc); t_desc_table.__isset.tableDescriptors = true; // TSlotDescriptor int offset = 1; int i = 0; // UserId { TSlotDescriptor t_slot_desc; t_slot_desc.__set_id(i); t_slot_desc.__set_slotType(to_thrift(TYPE_INT)); t_slot_desc.__set_columnPos(i); t_slot_desc.__set_byteOffset(offset); t_slot_desc.__set_nullIndicatorByte(0); t_slot_desc.__set_nullIndicatorBit(-1); t_slot_desc.__set_slotIdx(i); t_slot_desc.__set_isMaterialized(true); t_slot_desc.__set_colName("UserId"); t_desc_table.slotDescriptors.push_back(t_slot_desc); offset += sizeof(int32_t); } ++i; // UrlId { TSlotDescriptor t_slot_desc; t_slot_desc.__set_id(i); t_slot_desc.__set_slotType(to_thrift(TYPE_BIGINT)); t_slot_desc.__set_columnPos(i); t_slot_desc.__set_byteOffset(offset); t_slot_desc.__set_nullIndicatorByte(0); t_slot_desc.__set_nullIndicatorBit(-1); t_slot_desc.__set_slotIdx(i); t_slot_desc.__set_isMaterialized(true); t_slot_desc.__set_colName("UrlId"); t_desc_table.slotDescriptors.push_back(t_slot_desc); offset += sizeof(int64_t); } ++i; // Date { TSlotDescriptor t_slot_desc; t_slot_desc.__set_id(i); t_slot_desc.__set_slotType(to_thrift(TYPE_INT)); t_slot_desc.__set_columnPos(i); t_slot_desc.__set_byteOffset(offset); t_slot_desc.__set_nullIndicatorByte(0); t_slot_desc.__set_nullIndicatorBit(-1); t_slot_desc.__set_slotIdx(i); t_slot_desc.__set_isMaterialized(true); t_slot_desc.__set_colName("Date"); t_desc_table.slotDescriptors.push_back(t_slot_desc); offset += sizeof(int32_t); } ++i; // PageViews { TSlotDescriptor t_slot_desc; t_slot_desc.__set_id(i); t_slot_desc.__set_slotType(to_thrift(TYPE_BIGINT)); t_slot_desc.__set_columnPos(i); t_slot_desc.__set_byteOffset(offset); t_slot_desc.__set_nullIndicatorByte(0); t_slot_desc.__set_nullIndicatorBit(-1); t_slot_desc.__set_slotIdx(i); t_slot_desc.__set_isMaterialized(true); t_slot_desc.__set_colName("PageViews"); t_desc_table.slotDescriptors.push_back(t_slot_desc); offset += sizeof(int64_t); } t_desc_table.__isset.slotDescriptors = true; // TTupleDescriptor TTupleDescriptor t_tuple_desc; t_tuple_desc.id = 0; t_tuple_desc.byteSize = offset; t_tuple_desc.numNullBytes = 1; t_tuple_desc.tableId = 0; t_tuple_desc.__isset.tableId = true; t_desc_table.tupleDescriptors.push_back(t_tuple_desc); DescriptorTbl::create(&_obj_pool, t_desc_table, &_desc_tbl); _runtime_stat.set_desc_tbl(_desc_tbl); // Node Id _tnode.node_id = 0; _tnode.node_type = TPlanNodeType::OLAP_SCAN_NODE; _tnode.num_children = 0; _tnode.limit = 100; _tnode.row_tuples.push_back(0); _tnode.nullable_tuples.push_back(false); _tnode.tuple_ids.push_back(0); _tnode.olap_scan_node.tuple_id = 0; _tnode.olap_scan_node.key_column_name.push_back("UserId"); _tnode.olap_scan_node.key_column_name.push_back("UrlId"); _tnode.olap_scan_node.key_column_name.push_back("Date"); _tnode.olap_scan_node.key_column_type.push_back(to_thrift(TYPE_INT)); _tnode.olap_scan_node.key_column_type.push_back(to_thrift(TYPE_BIGINT)); _tnode.olap_scan_node.key_column_type.push_back(to_thrift(TYPE_INT)); _tnode.__isset.olap_scan_node = true; { TScanRangeParams param; TPaloScanRange doris_scan_range; TNetworkAddress host; host.__set_hostname("host"); host.__set_port(9999); doris_scan_range.hosts.push_back(host); doris_scan_range.__set_schema_hash("462300563"); doris_scan_range.__set_version("94"); // Useless but it is required in TPaloScanRange doris_scan_range.__set_version_hash("0"); doris_scan_range.engine_table_name.push_back("DorisTestStats"); doris_scan_range.__set_db_name("olap"); //TKeyRange key_range; //key_range.__set_column_type(to_thrift(TYPE_BIGINT)); //key_range.__set_begin_key(-5000); //key_range.__set_end_key(5000); //key_range.__set_column_name("UrlId"); //doris_scan_range.partition_column_ranges.push_back(key_range); param.scan_range.__set_doris_scan_range(doris_scan_range); _scan_ranges.push_back(param); } } virtual void TearDown() {} private: TPlanNode _tnode; ObjectPool _obj_pool; DescriptorTbl* _desc_tbl; RuntimeState _runtime_stat; std::vector<TScanRangeParams> _scan_ranges; }; TEST_F(OlapScanNodeTest, NormalUse) { OlapScanNode scan_node(&_obj_pool, _tnode, *_desc_tbl); Status status = scan_node.prepare(&_runtime_stat); ASSERT_TRUE(status.ok()); status = scan_node.open(&_runtime_stat); ASSERT_TRUE(status.ok()); ASSERT_TRUE(scan_node.set_scanRanges(_scan_ranges).ok()); RowBatch row_batch(scan_node._row_descriptor, _runtime_stat.batch_size()); bool eos = false; while (!eos) { status = scan_node.get_next(&_runtime_stat, &row_batch, &eos); ASSERT_TRUE(status.ok()); int num = std::min(row_batch.num_rows(), 10); ASSERT_TRUE(num > 0); for (int i = 0; i < num; ++i) { TupleRow* row = row_batch.get_row(i); LOG(WARNING) << "input row: " << print_row(row, scan_node._row_descriptor); if (0 == i) { ASSERT_EQ("[(-5000 -5000 -5000 1)]", print_row(row, scan_node._row_descriptor)); } } eos = true; } ASSERT_TRUE(scan_node.close(&_runtime_stat).ok()); } TEST_F(OlapScanNodeTest, PushDownBinaryPredicate) { OlapScanNode scan_node(&_obj_pool, _tnode, *_desc_tbl); TExprNode binary_node; binary_node.node_type = TExprNodeType::BINARY_PRED; binary_node.type = to_tcolumn_type_thrift(TPrimitiveType::BOOLEAN); binary_node.num_children = 2; binary_node.opcode = TExprOpcode::LT_INT_INT; binary_node.__isset.opcode = true; BinaryPredicate bin_pre(binary_node); TExprNode slot_node; slot_node.node_type = TExprNodeType::SLOT_REF; slot_node.type = to_tcolumn_type_thrift(TPrimitiveType::INT); slot_node.num_children = 0; slot_node.slot_ref.slot_id = 0; slot_node.slot_ref.tuple_id = 0; slot_node.__isset.slot_ref = true; std::vector<TTupleId> row_tuples; row_tuples.push_back(0); std::vector<bool> nullable_tuples; nullable_tuples.push_back(false); RowDescriptor row_desc(*_desc_tbl, row_tuples, nullable_tuples); bin_pre._children.push_back(_obj_pool.add(new SlotRef(slot_node))); int v = -4999; bin_pre._children.push_back(_obj_pool.add(new IntLiteral(TYPE_INT, &v))); Status status = bin_pre.prepare(&_runtime_stat, row_desc); ASSERT_TRUE(status.ok()); std::list<Expr*> exprs; exprs.push_back(&bin_pre); scan_node.push_down_predicate(&_runtime_stat, &exprs); status = scan_node.prepare(&_runtime_stat); ASSERT_TRUE(status.ok()); status = scan_node.open(&_runtime_stat); ASSERT_TRUE(status.ok()); ASSERT_TRUE(scan_node.set_scan_ranges(_scan_ranges).ok()); RowBatch row_batch(scan_node._row_descriptor, _runtime_stat.batch_size()); bool eos = false; while (!eos) { status = scan_node.get_next(&_runtime_stat, &row_batch, &eos); ASSERT_TRUE(status.ok()); int num = std::min(row_batch.num_rows(), 10); ASSERT_TRUE(num > 0); for (int i = 0; i < num; ++i) { TupleRow* row = row_batch.get_row(i); LOG(WARNING) << "input row: " << print_row(row, scan_node._row_descriptor); ASSERT_EQ("[(-5000 -5000 -5000 1)]", print_row(row, scan_node._row_descriptor)); } eos = true; } ASSERT_TRUE(scan_node.close(&_runtime_stat).ok()); } TEST_F(OlapScanNodeTest, PushDownBinaryEqualPredicate) { OlapScanNode scan_node(&_obj_pool, _tnode, *_desc_tbl); TExprNode binary_node; binary_node.node_type = TExprNodeType::BINARY_PRED; binary_node.type = to_tcolumn_type_thrift(TPrimitiveType::BOOLEAN); binary_node.num_children = 2; binary_node.opcode = TExprOpcode::EQ_INT_INT; binary_node.__isset.opcode = true; BinaryPredicate bin_pre(binary_node); TExprNode slot_node; slot_node.node_type = TExprNodeType::SLOT_REF; slot_node.type = to_tcolumn_type_thrift(TPrimitiveType::INT); slot_node.num_children = 0; slot_node.slot_ref.slot_id = 0; slot_node.slot_ref.tuple_id = 0; slot_node.__isset.slot_ref = true; std::vector<TTupleId> row_tuples; row_tuples.push_back(0); std::vector<bool> nullable_tuples; nullable_tuples.push_back(false); RowDescriptor row_desc(*_desc_tbl, row_tuples, nullable_tuples); bin_pre._children.push_back(_obj_pool.add(new SlotRef(slot_node))); int v = -5000; bin_pre._children.push_back(_obj_pool.add(new IntLiteral(TYPE_INT, &v))); Status status = bin_pre.prepare(&_runtime_stat, row_desc); ASSERT_TRUE(status.ok()); std::list<Expr*> exprs; exprs.push_back(&bin_pre); scan_node.push_down_predicate(&_runtime_stat, &exprs); status = scan_node.prepare(&_runtime_stat); ASSERT_TRUE(status.ok()); status = scan_node.open(&_runtime_stat); ASSERT_TRUE(status.ok()); ASSERT_TRUE(scan_node.set_scan_ranges(_scan_ranges).ok()); RowBatch row_batch(scan_node._row_descriptor, _runtime_stat.batch_size()); bool eos = false; while (!eos) { status = scan_node.get_next(&_runtime_stat, &row_batch, &eos); ASSERT_TRUE(status.ok()); int num = std::min(row_batch.num_rows(), 10); ASSERT_TRUE(num > 0); for (int i = 0; i < num; ++i) { TupleRow* row = row_batch.get_row(i); LOG(WARNING) << "input row: " << print_row(row, scan_node._row_descriptor); ASSERT_EQ("[(-5000 -5000 -5000 1)]", print_row(row, scan_node._row_descriptor)); } eos = true; } ASSERT_TRUE(scan_node.close(&_runtime_stat).ok()); } TEST_F(OlapScanNodeTest, PushDownInPredicateCase) { OlapScanNode scan_node(&_obj_pool, _tnode, *_desc_tbl); TExprNode in_node; in_node.node_type = TExprNodeType::IN_PRED; in_node.type = to_tcolumn_type_thrift(TPrimitiveType::BOOLEAN); in_node.num_children = 0; in_node.in_predicate.is_not_in = false; in_node.__isset.in_predicate = true; InPredicate in_pre(in_node); TExprNode slot_node; slot_node.node_type = TExprNodeType::SLOT_REF; slot_node.type = to_tcolumn_type_thrift(TPrimitiveType::INT); slot_node.num_children = 0; slot_node.slot_ref.slot_id = 0; slot_node.slot_ref.tuple_id = 0; slot_node.__isset.slot_ref = true; std::vector<TTupleId> row_tuples; row_tuples.push_back(0); std::vector<bool> nullable_tuples; nullable_tuples.push_back(false); RowDescriptor row_desc(*_desc_tbl, row_tuples, nullable_tuples); in_pre._children.push_back(_obj_pool.add(new SlotRef(slot_node))); Status status = in_pre.prepare(&_runtime_stat, row_desc); ASSERT_TRUE(status.ok()); for (int i = -5000; i < -4999; ++i) { in_pre.insert(&i); } std::list<Expr*> exprs; exprs.push_back(&in_pre); scan_node.push_down_predicate(&_runtime_stat, &exprs); status = scan_node.prepare(&_runtime_stat); ASSERT_TRUE(status.ok()); status = scan_node.open(&_runtime_stat); ASSERT_TRUE(status.ok()); ASSERT_TRUE(scan_node.set_scan_ranges(_scan_ranges).ok()); RowBatch row_batch(scan_node._row_descriptor, _runtime_stat.batch_size()); bool eos = false; while (!eos) { status = scan_node.get_next(&_runtime_stat, &row_batch, &eos); ASSERT_TRUE(status.ok()); int num = std::min(row_batch.num_rows(), 10); ASSERT_TRUE(num > 0); for (int i = 0; i < num; ++i) { TupleRow* row = row_batch.get_row(i); LOG(WARNING) << "input row: " << print_row(row, scan_node._row_descriptor); ASSERT_EQ("[(-5000 -5000 -5000 1)]", print_row(row, scan_node._row_descriptor)); } eos = true; } ASSERT_TRUE(scan_node.close(&_runtime_stat).ok()); } } // namespace doris int main(int argc, char** argv) { std::string conffile = std::string(getenv("DORIS_HOME")) + "/conf/be.conf"; if (!doris::config::init(conffile.c_str(), false)) { fprintf(stderr, "error read config file. \n"); return -1; } init_glog("be-test"); ::testing::InitGoogleTest(&argc, argv); doris::CpuInfo::Init(); return RUN_ALL_TESTS(); }
/* * Copyright (C) 2012 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); you * may not use this file except in compliance with the License. You may * obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or * implied. See the License for the specific language governing * permissions and limitations under the License. */ #include <errno.h> #include <string.h> #include <stdint.h> #include <hardware/hardware.h> #include <hardware/keymaster0.h> #include <openssl/evp.h> #include <openssl/bio.h> #include <openssl/rsa.h> #include <openssl/err.h> #include <openssl/x509.h> #include <linux/ioctl.h> #include <linux/msm_ion.h> #include <sys/mman.h> #include <stdio.h> #include <stdlib.h> #include <stddef.h> #include <unistd.h> #include <dirent.h> #include <fcntl.h> #include <sys/types.h> #include <sys/stat.h> #include <dlfcn.h> #include <UniquePtr.h> #include "QSEEComAPI.h" #include "keymaster_qcom.h" // For debugging //#define LOG_NDEBUG 0 #define LOG_TAG "QCOMKeyMaster" #include <cutils/log.h> struct qcom_km_ion_info_t { int32_t ion_fd; int32_t ifd_data_fd; struct ion_handle_data ion_alloc_handle; unsigned char * ion_sbuffer; uint32_t sbuf_len; }; struct qcom_keymaster_handle { struct QSEECom_handle *qseecom; void *libhandle; int (*QSEECom_start_app)(struct QSEECom_handle ** handle, char* path, char* appname, uint32_t size); int (*QSEECom_shutdown_app)(struct QSEECom_handle **handle); int (*QSEECom_send_cmd)(struct QSEECom_handle* handle, void *cbuf, uint32_t clen, void *rbuf, uint32_t rlen); int (*QSEECom_send_modified_cmd)(struct QSEECom_handle* handle, void *cbuf, uint32_t clen, void *rbuf, uint32_t rlen, struct QSEECom_ion_fd_info *ihandle); int (*QSEECom_set_bandwidth)(struct QSEECom_handle* handle, bool high); }; typedef struct qcom_keymaster_handle qcom_keymaster_handle_t; struct EVP_PKEY_Delete { void operator()(EVP_PKEY* p) const { EVP_PKEY_free(p); } }; typedef UniquePtr<EVP_PKEY, EVP_PKEY_Delete> Unique_EVP_PKEY; struct RSA_Delete { void operator()(RSA* p) const { RSA_free(p); } }; typedef UniquePtr<RSA, RSA_Delete> Unique_RSA; typedef UniquePtr<keymaster0_device_t> Unique_keymaster_device_t; /** * Many OpenSSL APIs take ownership of an argument on success but don't free the argument * on failure. This means we need to tell our scoped pointers when we've transferred ownership, * without triggering a warning by not using the result of release(). */ #define OWNERSHIP_TRANSFERRED(obj) \ typeof (obj.release()) _dummy __attribute__((unused)) = obj.release() static int qcom_km_get_keypair_public(const keymaster0_device_t* dev, const uint8_t* keyBlob, const size_t keyBlobLength, uint8_t** x509_data, size_t* x509_data_length) { struct qcom_km_key_blob * keyblob_ptr = (struct qcom_km_key_blob *)keyBlob; if (x509_data == NULL || x509_data_length == NULL) { ALOGE("Output public key buffer == NULL"); return -1; } if (keyBlob == NULL) { ALOGE("Supplied key blob was NULL"); return -1; } // Should be large enough for keyblob data: if (keyBlobLength < (sizeof(qcom_km_key_blob_t))) { ALOGE("key blob appears to be truncated"); return -1; } if (keyblob_ptr->magic_num != KM_MAGIC_NUM) { ALOGE("Cannot read key; it was not made by this keymaster"); return -1; } if (keyblob_ptr->public_exponent_size == 0 ) { ALOGE("Key blob appears to have incorrect exponent length"); return -1; } if (keyblob_ptr->modulus_size == 0 ) { ALOGE("Key blob appears to have incorrect modulus length"); return -1; } Unique_RSA rsa(RSA_new()); if (rsa.get() == NULL) { ALOGE("Could not allocate RSA structure"); return -1; } rsa->n = BN_bin2bn(reinterpret_cast<const unsigned char*>(keyblob_ptr->modulus), keyblob_ptr->modulus_size, NULL); if (rsa->n == NULL) { ALOGE("Failed to initialize modulus"); return -1; } rsa->e = BN_bin2bn(reinterpret_cast<const unsigned char*>(&keyblob_ptr->public_exponent), keyblob_ptr->public_exponent_size, NULL); if (rsa->e == NULL) { ALOGE("Failed to initialize public exponent"); return -1; } Unique_EVP_PKEY pkey(EVP_PKEY_new()); if (pkey.get() == NULL) { ALOGE("Could not allocate EVP_PKEY structure"); return -1; } if (EVP_PKEY_assign_RSA(pkey.get(), rsa.get()) != 1) { ALOGE("Failed to assign rsa parameters \n"); return -1; } OWNERSHIP_TRANSFERRED(rsa); int len = i2d_PUBKEY(pkey.get(), NULL); if (len <= 0) { ALOGE("Len returned is < 0 len = %d", len); return -1; } UniquePtr<uint8_t> key(static_cast<uint8_t*>(malloc(len))); if (key.get() == NULL) { ALOGE("Could not allocate memory for public key data"); return -1; } unsigned char* tmp = reinterpret_cast<unsigned char*>(key.get()); if (i2d_PUBKEY(pkey.get(), &tmp) != len) { ALOGE("Len 2 returned is < 0 len = %d", len); return -1; } *x509_data_length = len; *x509_data = key.release(); return 0; } static int32_t qcom_km_ION_memalloc(struct qcom_km_ion_info_t *handle, uint32_t size) { int32_t ret = 0; int32_t iret = 0; int32_t fd = 0; unsigned char *v_addr; struct ion_allocation_data ion_alloc_data; int32_t ion_fd; int32_t rc; struct ion_fd_data ifd_data; struct ion_handle_data handle_data; /* open ION device for memory management * O_DSYNC -> uncached memory */ if(handle == NULL){ ALOGE("Error:: null handle received"); return -1; } ion_fd = open("/dev/ion", O_RDONLY | O_DSYNC); if (ion_fd < 0) { ALOGE("Error::Cannot open ION device"); return -1; } handle->ion_sbuffer = NULL; handle->ifd_data_fd = 0; /* Size of allocation */ ion_alloc_data.len = (size + 4095) & (~4095); /* 4K aligned */ ion_alloc_data.align = 4096; /* memory is allocated from EBI heap */ ion_alloc_data.ION_HEAP_MASK = ION_HEAP(ION_QSECOM_HEAP_ID); /* Set the memory to be uncached */ ion_alloc_data.flags = 0; /* IOCTL call to ION for memory request */ rc = ioctl(ion_fd, ION_IOC_ALLOC, &ion_alloc_data); if (rc) { ret = -1; goto alloc_fail; } if (ion_alloc_data.handle != NULL) { ifd_data.handle = ion_alloc_data.handle; } else { ret = -1; goto alloc_fail; } /* Call MAP ioctl to retrieve the ifd_data.fd file descriptor */ rc = ioctl(ion_fd, ION_IOC_MAP, &ifd_data); if (rc) { ret = -1; goto ioctl_fail; } /* Make the ion mmap call */ v_addr = (unsigned char *)mmap(NULL, ion_alloc_data.len, PROT_READ | PROT_WRITE, MAP_SHARED, ifd_data.fd, 0); if (v_addr == MAP_FAILED) { ALOGE("Error::ION MMAP failed"); ret = -1; goto map_fail; } handle->ion_fd = ion_fd; handle->ifd_data_fd = ifd_data.fd; handle->ion_sbuffer = v_addr; handle->ion_alloc_handle.handle = ion_alloc_data.handle; handle->sbuf_len = size; return ret; map_fail: if (handle->ion_sbuffer != NULL) { iret = munmap(handle->ion_sbuffer, ion_alloc_data.len); if (iret) ALOGE("Error::Failed to unmap memory for load image. ret = %d", ret); } ioctl_fail: handle_data.handle = ion_alloc_data.handle; if (handle->ifd_data_fd) close(handle->ifd_data_fd); iret = ioctl(ion_fd, ION_IOC_FREE, &handle_data); if (iret) { ALOGE("Error::ION FREE ioctl returned error = %d",iret); } alloc_fail: if (ion_fd > 0) close(ion_fd); return ret; } /** @brief: Deallocate ION memory * * */ static int32_t qcom_km_ion_dealloc(struct qcom_km_ion_info_t *handle) { struct ion_handle_data handle_data; int32_t ret = 0; /* Deallocate the memory for the listener */ ret = munmap(handle->ion_sbuffer, (handle->sbuf_len + 4095) & (~4095)); if (ret) { ALOGE("Error::Unmapping ION Buffer failed with ret = %d", ret); } handle_data.handle = handle->ion_alloc_handle.handle; close(handle->ifd_data_fd); ret = ioctl(handle->ion_fd, ION_IOC_FREE, &handle_data); if (ret) { ALOGE("Error::ION Memory FREE ioctl failed with ret = %d", ret); } close(handle->ion_fd); return ret; } static int qcom_km_generate_keypair(const keymaster0_device_t* dev, const keymaster_keypair_t key_type, const void* key_params, uint8_t** keyBlob, size_t* keyBlobLength) { if (dev->context == NULL) { ALOGE("qcom_km_generate_keypair: Context == NULL"); return -1; } if (key_type != TYPE_RSA) { ALOGE("Unsupported key type %d", key_type); return -1; } else if (key_params == NULL) { ALOGE("key_params == null"); return -1; } if (keyBlob == NULL || keyBlobLength == NULL) { ALOGE("output key blob or length == NULL"); return -1; } keymaster_rsa_keygen_params_t* rsa_params = (keymaster_rsa_keygen_params_t*) key_params; keymaster_gen_keypair_cmd_t *send_cmd = NULL; keymaster_gen_keypair_resp_t *resp = NULL; struct QSEECom_handle *handle = NULL; struct qcom_keymaster_handle *km_handle =(struct qcom_keymaster_handle *)dev->context; int ret = 0; handle = (struct QSEECom_handle *)(km_handle->qseecom); send_cmd = (keymaster_gen_keypair_cmd_t *)handle->ion_sbuffer; resp = (keymaster_gen_keypair_resp_t *)(handle->ion_sbuffer + QSEECOM_ALIGN(sizeof(keymaster_gen_keypair_cmd_t))); send_cmd->cmd_id = KEYMASTER_GENERATE_KEYPAIR; send_cmd->key_type = key_type; send_cmd->rsa_params.modulus_size = rsa_params->modulus_size; send_cmd->rsa_params.public_exponent = rsa_params->public_exponent; resp->status = KEYMASTER_FAILURE; resp->key_blob_len = sizeof(qcom_km_key_blob_t); ret = (*km_handle->QSEECom_set_bandwidth)(handle, true); if (ret < 0) { ALOGE("Generate key command failed (unable to enable clks) ret =%d", ret); return -1; } ret = (*km_handle->QSEECom_send_cmd)(handle, send_cmd, QSEECOM_ALIGN(sizeof(keymaster_gen_keypair_cmd_t)), resp, QSEECOM_ALIGN(sizeof(keymaster_gen_keypair_resp_t))); if((*km_handle->QSEECom_set_bandwidth)(handle, false)) ALOGE("Import key command: (unable to disable clks)"); if ( (ret < 0) || (resp->status < 0)) { ALOGE("Generate key command failed resp->status = %d ret =%d", resp->status, ret); return -1; } else { UniquePtr<unsigned char[]> keydata(new unsigned char[resp->key_blob_len]); if (keydata.get() == NULL) { ALOGE("could not allocate memory for key blob"); return -1; } unsigned char* p = keydata.get(); memcpy(p, (unsigned char *)(&resp->key_blob), resp->key_blob_len); *keyBlob = keydata.release(); *keyBlobLength = resp->key_blob_len; } return 0; } static int qcom_km_import_keypair(const keymaster0_device_t* dev, const uint8_t* key, const size_t key_length, uint8_t** keyBlob, size_t* keyBlobLength) { if (dev->context == NULL) { ALOGE("qcom_km_import_keypair: Context == NULL"); return -1; } if (key == NULL) { ALOGE("Input key == NULL"); return -1; } else if (keyBlob == NULL || keyBlobLength == NULL) { ALOGE("Output key blob or length == NULL"); return -1; } struct QSEECom_ion_fd_info ion_fd_info; struct qcom_km_ion_info_t ihandle; int ret = 0; ihandle.ion_fd = 0; ihandle.ion_alloc_handle.handle = NULL; if (qcom_km_ION_memalloc(&ihandle, QSEECOM_ALIGN(key_length)) < 0) { ALOGE("ION allocation failed"); return -1; } memset(&ion_fd_info, 0, sizeof(struct QSEECom_ion_fd_info)); /* Populate the send data structure */ ion_fd_info.data[0].fd = ihandle.ifd_data_fd; ion_fd_info.data[0].cmd_buf_offset = sizeof(enum keymaster_cmd_t); struct QSEECom_handle *handle = NULL; keymaster_import_keypair_cmd_t *send_cmd = NULL; keymaster_import_keypair_resp_t *resp = NULL; struct qcom_keymaster_handle *km_handle =(struct qcom_keymaster_handle *)dev->context; handle = (struct QSEECom_handle *)(km_handle->qseecom); send_cmd = (keymaster_import_keypair_cmd_t *)handle->ion_sbuffer; resp = (keymaster_import_keypair_resp_t *)(handle->ion_sbuffer + QSEECOM_ALIGN(sizeof(keymaster_import_keypair_cmd_t))); send_cmd->cmd_id = KEYMASTER_IMPORT_KEYPAIR; send_cmd->pkcs8_key = (uint32_t)ihandle.ion_sbuffer; memcpy((unsigned char *)ihandle.ion_sbuffer, key, key_length); send_cmd->pkcs8_key_len = key_length; resp->status = KEYMASTER_FAILURE; resp->key_blob_len = sizeof(qcom_km_key_blob_t); ret = (*km_handle->QSEECom_set_bandwidth)(handle, true); if (ret < 0) { ALOGE("Import key command failed (unable to enable clks) ret =%d", ret); qcom_km_ion_dealloc(&ihandle); return -1; } ret = (*km_handle->QSEECom_send_modified_cmd)(handle, send_cmd, QSEECOM_ALIGN(sizeof(*send_cmd)), resp, QSEECOM_ALIGN(sizeof(*resp)), &ion_fd_info); if((*km_handle->QSEECom_set_bandwidth)(handle, false)) ALOGE("Import key command: (unable to disable clks)"); if ( (ret < 0) || (resp->status < 0)) { ALOGE("Import key command failed resp->status = %d ret =%d", resp->status, ret); qcom_km_ion_dealloc(&ihandle); return -1; } else { UniquePtr<unsigned char[]> keydata(new unsigned char[resp->key_blob_len]); if (keydata.get() == NULL) { ALOGE("could not allocate memory for key blob"); return -1; } unsigned char* p = keydata.get(); memcpy(p, (unsigned char *)(&resp->key_blob), resp->key_blob_len); *keyBlob = keydata.release(); *keyBlobLength = resp->key_blob_len; } qcom_km_ion_dealloc(&ihandle); return 0; } static int qcom_km_sign_data(const keymaster0_device_t* dev, const void* params, const uint8_t* keyBlob, const size_t keyBlobLength, const uint8_t* data, const size_t dataLength, uint8_t** signedData, size_t* signedDataLength) { if (dev->context == NULL) { ALOGE("qcom_km_sign_data: Context == NULL"); return -1; } if (dataLength > KM_KEY_SIZE_MAX) { ALOGE("Input data to be signed is too long %d bytes", dataLength); return -1; } if (data == NULL) { ALOGE("input data to sign == NULL"); return -1; } else if (signedData == NULL || signedDataLength == NULL) { ALOGE("Output signature buffer == NULL"); return -1; } keymaster_rsa_sign_params_t* sign_params = (keymaster_rsa_sign_params_t*) params; if (sign_params->digest_type != DIGEST_NONE) { ALOGE("Cannot handle digest type %d", sign_params->digest_type); return -1; } else if (sign_params->padding_type != PADDING_NONE) { ALOGE("Cannot handle padding type %d", sign_params->padding_type); return -1; } struct QSEECom_handle *handle = NULL; keymaster_sign_data_cmd_t *send_cmd = NULL; keymaster_sign_data_resp_t *resp = NULL; struct QSEECom_ion_fd_info ion_fd_info; struct qcom_km_ion_info_t ihandle; struct qcom_keymaster_handle *km_handle =(struct qcom_keymaster_handle *)dev->context; int ret = 0; handle = (struct QSEECom_handle *)(km_handle->qseecom); ihandle.ion_fd = 0; ihandle.ion_alloc_handle.handle = NULL; if (qcom_km_ION_memalloc(&ihandle, dataLength) < 0) { ALOGE("ION allocation failed"); return -1; } memset(&ion_fd_info, 0, sizeof(struct QSEECom_ion_fd_info)); /* Populate the send data structure */ ion_fd_info.data[0].fd = ihandle.ifd_data_fd; ion_fd_info.data[0].cmd_buf_offset = sizeof(enum keymaster_cmd_t) + sizeof(qcom_km_key_blob_t) + sizeof(keymaster_rsa_sign_params_t); send_cmd = (keymaster_sign_data_cmd_t *)handle->ion_sbuffer; resp = (keymaster_sign_data_resp_t *)(handle->ion_sbuffer + QSEECOM_ALIGN(sizeof(keymaster_sign_data_cmd_t))); send_cmd->cmd_id = KEYMASTER_SIGN_DATA ; send_cmd->sign_param.digest_type = sign_params->digest_type; send_cmd->sign_param.padding_type = sign_params->padding_type; memcpy((unsigned char *)(&send_cmd->key_blob), keyBlob, keyBlobLength); memcpy((unsigned char *)ihandle.ion_sbuffer, data, dataLength); send_cmd->data = (uint32_t)ihandle.ion_sbuffer; send_cmd->dlen = dataLength; resp->sig_len = KM_KEY_SIZE_MAX; resp->status = KEYMASTER_FAILURE; ret = (*km_handle->QSEECom_set_bandwidth)(handle, true); if (ret < 0) { ALOGE("Sign data command failed (unable to enable clks) ret =%d", ret); qcom_km_ion_dealloc(&ihandle); return -1; } ret = (*km_handle->QSEECom_send_modified_cmd)(handle, send_cmd, QSEECOM_ALIGN(sizeof(*send_cmd)), resp, QSEECOM_ALIGN(sizeof(*resp)), &ion_fd_info); if((*km_handle->QSEECom_set_bandwidth)(handle, false)) ALOGE("Sign data command: (unable to disable clks)"); if ( (ret < 0) || (resp->status < 0)) { ALOGE("Sign data command failed resp->status = %d ret =%d", resp->status, ret); qcom_km_ion_dealloc(&ihandle); return -1; } else { UniquePtr<uint8_t> signedDataPtr(reinterpret_cast<uint8_t*>(malloc(resp->sig_len))); if (signedDataPtr.get() == NULL) { ALOGE("Sign data memory allocation failed"); qcom_km_ion_dealloc(&ihandle); return -1; } unsigned char* p = signedDataPtr.get(); memcpy(p, (unsigned char *)(&resp->signed_data), resp->sig_len); *signedDataLength = resp->sig_len; *signedData = signedDataPtr.release(); } qcom_km_ion_dealloc(&ihandle); return 0; } static int qcom_km_verify_data(const keymaster0_device_t* dev, const void* params, const uint8_t* keyBlob, const size_t keyBlobLength, const uint8_t* signedData, const size_t signedDataLength, const uint8_t* signature, const size_t signatureLength) { if (dev->context == NULL) { ALOGE("qcom_km_verify_data: Context == NULL"); return -1; } if (signedData == NULL || signature == NULL) { ALOGE("data or signature buffers == NULL"); return -1; } keymaster_rsa_sign_params_t* sign_params = (keymaster_rsa_sign_params_t*) params; if (sign_params->digest_type != DIGEST_NONE) { ALOGE("Cannot handle digest type %d", sign_params->digest_type); return -1; } else if (sign_params->padding_type != PADDING_NONE) { ALOGE("Cannot handle padding type %d", sign_params->padding_type); return -1; } else if (signatureLength != signedDataLength) { ALOGE("signed data length must be signature length"); return -1; } struct QSEECom_handle *handle = NULL; keymaster_verify_data_cmd_t *send_cmd = NULL; keymaster_verify_data_resp_t *resp = NULL; struct QSEECom_ion_fd_info ion_fd_info; struct qcom_km_ion_info_t ihandle; struct qcom_keymaster_handle *km_handle =(struct qcom_keymaster_handle *)dev->context; int ret = 0; handle = (struct QSEECom_handle *)(km_handle->qseecom); ihandle.ion_fd = 0; ihandle.ion_alloc_handle.handle = NULL; if (qcom_km_ION_memalloc(&ihandle, signedDataLength + signatureLength) <0) { ALOGE("ION allocation failed"); return -1; } memset(&ion_fd_info, 0, sizeof(struct QSEECom_ion_fd_info)); /* Populate the send data structure */ ion_fd_info.data[0].fd = ihandle.ifd_data_fd; ion_fd_info.data[0].cmd_buf_offset = sizeof(enum keymaster_cmd_t) + sizeof(qcom_km_key_blob_t ) + sizeof(keymaster_rsa_sign_params_t); send_cmd = (keymaster_verify_data_cmd_t *)handle->ion_sbuffer; resp = (keymaster_verify_data_resp_t *)((char *)handle->ion_sbuffer + sizeof(keymaster_verify_data_cmd_t)); send_cmd->cmd_id = KEYMASTER_VERIFY_DATA ; send_cmd->sign_param.digest_type = sign_params->digest_type; send_cmd->sign_param.padding_type = sign_params->padding_type; memcpy((unsigned char *)(&send_cmd->key_blob), keyBlob, keyBlobLength); send_cmd->signed_data = (uint32_t)ihandle.ion_sbuffer; send_cmd->signed_dlen = signedDataLength; memcpy((unsigned char *)ihandle.ion_sbuffer, signedData, signedDataLength); send_cmd->signature = signedDataLength; send_cmd->slen = signatureLength; memcpy(((unsigned char *)ihandle.ion_sbuffer + signedDataLength), signature, signatureLength); resp->status = KEYMASTER_FAILURE; ret = (*km_handle->QSEECom_set_bandwidth)(handle, true); if (ret < 0) { ALOGE("Verify data command failed (unable to enable clks) ret =%d", ret); qcom_km_ion_dealloc(&ihandle); return -1; } ret = (*km_handle->QSEECom_send_modified_cmd)(handle, send_cmd, QSEECOM_ALIGN(sizeof(*send_cmd)), resp, QSEECOM_ALIGN(sizeof(*resp)), &ion_fd_info); if((*km_handle->QSEECom_set_bandwidth)(handle, false)) ALOGE("Verify data command: (unable to disable clks)"); if ( (ret < 0) || (resp->status < 0)) { ALOGE("Verify data command failed resp->status = %d ret =%d", resp->status, ret); qcom_km_ion_dealloc(&ihandle); return -1; } qcom_km_ion_dealloc(&ihandle); return 0; } /* Close an opened OpenSSL instance */ static int qcom_km_close(hw_device_t *dev) { keymaster0_device_t* km_dev = (keymaster0_device_t *)dev; struct qcom_keymaster_handle *km_handle =(struct qcom_keymaster_handle *)km_dev->context; if (km_handle->qseecom == NULL) { ALOGE("Context == NULL"); return -1; } (*km_handle->QSEECom_shutdown_app)((struct QSEECom_handle **)&km_handle->qseecom); free(km_dev->context); free(dev); return 0; } static int qcom_km_get_lib_sym(qcom_keymaster_handle_t* km_handle) { km_handle->libhandle = dlopen("libQSEEComAPI.so", RTLD_NOW); if ( km_handle->libhandle ) { *(void **)(&km_handle->QSEECom_start_app) = dlsym(km_handle->libhandle,"QSEECom_start_app"); if (km_handle->QSEECom_start_app == NULL) { ALOGE("dlsym: Error Loading QSEECom_start_app"); dlclose(km_handle->libhandle ); km_handle->libhandle = NULL; return -1; } *(void **)(&km_handle->QSEECom_shutdown_app) = dlsym(km_handle->libhandle,"QSEECom_shutdown_app"); if (km_handle->QSEECom_shutdown_app == NULL) { ALOGE("dlsym: Error Loading QSEECom_shutdown_app"); dlclose(km_handle->libhandle ); km_handle->libhandle = NULL; return -1; } *(void **)(&km_handle->QSEECom_send_cmd) = dlsym(km_handle->libhandle,"QSEECom_send_cmd"); if (km_handle->QSEECom_send_cmd == NULL) { ALOGE("dlsym: Error Loading QSEECom_send_cmd"); dlclose(km_handle->libhandle ); km_handle->libhandle = NULL; return -1; } *(void **)(&km_handle->QSEECom_send_modified_cmd) = dlsym(km_handle->libhandle,"QSEECom_send_modified_cmd"); if (km_handle->QSEECom_send_modified_cmd == NULL) { ALOGE("dlsym: Error Loading QSEECom_send_modified_cmd"); dlclose(km_handle->libhandle ); km_handle->libhandle = NULL; return -1; } *(void **)(&km_handle->QSEECom_set_bandwidth) = dlsym(km_handle->libhandle,"QSEECom_set_bandwidth"); if (km_handle->QSEECom_set_bandwidth == NULL) { ALOGE("dlsym: Error Loading QSEECom_set_bandwidth"); dlclose(km_handle->libhandle ); km_handle->libhandle = NULL; return -1; } } else { ALOGE("failed to load qseecom library"); return -1; } return 0; } /* * Generic device handling */ static int qcom_km_open(const hw_module_t* module, const char* name, hw_device_t** device) { int ret = 0; qcom_keymaster_handle_t* km_handle; if (strcmp(name, KEYSTORE_KEYMASTER) != 0) return -EINVAL; km_handle = (qcom_keymaster_handle_t *)malloc(sizeof(qcom_keymaster_handle_t)); if (km_handle == NULL) { ALOGE("Memalloc for keymaster handle failed"); return -1; } km_handle->qseecom = NULL; km_handle->libhandle = NULL; ret = qcom_km_get_lib_sym(km_handle); if (ret) { free(km_handle); return -1; } Unique_keymaster_device_t dev(new keymaster0_device_t); if (dev.get() == NULL){ free(km_handle); return -ENOMEM; } dev->context = (void *)km_handle; ret = (*km_handle->QSEECom_start_app)((struct QSEECom_handle **)&km_handle->qseecom, "/vendor/firmware/keymaster", "keymaster", 4096*2); if (ret) { ALOGE("Loading keymaster app failed"); free(km_handle); return -1; } dev->common.tag = HARDWARE_DEVICE_TAG; dev->common.version = 1; dev->common.module = (struct hw_module_t*) module; dev->common.close = qcom_km_close; dev->flags = KEYMASTER_BLOBS_ARE_STANDALONE; dev->generate_keypair = qcom_km_generate_keypair; dev->import_keypair = qcom_km_import_keypair; dev->get_keypair_public = qcom_km_get_keypair_public; dev->delete_keypair = NULL; dev->delete_all = NULL; dev->sign_data = qcom_km_sign_data; dev->verify_data = qcom_km_verify_data; *device = reinterpret_cast<hw_device_t*>(dev.release()); return 0; } static struct hw_module_methods_t keystore_module_methods = { .open = qcom_km_open, }; struct keystore_module HAL_MODULE_INFO_SYM __attribute__ ((visibility ("default"))) = { .common = { .tag = HARDWARE_MODULE_TAG, .module_api_version = QCOM_KEYMASTER_API_VERSION, .hal_api_version = HARDWARE_HAL_API_VERSION, .id = KEYSTORE_HARDWARE_MODULE_ID, .name = "Keymaster QCOM HAL", .author = "The Android Open Source Project", .methods = &keystore_module_methods, .dso = 0, .reserved = {}, }, };
#define CATCH_CONFIG_MAIN // This tells Catch to provide a main() - only do this in one cpp file #include "catch.hpp" #include "decision.h" TEST_CASE("Verify Test Configuration", "verification") { REQUIRE(true == true); } TEST_CASE("Test get letter grade with if") { REQUIRE(get_letter_grade_using_if(95) == 'A'); REQUIRE(get_letter_grade_using_if(85) == 'B'); REQUIRE(get_letter_grade_using_if(75) == 'C'); REQUIRE(get_letter_grade_using_if(65) == 'D'); REQUIRE(get_letter_grade_using_if(50) == 'F'); } TEST_CASE("Test get letter grade with switch") { REQUIRE(get_letter_grade_using_switch(95) == 'A'); REQUIRE(get_letter_grade_using_switch(85) == 'B'); REQUIRE(get_letter_grade_using_switch(75) == 'C'); REQUIRE(get_letter_grade_using_switch(65) == 'D'); REQUIRE(get_letter_grade_using_switch(50) == 'F'); }
// Copyright (c) 2012-2018 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 <wallet/wallet.h> #include <memory> #include <set> #include <stdint.h> #include <utility> #include <vector> #include <consensus/validation.h> #include <rpc/server.h> #include <test/test_wescoin.h> #include <validation.h> #include <wallet/coincontrol.h> #include <wallet/test/wallet_test_fixture.h> #include <policy/policy.h> #include <boost/test/unit_test.hpp> #include <univalue.h> extern UniValue importmulti(const JSONRPCRequest& request); extern UniValue dumpwallet(const JSONRPCRequest& request); extern UniValue importwallet(const JSONRPCRequest& request); BOOST_FIXTURE_TEST_SUITE(wallet_tests, WalletTestingSetup) static void AddKey(CWallet& wallet, const CKey& key) { LOCK(wallet.cs_wallet); wallet.AddKeyPubKey(key, key.GetPubKey()); } BOOST_FIXTURE_TEST_CASE(rescan, TestChain100Setup) { // Cap last block file size, and mine new block in a new block file. CBlockIndex* const nullBlock = nullptr; CBlockIndex* oldTip = chainActive.Tip(); GetBlockFileInfo(oldTip->GetBlockPos().nFile)->nSize = MAX_BLOCKFILE_SIZE; CreateAndProcessBlock({}, GetScriptForRawPubKey(coinbaseKey.GetPubKey())); CBlockIndex* newTip = chainActive.Tip(); LOCK(cs_main); // Verify ScanForWalletTransactions picks up transactions in both the old // and new block files. { CWallet wallet(WalletLocation(), WalletDatabase::CreateDummy()); AddKey(wallet, coinbaseKey); WalletRescanReserver reserver(&wallet); reserver.reserve(); BOOST_CHECK_EQUAL(nullBlock, wallet.ScanForWalletTransactions(oldTip, nullptr, reserver)); BOOST_CHECK_EQUAL(wallet.GetImmatureBalance(), 100 * COIN); } // Prune the older block file. PruneOneBlockFile(oldTip->GetBlockPos().nFile); UnlinkPrunedFiles({oldTip->GetBlockPos().nFile}); // Verify ScanForWalletTransactions only picks transactions in the new block // file. { CWallet wallet(WalletLocation(), WalletDatabase::CreateDummy()); AddKey(wallet, coinbaseKey); WalletRescanReserver reserver(&wallet); reserver.reserve(); BOOST_CHECK_EQUAL(oldTip, wallet.ScanForWalletTransactions(oldTip, nullptr, reserver)); BOOST_CHECK_EQUAL(wallet.GetImmatureBalance(), 50 * COIN); } // Verify importmulti RPC returns failure for a key whose creation time is // before the missing block, and success for a key whose creation time is // after. { std::shared_ptr<CWallet> wallet = std::make_shared<CWallet>(WalletLocation(), WalletDatabase::CreateDummy()); AddWallet(wallet); UniValue keys; keys.setArray(); UniValue key; key.setObject(); key.pushKV("scriptPubKey", HexStr(GetScriptForRawPubKey(coinbaseKey.GetPubKey()))); key.pushKV("timestamp", 0); key.pushKV("internal", UniValue(true)); keys.push_back(key); key.clear(); key.setObject(); CKey futureKey; futureKey.MakeNewKey(true); key.pushKV("scriptPubKey", HexStr(GetScriptForRawPubKey(futureKey.GetPubKey()))); key.pushKV("timestamp", newTip->GetBlockTimeMax() + TIMESTAMP_WINDOW + 1); key.pushKV("internal", UniValue(true)); keys.push_back(key); JSONRPCRequest request; request.params.setArray(); request.params.push_back(keys); UniValue response = importmulti(request); BOOST_CHECK_EQUAL(response.write(), strprintf("[{\"success\":false,\"error\":{\"code\":-1,\"message\":\"Rescan failed for key with creation " "timestamp %d. There was an error reading a block from time %d, which is after or within %d " "seconds of key creation, and could contain transactions pertaining to the key. As a result, " "transactions and coins using this key may not appear in the wallet. This error could be caused " "by pruning or data corruption (see wescoind log for details) and could be dealt with by " "downloading and rescanning the relevant blocks (see -reindex and -rescan " "options).\"}},{\"success\":true}]", 0, oldTip->GetBlockTimeMax(), TIMESTAMP_WINDOW)); RemoveWallet(wallet); } } // Verify importwallet RPC starts rescan at earliest block with timestamp // greater or equal than key birthday. Previously there was a bug where // importwallet RPC would start the scan at the latest block with timestamp less // than or equal to key birthday. BOOST_FIXTURE_TEST_CASE(importwallet_rescan, TestChain100Setup) { // Create two blocks with same timestamp to verify that importwallet rescan // will pick up both blocks, not just the first. const int64_t BLOCK_TIME = chainActive.Tip()->GetBlockTimeMax() + 5; SetMockTime(BLOCK_TIME); m_coinbase_txns.emplace_back(CreateAndProcessBlock({}, GetScriptForRawPubKey(coinbaseKey.GetPubKey())).vtx[0]); m_coinbase_txns.emplace_back(CreateAndProcessBlock({}, GetScriptForRawPubKey(coinbaseKey.GetPubKey())).vtx[0]); // Set key birthday to block time increased by the timestamp window, so // rescan will start at the block time. const int64_t KEY_TIME = BLOCK_TIME + TIMESTAMP_WINDOW; SetMockTime(KEY_TIME); m_coinbase_txns.emplace_back(CreateAndProcessBlock({}, GetScriptForRawPubKey(coinbaseKey.GetPubKey())).vtx[0]); LOCK(cs_main); std::string backup_file = (SetDataDir("importwallet_rescan") / "wallet.backup").string(); // Import key into wallet and call dumpwallet to create backup file. { std::shared_ptr<CWallet> wallet = std::make_shared<CWallet>(WalletLocation(), WalletDatabase::CreateDummy()); LOCK(wallet->cs_wallet); wallet->mapKeyMetadata[coinbaseKey.GetPubKey().GetID()].nCreateTime = KEY_TIME; wallet->AddKeyPubKey(coinbaseKey, coinbaseKey.GetPubKey()); JSONRPCRequest request; request.params.setArray(); request.params.push_back(backup_file); AddWallet(wallet); ::dumpwallet(request); RemoveWallet(wallet); } // Call importwallet RPC and verify all blocks with timestamps >= BLOCK_TIME // were scanned, and no prior blocks were scanned. { std::shared_ptr<CWallet> wallet = std::make_shared<CWallet>(WalletLocation(), WalletDatabase::CreateDummy()); JSONRPCRequest request; request.params.setArray(); request.params.push_back(backup_file); AddWallet(wallet); ::importwallet(request); RemoveWallet(wallet); LOCK(wallet->cs_wallet); BOOST_CHECK_EQUAL(wallet->mapWallet.size(), 3U); BOOST_CHECK_EQUAL(m_coinbase_txns.size(), 103U); for (size_t i = 0; i < m_coinbase_txns.size(); ++i) { bool found = wallet->GetWalletTx(m_coinbase_txns[i]->GetHash()); bool expected = i >= 100; BOOST_CHECK_EQUAL(found, expected); } } SetMockTime(0); } // Check that GetImmatureCredit() returns a newly calculated value instead of // the cached value after a MarkDirty() call. // // This is a regression test written to verify a bugfix for the immature credit // function. Similar tests probably should be written for the other credit and // debit functions. BOOST_FIXTURE_TEST_CASE(coin_mark_dirty_immature_credit, TestChain100Setup) { CWallet wallet(WalletLocation(), WalletDatabase::CreateDummy()); CWalletTx wtx(&wallet, m_coinbase_txns.back()); LOCK2(cs_main, wallet.cs_wallet); wtx.hashBlock = chainActive.Tip()->GetBlockHash(); wtx.nIndex = 0; // Call GetImmatureCredit() once before adding the key to the wallet to // cache the current immature credit amount, which is 0. BOOST_CHECK_EQUAL(wtx.GetImmatureCredit(), 0); // Invalidate the cached value, add the key, and make sure a new immature // credit amount is calculated. wtx.MarkDirty(); wallet.AddKeyPubKey(coinbaseKey, coinbaseKey.GetPubKey()); BOOST_CHECK_EQUAL(wtx.GetImmatureCredit(), 50*COIN); } static int64_t AddTx(CWallet& wallet, uint32_t lockTime, int64_t mockTime, int64_t blockTime) { CMutableTransaction tx; tx.nLockTime = lockTime; SetMockTime(mockTime); CBlockIndex* block = nullptr; if (blockTime > 0) { LOCK(cs_main); auto inserted = mapBlockIndex.emplace(GetRandHash(), new CBlockIndex); assert(inserted.second); const uint256& hash = inserted.first->first; block = inserted.first->second; block->nTime = blockTime; block->phashBlock = &hash; } CWalletTx wtx(&wallet, MakeTransactionRef(tx)); if (block) { wtx.SetMerkleBranch(block, 0); } { LOCK(cs_main); wallet.AddToWallet(wtx); } LOCK(wallet.cs_wallet); return wallet.mapWallet.at(wtx.GetHash()).nTimeSmart; } // Simple test to verify assignment of CWalletTx::nSmartTime value. Could be // expanded to cover more corner cases of smart time logic. BOOST_AUTO_TEST_CASE(ComputeTimeSmart) { // New transaction should use clock time if lower than block time. BOOST_CHECK_EQUAL(AddTx(m_wallet, 1, 100, 120), 100); // Test that updating existing transaction does not change smart time. BOOST_CHECK_EQUAL(AddTx(m_wallet, 1, 200, 220), 100); // New transaction should use clock time if there's no block time. BOOST_CHECK_EQUAL(AddTx(m_wallet, 2, 300, 0), 300); // New transaction should use block time if lower than clock time. BOOST_CHECK_EQUAL(AddTx(m_wallet, 3, 420, 400), 400); // New transaction should use latest entry time if higher than // min(block time, clock time). BOOST_CHECK_EQUAL(AddTx(m_wallet, 4, 500, 390), 400); // If there are future entries, new transaction should use time of the // newest entry that is no more than 300 seconds ahead of the clock time. BOOST_CHECK_EQUAL(AddTx(m_wallet, 5, 50, 600), 300); // Reset mock time for other tests. SetMockTime(0); } BOOST_AUTO_TEST_CASE(LoadReceiveRequests) { CTxDestination dest = CKeyID(); LOCK(m_wallet.cs_wallet); m_wallet.AddDestData(dest, "misc", "val_misc"); m_wallet.AddDestData(dest, "rr0", "val_rr0"); m_wallet.AddDestData(dest, "rr1", "val_rr1"); auto values = m_wallet.GetDestValues("rr"); BOOST_CHECK_EQUAL(values.size(), 2U); BOOST_CHECK_EQUAL(values[0], "val_rr0"); BOOST_CHECK_EQUAL(values[1], "val_rr1"); } class ListCoinsTestingSetup : public TestChain100Setup { public: ListCoinsTestingSetup() { CreateAndProcessBlock({}, GetScriptForRawPubKey(coinbaseKey.GetPubKey())); wallet = MakeUnique<CWallet>(WalletLocation(), WalletDatabase::CreateMock()); bool firstRun; wallet->LoadWallet(firstRun); AddKey(*wallet, coinbaseKey); WalletRescanReserver reserver(wallet.get()); reserver.reserve(); wallet->ScanForWalletTransactions(chainActive.Genesis(), nullptr, reserver); } ~ListCoinsTestingSetup() { wallet.reset(); } CWalletTx& AddTx(CRecipient recipient) { CTransactionRef tx; CReserveKey reservekey(wallet.get()); CAmount fee; int changePos = -1; std::string error; CCoinControl dummy; BOOST_CHECK(wallet->CreateTransaction({recipient}, tx, reservekey, fee, changePos, error, dummy)); CValidationState state; BOOST_CHECK(wallet->CommitTransaction(tx, {}, {}, {}, reservekey, nullptr, state)); CMutableTransaction blocktx; { LOCK(wallet->cs_wallet); blocktx = CMutableTransaction(*wallet->mapWallet.at(tx->GetHash()).tx); } CreateAndProcessBlock({CMutableTransaction(blocktx)}, GetScriptForRawPubKey(coinbaseKey.GetPubKey())); LOCK(wallet->cs_wallet); auto it = wallet->mapWallet.find(tx->GetHash()); BOOST_CHECK(it != wallet->mapWallet.end()); it->second.SetMerkleBranch(chainActive.Tip(), 1); return it->second; } std::unique_ptr<CWallet> wallet; }; BOOST_FIXTURE_TEST_CASE(ListCoins, ListCoinsTestingSetup) { std::string coinbaseAddress = coinbaseKey.GetPubKey().GetID().ToString(); // Confirm ListCoins initially returns 1 coin grouped under coinbaseKey // address. auto list = wallet->ListCoins(); BOOST_CHECK_EQUAL(list.size(), 1U); BOOST_CHECK_EQUAL(boost::get<CKeyID>(list.begin()->first).ToString(), coinbaseAddress); BOOST_CHECK_EQUAL(list.begin()->second.size(), 1U); // Check initial balance from one mature coinbase transaction. BOOST_CHECK_EQUAL(50 * COIN, wallet->GetAvailableBalance()); // Add a transaction creating a change address, and confirm ListCoins still // returns the coin associated with the change address underneath the // coinbaseKey pubkey, even though the change address has a different // pubkey. AddTx(CRecipient{GetScriptForRawPubKey({}), 1 * COIN, false /* subtract fee */}); list = wallet->ListCoins(); BOOST_CHECK_EQUAL(list.size(), 1U); BOOST_CHECK_EQUAL(boost::get<CKeyID>(list.begin()->first).ToString(), coinbaseAddress); BOOST_CHECK_EQUAL(list.begin()->second.size(), 2U); // Lock both coins. Confirm number of available coins drops to 0. { LOCK2(cs_main, wallet->cs_wallet); std::vector<COutput> available; wallet->AvailableCoins(available); BOOST_CHECK_EQUAL(available.size(), 2U); } for (const auto& group : list) { for (const auto& coin : group.second) { LOCK(wallet->cs_wallet); wallet->LockCoin(COutPoint(coin.tx->GetHash(), coin.i)); } } { LOCK2(cs_main, wallet->cs_wallet); std::vector<COutput> available; wallet->AvailableCoins(available); BOOST_CHECK_EQUAL(available.size(), 0U); } // Confirm ListCoins still returns same result as before, despite coins // being locked. list = wallet->ListCoins(); BOOST_CHECK_EQUAL(list.size(), 1U); BOOST_CHECK_EQUAL(boost::get<CKeyID>(list.begin()->first).ToString(), coinbaseAddress); BOOST_CHECK_EQUAL(list.begin()->second.size(), 2U); } BOOST_FIXTURE_TEST_CASE(wallet_disableprivkeys, TestChain100Setup) { std::shared_ptr<CWallet> wallet = std::make_shared<CWallet>(WalletLocation(), WalletDatabase::CreateDummy()); wallet->SetWalletFlag(WALLET_FLAG_DISABLE_PRIVATE_KEYS); BOOST_CHECK(!wallet->TopUpKeyPool(1000)); CPubKey pubkey; BOOST_CHECK(!wallet->GetKeyFromPool(pubkey, false)); } // Explicit calculation which is used to test the wallet constant // We get the same virtual size due to rounding(weight/4) for both use_max_sig values static size_t CalculateNestedKeyhashInputSize(bool use_max_sig) { // Generate ephemeral valid pubkey CKey key; key.MakeNewKey(true); CPubKey pubkey = key.GetPubKey(); // Generate pubkey hash uint160 key_hash(Hash160(pubkey.begin(), pubkey.end())); // Create inner-script to enter into keystore. Key hash can't be 0... CScript inner_script = CScript() << OP_0 << std::vector<unsigned char>(key_hash.begin(), key_hash.end()); // Create outer P2SH script for the output uint160 script_id(Hash160(inner_script.begin(), inner_script.end())); CScript script_pubkey = CScript() << OP_HASH160 << std::vector<unsigned char>(script_id.begin(), script_id.end()) << OP_EQUAL; // Add inner-script to key store and key to watchonly CBasicKeyStore keystore; keystore.AddCScript(inner_script); keystore.AddKeyPubKey(key, pubkey); // Fill in dummy signatures for fee calculation. SignatureData sig_data; if (!ProduceSignature(keystore, use_max_sig ? DUMMY_MAXIMUM_SIGNATURE_CREATOR : DUMMY_SIGNATURE_CREATOR, script_pubkey, sig_data)) { // We're hand-feeding it correct arguments; shouldn't happen assert(false); } CTxIn tx_in; UpdateInput(tx_in, sig_data); return (size_t)GetVirtualTransactionInputSize(tx_in); } BOOST_FIXTURE_TEST_CASE(dummy_input_size_test, TestChain100Setup) { BOOST_CHECK_EQUAL(CalculateNestedKeyhashInputSize(false), DUMMY_NESTED_P2WPKH_INPUT_SIZE); BOOST_CHECK_EQUAL(CalculateNestedKeyhashInputSize(true), DUMMY_NESTED_P2WPKH_INPUT_SIZE); } BOOST_AUTO_TEST_SUITE_END()
/* Copyright (C) 2006 - 2013 ScriptDev2 <http://www.scriptdev2.com/> * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ /* ScriptData SDName: boss_archbishop_benedictus SD%Complete: 0 SDComment: Placeholder SDCategory: Hour of Twilight EndScriptData */ #include "precompiled.h" void AddSC_boss_archbishop_benedictus() { }
#include "muscle.h" #include "seqvect.h" #include "msa.h" #include "muscle_context.h" /*** Methionine hack. Most proteins start with M. This results in odd-looking alignments with the terminal Ms aligned followed immediately by gaps. Hack this by treating terminal M like X. ***/ void MHackStart(SeqVect &v) { MuscleContext *ctx = getMuscleContext(); bool* &M = ctx->mhack.M; if (ALPHA_Amino != ctx->alpha.g_Alpha) return; const unsigned uSeqCount = v.Length(); M = new bool[uSeqCount]; memset(M, 0, uSeqCount*sizeof(bool)); for (unsigned uSeqIndex = 0; uSeqIndex < uSeqCount; ++uSeqIndex) { Seq &s = v.GetSeq(uSeqIndex); if (0 == s.Length()) continue; unsigned uId = s.GetId(); if (s[0] == 'M' || s[0] == 'm') { M[uId] = true; s[0] = 'X'; } } } void MHackEnd(MSA &msa) { MuscleContext *ctx = getMuscleContext(); bool* &M = ctx->mhack.M; if (ALPHA_Amino != ctx->alpha.g_Alpha) return; if (0 == M) return; const unsigned uSeqCount = msa.GetSeqCount(); const unsigned uColCount = msa.GetColCount(); for (unsigned uSeqIndex = 0; uSeqIndex < uSeqCount; ++uSeqIndex) { unsigned uId = msa.GetSeqId(uSeqIndex); if (M[uId]) { for (unsigned uColIndex = 0; uColIndex < uColCount; ++uColIndex) { if (!msa.IsGap(uSeqIndex, uColIndex)) { msa.SetChar(uSeqIndex, uColIndex, 'M'); break; } } } } delete[] M; M = 0; }
/*11875 - Brick Game*/ #include <cstdio> #include <algorithm> using namespace std; int main(){ int casos, i=1; scanf("%d", &casos); while(casos--){ int cap=0, tam=0; scanf("%d", &tam); int arr[tam]; int j; for (j = 0; j < tam; ++j) { scanf("%d", &arr[j]); } sort(arr, arr+tam); cap = (tam / 2); printf("Case %d: %d\n", i, arr[cap]); i++; } return 0; }
/* * GraphBLAS Template Library (GBTL), Version 3.0 * * Copyright 2020 Carnegie Mellon University, Battelle Memorial Institute, and * Authors. * * THIS MATERIAL WAS PREPARED AS AN ACCOUNT OF WORK SPONSORED BY AN AGENCY OF * THE UNITED STATES GOVERNMENT. NEITHER THE UNITED STATES GOVERNMENT NOR THE * UNITED STATES DEPARTMENT OF ENERGY, NOR THE UNITED STATES DEPARTMENT OF * DEFENSE, NOR CARNEGIE MELLON UNIVERSITY, NOR BATTELLE, NOR ANY OF THEIR * EMPLOYEES, NOR ANY JURISDICTION OR ORGANIZATION THAT HAS COOPERATED IN THE * DEVELOPMENT OF THESE MATERIALS, MAKES ANY WARRANTY, EXPRESS OR IMPLIED, OR * ASSUMES ANY LEGAL LIABILITY OR RESPONSIBILITY FOR THE ACCURACY, COMPLETENESS, * OR USEFULNESS OR ANY INFORMATION, APPARATUS, PRODUCT, SOFTWARE, OR PROCESS * DISCLOSED, OR REPRESENTS THAT ITS USE WOULD NOT INFRINGE PRIVATELY OWNED * RIGHTS. * * Released under a BSD-style license, please see LICENSE file or contact * permission@sei.cmu.edu for full terms. * * [DISTRIBUTION STATEMENT A] This material has been approved for public release * and unlimited distribution. Please see Copyright notice for non-US * Government use and distribution. * * DM20-0442 */ #pragma once #include <cstddef> #include <graphblas/platforms/sequential/LilSparseMatrix.hpp> //**************************************************************************** namespace grb { namespace backend { //******************************************************************** template<typename ScalarT, typename... TagsT> class Matrix : public LilSparseMatrix<ScalarT> { private: using ParentMatrixType = LilSparseMatrix<ScalarT>; public: using ScalarType = ScalarT; // construct an empty matrix of fixed dimensions Matrix(IndexType num_rows, IndexType num_cols) : ParentMatrixType(num_rows, num_cols) { } // copy construct Matrix(Matrix const &rhs) : ParentMatrixType(rhs) { } // construct a dense matrix from dense data. Matrix(std::vector<std::vector<ScalarT> > const &values) : ParentMatrixType(values) { } // construct a sparse matrix from dense data and a zero val. Matrix(std::vector<std::vector<ScalarT> > const &values, ScalarT zero) : ParentMatrixType(values, zero) { } ~Matrix() {} // virtual? // necessary? bool operator==(Matrix const &rhs) const { return ParentMatrixType::operator==(rhs); } // necessary? bool operator!=(Matrix const &rhs) const { return ParentMatrixType::operator!=(rhs); } void printInfo(std::ostream &os) const { os << "Sequential Backend: "; ParentMatrixType::printInfo(os); } }; } }
$NetBSD: patch-libgearman_backtrace.cc,v 1.1 2013/10/10 00:04:52 joerg Exp $ --- libgearman/backtrace.cc.orig 2013-10-09 23:42:25.000000000 +0000 +++ libgearman/backtrace.cc @@ -67,14 +67,14 @@ void custom_backtrace(void) #ifdef HAVE_EXECINFO_H void *backtrace_buffer[MAX_DEPTH +1]; - int stack_frames= backtrace(backtrace_buffer, MAX_DEPTH); - fprintf(stderr, "\nBegin stack trace, frames found: %d\n", stack_frames); + size_t stack_frames= backtrace(backtrace_buffer, MAX_DEPTH); + fprintf(stderr, "\nBegin stack trace, frames found: %zu\n", stack_frames); if (stack_frames) { char **symbollist= backtrace_symbols(backtrace_buffer, stack_frames); if (symbollist) { - for (int x= 0; x < stack_frames; x++) + for (size_t x= 0; x < stack_frames; x++) { bool was_demangled= false; @@ -102,7 +102,7 @@ void custom_backtrace(void) } was_demangled= true; - fprintf(stderr, "#%d %p in %s at %s\n", + fprintf(stderr, "#%zu %p in %s at %s\n", x, backtrace_buffer[x], called_in, dlinfo.dli_fname); @@ -113,7 +113,7 @@ void custom_backtrace(void) if (was_demangled == false) { - fprintf(stderr, "?%d %p in %s\n", x, backtrace_buffer[x], symbollist[x]); + fprintf(stderr, "?%zu %p in %s\n", x, backtrace_buffer[x], symbollist[x]); } }
#include "gtest/gtest.h" #include <iostream> #include <radioacek/listener.h> //using ::testing::Return; // The fixture for testing class Foo. class FooTest : public ::testing::Test { protected: // You can do set-up work for each test here. FooTest(); // You can do clean-up work that doesn't throw exceptions here. virtual ~FooTest(); // If the constructor and destructor are not enough for setting up // and cleaning up each test, you can define the following methods: // Code here will be called immediately after the constructor (right // before each test). virtual void SetUp(); // Code here will be called immediately after each test (right // before the destructor). virtual void TearDown(); // The mock bar library shaed by all tests }; TEST(FooTest, test_without_setup) { }
#ifndef NALL_XORG_GUARD_HPP #define NALL_XORG_GUARD_HPP #define Atom XlibAtom #define Bool XlibBool #define Display XlibDisplay #define Screen XlibScreen #define Window XlibWindow #else #undef NALL_XORG_GUARD_HPP #undef Atom #undef Bool #undef Display #undef Screen #undef Window #ifndef NALL_XORG_GUARD_CONSTANTS #define NALL_XORG_GUARD_CONSTANTS enum XlibConstants : int { XlibButton1 = Button1, XlibButton2 = Button2, XlibButton3 = Button3, XlibButton4 = Button4, XlibButton5 = Button5, XlibCurrentTime = CurrentTime, XlibFalse = False, XlibNone = None, XlibTrue = True, }; #endif #undef Button1 #undef Button2 #undef Button3 #undef Button4 #undef Button5 #undef CurrentTime #undef False #undef None #undef True #endif
/*** * * Copyright (c) 1996-2001, Valve LLC. All rights reserved. * * This product contains software technology licensed from Id * Software, Inc. ("Id Technology"). Id Technology (c) 1996 Id Software, Inc. * All Rights Reserved. * * Use, distribution, and modification of this source code and/or resulting * object code is restricted to non-commercial enhancements to products from * Valve LLC. All other use, distribution, or modification is prohibited * without written permission from Valve LLC. * ****/ #include "extdll.h" #include "util.h" #include "cbase.h" #include "monsters.h" #include "weapons.h" #include "nodes.h" #include "player.h" #include "gamerules.h" #include "UserMessages.h" // special deathmatch shotgun spreads #define VECTOR_CONE_DM_SHOTGUN Vector( 0.08716, 0.04362, 0.00 )// 10 degrees by 5 degrees #define VECTOR_CONE_DM_DOUBLESHOTGUN Vector( 0.17365, 0.04362, 0.00 ) // 20 degrees by 5 degrees LINK_ENTITY_TO_CLASS( weapon_shotgun, CShotgun ); void CShotgun::Spawn( ) { Precache( ); m_iId = WEAPON_SHOTGUN; SET_MODEL(ENT(pev), "models/w_shotgun.mdl"); m_iDefaultAmmo = SHOTGUN_DEFAULT_GIVE; FallInit();// get ready to fall } void CShotgun::Precache() { PRECACHE_MODEL("models/v_shotgun.mdl"); PRECACHE_MODEL("models/w_shotgun.mdl"); PRECACHE_MODEL("models/p_shotgun.mdl"); m_iShell = PRECACHE_MODEL ("models/shotgunshell.mdl");// shotgun shell PRECACHE_SOUND("items/9mmclip1.wav"); PRECACHE_SOUND ("weapons/dbarrel1.wav");//shotgun PRECACHE_SOUND ("weapons/sbarrel1.wav");//shotgun PRECACHE_SOUND ("weapons/reload1.wav"); // shotgun reload PRECACHE_SOUND ("weapons/reload3.wav"); // shotgun reload // PRECACHE_SOUND ("weapons/sshell1.wav"); // shotgun reload - played on client // PRECACHE_SOUND ("weapons/sshell3.wav"); // shotgun reload - played on client PRECACHE_SOUND ("weapons/357_cock1.wav"); // gun empty sound PRECACHE_SOUND ("weapons/scock1.wav"); // cock gun m_usSingleFire = PRECACHE_EVENT( 1, "events/shotgun1.sc" ); m_usDoubleFire = PRECACHE_EVENT( 1, "events/shotgun2.sc" ); } int CShotgun::AddToPlayer( CBasePlayer *pPlayer ) { if ( CBasePlayerWeapon::AddToPlayer( pPlayer ) ) { MESSAGE_BEGIN( MSG_ONE, gmsgWeapPickup, NULL, pPlayer->pev ); WRITE_BYTE( m_iId ); MESSAGE_END(); return TRUE; } return FALSE; } int CShotgun::GetItemInfo(ItemInfo *p) { p->pszName = STRING(pev->classname); p->pszAmmo1 = "buckshot"; p->iMaxAmmo1 = BUCKSHOT_MAX_CARRY; p->pszAmmo2 = NULL; p->iMaxAmmo2 = -1; p->iMaxClip = SHOTGUN_MAX_CLIP; p->iSlot = 2; p->iPosition = 1; p->iFlags = 0; p->iId = m_iId = WEAPON_SHOTGUN; p->iWeight = SHOTGUN_WEIGHT; return 1; } BOOL CShotgun::Deploy( ) { return DefaultDeploy( "models/v_shotgun.mdl", "models/p_shotgun.mdl", SHOTGUN_DRAW, "shotgun" ); } void CShotgun::PrimaryAttack() { // don't fire underwater if (m_pPlayer->pev->waterlevel == 3) { PlayEmptySound( ); m_flNextPrimaryAttack = GetNextAttackDelay(0.15); return; } if (m_iClip <= 0) { Reload( ); if (m_iClip == 0) PlayEmptySound( ); return; } m_pPlayer->m_iWeaponVolume = LOUD_GUN_VOLUME; m_pPlayer->m_iWeaponFlash = NORMAL_GUN_FLASH; m_iClip--; int flags; #if defined( CLIENT_WEAPONS ) flags = FEV_NOTHOST; #else flags = 0; #endif m_pPlayer->pev->effects = (int)(m_pPlayer->pev->effects) | EF_MUZZLEFLASH; Vector vecSrc = m_pPlayer->GetGunPosition( ); Vector vecAiming = m_pPlayer->GetAutoaimVector( AUTOAIM_5DEGREES ); Vector vecDir; #ifdef CLIENT_DLL if ( bIsMultiplayer() ) #else if ( g_pGameRules->IsMultiplayer() ) #endif { vecDir = m_pPlayer->FireBulletsPlayer( 4, vecSrc, vecAiming, VECTOR_CONE_DM_SHOTGUN, 2048, BULLET_PLAYER_BUCKSHOT, 0, 0, m_pPlayer->pev, m_pPlayer->random_seed ); } else { // regular old, untouched spread. vecDir = m_pPlayer->FireBulletsPlayer( 6, vecSrc, vecAiming, VECTOR_CONE_10DEGREES, 2048, BULLET_PLAYER_BUCKSHOT, 0, 0, m_pPlayer->pev, m_pPlayer->random_seed ); } PLAYBACK_EVENT_FULL( flags, m_pPlayer->edict(), m_usSingleFire, 0.0, g_vecZero, g_vecZero, vecDir.x, vecDir.y, 0, 0, 0, 0 ); if (!m_iClip && m_pPlayer->m_rgAmmo[m_iPrimaryAmmoType] <= 0) // HEV suit - indicate out of ammo condition m_pPlayer->SetSuitUpdate("!HEV_AMO0", FALSE, 0); //if (m_iClip != 0) m_flPumpTime = gpGlobals->time + 0.5; m_flNextPrimaryAttack = GetNextAttackDelay(0.75); m_flNextSecondaryAttack = UTIL_WeaponTimeBase() + 0.75; if (m_iClip != 0) m_flTimeWeaponIdle = UTIL_WeaponTimeBase() + 5.0; else m_flTimeWeaponIdle = UTIL_WeaponTimeBase() + 0.75; m_fInSpecialReload = 0; } void CShotgun::SecondaryAttack() { // don't fire underwater if (m_pPlayer->pev->waterlevel == 3) { PlayEmptySound( ); m_flNextPrimaryAttack = GetNextAttackDelay(0.15); return; } if (m_iClip <= 1) { Reload( ); PlayEmptySound( ); return; } m_pPlayer->m_iWeaponVolume = LOUD_GUN_VOLUME; m_pPlayer->m_iWeaponFlash = NORMAL_GUN_FLASH; m_iClip -= 2; int flags; #if defined( CLIENT_WEAPONS ) flags = FEV_NOTHOST; #else flags = 0; #endif m_pPlayer->pev->effects = (int)(m_pPlayer->pev->effects) | EF_MUZZLEFLASH; // player "shoot" animation m_pPlayer->SetAnimation( PLAYER_ATTACK1 ); Vector vecSrc = m_pPlayer->GetGunPosition( ); Vector vecAiming = m_pPlayer->GetAutoaimVector( AUTOAIM_5DEGREES ); Vector vecDir; #ifdef CLIENT_DLL if ( bIsMultiplayer() ) #else if ( g_pGameRules->IsMultiplayer() ) #endif { // tuned for deathmatch vecDir = m_pPlayer->FireBulletsPlayer( 8, vecSrc, vecAiming, VECTOR_CONE_DM_DOUBLESHOTGUN, 2048, BULLET_PLAYER_BUCKSHOT, 0, 0, m_pPlayer->pev, m_pPlayer->random_seed ); } else { // untouched default single player vecDir = m_pPlayer->FireBulletsPlayer( 12, vecSrc, vecAiming, VECTOR_CONE_10DEGREES, 2048, BULLET_PLAYER_BUCKSHOT, 0, 0, m_pPlayer->pev, m_pPlayer->random_seed ); } PLAYBACK_EVENT_FULL( flags, m_pPlayer->edict(), m_usDoubleFire, 0.0, g_vecZero, g_vecZero, vecDir.x, vecDir.y, 0, 0, 0, 0 ); if (!m_iClip && m_pPlayer->m_rgAmmo[m_iPrimaryAmmoType] <= 0) // HEV suit - indicate out of ammo condition m_pPlayer->SetSuitUpdate("!HEV_AMO0", FALSE, 0); //if (m_iClip != 0) m_flPumpTime = gpGlobals->time + 0.95; m_flNextPrimaryAttack = GetNextAttackDelay(1.5); m_flNextSecondaryAttack = UTIL_WeaponTimeBase() + 1.5; if (m_iClip != 0) m_flTimeWeaponIdle = UTIL_WeaponTimeBase() + 6.0; else m_flTimeWeaponIdle = 1.5; m_fInSpecialReload = 0; } void CShotgun::Reload() { if (m_pPlayer->m_rgAmmo[m_iPrimaryAmmoType] <= 0 || m_iClip == SHOTGUN_MAX_CLIP) return; // don't reload until recoil is done if (m_flNextPrimaryAttack > UTIL_WeaponTimeBase()) return; // check to see if we're ready to reload if (m_fInSpecialReload == 0) { SendWeaponAnim( SHOTGUN_START_RELOAD ); m_fInSpecialReload = 1; m_pPlayer->m_flNextAttack = UTIL_WeaponTimeBase() + 0.6; m_flTimeWeaponIdle = UTIL_WeaponTimeBase() + 0.6; m_flNextPrimaryAttack = GetNextAttackDelay(1.0); m_flNextSecondaryAttack = UTIL_WeaponTimeBase() + 1.0; return; } else if (m_fInSpecialReload == 1) { if (m_flTimeWeaponIdle > UTIL_WeaponTimeBase()) return; // was waiting for gun to move to side m_fInSpecialReload = 2; if (RANDOM_LONG(0,1)) EMIT_SOUND_DYN(ENT(m_pPlayer->pev), CHAN_ITEM, "weapons/reload1.wav", 1, ATTN_NORM, 0, 85 + RANDOM_LONG(0,0x1f)); else EMIT_SOUND_DYN(ENT(m_pPlayer->pev), CHAN_ITEM, "weapons/reload3.wav", 1, ATTN_NORM, 0, 85 + RANDOM_LONG(0,0x1f)); SendWeaponAnim( SHOTGUN_RELOAD ); m_flNextReload = UTIL_WeaponTimeBase() + 0.5; m_flTimeWeaponIdle = UTIL_WeaponTimeBase() + 0.5; } else { // Add them to the clip m_iClip += 1; m_pPlayer->m_rgAmmo[m_iPrimaryAmmoType] -= 1; m_fInSpecialReload = 1; } } void CShotgun::WeaponIdle() { ResetEmptySound( ); m_pPlayer->GetAutoaimVector( AUTOAIM_5DEGREES ); //Moved to ItemPostFrame /* if ( m_flPumpTime && m_flPumpTime < gpGlobals->time ) { // play pumping sound EMIT_SOUND_DYN(ENT(m_pPlayer->pev), CHAN_ITEM, "weapons/scock1.wav", 1, ATTN_NORM, 0, 95 + RANDOM_LONG(0,0x1f)); m_flPumpTime = 0; } */ if (m_flTimeWeaponIdle < UTIL_WeaponTimeBase() ) { if (m_iClip == 0 && m_fInSpecialReload == 0 && m_pPlayer->m_rgAmmo[m_iPrimaryAmmoType]) { Reload( ); } else if (m_fInSpecialReload != 0) { if (m_iClip != 8 && m_pPlayer->m_rgAmmo[m_iPrimaryAmmoType]) { Reload( ); } else { // reload debounce has timed out SendWeaponAnim( SHOTGUN_PUMP ); // play cocking sound EMIT_SOUND_DYN(ENT(m_pPlayer->pev), CHAN_ITEM, "weapons/scock1.wav", 1, ATTN_NORM, 0, 95 + RANDOM_LONG(0,0x1f)); m_fInSpecialReload = 0; m_flTimeWeaponIdle = UTIL_WeaponTimeBase() + 1.5; } } else { int iAnim; float flRand = UTIL_SharedRandomFloat( m_pPlayer->random_seed, 0, 1 ); if (flRand <= 0.8) { iAnim = SHOTGUN_IDLE_DEEP; m_flTimeWeaponIdle = UTIL_WeaponTimeBase() + (60.0/12.0);// * RANDOM_LONG(2, 5); } else if (flRand <= 0.95) { iAnim = SHOTGUN_IDLE; m_flTimeWeaponIdle = UTIL_WeaponTimeBase() + (20.0/9.0); } else { iAnim = SHOTGUN_IDLE4; m_flTimeWeaponIdle = UTIL_WeaponTimeBase() + (20.0/9.0); } SendWeaponAnim( iAnim ); } } } void CShotgun::ItemPostFrame() { if (m_flPumpTime && m_flPumpTime < gpGlobals->time) { // play pumping sound EMIT_SOUND_DYN(ENT(m_pPlayer->pev), CHAN_ITEM, "weapons/scock1.wav", 1, ATTN_NORM, 0, 95 + RANDOM_LONG(0, 0x1f)); m_flPumpTime = 0; } CBasePlayerWeapon::ItemPostFrame(); } class CShotgunAmmo : public CBasePlayerAmmo { void Spawn() override { Precache( ); SET_MODEL(ENT(pev), "models/w_shotbox.mdl"); CBasePlayerAmmo::Spawn( ); } void Precache() override { PRECACHE_MODEL ("models/w_shotbox.mdl"); PRECACHE_SOUND("items/9mmclip1.wav"); } BOOL AddAmmo( CBaseEntity *pOther ) override { if (pOther->GiveAmmo( AMMO_BUCKSHOTBOX_GIVE, "buckshot", BUCKSHOT_MAX_CARRY ) != -1) { EMIT_SOUND(ENT(pev), CHAN_ITEM, "items/9mmclip1.wav", 1, ATTN_NORM); return TRUE; } return FALSE; } }; LINK_ENTITY_TO_CLASS( ammo_buckshot, CShotgunAmmo );
// Copyright Carl Philipp Reh 2009 - 2021. // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) #ifndef FCPPT_CATCH_RECORD_HPP_INCLUDED #define FCPPT_CATCH_RECORD_HPP_INCLUDED #include <fcppt/tag.hpp> #include <fcppt/algorithm/fold.hpp> #include <fcppt/catch/convert.hpp> #include <fcppt/record/element.hpp> #include <fcppt/record/element_vector.hpp> #include <fcppt/record/get.hpp> #include <fcppt/record/label_name.hpp> #include <fcppt/record/object_fwd.hpp> #include <fcppt/config/external_begin.hpp> #include <catch2/catch.hpp> #include <string> #include <utility> #include <fcppt/config/external_end.hpp> namespace Catch { /** \brief Output specialization for #fcppt::record::object. \ingroup fcpptcatch */ template <typename... Elements> struct StringMaker<fcppt::record::object<Elements...>> { static std::string convert(fcppt::record::object<Elements...> const &_record) { return '{' + fcppt::algorithm::fold( fcppt::record::element_vector<fcppt::record::object<Elements...>>{}, std::string{}, [&_record]<typename L, typename T>(fcppt::tag<fcppt::record::element<L,T>>, std::string &&_output) { return std::move(_output) + fcppt::record::label_name<L>() + " = " + fcppt::catch_::convert(fcppt::record::get<L>(_record)) + ", "; }) + '}'; } }; } #endif
#include <iostream> #include <async/jump.hpp> #include <helix/memory.hpp> #include <protocols/clock/defs.hpp> #include <protocols/mbus/client.hpp> #include <clock.pb.h> // ---------------------------------------------------------------------------- // RTC handling. // ---------------------------------------------------------------------------- // Pair of (reference clock, rtc time). using RtcTime = std::pair<int64_t, int64_t>; helix::UniqueLane rtcLane; async::jump foundRtc; async::result<void> enumerateRtc() { auto root = co_await mbus::Instance::global().getRoot(); auto filter = mbus::Conjunction({ mbus::EqualsFilter("class", "rtc") }); auto handler = mbus::ObserverHandler{} .withAttach([] (mbus::Entity entity, mbus::Properties properties) -> async::detached { std::cout << "drivers/clocktracker: Found RTC" << std::endl; rtcLane = helix::UniqueLane(co_await entity.bind()); foundRtc.trigger(); }); co_await root.linkObserver(std::move(filter), std::move(handler)); co_await foundRtc.async_wait(); } async::result<RtcTime> getRtcTime() { managarm::clock::CntRequest req; req.set_req_type(managarm::clock::CntReqType::RTC_GET_TIME); auto ser = req.SerializeAsString(); auto [offer, send_req, recv_resp] = co_await helix_ng::exchangeMsgs( rtcLane, helix_ng::offer( helix_ng::sendBuffer(ser.data(), ser.size()), helix_ng::recvInline()) ); HEL_CHECK(offer.error()); HEL_CHECK(send_req.error()); HEL_CHECK(recv_resp.error()); managarm::clock::SvrResponse resp; resp.ParseFromArray(recv_resp.data(), recv_resp.length()); assert(resp.error() == managarm::clock::Error::SUCCESS); co_return RtcTime{resp.ref_nanos(), resp.time_nanos()}; } // ---------------------------------------------------------------------------- // Tracker page handling. // ---------------------------------------------------------------------------- helix::UniqueDescriptor trackerPageMemory; helix::Mapping trackerPageMapping; TrackerPage *accessPage() { return reinterpret_cast<TrackerPage *>(trackerPageMapping.get()); } // ---------------------------------------------------------------------------- // clocktracker mbus interface. // ---------------------------------------------------------------------------- async::detached serve(helix::UniqueLane lane) { while(true) { auto [accept, recv_req] = co_await helix_ng::exchangeMsgs( lane, helix_ng::accept( helix_ng::recvInline()) ); HEL_CHECK(accept.error()); HEL_CHECK(recv_req.error()); auto conversation = accept.descriptor(); managarm::clock::CntRequest req; req.ParseFromArray(recv_req.data(), recv_req.length()); if(req.req_type() == managarm::clock::CntReqType::ACCESS_PAGE) { managarm::clock::SvrResponse resp; resp.set_error(managarm::clock::Error::SUCCESS); auto ser = resp.SerializeAsString(); auto [send_resp, send_memory] = co_await helix_ng::exchangeMsgs( conversation, helix_ng::sendBuffer(ser.data(), ser.size()), helix_ng::pushDescriptor(trackerPageMemory) ); HEL_CHECK(send_resp.error()); HEL_CHECK(send_memory.error()); }else{ throw std::runtime_error("Unexpected request type"); } } } // ---------------------------------------------------------------- // Freestanding mbus functions. // ---------------------------------------------------------------- async::detached initializeDriver() { // Find an RTC on the mbus. // TODO #ifndef __aarch64__ co_await enumerateRtc(); #endif // Allocate and map our tracker page. size_t page_size = 4096; HelHandle handle; HEL_CHECK(helAllocateMemory(page_size, 0, nullptr, &handle)); trackerPageMemory = helix::UniqueDescriptor{handle}; trackerPageMapping = helix::Mapping{trackerPageMemory, 0, page_size}; // Initialize the tracker page. auto page = accessPage(); memset(page, 0, page_size); // Read the RTC to initialize the realtime clock. // TODO #ifdef __aarch64__ auto result = RtcTime{0, 0}; #else auto result = co_await getRtcTime(); // TODO: Use the seqlock. #endif std::cout << "drivers/clocktracker: Initializing time to " << std::get<1>(result) << std::endl; accessPage()->refClock = std::get<0>(result); accessPage()->baseRealtime = std::get<1>(result); // Create an mbus object for the device. auto root = co_await mbus::Instance::global().getRoot(); mbus::Properties descriptor{ {"class", mbus::StringItem{"clocktracker"}}, }; auto handler = mbus::ObjectHandler{} .withBind([=] () -> async::result<helix::UniqueDescriptor> { helix::UniqueLane local_lane, remote_lane; std::tie(local_lane, remote_lane) = helix::createStream(); serve(std::move(local_lane)); async::promise<helix::UniqueDescriptor> promise; promise.set_value(std::move(remote_lane)); return promise.async_get(); }); co_await root.createObject("clocktracker", descriptor, std::move(handler)); } int main() { std::cout << "drivers/clocktracker: Starting driver" << std::endl; { async::queue_scope scope{helix::globalQueue()}; initializeDriver(); } async::run_forever(helix::globalQueue()->run_token(), helix::currentDispatcher); return 0; }
/* * This software is distributed under BSD 3-clause license (see LICENSE file). * * Authors: Soeren Sonnenburg, Heiko Strathmann, Sergey Lisitsyn, * Leon Kuchenbecker */ #include <shogun/classifier/svm/LibSVMOneClass.h> #include <shogun/io/SGIO.h> using namespace shogun; CLibSVMOneClass::CLibSVMOneClass() : CSVM() { } CLibSVMOneClass::CLibSVMOneClass(float64_t C, CKernel* k) : CSVM(C, k, NULL) { } CLibSVMOneClass::~CLibSVMOneClass() { } bool CLibSVMOneClass::train_machine(CFeatures* data) { svm_problem problem; svm_parameter param; struct svm_model* model = nullptr; ASSERT(kernel) if (data) kernel->init(data, data); problem.l=kernel->get_num_vec_lhs(); struct svm_node* x_space; SG_INFO("%d train data points\n", problem.l) problem.y=NULL; problem.x=SG_MALLOC(struct svm_node*, problem.l); x_space=SG_MALLOC(struct svm_node, 2*problem.l); for (int32_t i=0; i<problem.l; i++) { problem.x[i]=&x_space[2*i]; x_space[2*i].index=i; x_space[2*i+1].index=-1; } int32_t weights_label[2]={-1,+1}; float64_t weights[2]={1.0,get_C2()/get_C1()}; param.svm_type=ONE_CLASS; // C SVM param.kernel_type = LINEAR; param.degree = 3; param.gamma = 0; // 1/k param.coef0 = 0; param.nu = get_nu(); param.kernel=kernel; param.cache_size = kernel->get_cache_size(); param.max_train_time = m_max_train_time; param.C = get_C1(); param.eps = epsilon; param.p = 0.1; param.shrinking = 1; param.nr_weight = 2; param.weight_label = weights_label; param.weight = weights; param.use_bias = get_bias_enabled(); const char* error_msg = svm_check_parameter(&problem,&param); if(error_msg) SG_ERROR("Error: %s\n",error_msg) model = svm_train(&problem, &param); if (model) { ASSERT(model->nr_class==2) ASSERT((model->l==0) || (model->l>0 && model->SV && model->sv_coef && model->sv_coef[0])) int32_t num_sv=model->l; create_new_model(num_sv); CSVM::set_objective(model->objective); set_bias(-model->rho[0]); for (int32_t i=0; i<num_sv; i++) { set_support_vector(i, (model->SV[i])->index); set_alpha(i, model->sv_coef[0][i]); } SG_FREE(problem.x); SG_FREE(x_space); svm_destroy_model(model); model=NULL; return true; } else return false; }
// file : mod/database.hxx -*- C++ -*- // license : MIT; see accompanying LICENSE file #ifndef MOD_DATABASE_HXX #define MOD_DATABASE_HXX #include <odb/forward.hxx> // database #include <libbrep/types.hxx> #include <libbrep/utility.hxx> namespace brep { // Return pointer to the shared database instance, creating one on the first // call. Throw odb::exception on failure. Is not thread-safe. // shared_ptr<odb::core::database> shared_database (string user, string role, string password, string name, string host, uint16_t port, size_t max_connections); } #endif // MOD_DATABASE_HXX
/** * @file * @copyright defined in pose/LICENSE */ #include <pose/chain/pose_contract.hpp> #include <pose/chain/contract_table_objects.hpp> #include <pose/chain/controller.hpp> #include <pose/chain/transaction_context.hpp> #include <pose/chain/apply_context.hpp> #include <pose/chain/transaction.hpp> #include <pose/chain/exceptions.hpp> #include <pose/chain/account_object.hpp> #include <pose/chain/permission_object.hpp> #include <pose/chain/permission_link_object.hpp> #include <pose/chain/global_property_object.hpp> #include <pose/chain/contract_types.hpp> #include <pose/chain/producer_object.hpp> #include <pose/chain/wasm_interface.hpp> #include <pose/chain/abi_serializer.hpp> #include <pose/chain/authorization_manager.hpp> #include <pose/chain/resource_limits.hpp> namespace eosio { namespace chain { uint128_t transaction_id_to_sender_id( const transaction_id_type& tid ) { fc::uint128_t _id(tid._hash[3], tid._hash[2]); return (unsigned __int128)_id; } void validate_authority_precondition( const apply_context& context, const authority& auth ) { for(const auto& a : auth.accounts) { auto* acct = context.db.find<account_object, by_name>(a.permission.actor); EOS_ASSERT( acct != nullptr, action_validate_exception, "account '${account}' does not exist", ("account", a.permission.actor) ); if( a.permission.permission == config::owner_name || a.permission.permission == config::active_name ) continue; // account was already checked to exist, so its owner and active permissions should exist if( a.permission.permission == config::eosio_code_name ) // virtual eosio.code permission does not really exist but is allowed continue; try { context.control.get_authorization_manager().get_permission({a.permission.actor, a.permission.permission}); } catch( const permission_query_exception& ) { EOS_THROW( action_validate_exception, "permission '${perm}' does not exist", ("perm", a.permission) ); } } if( context.trx_context.enforce_whiteblacklist && context.control.is_producing_block() ) { for( const auto& p : auth.keys ) { context.control.check_key_list( p.key ); } } } /** * This method is called assuming precondition_system_newaccount succeeds a */ void apply_pose_newaccount(apply_context& context) { auto create = context.act.data_as<newaccount>(); try { context.require_authorization(create.creator); // context.require_write_lock( config::eosio_auth_scope ); auto& authorization = context.control.get_mutable_authorization_manager(); EOS_ASSERT( validate(create.owner), action_validate_exception, "Invalid owner authority"); EOS_ASSERT( validate(create.active), action_validate_exception, "Invalid active authority"); auto& db = context.db; auto name_str = name(create.name).to_string(); EOS_ASSERT( !create.name.empty(), action_validate_exception, "account name cannot be empty" ); EOS_ASSERT( name_str.size() <= 12, action_validate_exception, "account names can only be 12 chars long" ); // Check if the creator is privileged const auto &creator = db.get<account_object, by_name>(create.creator); if( !creator.privileged ) { EOS_ASSERT( name_str.find( "pose." ) != 0, action_validate_exception, "only privileged accounts can have names that start with 'pose.'" ); } auto existing_account = db.find<account_object, by_name>(create.name); EOS_ASSERT(existing_account == nullptr, account_name_exists_exception, "Cannot create account named ${name}, as that name is already taken", ("name", create.name)); const auto& new_account = db.create<account_object>([&](auto& a) { a.name = create.name; a.creation_date = context.control.pending_block_time(); }); db.create<account_sequence_object>([&](auto& a) { a.name = create.name; }); for( const auto& auth : { create.owner, create.active } ){ validate_authority_precondition( context, auth ); } const auto& owner_permission = authorization.create_permission( create.name, config::owner_name, 0, std::move(create.owner) ); const auto& active_permission = authorization.create_permission( create.name, config::active_name, owner_permission.id, std::move(create.active) ); context.control.get_mutable_resource_limits_manager().initialize_account(create.name); int64_t ram_delta = config::overhead_per_account_ram_bytes; ram_delta += 2*config::billable_size_v<permission_object>; ram_delta += owner_permission.auth.get_billable_size(); ram_delta += active_permission.auth.get_billable_size(); context.add_ram_usage(create.name, ram_delta); } FC_CAPTURE_AND_RETHROW( (create) ) } void apply_pose_setcode(apply_context& context) { const auto& cfg = context.control.get_global_properties().configuration; auto& db = context.db; auto act = context.act.data_as<setcode>(); context.require_authorization(act.account); EOS_ASSERT( act.vmtype == 0, invalid_contract_vm_type, "code should be 0" ); EOS_ASSERT( act.vmversion == 0, invalid_contract_vm_version, "version should be 0" ); fc::sha256 code_id; /// default ID == 0 if( act.code.size() > 0 ) { code_id = fc::sha256::hash( act.code.data(), (uint32_t)act.code.size() ); wasm_interface::validate(context.control, act.code); } const auto& account = db.get<account_object,by_name>(act.account); int64_t code_size = (int64_t)act.code.size(); int64_t old_size = (int64_t)account.code.size() * config::setcode_ram_bytes_multiplier; int64_t new_size = code_size * config::setcode_ram_bytes_multiplier; EOS_ASSERT( account.code_version != code_id, set_exact_code, "contract is already running this version of code" ); db.modify( account, [&]( auto& a ) { /** TODO: consider whether a microsecond level local timestamp is sufficient to detect code version changes*/ // TODO: update setcode message to include the hash, then validate it in validate a.last_code_update = context.control.pending_block_time(); a.code_version = code_id; if ( code_size > 0 ) { a.code.assign(act.code.data(), code_size); } else { a.code.resize(0); } }); const auto& account_sequence = db.get<account_sequence_object, by_name>(act.account); db.modify( account_sequence, [&]( auto& aso ) { aso.code_sequence += 1; }); if (new_size != old_size) { context.add_ram_usage( act.account, new_size - old_size ); } } void apply_pose_setabi(apply_context& context) { auto& db = context.db; auto act = context.act.data_as<setabi>(); context.require_authorization(act.account); const auto& account = db.get<account_object,by_name>(act.account); int64_t abi_size = act.abi.size(); int64_t old_size = (int64_t)account.abi.size(); int64_t new_size = abi_size; db.modify( account, [&]( auto& a ) { if (abi_size > 0) { a.abi.assign(act.abi.data(), abi_size); } else { a.abi.resize(0); } }); const auto& account_sequence = db.get<account_sequence_object, by_name>(act.account); db.modify( account_sequence, [&]( auto& aso ) { aso.abi_sequence += 1; }); if (new_size != old_size) { context.add_ram_usage( act.account, new_size - old_size ); } } void apply_pose_updateauth(apply_context& context) { auto update = context.act.data_as<updateauth>(); context.require_authorization(update.account); // only here to mark the single authority on this action as used auto& authorization = context.control.get_mutable_authorization_manager(); auto& db = context.db; EOS_ASSERT(!update.permission.empty(), action_validate_exception, "Cannot create authority with empty name"); EOS_ASSERT( update.permission.to_string().find( "pose." ) != 0, action_validate_exception, "Permission names that start with 'pose.' are reserved" ); EOS_ASSERT(update.permission != update.parent, action_validate_exception, "Cannot set an authority as its own parent"); db.get<account_object, by_name>(update.account); EOS_ASSERT(validate(update.auth), action_validate_exception, "Invalid authority: ${auth}", ("auth", update.auth)); if( update.permission == config::active_name ) EOS_ASSERT(update.parent == config::owner_name, action_validate_exception, "Cannot change active authority's parent from owner", ("update.parent", update.parent) ); if (update.permission == config::owner_name) EOS_ASSERT(update.parent.empty(), action_validate_exception, "Cannot change owner authority's parent"); else EOS_ASSERT(!update.parent.empty(), action_validate_exception, "Only owner permission can have empty parent" ); if( update.auth.waits.size() > 0 ) { auto max_delay = context.control.get_global_properties().configuration.max_transaction_delay; EOS_ASSERT( update.auth.waits.back().wait_sec <= max_delay, action_validate_exception, "Cannot set delay longer than max_transacton_delay, which is ${max_delay} seconds", ("max_delay", max_delay) ); } validate_authority_precondition(context, update.auth); auto permission = authorization.find_permission({update.account, update.permission}); // If a parent_id of 0 is going to be used to indicate the absence of a parent, then we need to make sure that the chain // initializes permission_index with a dummy object that reserves the id of 0. authorization_manager::permission_id_type parent_id = 0; if( update.permission != config::owner_name ) { auto& parent = authorization.get_permission({update.account, update.parent}); parent_id = parent.id; } if( permission ) { EOS_ASSERT(parent_id == permission->parent, action_validate_exception, "Changing parent authority is not currently supported"); int64_t old_size = (int64_t)(config::billable_size_v<permission_object> + permission->auth.get_billable_size()); authorization.modify_permission( *permission, update.auth ); int64_t new_size = (int64_t)(config::billable_size_v<permission_object> + permission->auth.get_billable_size()); context.add_ram_usage( permission->owner, new_size - old_size ); } else { const auto& p = authorization.create_permission( update.account, update.permission, parent_id, update.auth ); int64_t new_size = (int64_t)(config::billable_size_v<permission_object> + p.auth.get_billable_size()); context.add_ram_usage( update.account, new_size ); } } void apply_pose_deleteauth(apply_context& context) { // context.require_write_lock( config::eosio_auth_scope ); auto remove = context.act.data_as<deleteauth>(); context.require_authorization(remove.account); // only here to mark the single authority on this action as used EOS_ASSERT(remove.permission != config::active_name, action_validate_exception, "Cannot delete active authority"); EOS_ASSERT(remove.permission != config::owner_name, action_validate_exception, "Cannot delete owner authority"); auto& authorization = context.control.get_mutable_authorization_manager(); auto& db = context.db; { // Check for links to this permission const auto& index = db.get_index<permission_link_index, by_permission_name>(); auto range = index.equal_range(boost::make_tuple(remove.account, remove.permission)); EOS_ASSERT(range.first == range.second, action_validate_exception, "Cannot delete a linked authority. Unlink the authority first. This authority is linked to ${code}::${type}.", ("code", string(range.first->code))("type", string(range.first->message_type))); } const auto& permission = authorization.get_permission({remove.account, remove.permission}); int64_t old_size = config::billable_size_v<permission_object> + permission.auth.get_billable_size(); authorization.remove_permission( permission ); context.add_ram_usage( remove.account, -old_size ); } void apply_pose_linkauth(apply_context& context) { // context.require_write_lock( config::eosio_auth_scope ); auto requirement = context.act.data_as<linkauth>(); try { EOS_ASSERT(!requirement.requirement.empty(), action_validate_exception, "Required permission cannot be empty"); context.require_authorization(requirement.account); // only here to mark the single authority on this action as used auto& db = context.db; const auto *account = db.find<account_object, by_name>(requirement.account); EOS_ASSERT(account != nullptr, account_query_exception, "Failed to retrieve account: ${account}", ("account", requirement.account)); // Redundant? const auto *code = db.find<account_object, by_name>(requirement.code); EOS_ASSERT(code != nullptr, account_query_exception, "Failed to retrieve code for account: ${account}", ("account", requirement.code)); if( requirement.requirement != config::eosio_any_name ) { const auto *permission = db.find<permission_object, by_name>(requirement.requirement); EOS_ASSERT(permission != nullptr, permission_query_exception, "Failed to retrieve permission: ${permission}", ("permission", requirement.requirement)); } auto link_key = boost::make_tuple(requirement.account, requirement.code, requirement.type); auto link = db.find<permission_link_object, by_action_name>(link_key); if( link ) { EOS_ASSERT(link->required_permission != requirement.requirement, action_validate_exception, "Attempting to update required authority, but new requirement is same as old"); db.modify(*link, [requirement = requirement.requirement](permission_link_object& link) { link.required_permission = requirement; }); } else { const auto& l = db.create<permission_link_object>([&requirement](permission_link_object& link) { link.account = requirement.account; link.code = requirement.code; link.message_type = requirement.type; link.required_permission = requirement.requirement; }); context.add_ram_usage( l.account, (int64_t)(config::billable_size_v<permission_link_object>) ); } } FC_CAPTURE_AND_RETHROW((requirement)) } void apply_pose_unlinkauth(apply_context& context) { // context.require_write_lock( config::eosio_auth_scope ); auto& db = context.db; auto unlink = context.act.data_as<unlinkauth>(); context.require_authorization(unlink.account); // only here to mark the single authority on this action as used auto link_key = boost::make_tuple(unlink.account, unlink.code, unlink.type); auto link = db.find<permission_link_object, by_action_name>(link_key); EOS_ASSERT(link != nullptr, action_validate_exception, "Attempting to unlink authority, but no link found"); context.add_ram_usage( link->account, -(int64_t)(config::billable_size_v<permission_link_object>) ); db.remove(*link); } void apply_pose_canceldelay(apply_context& context) { auto cancel = context.act.data_as<canceldelay>(); context.require_authorization(cancel.canceling_auth.actor); // only here to mark the single authority on this action as used const auto& trx_id = cancel.trx_id; context.cancel_deferred_transaction(transaction_id_to_sender_id(trx_id), account_name()); } } } // namespace eosio::chain
#include <iostream> using namespace std; int gcd(int a, int b) { if(b==0) return a; return gcd(b,a%b); } int gcd_iterative(int a, int b) { while(a!=0) { int rem = b%a; b = a; a = rem; } return b; } int main() { int a,b; cin>>a>>b; cout<<gcd(a,b)<<endl; cout<<gcd_iterative(a,b)<<endl; return 0; } //lcm of two numbers = a*b/GCD(a,b);
#include <torch/csrc/jit/passes/remove_inplace_ops.h> namespace torch { namespace jit { namespace { static const std::unordered_map<NodeKind, NodeKind> inPlaceToOutOfPlace = { {aten::add_, aten::add}, {aten::sub_, aten::sub}, {aten::div_, aten::div}, {aten::mul_, aten::mul}}; bool isInplaceOp(const Node* node) { return inPlaceToOutOfPlace.count(node->kind()) != 0; } // Remove all in-place ops and replace them with out-of-place equivalents. // e.g. // %foo = aten::add_(%foo, %n) // becomes // %foo.2 = aten::add(%foo, %n) // // NOTE: this is NOT SAFE, since it assumes that the LHS is not aliased by // another value. This is only to avoid breaking ONNX export; when alias // analysis is done we can emit a warning if someone tries to export. void RemoveInplaceOps(Block* block) { auto graph = block->owningGraph(); auto it = block->nodes().begin(); while (it != block->nodes().end()) { auto node = *it; ++it; for (auto block : node->blocks()) { RemoveInplaceOps(block); } if (isInplaceOp(node)) { // create a replacement out of place op auto newNode = graph->create(inPlaceToOutOfPlace.at(node->kind())); newNode->insertBefore(node); newNode->setScope(node->scope()); // copy inputs for (auto input : node->inputs()) { newNode->addInput(input); } // Create a new output node and replace all uses of self with it newNode->output()->copyMetadata(node->output()); node->replaceAllUsesWith(newNode); node->destroy(); } } } } // namespace void RemoveInplaceOps(const std::shared_ptr<Graph>& graph) { RemoveInplaceOps(graph->block()); } } // namespace jit } // namespace torch
#include "RFM95.h" #if !defined(RADIOLIB_EXCLUDE_RFM9X) RFM95::RFM95(Module* mod) : SX1278(mod) { } int16_t RFM95::begin(float freq, float bw, uint8_t sf, uint8_t cr, uint8_t syncWord, int8_t power, uint16_t preambleLength, uint8_t gain) { // execute common part int16_t state = SX127x::begin(RFM9X_CHIP_VERSION_OFFICIAL, syncWord, preambleLength); if(state == ERR_CHIP_NOT_FOUND) { // SX127X_REG_VERSION might be set 0x12 state = SX127x::begin(RFM9X_CHIP_VERSION_UNOFFICIAL, syncWord, preambleLength); RADIOLIB_ASSERT(state); } else if(state != ERR_NONE) { // some other error return(state); } RADIOLIB_DEBUG_PRINTLN(F("M\tSX1278")); RADIOLIB_DEBUG_PRINTLN(F("M\tRFM95")); // configure publicly accessible settings state = setFrequency(freq); RADIOLIB_ASSERT(state); state = setBandwidth(bw); RADIOLIB_ASSERT(state); state = setSpreadingFactor(sf); RADIOLIB_ASSERT(state); state = setCodingRate(cr); RADIOLIB_ASSERT(state); state = setOutputPower(power); RADIOLIB_ASSERT(state); state = setGain(gain); return(state); } int16_t RFM95::setFrequency(float freq) { RADIOLIB_CHECK_RANGE(freq, 862.0, 1020.0, ERR_INVALID_FREQUENCY); // set frequency return(SX127x::setFrequencyRaw(freq)); } #endif
/* * 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. * * Copyright (c) 2016 Edward Yang * All rights reserved. * */ #include "DS3231.h" uint8_t bcd(uint8_t val) { return( (val/10*16) + (val%10) ); } uint8_t dec(uint8_t val){ return( (val/16*10) + (val%16) ); } void get(ts *t) { Wire.beginTransmission(DS3231_I2C); Wire.write(0); Wire.endTransmission(); Wire.requestFrom(DS3231_I2C, 7); t->sec = dec(Wire.read() & 0x7f); t->min = dec(Wire.read()); t->hour = dec(Wire.read()); t->dayOfWeek = dec(Wire.read()); t->day = dec(Wire.read()); t->month = dec(Wire.read()); t->year = dec(Wire.read()); } void set(ts t) { Wire.beginTransmission(DS3231_I2C); Wire.write(0); Wire.write(bcd(t.sec)); Wire.write(bcd(t.min)); Wire.write(bcd(t.hour)); Wire.write(bcd(t.dayOfWeek)); Wire.write(bcd(t.day)); Wire.write(bcd(t.month)); Wire.write(bcd(t.year)); Wire.endTransmission(); }
/* File: CACFNumber.cpp Abstract: Part of CoreAudio Utility Classes Version: 1.0.1 Disclaimer: IMPORTANT: This Apple software is supplied to you by Apple Inc. ("Apple") in consideration of your agreement to the following terms, and your use, installation, modification or redistribution of this Apple software constitutes acceptance of these terms. If you do not agree with these terms, please do not use, install, modify or redistribute this Apple software. In consideration of your agreement to abide by the following terms, and subject to these terms, Apple grants you a personal, non-exclusive license, under Apple's copyrights in this original Apple software (the "Apple Software"), to use, reproduce, modify and redistribute the Apple Software, with or without modifications, in source and/or binary forms; provided that if you redistribute the Apple Software in its entirety and without modifications, you must retain this notice and the following text and disclaimers in all such redistributions of the Apple Software. Neither the name, trademarks, service marks or logos of Apple Inc. may be used to endorse or promote products derived from the Apple Software without specific prior written permission from Apple. Except as expressly stated in this notice, no other rights or licenses, express or implied, are granted by Apple herein, including but not limited to any patent rights that may be infringed by your derivative works or by other works in which the Apple Software may be incorporated. The Apple Software is provided by Apple on an "AS IS" basis. APPLE MAKES NO WARRANTIES, EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION THE IMPLIED WARRANTIES OF NON-INFRINGEMENT, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, REGARDING THE APPLE SOFTWARE OR ITS USE AND OPERATION ALONE OR IN COMBINATION WITH YOUR PRODUCTS. IN NO EVENT SHALL APPLE BE LIABLE FOR ANY SPECIAL, INDIRECT, INCIDENTAL OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) ARISING IN ANY WAY OUT OF THE USE, REPRODUCTION, MODIFICATION AND/OR DISTRIBUTION OF THE APPLE SOFTWARE, HOWEVER CAUSED AND WHETHER UNDER THEORY OF CONTRACT, TORT (INCLUDING NEGLIGENCE), STRICT LIABILITY OR OTHERWISE, EVEN IF APPLE HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. Copyright (C) 2013 Apple Inc. All Rights Reserved. */ //============================================================================= // Includes //============================================================================= #include "CACFNumber.h" //============================================================================= // CACFNumber //============================================================================= Float32 CACFNumber::GetFixed32() const { SInt32 theFixedValue = GetSInt32(); // this is a 16.16 value so convert it to a float Float32 theSign = theFixedValue < 0 ? -1.0f : 1.0f; theFixedValue *= (SInt32)theSign; Float32 theWholePart = (theFixedValue & 0x7FFF0000) >> 16; Float32 theFractPart = theFixedValue & 0x0000FFFF; theFractPart /= 65536.0f; return theSign * (theWholePart + theFractPart); } Float64 CACFNumber::GetFixed64() const { SInt64 theFixedValue = GetSInt64(); // this is a 32.32 value so convert it to a double Float64 theSign = theFixedValue < 0 ? -1.0 : 1.0; theFixedValue *= (SInt64)theSign; Float64 theWholePart = (theFixedValue & 0x7FFFFFFF00000000LL) >> 32; Float64 theFractPart = theFixedValue & 0x00000000FFFFFFFFLL; theFractPart /= 4294967296.0; return theSign * (theWholePart + theFractPart); }
#include <iostream> #define PRINT_PREFIX() \ { \ std::cout << std::endl << "[" << (__LINE__ + 1) << "]" \ << std::endl << "\t"; \ } class Widget { public: Widget(int i, bool b) { std::cout << "Widget(int, bool)" << " " << __LINE__ << std::endl; } Widget(int i, double d) { std::cout << "Widget(int, double)" << " " << __LINE__ << std::endl; } Widget(std::initializer_list<long double> initializer_list) { std::cout << "Widget(std::initializer_list<long double>)" << " " << __LINE__ << std::endl; } // a stub operator operator float() const { return 5; } }; int main() { // calls the 1-st constructor PRINT_PREFIX(); Widget w1(10, true); // calls the "std::initializer_list" constructor // (10 and true convert to long double) PRINT_PREFIX(); Widget w2 { 10, true }; // ditto PRINT_PREFIX(); Widget w2_2 = { 10, true }; // calls the 2-nd constructor PRINT_PREFIX(); Widget w3(10, 5.0); // calls the "std::initializer_list" constructor // (10 and 5.0 convert to long double) PRINT_PREFIX(); Widget w4 { 10, 5.0 }; // ditto PRINT_PREFIX(); Widget w4_2 = { 10, 5.0 }; // calls the copy constructor PRINT_PREFIX(); Widget w5(w4); // calls the "std::initialzier_list" constructor // (w4 converts to float and float converts to long double) PRINT_PREFIX(); Widget w6{ w4 }; // calls the move constructor PRINT_PREFIX(); Widget w7(std::move(w4)); // calls the "std::initializer_list" constructor // (for the same reason as w6) PRINT_PREFIX(); Widget w8{ std::move(w4) }; }
#include "ofApp.h" #define TIMESERIES_LENGTH 200 #define NUM_DIMENSIONS 2 float lastX = 0; float lastY = 0; float lastTic = 0; //-------------------------------------------------------------- void ofApp::setup(){ ofSetBackgroundColor(255); //Load the font for the graph font.load("verdana.ttf", 12, true, true); font.setLineHeight(14.0f); //Setup the first plot plot1.setup( TIMESERIES_LENGTH, NUM_DIMENSIONS, "Mouse Data" ); plot1.setDrawGrid( true ); plot1.setDrawInfoText( true ); plot1.setFont( font ); //Setup the second plot plot2.setup( TIMESERIES_LENGTH, NUM_DIMENSIONS, "Mouse Derivative" ); plot2.setDrawGrid( true ); plot2.setDrawInfoText( true ); plot2.setFont( font ); } //-------------------------------------------------------------- void ofApp::update(){ //Get the mouse data float mouseX = ofGetMouseX(); float mouseY = ofGetMouseY(); float tic = ofGetElapsedTimeMillis(); float delta = tic-lastTic; vector<float> data(2); //Update the 1st plot data[0] = mouseX; data[1] = mouseY; if (abs(mouseX - lastX) > abs(mouseY - lastY)) plot1.update( data, 1, "Horizontal" ); else if (abs(mouseX - lastX) < abs(mouseY - lastY)) plot1.update( data, 2, "Vertical" ); else plot1.update( data ); //Update the 2nd plot data[0] = lastX > 0 ? (mouseX-lastX) / delta : 0.0; data[1] = lastY > 0 ? (mouseY-lastY) / delta : 0.0; plot2.update( data ); //Store the mouse values for the next update lastX = mouseX; lastY = mouseY; lastTic = tic; } //-------------------------------------------------------------- void ofApp::draw(){ int plotX = 20; int plotY = 20; int plotW = ofGetWidth() - (plotX*2); int plotH = 200; plot1.draw( plotX, plotY, plotW, plotH ); plotY += 25 + plotH; plot2.draw( plotX, plotY, plotW, plotH ); } //-------------------------------------------------------------- void ofApp::keyPressed(int key){ switch( key ){ case 'r': //Reset the data contents and ranges of the plot plot1.reset(); plot2.reset(); break; } } //-------------------------------------------------------------- void ofApp::keyReleased(int key){ } //-------------------------------------------------------------- void ofApp::mouseMoved(int x, int y ){ } //-------------------------------------------------------------- void ofApp::mouseDragged(int x, int y, int button){ } //-------------------------------------------------------------- void ofApp::mousePressed(int x, int y, int button){ } //-------------------------------------------------------------- void ofApp::mouseReleased(int x, int y, int button){ } //-------------------------------------------------------------- void ofApp::mouseEntered(int x, int y){ } //-------------------------------------------------------------- void ofApp::mouseExited(int x, int y){ } //-------------------------------------------------------------- void ofApp::windowResized(int w, int h){ } //-------------------------------------------------------------- void ofApp::gotMessage(ofMessage msg){ } //-------------------------------------------------------------- void ofApp::dragEvent(ofDragInfo dragInfo){ }
/* * 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. */ /** * @author Xiao-Feng Li, 2007/01/24 */ #include "gc_common.h" #include "../utils/vector_block.h" #include "../utils/sync_pool.h" #include "../thread/collector.h" #include "../thread/mutator.h" #include "compressed_ref.h" typedef struct Uncompressed_Root{ Partial_Reveal_Object **p_ref; /* pointing to the uncompressed address of the root object */ REF ref; /* temporal compressed pointer pointing to the root object */ }Compressed_Root; POINTER_SIZE_INT vtable_base = 0; POINTER_SIZE_INT HEAP_BASE = 0; void gc_set_uncompressed_rootset(GC *gc) { Pool *rootset_pool = gc->metadata->gc_uncompressed_rootset_pool; pool_put_entry(rootset_pool, gc->uncompressed_root_set); gc->uncompressed_root_set = NULL; pool_iterator_init(rootset_pool); while(Vector_Block *root_set = pool_iterator_next(rootset_pool)){ POINTER_SIZE_INT *iter = vector_block_iterator_init(root_set); for(; !vector_block_iterator_end(root_set, iter); iter = vector_block_iterator_advance(root_set, iter)){ iter = vector_block_iterator_advance(root_set, iter); assert(!vector_block_iterator_end(root_set, iter)); /* add the pointer to ref of Uncmpressed_Root to rootset */ gc_compressed_rootset_add_entry(gc, (REF *)iter); } } } void gc_fix_uncompressed_rootset(GC *gc) { Pool *rootset_pool = gc->metadata->gc_uncompressed_rootset_pool; pool_iterator_init(rootset_pool); while(Vector_Block *root_set = pool_iterator_next(rootset_pool)){ POINTER_SIZE_INT *iter = vector_block_iterator_init(root_set); for(; !vector_block_iterator_end(root_set, iter); iter = vector_block_iterator_advance(root_set, iter)){ Partial_Reveal_Object **p_ref = (Partial_Reveal_Object **)*iter; iter = vector_block_iterator_advance(root_set, iter); assert(!vector_block_iterator_end(root_set, iter)); Partial_Reveal_Object *p_obj = read_slot((REF*)iter); *p_ref = p_obj; } } }
/*! * \author Vasco Manquinho - vmm@sat.inesc-id.pt * * @section LICENSE * * Open-WBO, Copyright (c) 2013-2022, Ruben Martins, Vasco Manquinho, Ines Lynce * UpMax, Copyright (c) 2022, Pedro Orvalho, Vasco Manquinho, Ruben Martins * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. * */ #include <iostream> #include <float.h> #include <stdio.h> #include <stdlib.h> #include "Graph.h" #include "NodeHeap.h" using namespace upmax; #define INF DBL_MAX // Depth-first search and topological sort void Graph::visitedVertexes(int u, vec<int> &reachedVertexes) { DFSVisit(u, reachedVertexes); for (int i = 0; i < reachedVertexes.size(); i++) { _marks[reachedVertexes[i]] = WHITE; } } void Graph::DFSVisitIter(int u, vec<int> &reachedVertexes) { vec<int> *l = new vec<int>; int n = 0; l->push(u); while (l->size() > 0) { n++; u = l->last(); l->pop(); if (_marks[u] == WHITE) { _marks[u] = BLACK; for (int i = 0; i < _edges[u].size(); i++) { if (_marks[_edges[u][i]] == WHITE) { l->push(_edges[u][i]); } } reachedVertexes.push(u); } } printf("Reached %d vertexes.\n", n); delete l; } void Graph::DFSVisit(int u, vec<int> &reachedVertexes) { if (_marks[u] == WHITE) { _marks[u] = BLACK; for (int i = 0; i < _edges[u].size(); i++) { if (_marks[_edges[u][i]] == WHITE) { DFSVisit(_edges[u][i], reachedVertexes); } } reachedVertexes.push(u); } } void Graph::topologicalSort(vec<int> &vertexes) { for (int i = 0; i < _nVert; i++) { if (_marks[i] == WHITE && _edges[i].size()) { DFSVisit(i, vertexes); } } for (int i = 0; i < vertexes.size(); i++) _marks[vertexes[i]] = WHITE; } int Graph::connectedComponents() { int n = 0; vec<int> vertexes; for (int i = 0; i < _nVert; i++) { if (_marks[i] == WHITE && _edges[i].size()) { n++; DFSVisitIter(i, vertexes); } } return n; } // Strong Connected Components (SCC) // void Graph::findAllScc() { // _time = 1; // _stack.clear(); // clearSCC(); // for(int i = 0; i < _nVert; i++) { // if (_marks[i] == WHITE) { // tarjan(i); // } // } // for(int m = 0; m < _nMarked; m++) { // int i = _markedVertexes[m]; // _marks[i] = WHITE; // _index[i] = _lowlink[i] = 0; // } // _nMarked = 0; // } // void Graph::tarjan(int u) { // _marks[u] = GRAY; // _markedVertexes[_nMarked++] = u; // _index[u] = _time; // _lowlink[u] = _time++; // _stack.push_front(u); // for (list<int>::iterator iter = _edges[u]->begin(); iter != // _edges[u]->end(); iter++) { // int v = *iter; // if (_marks[v] == WHITE) { // tarjan(v); // if (_lowlink[v] < _lowlink[u]) _lowlink[u] = _lowlink[v]; // } // else if (_marks[v] == GRAY) { // if (_lowlink[v] < _lowlink[u]) _lowlink[u] = _lowlink[v]; // } // } // if (_index[u] == _lowlink[u]) { // int v = -1; // list<int>* scc = new list<int>; // do { // v = _stack.front(); // _stack.pop_front(); // scc->push_front(v); // _marks[v] = BLACK; // } while (v != u); // if (scc->size() == 1) { // scc->clear(); // delete scc; // } // else { // _sccs[_nSCC++] = scc; // } // } // } // void Graph::clearSCC() { // for (int i = 0; i < _nSCC; i++) { // _sccs[i]->clear(); // delete _sccs[i]; // } // _nSCC = 0; // } // Single Source Shortest Path (Dijkstra's algorithm) // void Graph::dijkstra(int s, double* d, int* p, list<int>* pred, list<int>* // stack) { // NodeHeap<double>* h = new NodeHeap<double>(_nVert, INF, true); // for (int i = 0; i < _nVert; i++) { // d[i] = INF; // p[i] = 0; // pred[i].clear(); // } // d[s] = 0; // p[s] = 1; // h->changeValue(s, 0); // while (h->size()) { // int u = h->pop(); // list<int>::iterator v; // list<double>::iterator w; // stack->push_front(u); // for (v = _edges[u]->begin(), w = _weights[u]->begin(); v != // _edges[u]->end(); v++, w++) { // if (d[*v] > d[u]+*w+PRECISION) { // d[*v] = d[u]+*w; // h->changeValue(*v, d[*v]); // pred[*v].clear(); // p[*v] = 0; // } // if (d[*v] < d[u]+*w+PRECISION && d[*v] > d[u]+*w-PRECISION) { // pred[*v].push_front(u); // p[*v] += p[u]; // } // } // } // delete h; // }
/** * \file * \brief Factory to create SickLidar2d objects * * Copyright 2019, SICK AG, Waldkirch * * 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 "API/Family/Lidar2d/Common/include/Lidar2d.h" #include "API/Family/Lidar2d/Common/private/TiM5xx_Model_Factory.h" #include "API/Family/Lidar2d/Common/private/TiM5xx_Skeleton_Factory.h" #include "Base/Core/Common/include/Hash.h" #include "Base/Core/OS/include/Task.h" #include "Base/Core/OS/include/Timer.h" #include "Base/Logger/include/Logger.h" #include <string> using namespace std; #ifdef _MSC_VER #pragma warning(disable : 4307) #endif namespace ssbl { Lidar2dStateText StateInfo[] = {{LIDAR2D_STATE_ERROR, "Error"}, {LIDAR2D_STATE_INIT, "Init"}, {LIDAR2D_STATE_IDLE, "Idle"}, {LIDAR2D_STATE_BUSY_IDLE, "BusyIdle"}, {LIDAR2D_STATE_STARTED, "Started"}, {LIDAR2D_STATE_STOPPED, "Stopped"} }; class ReconnectTimer : public Timer, Task { public: //======================================================================== ReconnectTimer(Lidar2d_Model* pParent) : Timer(5000), start_(false), pParent_(pParent){}; //======================================================================== ~ReconnectTimer() { Timer::Stop(); }; //======================================================================== void OnTimer() { trigger_.SignalEvent(); }; //======================================================================== bool TaskLoop(void) { if (EVENT_RECEIVED == trigger_.WaitForEvent(0xFFFFFFFF)) { Lidar2dState tmp = pParent_->StoredState_; SensorResult ret = pParent_->ProcessStateMachine(LIDAR2D_STATE_BUSY_IDLE); pParent_->StoredState_ = tmp; if (start_) { if (SSBL_SUCCESS != ret) { if (pParent_->AutoReconnect_) { SSBL_LOG_INFO("ReconnectTimer: Trying to reconnect in 5 seconds"); Timer::Start(); } } else { pParent_->ProcessStateMachine(pParent_->StoredState_); // Stop(); } } } return true; } //======================================================================== void Start() { start_ = true; Task::Run(); Timer::Start(); }; //======================================================================== void Stop() { start_ = false; Timer::Stop(); Task::Stop(); }; private: bool start_; Lidar2d_Model* pParent_; Event trigger_; }; Lidar2d_Model::Lidar2d_Model(SensorSkeleton* pSkeleton) : pLidar2DSkeleton_(pSkeleton), IsInitialized_(false), AutoReconnect_(true), LidarState_(LIDAR2D_STATE_ERROR), StoredState_(LIDAR2D_STATE_ERROR), StartAngle_(0), StopAngle_(0), CallbackFunc_(nullptr), CallbackParam_(0), ScanProcessorFunc_(nullptr) { pReconnectTimer = new ReconnectTimer(this); } //=========================================================================== //=========================================================================== Lidar2dState Lidar2d_Model::GetLidarState(void) { return LidarState_; } //=========================================================================== //=========================================================================== SensorResult Lidar2d_Model::GetDeviceName(std::string& DeviceName) { SensorResult ret = SSBL_ERR_SENSOR_REQUEST_FAILED; DeviceName = ""; if (pLidar2DSkeleton_ != nullptr) { ret = pLidar2DSkeleton_->GetDeviceName(DeviceName); } return ret; } //=========================================================================== //=========================================================================== void Lidar2d_Model::SetLidarState(Lidar2dState LidarState) { LidarState_ = LidarState; } //=========================================================================== //=========================================================================== void Lidar2d_Model::SetInitialized() { pLidar2DSkeleton_->RegisterToCallbackEvent( "DeviceLost", std::bind(&Lidar2d_Model::HandleDeviceLost, this, 0)); IsInitialized_ = true; }; //=========================================================================== //=========================================================================== SensorResult Lidar2d_Model::ProcessStateMachine(Lidar2dState TargetState) { SensorResult ret = SSBL_SUCCESS; if (TargetState != GetLidarState()) { if (GetLidarState() == LIDAR2D_STATE_ERROR) { SetLidarState(LIDAR2D_STATE_INIT); } while ((GetLidarState() != TargetState) && (GetLidarState() != LIDAR2D_STATE_ERROR)) { ret = MoveToLidarState(TargetState); } } return ret; } //=========================================================================== //=========================================================================== SensorResult Lidar2d_Model::MoveToLidarState(Lidar2dState TargetState) { SensorResult ret = SSBL_SUCCESS; switch (LidarState_) { case LIDAR2D_STATE_INIT: ret = HandleStateInit(TargetState); break; case LIDAR2D_STATE_IDLE: ret = HandleStateIdle(TargetState); break; case LIDAR2D_STATE_BUSY_IDLE: ret = HandleStateBusyIdle(TargetState); break; case LIDAR2D_STATE_STARTED: ret = HandleStateStart(TargetState); break; case LIDAR2D_STATE_STOPPED: ret = HandleStateStop(TargetState); break; default: break; } return ret; } //=========================================================================== //=========================================================================== SensorResult Lidar2d_Model::HandleStateInit(Lidar2dState TargetState) { SensorResult ret = SSBL_ERR_INVALID_STATE; if (TargetState >= LIDAR2D_STATE_IDLE) { if (IsInitialized_) { // Transition Ok ret = SSBL_SUCCESS; SetLidarState(LIDAR2D_STATE_IDLE); } else { ret = HandleStateError(TargetState, ret, "Lidar not initialized"); } } else { ret = HandleStateError(TargetState, ret, "Invalid Lidar state transition"); } return ret; } //=========================================================================== //=========================================================================== SensorResult Lidar2d_Model::HandleStateIdle(Lidar2dState TargetState) { SensorResult ret = SSBL_ERR_INVALID_STATE; if (TargetState >= LIDAR2D_STATE_BUSY_IDLE) { ret = pLidar2DSkeleton_->Connect(); if (ret == SSBL_SUCCESS) { ret = HandleLidarConfigure(); if (ret == SSBL_SUCCESS) { SetLidarState(LIDAR2D_STATE_BUSY_IDLE); } else { ret = HandleStateError(TargetState, ret, "Configuration error"); } } else { ret = HandleStateError(TargetState, ret, "Connection error"); } } else { ret = HandleStateError(TargetState, ret, "Invalid Lidar state transition"); } return ret; } //=========================================================================== //=========================================================================== SensorResult Lidar2d_Model::HandleStateBusyIdle(Lidar2dState TargetState) { SensorResult ret = SSBL_ERR_INVALID_STATE; switch (TargetState) { case LIDAR2D_STATE_STARTED: ret = HandleLidarStart(); break; case LIDAR2D_STATE_STOPPED: ret = HandleLidarStop(); break; case LIDAR2D_STATE_IDLE: ret = pLidar2DSkeleton_->Disconnect(); break; default: ret = HandleStateError(TargetState, ret, "Invalid Lidar state transition"); break; } if (ret == SSBL_SUCCESS) { SetLidarState(TargetState); } return ret; } //=========================================================================== //=========================================================================== SensorResult Lidar2d_Model::HandleStateStart(Lidar2dState TargetState) { SensorResult ret = SSBL_ERR_INVALID_STATE; switch (TargetState) { case LIDAR2D_STATE_STARTED: ret = HandleLidarStart(); break; case LIDAR2D_STATE_STOPPED: ret = HandleLidarStop(); break; case LIDAR2D_STATE_IDLE: ret = pLidar2DSkeleton_->Disconnect(); break; default: ret = HandleStateError(TargetState, ret, "Invalid Lidar state transition"); break; } if (ret == SSBL_SUCCESS) { SetLidarState(TargetState); } return ret; } //=========================================================================== //=========================================================================== SensorResult Lidar2d_Model::HandleStateStop(Lidar2dState TargetState) { SensorResult ret = SSBL_ERR_INVALID_STATE; switch (TargetState) { case LIDAR2D_STATE_STARTED: ret = HandleLidarStart(); break; case LIDAR2D_STATE_STOPPED: ret = HandleLidarStop(); break; case LIDAR2D_STATE_IDLE: ret = pLidar2DSkeleton_->Disconnect(); break; default: ret = HandleStateError(TargetState, ret, "Invalid Lidar state transition"); break; } if (ret == SSBL_SUCCESS) { SetLidarState(TargetState); } return ret; } //=========================================================================== //=========================================================================== SensorResult Lidar2d_Model::HandleStateError(Lidar2dState TargetState, SensorResult prevResult, std::string error) { SetLidarState(LIDAR2D_STATE_ERROR); SSBL_LOG_ERROR("Error during transition from %s to %s", StateInfo[LidarState_].name_.c_str(), StateInfo[TargetState].name_.c_str()); SSBL_LOG_ERROR("%s", error.c_str()); return prevResult; } //=========================================================================== //=========================================================================== void Lidar2d_Model::HandleDeviceLost(int32_t val) { SSBL_UNUSED(val); StoredState_ = GetLidarState(); pLidar2DSkeleton_->DeregisterAllEvents(true); pLidar2DSkeleton_->Disconnect(true); SetLidarState(LIDAR2D_STATE_ERROR); SSBL_LOG_ERROR("Device lost - is wireing ok?"); if (AutoReconnect_) { SSBL_LOG_INFO("Trying automatic reconnect in 5 seconds"); pReconnectTimer->Start(); } else { SSBL_LOG_INFO("Automatic reconnect disabled."); } } //=========================================================================== //=========================================================================== bool Lidar2d::Create_Lidar2d(string const& ModelName, string const& SkeletonVersion, string const& IP) { bool bRet = true; SensorSkeleton* pSkeleton = nullptr; uint64_t test = hash_64_fnv1a(ModelName.c_str(), ModelName.size()); switch (test) { //-------------------------- case hash_64_fnv1a_const("TiM561"): pSkeleton = Create_TiM5xx_Skeleton(ModelName, SkeletonVersion, IP); if (nullptr != pSkeleton) { pLidarModel_ = Create_TiM5xx_Model(ModelName, pSkeleton); } break; //-------------------------- case hash_64_fnv1a_const("TiM571"): pSkeleton = Create_TiM5xx_Skeleton(ModelName, SkeletonVersion, IP); if (nullptr != pSkeleton) { pLidarModel_ = Create_TiM5xx_Model(ModelName, pSkeleton); } break; //-------------------------- case hash_64_fnv1a_const("TiM581"): pSkeleton = Create_TiM5xx_Skeleton(ModelName, SkeletonVersion, IP); if (nullptr != pSkeleton) { pLidarModel_ = Create_TiM5xx_Model(ModelName, pSkeleton); } break; //-------------------------- default: bRet = false; SSBL_LOG_ERROR("No such device: %s", ModelName.c_str()); break; } if (bRet) { if (nullptr == pLidarModel_) { if (nullptr != pSkeleton) { delete pSkeleton; } bRet = false; } } return bRet; } } // namespace ssbl
// Copyright (c) 2010, Adam Petersen <adam@adampetersen.se>. All rights reserved. // // Redistribution and use in source and binary forms, with or without modification, are // permitted provided that the following conditions are met: // // 1. Redistributions of source code must retain the above copyright notice, this list of // conditions and the following disclaimer. // // 2. Redistributions in binary form must reproduce the above copyright notice, this list // of conditions and the following disclaimer in the documentation and/or other materials // provided with the distribution. // // THIS SOFTWARE IS PROVIDED BY Adam Petersen ``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 Adam Petersen OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR // SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON // ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING // NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF // ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #include "tinch_pp/node.h" #include "tinch_pp/mailbox.h" #include "tinch_pp/erlang_types.h" #include <functional> #include <boost/assign/list_of.hpp> #include <iostream> using namespace tinch_pp; using namespace tinch_pp::erl; using namespace boost::assign; // USAGE: // ====== // 1. Start an Erlang node with the cookie abcdef. // 2. Start the Erlang program reflect_msg: // (testnode@127.0.0.1)4> reflect_msg:start_link(). // 3. Start this program. The program will send different messages // to reflect_msg, which echoes the messages back. namespace { void echo_atom(mailbox_ptr mbox); void echo_binary(mailbox_ptr mbox); void echo_bit_string(mailbox_ptr mbox); void echo_nested_tuples(mailbox_ptr mbox, const std::string& name); void echo_list(mailbox_ptr mbox); void echo_empty_tuple(mailbox_ptr mbox); void echo_string(mailbox_ptr mbox, const std::string& msg_name); void echo_float(mailbox_ptr mbox, const std::string& msg_name); // TODO: we can send such a list, but not match it...yet! void echo_heterogenous_list(mailbox_ptr mbox); typedef boost::function<void (mailbox_ptr)> sender_fn_type; } int main() { node_ptr my_node = node::create("my_test_node@127.0.0.1", "abcdef"); mailbox_ptr mbox = my_node->create_mailbox(); const sender_fn_type senders[] = { std::bind(echo_atom, std::placeholders::_1), std::bind(echo_atom, std::placeholders::_1), std::bind(echo_binary, std::placeholders::_1), std::bind(echo_binary, std::placeholders::_1), std::bind(echo_bit_string, std::placeholders::_1), std::bind(echo_nested_tuples, std::placeholders::_1, "start"), std::bind(echo_nested_tuples, std::placeholders::_1, "next"), std::bind(echo_empty_tuple, std::placeholders::_1), std::bind(echo_list, std::placeholders::_1), std::bind(echo_list, std::placeholders::_1), std::bind(echo_string, std::placeholders::_1, "start"), std::bind(echo_string, std::placeholders::_1, "next"), std::bind(echo_float, std::placeholders::_1, "start"), std::bind(echo_float, std::placeholders::_1, "next")}; const size_t number_of_senders = sizeof senders / sizeof senders[0]; for(size_t i = 0; i < number_of_senders; ++i) senders[i](mbox); mbox->close(); } namespace { const std::string remote_node_name("testnode@127.0.0.1"); const std::string to_name("reflect_msg"); // All messages have the following format: {echo, self(), Msg} void echo_atom(mailbox_ptr mbox) { mbox->send(to_name, remote_node_name, make_e_tuple(atom("echo"), pid(mbox->self()), atom("hello"))); const matchable_ptr reply = mbox->receive(); std::string name; if(reply->match(atom("hello"))) std::cout << "Matched atom(hello)" << std::endl; else if(reply->match(atom(&name))) std::cout << "Matched atom(" << name << ")" << std::endl; else std::cerr << "No match - unexpected message!" << std::endl; } void echo_binary(mailbox_ptr mbox) { const msg_seq byte_stream = list_of(1)(2)(3)(42); const binary_value_type data(byte_stream); mbox->send(to_name, remote_node_name, make_e_tuple(atom("echo"), pid(mbox->self()), binary(data))); const matchable_ptr reply = mbox->receive(); if(reply->match(binary(data))) std::cout << "Matched binary([1, 2, 3, 42])" << std::endl; else std::cerr << "No match for binary - unexpected message!" << std::endl; } void echo_bit_string(mailbox_ptr mbox) { const msg_seq byte_stream = list_of(1)(2)(3)(0xF0); const int padding_bits = 4; const binary_value_type data(byte_stream, padding_bits); mbox->send(to_name, remote_node_name, make_e_tuple(atom("echo"), pid(mbox->self()), binary(data))); const matchable_ptr reply = mbox->receive(); if(reply->match(binary(data))) std::cout << "Matched binary with padding ([1, 2, 3, 0xF0:4] )" << std::endl; else std::cerr << "No match for binary bit-string - unexpected message!" << std::endl; } void echo_nested_tuples(mailbox_ptr mbox, const std::string& name) { mbox->send(to_name, remote_node_name, make_e_tuple(atom("echo"), pid(mbox->self()), make_e_tuple(atom(name), make_e_tuple(atom("nested"), int_(42))))); const matchable_ptr reply = mbox->receive(); if(reply->match(make_e_tuple(atom("start"), erl::any()))) std::cout << "Matched {start, _}" << std::endl; else if(reply->match(make_e_tuple(atom("next"), make_e_tuple(atom("nested"), int_(42))))) std::cout << "Matched {next, {nested, 42}}" << std::endl; else std::cerr << "No match - unexpected message!" << std::endl; } void echo_empty_tuple(mailbox_ptr mbox) { mbox->send(to_name, remote_node_name, make_e_tuple(atom("echo"), pid(mbox->self()), make_e_tuple())); const matchable_ptr reply = mbox->receive(); if(reply->match(make_e_tuple())) std::cout << "Matched empty tuple {}" << std::endl; else std::cerr << "No match - unexpected message!" << std::endl; } void echo_string(mailbox_ptr mbox, const std::string& msg_name) { mbox->send(to_name, remote_node_name, make_e_tuple(atom("echo"), pid(mbox->self()), make_e_tuple(atom(msg_name), e_string("my string")))); const matchable_ptr reply = mbox->receive(); std::string matched_val; if(reply->match(make_e_tuple(atom("start"), erl::any()))) std::cout << "Matched string {start, _}" << std::endl; else if(reply->match(make_e_tuple(atom("next"), e_string(&matched_val)))) std::cout << "Matched string {start, " << matched_val << "}" << std::endl; else std::cerr << "No match - unexpected message!" << std::endl; } void echo_float(mailbox_ptr mbox, const std::string& msg_name) { const double value = 1234567.98765; mbox->send(to_name, remote_node_name, make_e_tuple(atom("echo"), pid(mbox->self()), make_e_tuple(atom(msg_name), float_(value)))); const matchable_ptr reply = mbox->receive(); double matched_val; if(reply->match(make_e_tuple(atom("start"), erl::any()))) std::cout << "Matched float {start, _}" << std::endl; else if(reply->match(make_e_tuple(atom("next"), float_(&matched_val)))) std::cout << "Matched float {start, " << matched_val << "}" << std::endl; else std::cerr << "No match - unexpected message!" << std::endl; } void echo_list(mailbox_ptr mbox) { const std::list<erl::object_ptr> send_numbers = list_of(make_int(1))(make_int(2))(make_int(1000)); mbox->send(to_name, remote_node_name, make_e_tuple(atom("echo"), pid(mbox->self()), make_e_tuple(atom("numbers"), make_list(send_numbers)))); const matchable_ptr reply = mbox->receive(); std::list<int_> numbers; if(reply->match(make_e_tuple(atom("numbers"), make_list(&numbers)))) std::cout << "Matched {numbers, List} with List size = " << numbers.size() << std::endl; else if(reply->match(make_e_tuple(atom("start"), erl::any()))) std::cout << "Matched {start, _}" << std::endl; else std::cerr << "No match - unexpected message!" << std::endl; } }
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <cms/CMSProperties.h> using namespace cms; //////////////////////////////////////////////////////////////////////////////// CMSProperties::~CMSProperties() { }
/**************************************************************************** * * Copyright (c) 2020 PX4 Development Team. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * 3. Neither the name PX4 nor the names of its contributors may be * used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * ****************************************************************************/ #pragma once #include "Integrator.hpp" #include <lib/mathlib/math/Limits.hpp> #include <lib/matrix/matrix/math.hpp> #include <lib/perf/perf_counter.h> #include <lib/sensor_calibration/Accelerometer.hpp> #include <lib/sensor_calibration/Gyroscope.hpp> #include <px4_platform_common/log.h> #include <px4_platform_common/module_params.h> #include <px4_platform_common/px4_config.h> #include <px4_platform_common/px4_work_queue/ScheduledWorkItem.hpp> #include <uORB/PublicationMulti.hpp> #include <uORB/Subscription.hpp> #include <uORB/SubscriptionCallback.hpp> #include <uORB/topics/parameter_update.h> #include <uORB/topics/sensor_accel.h> #include <uORB/topics/sensor_gyro.h> #include <uORB/topics/vehicle_imu.h> #include <uORB/topics/vehicle_imu_status.h> namespace sensors { class VehicleIMU : public ModuleParams, public px4::ScheduledWorkItem { public: VehicleIMU() = delete; VehicleIMU(int instance, uint8_t accel_index, uint8_t gyro_index, const px4::wq_config_t &config); ~VehicleIMU() override; bool Start(); void Stop(); void PrintStatus(); private: void ParametersUpdate(bool force = false); void Run() override; struct IntervalAverage { hrt_abstime timestamp_sample_last{0}; float interval_sum{0.f}; float interval_count{0.f}; float update_interval{0.f}; }; bool UpdateIntervalAverage(IntervalAverage &intavg, const hrt_abstime &timestamp_sample); void UpdateIntegratorConfiguration(); void UpdateGyroVibrationMetrics(const matrix::Vector3f &delta_angle); void UpdateAccelVibrationMetrics(const matrix::Vector3f &delta_velocity); uORB::PublicationMulti<vehicle_imu_s> _vehicle_imu_pub{ORB_ID(vehicle_imu)}; uORB::PublicationMulti<vehicle_imu_status_s> _vehicle_imu_status_pub{ORB_ID(vehicle_imu_status)}; uORB::Subscription _params_sub{ORB_ID(parameter_update)}; uORB::SubscriptionCallbackWorkItem _sensor_accel_sub; uORB::SubscriptionCallbackWorkItem _sensor_gyro_sub; calibration::Accelerometer _accel_calibration{}; calibration::Gyroscope _gyro_calibration{}; Integrator _accel_integrator{}; // 200 Hz default Integrator _gyro_integrator{true}; // 200 Hz default, coning compensation enabled hrt_abstime _last_timestamp_sample_accel{0}; hrt_abstime _last_timestamp_sample_gyro{0}; IntervalAverage _accel_interval{}; IntervalAverage _gyro_interval{}; unsigned _accel_last_generation{0}; unsigned _gyro_last_generation{0}; unsigned _consecutive_data_gap{0}; matrix::Vector3f _accel_sum{}; matrix::Vector3f _gyro_sum{}; int _accel_sum_count{0}; int _gyro_sum_count{0}; float _accel_temperature{0}; float _gyro_temperature{0}; matrix::Vector3f _delta_angle_prev{0.f, 0.f, 0.f}; // delta angle from the previous IMU measurement matrix::Vector3f _delta_velocity_prev{0.f, 0.f, 0.f}; // delta velocity from the previous IMU measurement vehicle_imu_status_s _status{}; uint8_t _delta_velocity_clipping{0}; bool _intervals_configured{false}; const uint8_t _instance; perf_counter_t _accel_update_perf{perf_alloc(PC_INTERVAL, MODULE_NAME": accel update interval")}; perf_counter_t _accel_generation_gap_perf{perf_alloc(PC_COUNT, MODULE_NAME": accel data gap")}; perf_counter_t _gyro_update_perf{perf_alloc(PC_INTERVAL, MODULE_NAME": gyro update interval")}; perf_counter_t _gyro_generation_gap_perf{perf_alloc(PC_COUNT, MODULE_NAME": gyro data gap")}; DEFINE_PARAMETERS( (ParamInt<px4::params::IMU_INTEG_RATE>) _param_imu_integ_rate, (ParamInt<px4::params::IMU_GYRO_RATEMAX>) _param_imu_gyro_ratemax ) }; } // namespace sensors
// // Copyright RIME Developers // Distributed under the BSD License // // 2011-12-10 GONG Chen <chen.sst@gmail.com> // #include <algorithm> #include <boost/algorithm/string.hpp> #include <boost/filesystem.hpp> #include <boost/uuid/random_generator.hpp> #include <boost/uuid/uuid.hpp> #include <boost/uuid/uuid_io.hpp> #include <rime/common.h> #include <rime/resource.h> #include <rime/schema.h> #include <rime/service.h> #include <rime/setup.h> #include <rime/ticket.h> #include <rime/algo/utilities.h> #include <rime/dict/dictionary.h> #include <rime/dict/dict_compiler.h> #include <rime/lever/deployment_tasks.h> #include <rime/lever/user_dict_manager.h> #ifdef _WIN32 #include <windows.h> #endif using namespace std::placeholders; namespace fs = boost::filesystem; namespace rime { DetectModifications::DetectModifications(TaskInitializer arg) { try { data_dirs_ = boost::any_cast<vector<string>>(arg); } catch (const boost::bad_any_cast&) { LOG(ERROR) << "DetectModifications: invalid arguments."; } } bool DetectModifications::Run(Deployer* deployer) { time_t last_modified = 0; try { for (auto dir : data_dirs_) { fs::path p = fs::canonical(dir); last_modified = (std::max)(last_modified, fs::last_write_time(p)); if (fs::is_directory(p)) { for (fs::directory_iterator iter(p), end; iter != end; ++iter) { fs::path entry(iter->path()); if (fs::is_regular_file(fs::canonical(entry)) && entry.extension().string() == ".yaml" && entry.filename().string() != "user.yaml") { last_modified = (std::max)(last_modified, fs::last_write_time(entry)); } } } } } catch(const fs::filesystem_error& ex) { LOG(ERROR) << "Error reading file information: " << ex.what(); return true; } // TODO: store as 64-bit number to avoid the year 2038 problem int last_build_time = 0; { the<Config> user_config(Config::Require("user_config")->Create("user")); user_config->GetInt("var/last_build_time", &last_build_time); } if (last_modified > (time_t)last_build_time) { LOG(INFO) << "modifications detected. workspace needs update."; return true; } return false; } bool InstallationUpdate::Run(Deployer* deployer) { LOG(INFO) << "updating rime installation info."; fs::path shared_data_path(deployer->shared_data_dir); fs::path user_data_path(deployer->user_data_dir); if (!fs::exists(user_data_path)) { LOG(INFO) << "creating user data dir: " << user_data_path.string(); boost::system::error_code ec; if (!fs::create_directories(user_data_path, ec)) { LOG(ERROR) << "Error creating user data dir: " << user_data_path.string(); } } fs::path installation_info(user_data_path / "installation.yaml"); Config config; string installation_id; string last_distro_code_name; string last_distro_version; string last_rime_version; if (config.LoadFromFile(installation_info.string())) { if (config.GetString("installation_id", &installation_id)) { LOG(INFO) << "installation info exists. installation id: " << installation_id; // for now: deployer->user_id = installation_id; } if (!config.GetString("sync_dir", &deployer->sync_dir)) { deployer->sync_dir = (user_data_path / "sync").string(); } LOG(INFO) << "sync dir: " << deployer->sync_dir; if (config.GetString("distribution_code_name", &last_distro_code_name)) { LOG(INFO) << "previous distribution: " << last_distro_code_name; } if (config.GetString("distribution_version", &last_distro_version)) { LOG(INFO) << "previous distribution version: " << last_distro_version; } if (config.GetString("rime_version", &last_rime_version)) { LOG(INFO) << "previous Rime version: " << last_rime_version; } } if (!installation_id.empty() && last_distro_code_name == deployer->distribution_code_name && last_distro_version == deployer->distribution_version && last_rime_version == RIME_VERSION) { return true; } LOG(INFO) << "creating installation info."; time_t now = time(NULL); string time_str(ctime(&now)); boost::trim(time_str); if (installation_id.empty()) { installation_id = boost::uuids::to_string(boost::uuids::random_generator()()); LOG(INFO) << "generated installation id: " << installation_id; // for now: deployer->user_id = installation_id; config.SetString("installation_id", installation_id); config.SetString("install_time", time_str); } else { config.SetString("update_time", time_str); } if (!deployer->distribution_name.empty()) { config.SetString("distribution_name", deployer->distribution_name); LOG(INFO) << "distribution: " << deployer->distribution_name; } if (!deployer->distribution_code_name.empty()) { config.SetString("distribution_code_name", deployer->distribution_code_name); LOG(INFO) << "distribution code name: " << deployer->distribution_code_name; } if (!deployer->distribution_version.empty()) { config.SetString("distribution_version", deployer->distribution_version); LOG(INFO) << "distribution version: " << deployer->distribution_version; } config.SetString("rime_version", RIME_VERSION); LOG(INFO) << "Rime version: " << RIME_VERSION; return config.SaveToFile(installation_info.string()); } bool WorkspaceUpdate::Run(Deployer* deployer) { LOG(INFO) << "updating workspace."; { the<DeploymentTask> t; t.reset(new ConfigFileUpdate("default.yaml", "config_version")); t->Run(deployer); // Deprecated: symbols.yaml is only used as source file //t.reset(new ConfigFileUpdate("symbols.yaml", "config_version")); //t->Run(deployer); t.reset(new SymlinkingPrebuiltDictionaries); t->Run(deployer); } the<Config> config(Config::Require("config")->Create("default")); if (!config) { LOG(ERROR) << "Error loading default config."; return false; } auto schema_list = config->GetList("schema_list"); if (!schema_list) { LOG(WARNING) << "schema list not defined."; return false; } LOG(INFO) << "updating schemas."; int success = 0; int failure = 0; map<string, string> schemas; the<ResourceResolver> resolver( Service::instance().CreateResourceResolver( {"schema", "", ".schema.yaml"})); auto build_schema = [&](const string& schema_id, bool as_dependency = false) { if (schemas.find(schema_id) != schemas.end()) // already built return; LOG(INFO) << "schema: " << schema_id; string schema_path; if (schemas.find(schema_id) == schemas.end()) { schema_path = resolver->ResolvePath(schema_id).string(); schemas[schema_id] = schema_path; } else { schema_path = schemas[schema_id]; } if (schema_path.empty() || !fs::exists(schema_path)) { if (as_dependency) { LOG(WARNING) << "missing input schema; skipped unsatisfied dependency: " << schema_id; } else { LOG(ERROR) << "missing input schema: " << schema_id; ++failure; } return; } the<DeploymentTask> t(new SchemaUpdate(schema_path)); if (t->Run(deployer)) ++success; else ++failure; }; auto schema_component = Config::Require("schema"); for (auto it = schema_list->begin(); it != schema_list->end(); ++it) { auto item = As<ConfigMap>(*it); if (!item) continue; auto schema_property = item->GetValue("schema"); if (!schema_property) continue; const string& schema_id = schema_property->str(); build_schema(schema_id); the<Config> schema_config(schema_component->Create(schema_id)); if (!schema_config) continue; if (auto dependencies = schema_config->GetList("schema/dependencies")) { for (auto d = dependencies->begin(); d != dependencies->end(); ++d) { auto dependency = As<ConfigValue>(*d); if (!dependency) continue; const string& dependency_id = dependency->str(); bool as_dependency = true; build_schema(dependency_id, as_dependency); } } } LOG(INFO) << "finished updating schemas: " << success << " success, " << failure << " failure."; the<Config> user_config(Config::Require("user_config")->Create("user")); // TODO: store as 64-bit number to avoid the year 2038 problem user_config->SetInt("var/last_build_time", (int)time(NULL)); return failure == 0; } SchemaUpdate::SchemaUpdate(TaskInitializer arg) : verbose_(false) { try { schema_file_ = boost::any_cast<string>(arg); } catch (const boost::bad_any_cast&) { LOG(ERROR) << "SchemaUpdate: invalid arguments."; } } static bool MaybeCreateDirectory(fs::path dir) { if (!fs::exists(dir)) { boost::system::error_code ec; if (!fs::create_directories(dir, ec)) { LOG(ERROR) << "error creating directory '" << dir.string() << "'."; return false; } } return true; } static bool RemoveVersionSuffix(string* version, const string& suffix) { size_t suffix_pos = version->find(suffix); if (suffix_pos != string::npos) { version->erase(suffix_pos); return true; } return false; } static bool TrashDeprecatedUserCopy(const fs::path& shared_copy, const fs::path& user_copy, const string& version_key, const fs::path& trash) { if (!fs::exists(shared_copy) || !fs::exists(user_copy) || fs::equivalent(shared_copy, user_copy)) { return false; } string shared_copy_version; string user_copy_version; Config shared_config; if (shared_config.LoadFromFile(shared_copy.string())) { shared_config.GetString(version_key, &shared_copy_version); // treat "X.Y.minimal" as equal to (not greater than) "X.Y" // to avoid trashing the user installed full version RemoveVersionSuffix(&shared_copy_version, ".minimal"); } Config user_config; bool is_customized_user_copy = user_config.LoadFromFile(user_copy.string()) && user_config.GetString(version_key, &user_copy_version) && RemoveVersionSuffix(&user_copy_version, ".custom."); int cmp = CompareVersionString(shared_copy_version, user_copy_version); // rime-installed user copy of the same version should be kept for integrity. // also it could have been manually edited by user. if (cmp > 0 || (cmp == 0 && is_customized_user_copy)) { if (!MaybeCreateDirectory(trash)) { return false; } fs::path backup = trash / user_copy.filename(); boost::system::error_code ec; fs::rename(user_copy, backup, ec); if (ec) { LOG(ERROR) << "error trashing file " << user_copy.string(); return false; } return true; } return false; } bool SchemaUpdate::Run(Deployer* deployer) { fs::path source_path(schema_file_); if (!fs::exists(source_path)) { LOG(ERROR) << "Error updating schema: nonexistent file '" << schema_file_ << "'."; return false; } string schema_id; the<Config> config(new Config); if (!config->LoadFromFile(schema_file_) || !config->GetString("schema/schema_id", &schema_id) || schema_id.empty()) { LOG(ERROR) << "invalid schema definition in '" << schema_file_ << "'."; return false; } the<DeploymentTask> config_file_update( new ConfigFileUpdate(schema_id + ".schema.yaml", "schema/version")); if (!config_file_update->Run(deployer)) { return false; } // reload compiled config config.reset(Config::Require("schema")->Create(schema_id)); string dict_name; if (!config->GetString("translator/dictionary", &dict_name)) { // not requiring a dictionary return true; } Schema schema(schema_id, config.release()); the<Dictionary> dict( Dictionary::Require("dictionary")->Create({&schema, "translator"})); if (!dict) { LOG(ERROR) << "Error creating dictionary '" << dict_name << "'."; return false; } LOG(INFO) << "preparing dictionary '" << dict_name << "'."; fs::path user_data_path(deployer->user_data_dir); if (!MaybeCreateDirectory(user_data_path / "build")) { return false; } DictCompiler dict_compiler(dict.get(), "build/"); if (verbose_) { dict_compiler.set_options(DictCompiler::kRebuild | DictCompiler::kDump); } the<ResourceResolver> resolver( Service::instance().CreateResourceResolver( {"compiled_schema", "build/", ".schema.yaml"})); resolver->set_root_path(user_data_path); auto compiled_schema = resolver->ResolvePath(schema_id).string(); if (!dict_compiler.Compile(compiled_schema)) { LOG(ERROR) << "dictionary '" << dict_name << "' failed to compile."; return false; } LOG(INFO) << "dictionary '" << dict_name << "' is ready."; return true; } ConfigFileUpdate::ConfigFileUpdate(TaskInitializer arg) { try { auto p = boost::any_cast<pair<string, string>>(arg); file_name_ = p.first; version_key_ = p.second; } catch (const boost::bad_any_cast&) { LOG(ERROR) << "ConfigFileUpdate: invalid arguments."; } } static bool ConfigNeedsUpdate(Config* config) { auto build_info = (*config)["__build_info"]; if (!build_info.IsMap()) { LOG(INFO) << "missing build info"; return true; } auto timestamps = build_info["timestamps"]; if (!timestamps.IsMap()) { LOG(INFO) << "missing timestamps"; return true; } the<ResourceResolver> resolver( Service::instance().CreateResourceResolver( {"config_source_file", "", ".yaml"})); for (auto entry : *timestamps.AsMap()) { auto value = As<ConfigValue>(entry.second); int recorded_time = 0; if (!value || !value->GetInt(&recorded_time)) { LOG(WARNING) << "invalid timestamp for " << entry.first; return true; } fs::path source_file = resolver->ResolvePath(entry.first); if (!fs::exists(source_file)) { if (recorded_time) { LOG(INFO) << "source file no longer exists: " << source_file.string(); return true; } continue; } if (recorded_time != (int) fs::last_write_time(source_file)) { LOG(INFO) << "source file " << (recorded_time ? "changed: " : "added: ") << source_file.string(); return true; } } return false; } bool ConfigFileUpdate::Run(Deployer* deployer) { fs::path shared_data_path(deployer->shared_data_dir); fs::path user_data_path(deployer->user_data_dir); // trash depecated user copy created by an older version of Rime fs::path source_config_path(shared_data_path / file_name_); fs::path dest_config_path(user_data_path / file_name_); fs::path trash = user_data_path / "trash"; if (TrashDeprecatedUserCopy(source_config_path, dest_config_path, version_key_, trash)) { LOG(INFO) << "deprecated user copy of '" << file_name_ << "' is moved to " << trash; } // build the config file if needs update the<Config> config(Config::Require("config")->Create(file_name_)); if (ConfigNeedsUpdate(config.get())) { if (!MaybeCreateDirectory(user_data_path / "build")) { return false; } config.reset(Config::Require("config_builder")->Create(file_name_)); } return true; } bool PrebuildAllSchemas::Run(Deployer* deployer) { fs::path shared_data_path(deployer->shared_data_dir); fs::path user_data_path(deployer->user_data_dir); if (!fs::exists(shared_data_path) || !fs::is_directory(shared_data_path)) return false; bool success = true; for (fs::directory_iterator iter(shared_data_path), end; iter != end; ++iter) { fs::path entry(iter->path()); if (boost::ends_with(entry.string(), ".schema.yaml")) { the<DeploymentTask> t(new SchemaUpdate(entry.string())); if (!t->Run(deployer)) success = false; } } return success; } bool SymlinkingPrebuiltDictionaries::Run(Deployer* deployer) { fs::path shared_data_path(deployer->shared_data_dir); fs::path user_data_path(deployer->user_data_dir); if (!fs::exists(shared_data_path) || !fs::is_directory(shared_data_path) || !fs::exists(user_data_path) || !fs::is_directory(user_data_path) || fs::equivalent(shared_data_path, user_data_path)) return false; bool success = false; // remove symlinks to shared data files created by previous version for (fs::directory_iterator test(user_data_path), end; test != end; ++test) { fs::path entry(test->path()); if (fs::is_symlink(entry)) { try { // a symlink becomes dangling if the target file is no longer provided boost::system::error_code ec; auto target_path = fs::canonical(entry, ec); bool bad_link = bool(ec); bool linked_to_shared_data = !bad_link && target_path.has_parent_path() && fs::equivalent(shared_data_path, target_path.parent_path()); if (bad_link || linked_to_shared_data) { LOG(INFO) << "removing symlink: " << entry.filename().string(); fs::remove(entry); } } catch (const fs::filesystem_error& ex) { LOG(ERROR) << entry << ": " << ex.what(); success = false; } } } return success; } bool UserDictUpgrade::Run(Deployer* deployer) { LoadModules(kLegacyModules); auto legacy_userdb_component = UserDb::Require("legacy_userdb"); if (!legacy_userdb_component) { return true; // nothing to upgrade } UserDictManager manager(deployer); UserDictList dicts; manager.GetUserDictList(&dicts, legacy_userdb_component); bool ok = true; for (auto it = dicts.cbegin(); it != dicts.cend(); ++it) { if (!manager.UpgradeUserDict(*it)) ok = false; } return ok; } bool UserDictSync::Run(Deployer* deployer) { UserDictManager mgr(deployer); return mgr.SynchronizeAll(); } static bool IsCustomizedCopy(const string& file_name) { if (boost::ends_with(file_name, ".yaml") && !boost::ends_with(file_name, ".custom.yaml")) { Config config; string checksum; if (config.LoadFromFile(file_name) && config.GetString("customization", &checksum)) { return true; } } return false; } bool BackupConfigFiles::Run(Deployer* deployer) { LOG(INFO) << "backing up config files."; fs::path user_data_path(deployer->user_data_dir); if (!fs::exists(user_data_path)) return false; fs::path backup_dir(deployer->user_data_sync_dir()); if (!MaybeCreateDirectory(backup_dir)) { return false; } int success = 0, failure = 0, latest = 0, skipped = 0; for (fs::directory_iterator iter(user_data_path), end; iter != end; ++iter) { fs::path entry(iter->path()); if (!fs::is_regular_file(entry)) continue; auto file_extension = entry.extension().string(); bool is_yaml_file = file_extension == ".yaml"; bool is_text_file = file_extension == ".txt"; if (!is_yaml_file && !is_text_file) continue; fs::path backup = backup_dir / entry.filename(); if (fs::exists(backup) && Checksum(backup.string()) == Checksum(entry.string())) { ++latest; // already up-to-date continue; } if (is_yaml_file && IsCustomizedCopy(entry.string())) { ++skipped; // customized copy continue; } boost::system::error_code ec; fs::copy_file(entry, backup, fs::copy_option::overwrite_if_exists, ec); if (ec) { LOG(ERROR) << "error backing up file " << backup.string(); ++failure; } else { ++success; } } LOG(INFO) << "backed up " << success << " config files to " << backup_dir.string() << ", " << failure << " failed, " << latest << " up-to-date, " << skipped << " skipped."; return !failure; } bool CleanupTrash::Run(Deployer* deployer) { LOG(INFO) << "clean up trash."; fs::path user_data_path(deployer->user_data_dir); if (!fs::exists(user_data_path)) return false; fs::path trash = user_data_path / "trash"; int success = 0, failure = 0; for (fs::directory_iterator iter(user_data_path), end; iter != end; ++iter) { fs::path entry(iter->path()); if (!fs::is_regular_file(entry)) continue; auto filename = entry.filename().string(); if (filename == "rime.log" || boost::ends_with(filename, ".bin") || boost::ends_with(filename, ".reverse.kct") || boost::ends_with(filename, ".userdb.kct.old") || boost::ends_with(filename, ".userdb.kct.snapshot")) { if (!success && !MaybeCreateDirectory(trash)) { return false; } fs::path backup = trash / entry.filename(); boost::system::error_code ec; fs::rename(entry, backup, ec); if (ec) { LOG(ERROR) << "error clean up file " << entry.string(); ++failure; } else { ++success; } } } if (success) { LOG(INFO) << "moved " << success << " files to " << trash.string(); } return !failure; } bool CleanOldLogFiles::Run(Deployer* deployer) { char ymd[12] = {0}; time_t now = time(NULL); strftime(ymd, sizeof(ymd), ".%Y%m%d", localtime(&now)); string today(ymd); DLOG(INFO) << "today: " << today; vector<string> dirs; #ifdef RIME_ENABLE_LOGGING #ifdef _WIN32 // work-around: google::GetExistingTempDirectories crashes on windows 7 char tmp[MAX_PATH]; if (GetTempPathA(MAX_PATH, tmp)) dirs.push_back(tmp); #else google::GetExistingTempDirectories(&dirs); #endif // _WIN32 #endif // RIME_ENABLE_LOGGING DLOG(INFO) << "scanning " << dirs.size() << " temp directory for log files."; bool success = true; int removed = 0; for (auto i = dirs.cbegin(); i != dirs.cend(); ++i) { DLOG(INFO) << "temp directory: " << *i; for (fs::directory_iterator j(*i), end; j != end; ++j) { fs::path entry(j->path()); string file_name(entry.filename().string()); try { if (fs::is_regular_file(entry) && !fs::is_symlink(entry) && boost::starts_with(file_name, "rime.") && !boost::contains(file_name, today)) { DLOG(INFO) << "removing log file '" << file_name << "'."; fs::remove(entry); ++removed; } } catch (const fs::filesystem_error& ex) { LOG(ERROR) << ex.what(); success = false; } } } if (removed != 0) { LOG(INFO) << "cleaned " << removed << " log files."; } return success; } } // namespace rime
#include "ClothingMeshUtils.h" #include "UnrealMathUtility.h" #include "LogMacros.h" #if WITH_EDITOR #include "NotificationManager.h" #include "SNotificationList.h" #endif DEFINE_LOG_CATEGORY(LogClothingMeshUtils) #define LOCTEXT_NAMESPACE "ClothingMeshUtils" namespace ClothingMeshUtils { /** * Gets the best match triangle for a specified position from the triangles in Mesh. * Performs no validation on the incoming mesh data, the mesh data should be verified * to be valid before using this function */ int32 GetBestTriangleBaseIndex(const ClothMeshDesc& Mesh, const FVector& Position) { float MinimumDistanceSq = MAX_flt; int32 ClosestBaseIndex = INDEX_NONE; const int32 NumTriangles = Mesh.Indices.Num() / 3; for(int32 TriIdx = 0; TriIdx < NumTriangles; ++TriIdx) { int32 TriBaseIdx = TriIdx * 3; const uint32 IA = Mesh.Indices[TriBaseIdx + 0]; const uint32 IB = Mesh.Indices[TriBaseIdx + 1]; const uint32 IC = Mesh.Indices[TriBaseIdx + 2]; const FVector& A = Mesh.Positions[IA]; const FVector& B = Mesh.Positions[IB]; const FVector& C = Mesh.Positions[IC]; FVector PointOnTri = FMath::ClosestPointOnTriangleToPoint(Position, A, B, C); float DistSq = (PointOnTri - Position).SizeSquared(); if(DistSq < MinimumDistanceSq) { MinimumDistanceSq = DistSq; ClosestBaseIndex = TriBaseIdx; } } return ClosestBaseIndex; } void GenerateMeshToMeshSkinningData(TArray<FMeshToMeshVertData>& OutSkinningData, const ClothMeshDesc& TargetMesh, const TArray<FVector>* TargetTangents, const ClothMeshDesc& SourceMesh) { if(!TargetMesh.HasValidMesh()) { UE_LOG(LogClothingMeshUtils, Warning, TEXT("Failed to generate mesh to mesh skinning data. Invalid Target Mesh.")); return; } if(!SourceMesh.HasValidMesh()) { UE_LOG(LogClothingMeshUtils, Warning, TEXT("Failed to generate mesh to mesh skinning data. Invalid Source Mesh.")); return; } const int32 NumMesh0Verts = TargetMesh.Positions.Num(); const int32 NumMesh0Normals = TargetMesh.Normals.Num(); const int32 NumMesh0Tangents = TargetTangents ? TargetTangents->Num() : 0; const int32 NumMesh1Verts = SourceMesh.Positions.Num(); const int32 NumMesh1Normals = SourceMesh.Normals.Num(); const int32 NumMesh1Indices = SourceMesh.Indices.Num(); // Check we have properly formed triangles check(NumMesh1Indices % 3 == 0); const int32 NumMesh1Triangles = NumMesh1Indices / 3; // Check mesh data to make sure we have the same number of each element if(NumMesh0Verts != NumMesh0Normals || (TargetTangents && NumMesh0Tangents != NumMesh0Verts)) { UE_LOG(LogClothingMeshUtils, Warning, TEXT("Can't generate mesh to mesh skinning data, Mesh0 data is missing verts.")); return; } if(NumMesh1Verts != NumMesh1Normals) { UE_LOG(LogClothingMeshUtils, Warning, TEXT("Can't generate mesh to mesh skinning data, Mesh1 data is missing verts.")); return; } OutSkinningData.Reserve(NumMesh0Verts); // For all mesh0 verts for(int32 VertIdx0 = 0; VertIdx0 < NumMesh0Verts; ++VertIdx0) { OutSkinningData.AddZeroed(); FMeshToMeshVertData& SkinningData = OutSkinningData.Last(); const FVector& VertPosition = TargetMesh.Positions[VertIdx0]; const FVector& VertNormal = TargetMesh.Normals[VertIdx0]; FVector VertTangent; if(TargetTangents) { VertTangent = (*TargetTangents)[VertIdx0]; } else { FVector Tan0, Tan1; VertNormal.FindBestAxisVectors(Tan0, Tan1); VertTangent = Tan0; } int32 ClosestTriangleBaseIdx = GetBestTriangleBaseIndex(SourceMesh, VertPosition); check(ClosestTriangleBaseIdx != INDEX_NONE); const FVector& A = SourceMesh.Positions[SourceMesh.Indices[ClosestTriangleBaseIdx]]; const FVector& B = SourceMesh.Positions[SourceMesh.Indices[ClosestTriangleBaseIdx + 1]]; const FVector& C = SourceMesh.Positions[SourceMesh.Indices[ClosestTriangleBaseIdx + 2]]; const FVector& NA = SourceMesh.Normals[SourceMesh.Indices[ClosestTriangleBaseIdx]]; const FVector& NB = SourceMesh.Normals[SourceMesh.Indices[ClosestTriangleBaseIdx + 1]]; const FVector& NC = SourceMesh.Normals[SourceMesh.Indices[ClosestTriangleBaseIdx + 2]]; // Before generating the skinning data we need to check for a degenerate triangle. // If we find _any_ degenerate triangles we will notify and fail to generate the skinning data const FVector TriNormal = FVector::CrossProduct(B - A, C - A); if(TriNormal.SizeSquared() < SMALL_NUMBER) { // Failed, we have 2 identical vertices OutSkinningData.Reset(); // Log and toast FText Error = FText::Format(LOCTEXT("DegenerateTriangleError", "Failed to generate skinning data, found conincident vertices in triangle A={0} B={1} C={2}"), FText::FromString(A.ToString()), FText::FromString(B.ToString()), FText::FromString(C.ToString())); UE_LOG(LogClothingMeshUtils, Warning, TEXT("%s"), *Error.ToString()); #if WITH_EDITOR FNotificationInfo Info(Error); Info.ExpireDuration = 5.0f; FSlateNotificationManager::Get().AddNotification(Info); #endif return; } SkinningData.PositionBaryCoordsAndDist = GetPointBaryAndDist(A, B, C, NA, NB, NC, VertPosition); SkinningData.NormalBaryCoordsAndDist = GetPointBaryAndDist(A, B, C, NA, NB, NC, VertPosition + VertNormal); SkinningData.TangentBaryCoordsAndDist = GetPointBaryAndDist(A, B, C, NA, NB, NC, VertPosition + VertTangent); SkinningData.SourceMeshVertIndices[0] = SourceMesh.Indices[ClosestTriangleBaseIdx]; SkinningData.SourceMeshVertIndices[1] = SourceMesh.Indices[ClosestTriangleBaseIdx + 1]; SkinningData.SourceMeshVertIndices[2] = SourceMesh.Indices[ClosestTriangleBaseIdx + 2]; SkinningData.SourceMeshVertIndices[3] = 0; } } FVector4 GetPointBaryAndDist(const FVector& A, const FVector& B, const FVector& C, const FVector& NA, const FVector& NB, const FVector& NC, const FVector& Point) { FPlane TrianglePlane(A, B, C); const FVector PointOnTriPlane = FVector::PointPlaneProject(Point, TrianglePlane); const FVector BaryCoords = FMath::ComputeBaryCentric2D(PointOnTriPlane, A, B, C); const FVector NormalAtPoint = TrianglePlane; FVector TriPointToVert = Point - PointOnTriPlane; TriPointToVert = TriPointToVert.ProjectOnTo(NormalAtPoint); float Dist = TriPointToVert.Size(); float Sign = TrianglePlane.PlaneDot(Point) < 0.0f ? -1.0f : 1.0f; return FVector4(BaryCoords, TrianglePlane.PlaneDot(Point)); } void GenerateEmbeddedPositions(const ClothMeshDesc& SourceMesh, TArrayView<const FVector> Positions, TArray<FVector4>& OutEmbeddedPositions, TArray<int32>& OutSourceIndices) { if(!SourceMesh.HasValidMesh()) { // No valid source mesh return; } const int32 NumPositions = Positions.Num(); OutEmbeddedPositions.Reset(); OutEmbeddedPositions.AddUninitialized(NumPositions); OutSourceIndices.Reset(NumPositions * 3); for(int32 PositionIndex = 0 ; PositionIndex < NumPositions ; ++PositionIndex) { const FVector& Position = Positions[PositionIndex]; int32 TriBaseIndex = GetBestTriangleBaseIndex(SourceMesh, Position); const int32 IA = SourceMesh.Indices[TriBaseIndex]; const int32 IB = SourceMesh.Indices[TriBaseIndex + 1]; const int32 IC = SourceMesh.Indices[TriBaseIndex + 2]; const FVector& A = SourceMesh.Positions[IA]; const FVector& B = SourceMesh.Positions[IB]; const FVector& C = SourceMesh.Positions[IC]; const FVector& NA = SourceMesh.Normals[IA]; const FVector& NB = SourceMesh.Normals[IB]; const FVector& NC = SourceMesh.Normals[IC]; OutEmbeddedPositions[PositionIndex] = GetPointBaryAndDist(A, B, C, NA, NB, NC, Position); OutSourceIndices.Add(IA); OutSourceIndices.Add(IB); OutSourceIndices.Add(IC); } } void FVertexParameterMapper::Map(TArrayView<const float> Source, TArray<float>& Dest) { Map(Source, Dest, [](FVector Bary, float A, float B, float C) { return Bary.X * A + Bary.Y * B + Bary.Z * C; }); } } #undef LOCTEXT_NAMESPACE
// ========================== UNINITIALIZED FILL N ========================== // // Project: The Experimental Bit Algorithms Library // Name: uninitialized_fill_n.hpp // Description: bit_iterator overloads for std::uninitialized_fill_n // Creator: Vincent Reverdy // Contributor(s): // License: BSD 3-Clause License // ========================================================================== // #ifndef _UNINITIALIZED_FILL_N_HPP_INCLUDED #define _UNINITIALIZED_FILL_N_HPP_INCLUDED // ========================================================================== // // ============================== PREAMBLE ================================== // // C++ standard library // Project sources // Third-party libraries // Miscellaneous namespace bit { // ========================================================================== // // Status: to do template <class ForwardIt, class Size, class T> bit_iterator<ForwardIt> uninitialized_fill_n(bit_iterator<ForwardIt> first, Size count, bit_value value) { (count, value); return first; } // Status: to do template <class ExecutionPolicy, class ForwardIt, class Size, class T> bit_iterator<ForwardIt> uninitialized_fill_n(ExecutionPolicy&& policy, bit_iterator<ForwardIt> first, Size count, bit_value value) { (policy, count, value); return first; } // ========================================================================== // } // namespace bit #endif // _UNINITIALIZED_FILL_N_HPP_INCLUDED // ========================================================================== //
/**************************************************************************** ** Meta object code from reading C++ file 'AreaCoverageTool.h' ** ** Created by: The Qt Meta Object Compiler version 67 (Qt 5.14.2) ** ** WARNING! All changes made in this file will be lost! *****************************************************************************/ #include <memory> #include "AreaCoverageTool.h" #include <QtCore/qbytearray.h> #include <QtCore/qmetatype.h> #if !defined(Q_MOC_OUTPUT_REVISION) #error "The header file 'AreaCoverageTool.h' doesn't include <QObject>." #elif Q_MOC_OUTPUT_REVISION != 67 #error "This file was generated using the moc from 5.14.2. It" #error "cannot be used with the include files from this version of Qt." #error "(The moc has changed too much.)" #endif QT_BEGIN_MOC_NAMESPACE QT_WARNING_PUSH QT_WARNING_DISABLE_DEPRECATED struct qt_meta_stringdata_CAreaCoverageTool_t { QByteArrayData data[5]; char stringdata0[47]; }; #define QT_MOC_LITERAL(idx, ofs, len) \ Q_STATIC_BYTE_ARRAY_DATA_HEADER_INITIALIZER_WITH_OFFSET(len, \ qptrdiff(offsetof(qt_meta_stringdata_CAreaCoverageTool_t, stringdata0) + ofs \ - idx * sizeof(QByteArrayData)) \ ) static const qt_meta_stringdata_CAreaCoverageTool_t qt_meta_stringdata_CAreaCoverageTool = { { QT_MOC_LITERAL(0, 0, 17), // "CAreaCoverageTool" QT_MOC_LITERAL(1, 18, 9), // "OnAssign1" QT_MOC_LITERAL(2, 28, 0), // "" QT_MOC_LITERAL(3, 29, 9), // "OnAssign2" QT_MOC_LITERAL(4, 39, 7) // "OnApply" }, "CAreaCoverageTool\0OnAssign1\0\0OnAssign2\0" "OnApply" }; #undef QT_MOC_LITERAL static const uint qt_meta_data_CAreaCoverageTool[] = { // content: 8, // revision 0, // classname 0, 0, // classinfo 3, 14, // methods 0, 0, // properties 0, 0, // enums/sets 0, 0, // constructors 0, // flags 0, // signalCount // slots: name, argc, parameters, tag, flags 1, 0, 29, 2, 0x08 /* Private */, 3, 0, 30, 2, 0x08 /* Private */, 4, 0, 31, 2, 0x08 /* Private */, // slots: parameters QMetaType::Void, QMetaType::Void, QMetaType::Void, 0 // eod }; void CAreaCoverageTool::qt_static_metacall(QObject *_o, QMetaObject::Call _c, int _id, void **_a) { if (_c == QMetaObject::InvokeMetaMethod) { auto *_t = static_cast<CAreaCoverageTool *>(_o); Q_UNUSED(_t) switch (_id) { case 0: _t->OnAssign1(); break; case 1: _t->OnAssign2(); break; case 2: _t->OnApply(); break; default: ; } } Q_UNUSED(_a); } QT_INIT_METAOBJECT const QMetaObject CAreaCoverageTool::staticMetaObject = { { QMetaObject::SuperData::link<CAbstractTool::staticMetaObject>(), qt_meta_stringdata_CAreaCoverageTool.data, qt_meta_data_CAreaCoverageTool, qt_static_metacall, nullptr, nullptr } }; const QMetaObject *CAreaCoverageTool::metaObject() const { return QObject::d_ptr->metaObject ? QObject::d_ptr->dynamicMetaObject() : &staticMetaObject; } void *CAreaCoverageTool::qt_metacast(const char *_clname) { if (!_clname) return nullptr; if (!strcmp(_clname, qt_meta_stringdata_CAreaCoverageTool.stringdata0)) return static_cast<void*>(this); return CAbstractTool::qt_metacast(_clname); } int CAreaCoverageTool::qt_metacall(QMetaObject::Call _c, int _id, void **_a) { _id = CAbstractTool::qt_metacall(_c, _id, _a); if (_id < 0) return _id; if (_c == QMetaObject::InvokeMetaMethod) { if (_id < 3) qt_static_metacall(this, _c, _id, _a); _id -= 3; } else if (_c == QMetaObject::RegisterMethodArgumentMetaType) { if (_id < 3) *reinterpret_cast<int*>(_a[0]) = -1; _id -= 3; } return _id; } QT_WARNING_POP QT_END_MOC_NAMESPACE
/*========================================================================= Program: Visualization Toolkit Module: vtkByteSwap.cxx Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen All rights reserved. See Copyright.txt or http://www.kitware.com/Copyright.htm for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notice for more information. =========================================================================*/ #include "vtkByteSwap.h" #include <memory.h> #include "vtkObjectFactory.h" vtkStandardNewMacro(vtkByteSwap); //---------------------------------------------------------------------------- vtkByteSwap::vtkByteSwap() { } //---------------------------------------------------------------------------- vtkByteSwap::~vtkByteSwap() { } //---------------------------------------------------------------------------- // Define swap functions for each type size. template <size_t s> struct vtkByteSwapper; template<> struct vtkByteSwapper<1> { static inline void Swap(char*) {} }; template<> struct vtkByteSwapper<2> { static inline void Swap(char* data) { char one_byte; one_byte = data[0]; data[0] = data[1]; data[1] = one_byte; } }; template<> struct vtkByteSwapper<4> { static inline void Swap(char* data) { char one_byte; one_byte = data[0]; data[0] = data[3]; data[3] = one_byte; one_byte = data[1]; data[1] = data[2]; data[2] = one_byte; } }; template<> struct vtkByteSwapper<8> { static inline void Swap(char* data) { char one_byte; one_byte = data[0]; data[0] = data[7]; data[7] = one_byte; one_byte = data[1]; data[1] = data[6]; data[6] = one_byte; one_byte = data[2]; data[2] = data[5]; data[5] = one_byte; one_byte = data[3]; data[3] = data[4]; data[4] = one_byte; } }; //---------------------------------------------------------------------------- // Define range swap functions. template <class T> inline void vtkByteSwapRange(T* first, size_t num) { // Swap one value at a time. T* last = first + num; for(T* p=first; p != last; ++p) { vtkByteSwapper<sizeof(T)>::Swap(reinterpret_cast<char*>(p)); } } inline bool vtkByteSwapRangeWrite(const char* first, size_t num, FILE* f, int) { // No need to swap segments of 1 byte. size_t status=fwrite(first, sizeof(char), static_cast<size_t>(num), f); return status==static_cast<size_t>(num); } inline bool vtkByteSwapRangeWrite(const signed char* first, size_t num, FILE* f, int) { // No need to swap segments of 1 byte. size_t status=fwrite(first, sizeof(signed char),static_cast<size_t>(num),f); return status==static_cast<size_t>(num); } inline bool vtkByteSwapRangeWrite(const unsigned char* first, size_t num, FILE* f, int) { // No need to swap segments of 1 byte. size_t status=fwrite(first,sizeof(unsigned char),static_cast<size_t>(num),f); return status==static_cast<size_t>(num); } template <class T> inline bool vtkByteSwapRangeWrite(const T* first, size_t num, FILE* f, long) { // Swap and write one value at a time. We do not need to do this in // blocks because the file stream is already buffered. const T* last = first + num; bool result=true; for(const T* p=first; p != last && result; ++p) { // Use a union to avoid breaking C++ aliasing rules. union { T value; char data[sizeof(T)]; } temp = {*p}; vtkByteSwapper<sizeof(T)>::Swap(temp.data); size_t status=fwrite(temp.data, sizeof(T), 1, f); result=status==1; } return result; } inline void vtkByteSwapRangeWrite(const char* first, size_t num, ostream* os, int) { // No need to swap segments of 1 byte. os->write(first, num*static_cast<size_t>(sizeof(char))); } inline void vtkByteSwapRangeWrite(const signed char* first, size_t num, ostream* os, int) { // No need to swap segments of 1 byte. os->write(reinterpret_cast<const char*>(first), num*static_cast<size_t>(sizeof(signed char))); } inline void vtkByteSwapRangeWrite(const unsigned char* first, size_t num, ostream* os, int) { // No need to swap segments of 1 byte. os->write(reinterpret_cast<const char*>(first), num*static_cast<size_t>(sizeof(unsigned char))); } template <class T> inline void vtkByteSwapRangeWrite(const T* first, size_t num, ostream* os, long) { // Swap and write one value at a time. We do not need to do this in // blocks because the file stream is already buffered. const T* last = first + num; for(const T* p=first; p != last; ++p) { // Use a union to avoid breaking C++ aliasing rules. union { T value; char data[sizeof(T)]; } temp = {*p}; vtkByteSwapper<sizeof(T)>::Swap(temp.data); os->write(temp.data, sizeof(T)); } } //---------------------------------------------------------------------------- // Define swap functions for each endian-ness. #if defined(VTK_WORDS_BIGENDIAN) template <class T> inline void vtkByteSwapBE(T*) {} template <class T> inline void vtkByteSwapBERange(T*, size_t) {} template <class T> inline bool vtkByteSwapBERangeWrite(const T* p, size_t num, FILE* f) { size_t status=fwrite(p, sizeof(T), static_cast<size_t>(num), f); return status==static_cast<size_t>(num); } template <class T> inline void vtkByteSwapBERangeWrite(const T* p, size_t num, ostream* os) { os->write((char*)p, sizeof(T)*num); } template <class T> inline void vtkByteSwapLE(T* p) { vtkByteSwapper<sizeof(T)>::Swap(reinterpret_cast<char*>(p)); } template <class T> inline void vtkByteSwapLERange(T* p, size_t num) { vtkByteSwapRange(p, num); } template <class T> inline bool vtkByteSwapLERangeWrite(const T* p, size_t num, FILE* f) { return vtkByteSwapRangeWrite(p, num, f, 1); } template <class T> inline void vtkByteSwapLERangeWrite(const T* p, size_t num, ostream* os) { vtkByteSwapRangeWrite(p, num, os, 1); } #else template <class T> inline void vtkByteSwapBE(T* p) { vtkByteSwapper<sizeof(T)>::Swap(reinterpret_cast<char*>(p)); } template <class T> inline void vtkByteSwapBERange(T* p, size_t num) { vtkByteSwapRange(p, num); } template <class T> inline bool vtkByteSwapBERangeWrite(const T* p, size_t num, FILE* f) { return vtkByteSwapRangeWrite(p, num, f, 1); } template <class T> inline void vtkByteSwapBERangeWrite(const T* p, size_t num, ostream* os) { vtkByteSwapRangeWrite(p, num, os, 1); } template <class T> inline void vtkByteSwapLE(T*) {} template <class T> inline void vtkByteSwapLERange(T*, size_t) {} template <class T> inline bool vtkByteSwapLERangeWrite(const T* p, size_t num, FILE* f) { size_t status=fwrite(p, sizeof(T), static_cast<size_t>(num), f); return status==static_cast<size_t>(num); } template <class T> inline void vtkByteSwapLERangeWrite(const T* p, size_t num, ostream* os) { os->write(reinterpret_cast<const char*>(p), static_cast<size_t>(sizeof(T))*num); } #endif //---------------------------------------------------------------------------- #define VTK_BYTE_SWAP_IMPL(T) \ void vtkByteSwap::SwapLE(T* p) { vtkByteSwapLE(p); } \ void vtkByteSwap::SwapBE(T* p) { vtkByteSwapBE(p); } \ void vtkByteSwap::SwapLERange(T* p, size_t num) \ { vtkByteSwapLERange(p, num); } \ void vtkByteSwap::SwapBERange(T* p, size_t num) \ { vtkByteSwapBERange(p, num); } \ bool vtkByteSwap::SwapLERangeWrite(const T* p, size_t num, FILE* file) \ { return vtkByteSwapLERangeWrite(p, num, file); } \ bool vtkByteSwap::SwapBERangeWrite(const T* p, size_t num, FILE* file) \ { return vtkByteSwapBERangeWrite(p, num, file); } \ void vtkByteSwap::SwapLERangeWrite(const T* p, size_t num, ostream* os) \ { vtkByteSwapLERangeWrite(p, num, os); } \ void vtkByteSwap::SwapBERangeWrite(const T* p, size_t num, ostream* os) \ { vtkByteSwapBERangeWrite(p, num, os); } VTK_BYTE_SWAP_IMPL(float) VTK_BYTE_SWAP_IMPL(double) VTK_BYTE_SWAP_IMPL(char) VTK_BYTE_SWAP_IMPL(short) VTK_BYTE_SWAP_IMPL(int) VTK_BYTE_SWAP_IMPL(long) VTK_BYTE_SWAP_IMPL(long long) VTK_BYTE_SWAP_IMPL(signed char) VTK_BYTE_SWAP_IMPL(unsigned char) VTK_BYTE_SWAP_IMPL(unsigned short) VTK_BYTE_SWAP_IMPL(unsigned int) VTK_BYTE_SWAP_IMPL(unsigned long) VTK_BYTE_SWAP_IMPL(unsigned long long) #undef VTK_BYTE_SWAP_IMPL #if VTK_SIZEOF_SHORT == 2 typedef short vtkByteSwapType2; #else # error "..." #endif #if VTK_SIZEOF_INT == 4 typedef int vtkByteSwapType4; #else # error "..." #endif #if VTK_SIZEOF_DOUBLE == 8 typedef double vtkByteSwapType8; #else # error "..." #endif //---------------------------------------------------------------------------- #define VTK_BYTE_SWAP_SIZE(S) \ void vtkByteSwap::Swap##S##LE(void* p) \ { vtkByteSwap::SwapLE(static_cast<vtkByteSwapType##S*>(p)); } \ void vtkByteSwap::Swap##S##BE(void* p) \ { vtkByteSwap::SwapBE(static_cast<vtkByteSwapType##S*>(p)); } \ void vtkByteSwap::Swap##S##LERange(void* p, size_t n) \ { vtkByteSwap::SwapLERange(static_cast<vtkByteSwapType##S*>(p), n); } \ void vtkByteSwap::Swap##S##BERange(void* p, size_t n) \ { vtkByteSwap::SwapBERange(static_cast<vtkByteSwapType##S*>(p), n); } \ bool vtkByteSwap::SwapWrite##S##LERange(void const* p, size_t n, FILE* f) \ { return vtkByteSwap::SwapLERangeWrite( \ static_cast<const vtkByteSwapType##S*>(p), n, f); } \ bool vtkByteSwap::SwapWrite##S##BERange(void const* p, size_t n, FILE* f) \ { return vtkByteSwap::SwapBERangeWrite( \ static_cast<const vtkByteSwapType##S*>(p), n, f); } \ void vtkByteSwap::SwapWrite##S##LERange(void const* p, size_t n, ostream* os) \ { vtkByteSwap::SwapLERangeWrite( \ static_cast<const vtkByteSwapType##S*>(p), n, os); } \ void vtkByteSwap::SwapWrite##S##BERange(void const* p, size_t n, ostream* os) \ { vtkByteSwap::SwapBERangeWrite( \ static_cast<const vtkByteSwapType##S*>(p), n, os); } VTK_BYTE_SWAP_SIZE(2) VTK_BYTE_SWAP_SIZE(4) VTK_BYTE_SWAP_SIZE(8) #undef VTK_BYTE_SWAP_SIZE //---------------------------------------------------------------------------- // Swaps the bytes of a buffer. Uses an arbitrary word size, but // assumes the word size is divisible by two. void vtkByteSwap::SwapVoidRange(void *buffer, size_t numWords, size_t wordSize) { unsigned char temp, *out, *buf; size_t idx1, idx2, inc, half; half = wordSize / 2; inc = wordSize - 1; buf = static_cast<unsigned char *>(buffer); for (idx1 = 0; idx1 < numWords; ++idx1) { out = buf + inc; for (idx2 = 0; idx2 < half; ++idx2) { temp = *out; *out = *buf; *buf = temp; ++buf; --out; } buf += half; } }
/** * Copyright (c) 2011, 2012 * Claudio Kopper <claudio.kopper@icecube.wisc.edu> * and the IceCube Collaboration <http://www.icecube.wisc.edu> * * Permission to use, copy, modify, and/or distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY * SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION * OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. * * * $Id: I3ExtraGeometryItemUnion.cxx 128624 2015-02-04 04:01:55Z claudio.kopper $ * * @file I3ExtraGeometryItemUnion.cxx * @version $Revision: 128624 $ * @date $Date: 2015-02-03 22:01:55 -0600 (Tue, 03 Feb 2015) $ * @author Claudio Kopper */ #include <limits> #include <icetray/serialization.h> #include <simclasses/I3ExtraGeometryItemUnion.h> #include <boost/foreach.hpp> I3ExtraGeometryItemUnion::I3ExtraGeometryItemUnion() : boundingBoxCalculated_(false) {;} I3ExtraGeometryItemUnion:: I3ExtraGeometryItemUnion(const std::vector<I3ExtraGeometryItemConstPtr> &elements) : elements_(elements), boundingBoxCalculated_(false) { } I3ExtraGeometryItemUnion::~I3ExtraGeometryItemUnion() { } void I3ExtraGeometryItemUnion::CalculateBoundingBox() const { if (boundingBoxCalculated_) return; double lowX=std::numeric_limits<double>::infinity(); double lowY=std::numeric_limits<double>::infinity(); double lowZ=std::numeric_limits<double>::infinity(); double highX=-std::numeric_limits<double>::infinity(); double highY=-std::numeric_limits<double>::infinity(); double highZ=-std::numeric_limits<double>::infinity(); BOOST_FOREACH(const I3ExtraGeometryItemConstPtr &ptr, elements_) { if (!ptr) continue; const std::pair<I3Position, I3Position> box = ptr->GetBoundingBox(); if (box.first.GetX() < lowX) lowX = box.first.GetX(); if (box.second.GetX() < lowX) lowX = box.second.GetX(); if (box.first.GetX() > highX) highX = box.first.GetX(); if (box.second.GetX() > highX) highX = box.second.GetX(); if (box.first.GetY() < lowY) lowY = box.first.GetY(); if (box.second.GetY() < lowY) lowY = box.second.GetY(); if (box.first.GetY() > highY) highY = box.first.GetY(); if (box.second.GetY() > highY) highY = box.second.GetY(); if (box.first.GetZ() < lowZ) lowZ = box.first.GetZ(); if (box.second.GetZ() < lowZ) lowZ = box.second.GetZ(); if (box.first.GetZ() > highZ) highZ = box.first.GetZ(); if (box.second.GetZ() > highZ) highZ = box.second.GetZ(); } boundingBoxLower_=I3Position(lowX, lowY, lowZ); boundingBoxUpper_=I3Position(highX, highY, highZ); boundingBoxCalculated_=true; } bool I3ExtraGeometryItemUnion::DoesLineIntersect (const I3Position &lineStart, const I3Position &lineEnd) const { BOOST_FOREACH(const I3ExtraGeometryItemConstPtr &ptr, elements_) { if (!ptr) continue; if (ptr->DoesLineIntersect(lineStart, lineEnd)) return true; } return false; } std::pair<I3Position, I3Position> I3ExtraGeometryItemUnion::GetBoundingBox () const { CalculateBoundingBox(); return std::make_pair(boundingBoxLower_, boundingBoxUpper_); } template <class Archive> void I3ExtraGeometryItemUnion::load(Archive &ar, unsigned version) { if (version > i3extrageometryitemunion_version_) log_fatal("Attempting to read version %u from file but running version %u of I3ExtraGeometryItem class.",version,i3extrageometryitemunion_version_); ar >> make_nvp("I3ExtraGeometryItem", base_object<I3ExtraGeometryItem>(*this)); { // work-around to allow de-serialization into vector<const ptr> std::vector<I3ExtraGeometryItemPtr> elements_non_const; ar >> make_nvp("elements", elements_non_const); BOOST_FOREACH(const I3ExtraGeometryItemPtr &item, elements_non_const) { elements_.push_back(item); } } } template <class Archive> void I3ExtraGeometryItemUnion::save(Archive &ar, unsigned version) const { ar << make_nvp("I3ExtraGeometryItem", base_object<I3ExtraGeometryItem>(*this)); ar << make_nvp("elements", elements_); } std::ostream& I3ExtraGeometryItemUnion::operator<<(std::ostream& oss) const { oss << "[ I3ExtraGeometryItemUnion :" << std::endl; // BOOST_FOREACH(const I3ExtraGeometryItemConstPtr &ptr, elements_) // { // oss << " -> subitem: (not impl yet)" << std::endl; // } oss << "]" << std::endl; return oss; } // TODO: the following line needs to go away once a more recent version of icetray makes it into a release: #include "split_serializable_backport.h" I3_SPLIT_SERIALIZABLE(I3ExtraGeometryItemUnion);
//<Snippet1> using namespace System; namespace Samples { [FlagsAttribute] public enum class Days { None = 0, Monday = 1, Tuesday = 2, Wednesday = 4, Thursday = 8, Friday = 16, All = Monday| Tuesday | Wednesday | Thursday | Friday }; } //</Snippet1>
// File include/oalplus/enums/source_state.ipp // // Automatically generated file, DO NOT modify manually. // Edit the source 'source/enums/oalplus/source_state.txt' // or the 'source/enums/make_enum.py' script instead. // // Copyright 2010-2015 Matus Chochlik. // Distributed under the Boost Software License, Version 1.0. // See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt // #if OALPLUS_DOCUMENTATION_ONLY /// INITIAL Initial, /// PLAYING Playing, /// PAUSED Paused, /// STOPPED Stopped #else // !OALPLUS_DOCUMENTATION_ONLY #include <oalplus/enums/source_state_def.ipp> #endif
#define __SPIN2CPP__ #include <propeller.h> #include "test135.h" void test135::Main(void) { int32_t Left[10]; Val = (( Defs.Doout(miscdefs::Left), 0 ) * 8) / 10; Val2 = miscdefs::Center; }
/** Copyright (c) 2015, Intel Corporation. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the Intel Corporation nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL INTEL CORPORATION BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include <cstring> #include <algorithm> #include "COO.hpp" #include "mm_io.h" using namespace std; namespace SpMP { COO::COO() : rowidx(NULL), colidx(NULL), values(NULL), isSymmetric(false) { } COO::~COO() { dealloc(); } void COO::dealloc() { FREE(rowidx); FREE(colidx); FREE(values); } void COO::storeMatrixMarket(const char *fileName) const { FILE *fp = fopen(fileName, "w"); assert(fp); MM_typecode matcode; mm_initialize_typecode(&matcode); mm_set_matrix(&matcode); mm_set_sparse(&matcode); mm_set_real(&matcode); int err = mm_write_mtx_crd( (char *)fileName, m, n, nnz, rowidx, colidx, values, matcode); if (err) { fprintf( stderr, "Fail to write matrix to %s (error code = %d)\n", fileName, err); exit(-1); } } template<class T> static void qsort(int *idx, T *w, int left, int right) { if (left >= right) return; swap(idx[left], idx[left + (right - left)/2]); swap(w[left], w[left + (right - left)/2]); int last = left; for (int i = left+1; i <= right; i++) { if (idx[i] < idx[left]) { ++last; swap(idx[last], idx[i]); swap(w[last], w[i]); } } swap(idx[left], idx[last]); swap(w[left], w[last]); qsort(idx, w, left, last-1); qsort(idx, w, last+1, right); } /* converts COO format to CSR format, not in-place, if SORT_IN_ROW is defined, each row is sorted in column index. assume COO is one-based index */ template<class T> void coo2csr( int m, int nnz, int *rowptr, int *colidx, T *values, const int *cooRowidx, const int *cooColidx, const T *cooValues, bool sort, int outBase = 0) { int i, l; #pragma omp parallel for for (i = 0; i <= m; i++) rowptr[i] = 0; /* determine row lengths */ for (i = 0; i < nnz; i++) rowptr[cooRowidx[i]]++; for (i = 0; i < m; i++) rowptr[i+1] += rowptr[i]; /* go through the structure once more. Fill in output matrix. */ for (l = 0; l < nnz; l++) { i = rowptr[cooRowidx[l] - 1]; values[i] = cooValues[l]; colidx[i] = cooColidx[l] - 1 + outBase; rowptr[cooRowidx[l] - 1]++; } /* shift back rowptr */ for (i = m; i > 0; i--) rowptr[i] = rowptr[i-1] + outBase; rowptr[0] = outBase; if (sort) { #pragma omp parallel for for (i=0; i < m; i++){ qsort(colidx, values, rowptr[i] - outBase, rowptr[i+1] - 1 - outBase); assert(is_sorted(colidx + rowptr[i] - outBase, colidx + rowptr[i+1] - outBase)); } } } void dcoo2csr( int m, int nnz, int *rowptr, int *colidx, double *values, const int *cooRowidx, const int *cooColidx, const double *cooValues, bool sort /*=true*/, int outBase /*=0*/) { coo2csr(m, nnz, rowptr, colidx, values, cooRowidx, cooColidx, cooValues, sort, outBase); } void dcoo2csr(CSR *Acrs, const COO *Acoo, int outBase /*=0*/, bool createSeparateDiagData /*= true*/) { Acrs->n=Acoo->n; Acrs->m=Acoo->m; dcoo2csr( Acrs->m, Acoo->nnz, Acrs->rowptr, Acrs->colidx, Acrs->values, Acoo->rowidx, Acoo->colidx, Acoo->values, true /*sort*/, outBase); int base = Acrs->getBase(); if (Acrs->diagptr) { if (!Acrs->idiag || !Acrs->diag) { createSeparateDiagData = false; } #pragma omp parallel for for (int i = 0; i < Acrs->m; ++i) { for (int j = Acrs->rowptr[i] - base; j < Acrs->rowptr[i + 1] - base; ++j) { if (Acrs->colidx[j] - base == i) { Acrs->diagptr[i] = j + base; if (createSeparateDiagData) { Acrs->idiag[i] = 1/Acrs->values[j]; Acrs->diag[i] = Acrs->values[j]; } } } } } } static bool loadMatrixMarket_(const char *file, COO &coo, bool force_symmetric, bool transpose, int pad) { FILE *fp=fopen(file, "r"); if (NULL == fp) { fprintf(stderr, "Failed to open file %s\n", file); exit(-1); } // read banner MM_typecode matcode; if (mm_read_banner (fp, &matcode) != 0) { fprintf(stderr, "Error: could not process Matrix Market banner.\n"); fclose(fp); return false; } if (!mm_is_valid (matcode) || mm_is_array (matcode) || mm_is_dense (matcode) ) { fprintf(stderr, "Error: only support sparse and real matrices.\n"); fclose(fp); return false; } bool pattern = mm_is_pattern (matcode); // read sizes int m, n; int nnz; // # of non-zeros specified in the file if (mm_read_mtx_crd_size(fp, &m, &n, &nnz) !=0) { fprintf(stderr, "Error: could not read matrix size.\n"); fclose(fp); return false; } if (transpose) { assert(!force_symmetric); swap(m, n); } int origM = m, origN = n; m = (m + pad - 1)/pad*pad; n = (n + pad - 1)/pad*pad; size_t count; if (force_symmetric || mm_is_symmetric (matcode) == 1) { coo.isSymmetric = true; count = 2L*nnz; } else { count = nnz; } // allocate memory size_t extraCount = min(m, n) - min(origM, origN); double *values = MALLOC(double, count + extraCount); int *colidx = MALLOC(int, count + extraCount); int *rowidx = MALLOC(int, count + extraCount); if (!values || !colidx || !rowidx) { fprintf(stderr, "Failed to allocate memory\n"); fclose(fp); return false; } int *colidx_temp, *rowcnt = NULL; if (coo.isSymmetric) { colidx_temp = MALLOC(int, count); rowcnt = MALLOC(int, m + 1); if (!colidx_temp || !rowcnt) { fprintf(stderr, "Failed to allocate memory\n"); fclose(fp); return false; } memset(rowcnt, 0, sizeof(int)*(m + 1)); } // read values count = 0; int lines = 0; int x, y; double real, imag; int base = 1; while (mm_read_mtx_crd_entry (fp, &x, &y, &real, &imag, matcode) == 0) { if (transpose) swap(x, y); if (x > origM || y > origN) { fprintf(stderr, "Error: (%d %d) coordinate is out of range.\n", x, y); fclose(fp); return false; } rowidx[count] = x; colidx[count] = y; values[count] = pattern ? 1 : real; if (0 == x || 0 == y) base = 0; ++count; ++lines; if (coo.isSymmetric) rowcnt[x]++; // this is not a bug. we're intentionally indexing rowcnt[x] instead of rowcnt[x-1] } // padding for vectorization for (int i = min(origM, origN); i < min(m, n); ++i) { rowidx[count] = i + 1; colidx[count] = i + 1; values[count] = 1; ++count; } fclose(fp); if (0 == base) { for (int i = 0; i < count; ++i) { rowidx[i]++; colidx[i]++; } if (coo.isSymmetric) { for (int i = m; i > 0; --i) { rowcnt[i] = rowcnt[i - 1]; } } } if (lines != nnz) { fprintf(stderr, "Error: nnz (%d) specified in the header doesn't match with # of lines (%d) in file %s\n", nnz, lines, file); return false; } if (coo.isSymmetric) { // add transposed elements only if it doesn't exist size_t real_count = count; // preix-sum for (int i = 0; i < m; ++i) { rowcnt[i + 1] += rowcnt[i]; } for (int i = 0; i < count; ++i) { int j = rowcnt[rowidx[i] - 1]; colidx_temp[j] = colidx[i]; rowcnt[rowidx[i] - 1]++; } for (int i = m; i > 0; --i) { rowcnt[i] = rowcnt[i - 1]; } rowcnt[0] = 0; #pragma omp parallel for for (int i = 0; i < m; ++i) { sort(colidx_temp + rowcnt[i], colidx_temp + rowcnt[i + 1]); } for (int i = 0; i < count; ++i) { int x = rowidx[i], y = colidx[i]; if (x != y) { if (!binary_search( colidx_temp + rowcnt[y - 1], colidx_temp + rowcnt[y], x)) { rowidx[real_count] = y; colidx[real_count] = x; values[real_count] = values[i]; ++real_count; } } } count = real_count; FREE(rowcnt); FREE(colidx_temp); } coo.m = m; coo.n = n; coo.nnz = count; coo.dealloc(); coo.values = values; coo.colidx = colidx; coo.rowidx = rowidx; return true; } bool loadMatrixMarketTransposed(const char *file, COO &coo, int pad /*= 1*/) { return loadMatrixMarket_(file, coo, false, true /*transpose*/, pad); } bool loadMatrixMarket (const char *file, COO &coo, bool force_symmetric /*=false*/, int pad /*=1*/) { return loadMatrixMarket_(file, coo, force_symmetric, false /*no-transpose*/, pad); } } // namespace SpMP
//===--------------------------------------------------------------------------------*- C++ -*-===// // _ // | | // __| | __ ___ ___ ___ // / _` |/ _` \ \ /\ / / '_ | // | (_| | (_| |\ V V /| | | | // \__,_|\__,_| \_/\_/ |_| |_| - Compiler Toolchain // // // This file is distributed under the MIT License (MIT). // See LICENSE.txt for details. // //===------------------------------------------------------------------------------------------===// #include "dawn/Compiler/DawnCompiler.h" #include "dawn/Compiler/Options.h" #include "dawn/IIR/IIR.h" #include "dawn/IIR/StencilInstantiation.h" #include "dawn/SIR/SIR.h" #include "dawn/Serialization/SIRSerializer.h" #include "test/unit-test/dawn/Optimizer/TestEnvironment.h" #include <fstream> #include <gtest/gtest.h> #include <streambuf> using namespace dawn; namespace { class ComputeMaxExtents : public ::testing::Test { dawn::DawnCompiler compiler_; protected: virtual void SetUp() {} const std::shared_ptr<iir::StencilInstantiation> loadTest(std::string sirFilename) { std::string filename = TestEnvironment::path_ + "/" + sirFilename; std::ifstream file(filename); DAWN_ASSERT_MSG((file.good()), std::string("File " + filename + " does not exists").c_str()); std::string jsonstr((std::istreambuf_iterator<char>(file)), std::istreambuf_iterator<char>()); std::shared_ptr<SIR> sir = SIRSerializer::deserializeFromString(jsonstr, SIRSerializer::Format::Json); std::unique_ptr<OptimizerContext> optimizer = compiler_.runOptimizer(sir); // Report diganostics if(compiler_.getDiagnostics().hasDiags()) { for(const auto& diag : compiler_.getDiagnostics().getQueue()) std::cerr << "Compilation Error " << diag->getMessage() << std::endl; throw std::runtime_error("compilation failed"); } DAWN_ASSERT_MSG((optimizer->getStencilInstantiationMap().count("compute_extent_test_stencil")), "compute_extent_test_stencil not found in sir"); return optimizer->getStencilInstantiationMap()["compute_extent_test_stencil"]; } }; TEST_F(ComputeMaxExtents, test_stencil_01) { const std::shared_ptr<iir::StencilInstantiation>& instantiation = loadTest("compute_extent_test_stencil_01.sir"); const auto& metadata = instantiation->getMetaData(); const std::unique_ptr<iir::IIR>& IIR = instantiation->getIIR(); const auto& stencils = IIR->getChildren(); ASSERT_TRUE((stencils.size() == 1)); const std::unique_ptr<iir::Stencil>& stencil = stencils[0]; ASSERT_TRUE((stencil->getNumStages() == 2)); auto exts = stencil->getFields(); EXPECT_EQ(exts.size(), 3); int u_id = metadata.getAccessIDFromName("u"); int out_id = metadata.getAccessIDFromName("out"); int lap_id = metadata.getAccessIDFromName("lap"); EXPECT_EQ(exts.at(u_id).field.getExtentsRB(), (iir::Extents(dawn::ast::cartesian, -2, 2, -2, 2, 0, 0))); EXPECT_EQ(exts.at(out_id).field.getExtentsRB(), (iir::Extents(dawn::ast::cartesian, 0, 0, 0, 0, 0, 0))); EXPECT_EQ(exts.at(lap_id).field.getExtentsRB(), (iir::Extents(dawn::ast::cartesian, -1, 1, -1, 1, 0, 0))); } TEST_F(ComputeMaxExtents, test_stencil_02) { const std::shared_ptr<iir::StencilInstantiation>& instantiation = loadTest("compute_extent_test_stencil_02.sir"); const auto& metadata = instantiation->getMetaData(); const std::unique_ptr<iir::IIR>& IIR = instantiation->getIIR(); const auto& stencils = IIR->getChildren(); ASSERT_TRUE((stencils.size() == 1)); const std::unique_ptr<iir::Stencil>& stencil = stencils[0]; ASSERT_TRUE((stencil->getNumStages() == 3)); auto exts = stencil->getFields(); EXPECT_EQ(exts.size(), 6); int u_id = metadata.getAccessIDFromName("u"); int out_id = metadata.getAccessIDFromName("out"); int coeff_id = metadata.getAccessIDFromName("coeff"); EXPECT_EQ(exts.at(u_id).field.getExtentsRB(), (iir::Extents(dawn::ast::cartesian, -2, 2, -2, 2, 0, 0))); EXPECT_EQ(exts.at(out_id).field.getExtentsRB(), (iir::Extents(dawn::ast::cartesian, 0, 0, 0, 0, 0, 0))); EXPECT_EQ(exts.at(coeff_id).field.getExtentsRB(), (iir::Extents(dawn::ast::cartesian, 0, 0, 0, 0, 0, 0))); } TEST_F(ComputeMaxExtents, test_stencil_03) { const std::shared_ptr<iir::StencilInstantiation>& instantiation = loadTest("compute_extent_test_stencil_03.sir"); const auto& metadata = instantiation->getMetaData(); const std::unique_ptr<iir::IIR>& IIR = instantiation->getIIR(); const auto& stencils = IIR->getChildren(); ASSERT_TRUE((stencils.size() == 1)); const std::unique_ptr<iir::Stencil>& stencil = stencils[0]; ASSERT_TRUE((stencil->getNumStages() == 4)); auto exts = stencil->getFields(); EXPECT_EQ(exts.size(), 7); int u_id = metadata.getAccessIDFromName("u"); int out_id = metadata.getAccessIDFromName("out"); int coeff_id = metadata.getAccessIDFromName("coeff"); EXPECT_EQ(exts.at(u_id).field.getExtentsRB(), (iir::Extents(dawn::ast::cartesian, -2, 2, -2, 3, 0, 0))); EXPECT_EQ(exts.at(out_id).field.getExtentsRB(), (iir::Extents(dawn::ast::cartesian, 0, 0, 0, 0, 0, 0))); EXPECT_EQ(exts.at(coeff_id).field.getExtentsRB(), (iir::Extents(dawn::ast::cartesian, 0, 0, 0, 1, 0, 0))); } TEST_F(ComputeMaxExtents, test_stencil_04) { const std::shared_ptr<iir::StencilInstantiation>& instantiation = loadTest("compute_extent_test_stencil_04.sir"); const auto& metadata = instantiation->getMetaData(); const std::unique_ptr<iir::IIR>& IIR = instantiation->getIIR(); const auto& stencils = IIR->getChildren(); ASSERT_TRUE((stencils.size() == 1)); const std::unique_ptr<iir::Stencil>& stencil = stencils[0]; ASSERT_TRUE((stencil->getNumStages() == 4)); auto exts = stencil->getFields(); EXPECT_EQ(exts.size(), 6); int u_id = metadata.getAccessIDFromName("u"); int out_id = metadata.getAccessIDFromName("out"); EXPECT_EQ(exts.at(u_id).field.getExtentsRB(), (iir::Extents(dawn::ast::cartesian, -3, 4, -2, 1, 0, 0))); EXPECT_EQ(exts.at(out_id).field.getExtentsRB(), (iir::Extents(dawn::ast::cartesian, 0, 0, 0, 0, 0, 0))); } TEST_F(ComputeMaxExtents, test_stencil_05) { const std::shared_ptr<iir::StencilInstantiation>& instantiation = loadTest("compute_extent_test_stencil_05.sir"); const auto& metadata = instantiation->getMetaData(); const std::unique_ptr<iir::IIR>& IIR = instantiation->getIIR(); const auto& stencils = IIR->getChildren(); ASSERT_TRUE((stencils.size() == 1)); const std::unique_ptr<iir::Stencil>& stencil = stencils[0]; ASSERT_TRUE((stencil->getNumStages() == 4)); auto exts = stencil->getFields(); EXPECT_EQ(exts.size(), 6); int u_id = metadata.getAccessIDFromName("u"); int out_id = metadata.getAccessIDFromName("out"); EXPECT_EQ(exts.at(u_id).field.getExtentsRB(), (iir::Extents(dawn::ast::cartesian, -3, 4, -2, 1, 0, 0))); EXPECT_EQ(exts.at(out_id).field.getExtentsRB(), (iir::Extents(dawn::ast::cartesian, 0, 0, 0, 0, 0, 0))); } } // anonymous namespace
#include "ShaderBase.h" #include "DxUtils/D3DHelper.hpp" bool ShaderBase::Initialize() { DWORD m_dwShaderFlag = D3DCOMPILE_ENABLE_STRICTNESS; #if defined(DEBUG) || defined(_DEBUG) m_dwShaderFlag |= D3DCOMPILE_DEBUG; #endif // DEBUG ID3DBlob* pShaderBuffer = nullptr; ID3DBlob* pErrorBuffer = nullptr; auto hResult = D3DCompileFromFile( this->GetShaderFile().c_str(), nullptr, nullptr, GetShaderEntryName().c_str(), GetShaderVersion().c_str(), m_dwShaderFlag, 0, &pShaderBuffer, &pErrorBuffer ); if (pErrorBuffer) { // OutputDebugStringA(static_cast<char*>(pErrorBuffer->GetBufferPointer())); ::MessageBoxA(nullptr, static_cast<char*>(pErrorBuffer->GetBufferPointer()), "Shader Msg", 0); goto failed_exit; } if (FAILED(hResult)) { goto failed_exit; } if (!CreateShader(pShaderBuffer)) { goto failed_exit; } if (!DefineShaderSubResource()) { goto failed_exit; } D3DHelper::SafeRelease(pShaderBuffer); D3DHelper::SafeRelease(pErrorBuffer); return true; failed_exit: D3DHelper::SafeRelease(pShaderBuffer); D3DHelper::SafeRelease(pErrorBuffer); assert(false); return false; }
/****************************************************************************** * The MIT License (MIT) * * Copyright (c) 2019-2020 Baldur Karlsson * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. ******************************************************************************/ #include "TextureViewer.h" #include <float.h> #include <math.h> #include <QClipboard> #include <QColorDialog> #include <QFileSystemWatcher> #include <QFontDatabase> #include <QItemDelegate> #include <QJsonDocument> #include <QMenu> #include <QPainter> #include <QPointer> #include <QStyledItemDelegate> #include "Code/QRDUtils.h" #include "Code/Resources.h" #include "Dialogs/TextureSaveDialog.h" #include "Widgets/ResourcePreview.h" #include "Widgets/TextureGoto.h" #include "flowlayout/FlowLayout.h" #include "toolwindowmanager/ToolWindowManagerArea.h" #include "ui_TextureViewer.h" float area(const QSizeF &s) { return s.width() * s.height(); } float aspect(const QSizeF &s) { return s.width() / s.height(); } static QMap<QString, ShaderEncoding> encodingExtensions = { {lit("hlsl"), ShaderEncoding::HLSL}, {lit("glsl"), ShaderEncoding::GLSL}, {lit("frag"), ShaderEncoding::GLSL}, {lit("spvasm"), ShaderEncoding::SPIRVAsm}, }; Q_DECLARE_METATYPE(Following); const Following Following::Default = Following(); Following::Following(FollowType t, ShaderStage s, int i, int a) { Type = t; Stage = s; index = i; arrayEl = a; readOnlyResources = NULL; readWriteResources = NULL; } Following::Following() { Type = FollowType::OutputColour; Stage = ShaderStage::Pixel; index = 0; arrayEl = 0; readOnlyResources = NULL; readWriteResources = NULL; } bool Following::operator!=(const Following &o) { return !(*this == o); } bool Following::operator==(const Following &o) { return Type == o.Type && Stage == o.Stage && index == o.index; } void Following::GetDrawContext(ICaptureContext &ctx, bool &copy, bool &clear, bool &compute) { const DrawcallDescription *curDraw = ctx.CurDrawcall(); copy = curDraw != NULL && (curDraw->flags & (DrawFlags::Copy | DrawFlags::Resolve | DrawFlags::Present)); clear = curDraw != NULL && (curDraw->flags & DrawFlags::Clear); compute = curDraw != NULL && (curDraw->flags & DrawFlags::Dispatch) && ctx.CurPipelineState().GetShader(ShaderStage::Compute) != ResourceId(); } void Following::SetResources(const rdcarray<BoundResourceArray> &readOnly, const rdcarray<BoundResourceArray> &readWrite) { readOnlyResources = &readOnly; readWriteResources = &readWrite; } int Following::GetHighestMip(ICaptureContext &ctx) { return GetBoundResource(ctx, arrayEl).firstMip; } int Following::GetFirstArraySlice(ICaptureContext &ctx) { return GetBoundResource(ctx, arrayEl).firstSlice; } CompType Following::GetTypeHint(ICaptureContext &ctx) { return GetBoundResource(ctx, arrayEl).typeCast; } ResourceId Following::GetResourceId(ICaptureContext &ctx) { return GetBoundResource(ctx, arrayEl).resourceId; } BoundResource Following::GetBoundResource(ICaptureContext &ctx, int arrayIdx) { BoundResource ret; if(Type == FollowType::OutputColour) { rdcarray<BoundResource> outputs = GetOutputTargets(ctx); if(index < outputs.count()) ret = outputs[index]; } else if(Type == FollowType::OutputDepth) { ret = GetDepthTarget(ctx); } else if(Type == FollowType::ReadWrite) { const rdcarray<BoundResourceArray> &rw = (readWriteResources != NULL) ? *readWriteResources : GetReadWriteResources(ctx); ShaderBindpointMapping mapping = GetMapping(ctx); if(index < mapping.readWriteResources.count()) { Bindpoint &key = mapping.readWriteResources[index]; int residx = rw.indexOf(key); if(residx >= 0) ret = rw[residx].resources[arrayIdx]; } } else if(Type == FollowType::ReadOnly) { const rdcarray<BoundResourceArray> &ro = (readOnlyResources != NULL) ? *readOnlyResources : GetReadOnlyResources(ctx); ShaderBindpointMapping mapping = GetMapping(ctx); if(index < mapping.readOnlyResources.count()) { Bindpoint &key = mapping.readOnlyResources[index]; int residx = ro.indexOf(key); if(residx >= 0) ret = ro[residx].resources[arrayIdx]; } } return ret; } rdcarray<BoundResource> Following::GetOutputTargets(ICaptureContext &ctx) { const DrawcallDescription *curDraw = ctx.CurDrawcall(); bool copy = false, clear = false, compute = false; GetDrawContext(ctx, copy, clear, compute); if(copy || clear) { return {BoundResource(curDraw->copyDestination, curDraw->copyDestinationSubresource)}; } else if(compute) { return {}; } else { rdcarray<BoundResource> ret = ctx.CurPipelineState().GetOutputTargets(); if(ret.isEmpty() && curDraw != NULL && (curDraw->flags & DrawFlags::Present)) { if(curDraw->copyDestination != ResourceId()) return {BoundResource(curDraw->copyDestination, curDraw->copyDestinationSubresource)}; for(const TextureDescription &tex : ctx.GetTextures()) { if(tex.creationFlags & TextureCategory::SwapBuffer) return {BoundResource(tex.resourceId)}; } } return ret; } } BoundResource Following::GetDepthTarget(ICaptureContext &ctx) { bool copy = false, clear = false, compute = false; GetDrawContext(ctx, copy, clear, compute); if(copy || clear || compute) return BoundResource(ResourceId()); else return ctx.CurPipelineState().GetDepthTarget(); } rdcarray<BoundResourceArray> Following::GetReadWriteResources(ICaptureContext &ctx, ShaderStage stage) { bool copy = false, clear = false, compute = false; GetDrawContext(ctx, copy, clear, compute); if(copy || clear) { return rdcarray<BoundResourceArray>(); } else if(compute) { // only return compute resources for one stage if(stage == ShaderStage::Pixel || stage == ShaderStage::Compute) return ctx.CurPipelineState().GetReadWriteResources(ShaderStage::Compute); else return rdcarray<BoundResourceArray>(); } else { return ctx.CurPipelineState().GetReadWriteResources(stage); } } rdcarray<BoundResourceArray> Following::GetReadWriteResources(ICaptureContext &ctx) { return GetReadWriteResources(ctx, Stage); } rdcarray<BoundResourceArray> Following::GetReadOnlyResources(ICaptureContext &ctx, ShaderStage stage) { const DrawcallDescription *curDraw = ctx.CurDrawcall(); bool copy = false, clear = false, compute = false; GetDrawContext(ctx, copy, clear, compute); if(copy || clear) { rdcarray<BoundResourceArray> ret; // only return copy source for one stage if(copy && stage == ShaderStage::Pixel) ret.push_back(BoundResourceArray( Bindpoint(0, 0), {BoundResource(curDraw->copySource, curDraw->copySourceSubresource)})); return ret; } else if(compute) { // only return compute resources for one stage if(stage == ShaderStage::Pixel || stage == ShaderStage::Compute) return ctx.CurPipelineState().GetReadOnlyResources(ShaderStage::Compute); else return rdcarray<BoundResourceArray>(); } else { return ctx.CurPipelineState().GetReadOnlyResources(stage); } } rdcarray<BoundResourceArray> Following::GetReadOnlyResources(ICaptureContext &ctx) { return GetReadOnlyResources(ctx, Stage); } const ShaderReflection *Following::GetReflection(ICaptureContext &ctx, ShaderStage stage) { bool copy = false, clear = false, compute = false; GetDrawContext(ctx, copy, clear, compute); if(copy || clear) return NULL; else if(compute) return ctx.CurPipelineState().GetShaderReflection(ShaderStage::Compute); else return ctx.CurPipelineState().GetShaderReflection(stage); } const ShaderReflection *Following::GetReflection(ICaptureContext &ctx) { return GetReflection(ctx, Stage); } const ShaderBindpointMapping &Following::GetMapping(ICaptureContext &ctx, ShaderStage stage) { bool copy = false, clear = false, compute = false; GetDrawContext(ctx, copy, clear, compute); if(copy || clear) { static ShaderBindpointMapping mapping; // for PS only add a single mapping to get the copy source if(copy && stage == ShaderStage::Pixel) mapping.readOnlyResources = {Bindpoint(0, 0)}; else mapping.readOnlyResources.clear(); return mapping; } else if(compute) { return ctx.CurPipelineState().GetBindpointMapping(ShaderStage::Compute); } else { return ctx.CurPipelineState().GetBindpointMapping(stage); } } const ShaderBindpointMapping &Following::GetMapping(ICaptureContext &ctx) { return GetMapping(ctx, Stage); } class TextureListItemModel : public QAbstractItemModel { public: enum FilterType { Textures, RenderTargets, String }; TextureListItemModel(ICaptureContext &ctx, QWidget *parent) : QAbstractItemModel(parent), m_Ctx(ctx) { goArrow.addPixmap(Pixmaps::action(parent), QIcon::Normal, QIcon::Off); goArrow.addPixmap(Pixmaps::action_hover(parent), QIcon::Normal, QIcon::Off); } void reset(FilterType type, const QString &filter) { const rdcarray<TextureDescription> src = m_Ctx.GetTextures(); texs.clear(); texs.reserve(src.count()); emit beginResetModel(); TextureCategory rtFlags = TextureCategory::ColorTarget | TextureCategory::DepthTarget; for(const TextureDescription &t : src) { if(type == Textures) { if(!(t.creationFlags & rtFlags)) texs.push_back(t); } else if(type == RenderTargets) { if((t.creationFlags & rtFlags)) texs.push_back(t); } else { if(filter.isEmpty()) texs.push_back(t); else if(QString(m_Ctx.GetResourceName(t.resourceId)).contains(filter, Qt::CaseInsensitive)) texs.push_back(t); } } emit endResetModel(); } QModelIndex index(int row, int column, const QModelIndex &parent = QModelIndex()) const override { if(row < 0 || row >= rowCount()) return QModelIndex(); return createIndex(row, 0); } QModelIndex parent(const QModelIndex &index) const override { return QModelIndex(); } int rowCount(const QModelIndex &parent = QModelIndex()) const override { return texs.count(); } int columnCount(const QModelIndex &parent = QModelIndex()) const override { return 1; } Qt::ItemFlags flags(const QModelIndex &index) const override { if(!index.isValid()) return 0; return QAbstractItemModel::flags(index); } QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const override { if(index.isValid()) { if(role == Qt::DisplayRole) { if(index.row() >= 0 && index.row() < texs.count()) return m_Ctx.GetResourceName(texs[index.row()].resourceId); } if(role == Qt::UserRole) { return QVariant::fromValue(texs[index.row()].resourceId); } if(role == Qt::DecorationRole) { return QVariant(goArrow); } } return QVariant(); } private: ICaptureContext &m_Ctx; QVector<TextureDescription> texs; QIcon goArrow; }; class TextureListItemDelegate : public QItemDelegate { public: TextureListItemDelegate(QObject *parent = 0) : QItemDelegate(parent) {} void paint(QPainter *painter, const QStyleOptionViewItem &opt, const QModelIndex &index) const override { if(index.isValid()) { QStyleOptionViewItem option = opt; option.decorationAlignment = Qt::AlignBaseline | Qt::AlignRight; painter->eraseRect(option.rect); QIcon icon = index.model()->data(index, Qt::DecorationRole).value<QIcon>(); drawBackground(painter, option, index); if(option.state & QStyle::State_MouseOver) drawDecoration(painter, option, option.rect, icon.pixmap(option.decorationSize, QIcon::Active)); else drawDecoration(painter, option, option.rect, icon.pixmap(option.decorationSize, QIcon::Normal)); drawDisplay(painter, option, option.rect, index.model()->data(index, Qt::DisplayRole).toString()); drawFocus(painter, option, option.rect); if(option.state & QStyle::State_MouseOver) { QRect r = option.rect; r.adjust(0, 0, -1, -1); painter->drawRect(r); } } } }; TextureDescription *TextureViewer::GetCurrentTexture() { return m_CachedTexture; } void TextureViewer::UI_UpdateCachedTexture() { if(!m_Ctx.IsCaptureLoaded()) { m_CachedTexture = NULL; return; } ResourceId id = m_LockedId; if(id == ResourceId()) id = m_Following.GetResourceId(m_Ctx); if(id == ResourceId()) id = m_TexDisplay.resourceId; m_CachedTexture = m_Ctx.GetTexture(id); if(m_CachedTexture != NULL) { if(m_Ctx.APIProps().shaderDebugging) { const ShaderReflection *shaderDetails = m_Ctx.CurPipelineState().GetShaderReflection(ShaderStage::Pixel); if(!m_Ctx.CurDrawcall() || !(m_Ctx.CurDrawcall()->flags & DrawFlags::Drawcall)) { ui->debugPixelContext->setEnabled(false); ui->debugPixelContext->setToolTip(tr("No draw call selected")); } else if(!shaderDetails) { ui->debugPixelContext->setEnabled(false); ui->debugPixelContext->setToolTip(tr("No pixel shader bound")); } else if(!shaderDetails->debugInfo.debuggable) { ui->debugPixelContext->setEnabled(false); ui->debugPixelContext->setToolTip( tr("The current pixel shader does not support debugging: %1") .arg(shaderDetails->debugInfo.debugStatus)); } else { ui->debugPixelContext->setEnabled(true); ui->debugPixelContext->setToolTip(QString()); } } else { ui->debugPixelContext->setEnabled(false); ui->debugPixelContext->setToolTip(tr("Shader Debugging not supported on this API")); } if(m_Ctx.APIProps().pixelHistory) { ui->pixelHistory->setEnabled(true); ui->pixelHistory->setToolTip(QString()); } else { ui->pixelHistory->setEnabled(false); ui->pixelHistory->setToolTip(tr("Pixel History not supported on this API")); } } else { ui->debugPixelContext->setEnabled(false); ui->debugPixelContext->setToolTip(tr("No active texture selected")); ui->pixelHistory->setEnabled(false); ui->pixelHistory->setToolTip(tr("No active texture selected")); } } TextureViewer::TextureViewer(ICaptureContext &ctx, QWidget *parent) : QFrame(parent), ui(new Ui::TextureViewer), m_Ctx(ctx) { ui->setupUi(this); ui->textureList->setFont(Formatter::PreferredFont()); ui->textureListFilter->setFont(Formatter::PreferredFont()); ui->rangeBlack->setFont(Formatter::PreferredFont()); ui->rangeWhite->setFont(Formatter::PreferredFont()); ui->hdrMul->setFont(Formatter::PreferredFont()); ui->channels->setFont(Formatter::PreferredFont()); ui->mipLevel->setFont(Formatter::PreferredFont()); ui->sliceFace->setFont(Formatter::PreferredFont()); ui->zoomOption->setFont(Formatter::PreferredFont()); Reset(); on_checkerBack_clicked(); QObject::connect(ui->zoomOption->lineEdit(), &QLineEdit::returnPressed, this, &TextureViewer::zoomOption_returnPressed); QObject::connect(ui->depthDisplay, &QToolButton::toggled, this, &TextureViewer::channelsWidget_toggled); QObject::connect(ui->stencilDisplay, &QToolButton::toggled, this, &TextureViewer::channelsWidget_toggled); QObject::connect(ui->flip_y, &QToolButton::toggled, this, &TextureViewer::channelsWidget_toggled); QObject::connect(ui->gammaDisplay, &QToolButton::toggled, this, &TextureViewer::channelsWidget_toggled); QObject::connect(ui->channels, OverloadedSlot<int>::of(&QComboBox::currentIndexChanged), this, &TextureViewer::channelsWidget_selected); QObject::connect(ui->hdrMul, OverloadedSlot<int>::of(&QComboBox::currentIndexChanged), this, &TextureViewer::channelsWidget_selected); QObject::connect(ui->hdrMul, &QComboBox::currentTextChanged, [this] { UI_UpdateChannels(); }); QObject::connect(ui->customShader, OverloadedSlot<int>::of(&QComboBox::currentIndexChanged), this, &TextureViewer::channelsWidget_selected); QObject::connect(ui->customShader, &QComboBox::currentTextChanged, [this] { UI_UpdateChannels(); }); QObject::connect(ui->rangeHistogram, &RangeHistogram::rangeUpdated, this, &TextureViewer::range_rangeUpdated); QObject::connect(ui->rangeBlack, &RDLineEdit::textChanged, this, &TextureViewer::rangePoint_textChanged); QObject::connect(ui->rangeBlack, &RDLineEdit::leave, this, &TextureViewer::rangePoint_leave); QObject::connect(ui->rangeBlack, &RDLineEdit::keyPress, this, &TextureViewer::rangePoint_keyPress); QObject::connect(ui->rangeWhite, &RDLineEdit::textChanged, this, &TextureViewer::rangePoint_textChanged); QObject::connect(ui->rangeWhite, &RDLineEdit::leave, this, &TextureViewer::rangePoint_leave); QObject::connect(ui->rangeWhite, &RDLineEdit::keyPress, this, &TextureViewer::rangePoint_keyPress); for(RDToolButton *butt : {ui->channelRed, ui->channelGreen, ui->channelBlue, ui->channelAlpha}) { QObject::connect(butt, &RDToolButton::toggled, this, &TextureViewer::channelsWidget_toggled); QObject::connect(butt, &RDToolButton::mouseClicked, this, &TextureViewer::channelsWidget_mouseClicked); QObject::connect(butt, &RDToolButton::doubleClicked, this, &TextureViewer::channelsWidget_mouseClicked); } { QMenu *extensionsMenu = new QMenu(this); ui->extensions->setMenu(extensionsMenu); ui->extensions->setPopupMode(QToolButton::InstantPopup); QObject::connect(extensionsMenu, &QMenu::aboutToShow, [this, extensionsMenu]() { extensionsMenu->clear(); m_Ctx.Extensions().MenuDisplaying(PanelMenu::TextureViewer, extensionsMenu, ui->extensions, {}); }); } QWidget *renderContainer = ui->renderContainer; ui->dockarea->addToolWindow(ui->renderContainer, ToolWindowManager::EmptySpace); ui->dockarea->setToolWindowProperties( renderContainer, ToolWindowManager::DisallowUserDocking | ToolWindowManager::HideCloseButton | ToolWindowManager::DisableDraggableTab | ToolWindowManager::AlwaysDisplayFullTabs); ui->dockarea->addToolWindow(ui->inputThumbs, ToolWindowManager::AreaReference( ToolWindowManager::RightOf, ui->dockarea->areaOf(renderContainer), 0.25f)); ui->dockarea->setToolWindowProperties(ui->inputThumbs, ToolWindowManager::HideCloseButton); ui->dockarea->addToolWindow( ui->outputThumbs, ToolWindowManager::AreaReference(ToolWindowManager::AddTo, ui->dockarea->areaOf(ui->inputThumbs))); ui->dockarea->setToolWindowProperties(ui->outputThumbs, ToolWindowManager::HideCloseButton); ui->dockarea->addToolWindow( ui->pixelContextLayout, ToolWindowManager::AreaReference(ToolWindowManager::BottomOf, ui->dockarea->areaOf(ui->outputThumbs), 0.25f)); ui->dockarea->setToolWindowProperties(ui->pixelContextLayout, ToolWindowManager::HideCloseButton); ui->dockarea->addToolWindow(ui->textureListFrame, ToolWindowManager::NoArea); ui->dockarea->setToolWindowProperties(ui->textureListFrame, ToolWindowManager::HideOnClose); ui->dockarea->setAllowFloatingWindow(false); renderContainer->setWindowTitle(tr("Unbound")); ui->pixelContextLayout->setWindowTitle(tr("Pixel Context")); ui->outputThumbs->setWindowTitle(tr("Outputs")); ui->inputThumbs->setWindowTitle(tr("Inputs")); ui->textureListFrame->setWindowTitle(tr("Texture List")); ui->textureList->setHoverCursor(Qt::PointingHandCursor); m_Goto = new TextureGoto(this, [this](QPoint p) { GotoLocation(p.x(), p.y()); }); QVBoxLayout *vertical = new QVBoxLayout(this); vertical->setSpacing(3); vertical->setContentsMargins(3, 3, 3, 3); QWidget *flow1widget = new QWidget(this); QWidget *flow2widget = new QWidget(this); FlowLayout *flow1 = new FlowLayout(flow1widget, 0, 3, 3); FlowLayout *flow2 = new FlowLayout(flow2widget, 0, 3, 3); flow1widget->setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Minimum); flow2widget->setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Minimum); flow1->addWidget(ui->channelsToolbar); flow1->addWidget(ui->subresourceToolbar); flow1->addWidget(ui->actionToolbar); flow2->addWidget(ui->zoomToolbar); flow2->addWidget(ui->overlayToolbar); flow2->addWidget(ui->rangeToolbar); vertical->addWidget(flow1widget); vertical->addWidget(flow2widget); vertical->addWidget(ui->dockarea); Ui_TextureViewer *u = ui; u->pixelcontextgrid->setAlignment(u->pixelHistory, Qt::AlignCenter); u->pixelcontextgrid->setAlignment(u->debugPixelContext, Qt::AlignCenter); QWidget *statusflowWidget = new QWidget(this); ui->statusbar->removeWidget(ui->texStatusName); ui->statusbar->removeWidget(ui->texStatusDim); ui->statusbar->removeWidget(ui->texStatusFormat); ui->statusbar->removeWidget(ui->pickSwatch); ui->statusbar->removeWidget(ui->hoverText); ui->statusbar->removeWidget(ui->pickedText); FlowLayout *statusflow = new FlowLayout(0, 3, 0); statusflowWidget->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Minimum); statusflow->addWidget(ui->texStatusName); statusflow->addWidget(ui->texStatusDim); statusflow->addWidget(ui->texStatusFormat); statusflow->addWidget(ui->pickSwatch); statusflow->addWidget(ui->hoverText); statusflow->addWidget(ui->pickedText); ui->texStatusName->setFont(QFontDatabase::systemFont(QFontDatabase::FixedFont)); ui->texStatusDim->setFont(QFontDatabase::systemFont(QFontDatabase::FixedFont)); ui->texStatusFormat->setFont(QFontDatabase::systemFont(QFontDatabase::FixedFont)); ui->hoverText->setFont(QFontDatabase::systemFont(QFontDatabase::FixedFont)); ui->pickedText->setFont(QFontDatabase::systemFont(QFontDatabase::FixedFont)); ui->renderLayout->removeItem(ui->statusbar); ui->renderLayout->addItem(statusflow); ui->channels->addItems({lit("RGBA"), lit("RGBM"), lit("YUVA decode"), tr("Custom")}); ui->zoomOption->addItems({lit("10%"), lit("25%"), lit("50%"), lit("75%"), lit("100%"), lit("200%"), lit("400%"), lit("800%")}); ui->hdrMul->addItems({lit("2"), lit("4"), lit("8"), lit("16"), lit("32"), lit("128")}); ui->overlay->addItems({tr("None"), tr("Highlight Drawcall"), tr("Wireframe Mesh"), tr("Depth Test"), tr("Stencil Test"), tr("Backface Cull"), tr("Viewport/Scissor Region"), tr("NaN/INF/-ve Display"), tr("Histogram Clipping"), tr("Clear Before Pass"), tr("Clear Before Draw"), tr("Quad Overdraw (Pass)"), tr("Quad Overdraw (Draw)"), tr("Triangle Size (Pass)"), tr("Triangle Size (Draw)")}); ui->textureListFilter->addItems({QString(), tr("Textures"), tr("Render Targets")}); ui->textureList->setModel(new TextureListItemModel(m_Ctx, this)); ui->textureList->setItemDelegate(new TextureListItemDelegate(ui->textureList)); ui->textureList->viewport()->setAttribute(Qt::WA_Hover); ui->zoomOption->setCurrentText(QString()); ui->fitToWindow->toggle(); m_Ctx.AddCaptureViewer(this); SetupTextureTabs(); } TextureViewer::~TextureViewer() { if(m_Output) { m_Ctx.Replay().BlockInvoke([this](IReplayController *r) { m_Output->Shutdown(); }); } m_Ctx.BuiltinWindowClosed(this); m_Ctx.RemoveCaptureViewer(this); delete ui; } void TextureViewer::enterEvent(QEvent *event) { HighlightUsage(); } void TextureViewer::showEvent(QShowEvent *event) { HighlightUsage(); } void TextureViewer::changeEvent(QEvent *event) { if(event->type() == QEvent::PaletteChange || event->type() == QEvent::StyleChange) { updateBackgroundColors(); ui->render->update(); } } void TextureViewer::HighlightUsage() { TextureDescription *texptr = GetCurrentTexture(); if(texptr && m_Ctx.HasTimelineBar()) m_Ctx.GetTimelineBar()->HighlightResourceUsage(texptr->resourceId); } void TextureViewer::RT_FetchCurrentPixel(IReplayController *r, uint32_t x, uint32_t y, PixelValue &pickValue, PixelValue &realValue) { TextureDescription *texptr = GetCurrentTexture(); if(texptr == NULL) return; if(m_TexDisplay.flipY) y = (texptr->height - 1) - y; x = qMax(0U, x >> m_TexDisplay.subresource.mip); y = qMax(0U, y >> m_TexDisplay.subresource.mip); ResourceId id = m_TexDisplay.resourceId; Subresource sub = m_TexDisplay.subresource; CompType typeCast = m_TexDisplay.typeCast; if(m_TexDisplay.overlay == DebugOverlay::QuadOverdrawDraw || m_TexDisplay.overlay == DebugOverlay::QuadOverdrawPass || m_TexDisplay.overlay == DebugOverlay::TriangleSizeDraw || m_TexDisplay.overlay == DebugOverlay::TriangleSizePass) { ResourceId overlayResId = m_Output->GetDebugOverlayTexID(); if(overlayResId != ResourceId()) { id = overlayResId; typeCast = CompType::Typeless; } } realValue = r->PickPixel(id, x, y, sub, typeCast); if(m_TexDisplay.customShaderId != ResourceId()) { pickValue = r->PickPixel(m_Output->GetCustomShaderTexID(), x, y, {m_TexDisplay.subresource.mip, 0, 0}, CompType::Typeless); } else { pickValue = realValue; } } void TextureViewer::RT_PickPixelsAndUpdate(IReplayController *r) { PixelValue pickValue, realValue; if(m_PickedPoint.x() < 0 || m_PickedPoint.y() < 0) return; uint32_t x = (uint32_t)m_PickedPoint.x(); uint32_t y = (uint32_t)m_PickedPoint.y(); RT_FetchCurrentPixel(r, x, y, pickValue, realValue); m_Output->SetPixelContextLocation(x, y); m_CurHoverValue = pickValue; m_CurPixelValue = pickValue; m_CurRealValue = realValue; GUIInvoke::call(this, [this]() { UI_UpdateStatusText(); }); } void TextureViewer::RT_PickHoverAndUpdate(IReplayController *r) { PixelValue pickValue, realValue; uint32_t x = (uint32_t)m_CurHoverPixel.x(); uint32_t y = (uint32_t)m_CurHoverPixel.y(); RT_FetchCurrentPixel(r, x, y, pickValue, realValue); m_CurHoverValue = pickValue; GUIInvoke::call(this, [this]() { UI_UpdateStatusText(); }); } void TextureViewer::RT_UpdateAndDisplay(IReplayController *r) { if(m_Output != NULL) m_Output->SetTextureDisplay(m_TexDisplay); GUIInvoke::call(this, [this]() { ui->render->update(); }); } void TextureViewer::RT_UpdateVisualRange(IReplayController *r) { TextureDescription *texptr = GetCurrentTexture(); if(!m_Visualise || texptr == NULL || m_Output == NULL) return; TextureDescription &tex = *texptr; ResourceFormat fmt = tex.format; bool uintTex = (tex.format.compType == CompType::UInt); bool sintTex = (tex.format.compType == CompType::SInt); if(tex.format.compType == CompType::Typeless && m_TexDisplay.typeCast == CompType::UInt) uintTex = true; if(tex.format.compType == CompType::Typeless && m_TexDisplay.typeCast == CompType::SInt) sintTex = true; if(m_TexDisplay.customShaderId != ResourceId()) fmt.compCount = 4; bool channels[] = { m_TexDisplay.red ? true : false, m_TexDisplay.green && fmt.compCount > 1, m_TexDisplay.blue && fmt.compCount > 2, m_TexDisplay.alpha && fmt.compCount > 3, }; ResourceId textureId = m_TexDisplay.resourceId; Subresource sub = m_TexDisplay.subresource; CompType typeCast = m_TexDisplay.typeCast; if(m_TexDisplay.customShaderId != ResourceId() && m_Output->GetCustomShaderTexID() != ResourceId()) { textureId = m_Output->GetCustomShaderTexID(); sub.slice = sub.sample = 0; typeCast = CompType::Typeless; } PixelValue min, max; rdctie(min, max) = r->GetMinMax(textureId, sub, typeCast); // exclude any channels where the min == max, as this destroys the histogram's utility. // When we do this, after we have the histogram we set the appropriate bucket to max - to still // show that there was data there but it's "clamped". float excludedBucket[4] = {-1.0f, -1.0f, -1.0f, -1.0f}; const float rangeSize = ui->rangeHistogram->rangeMax() - ui->rangeHistogram->rangeMin(); for(int i = 0; i < 4; i++) { if(min.uintValue[i] == max.uintValue[i]) { channels[i] = false; if(uintTex) excludedBucket[i] = (float(min.uintValue[i]) - ui->rangeHistogram->rangeMin()) / rangeSize; else if(sintTex) excludedBucket[i] = (float(min.intValue[i]) - ui->rangeHistogram->rangeMin()) / rangeSize; else excludedBucket[i] = (min.floatValue[i] - ui->rangeHistogram->rangeMin()) / rangeSize; } } rdcarray<uint32_t> histogram = r->GetHistogram(textureId, sub, typeCast, ui->rangeHistogram->rangeMin(), ui->rangeHistogram->rangeMax(), channels); if(!histogram.empty()) { QVector<uint32_t> histogramVec(histogram.count()); if(!histogram.isEmpty()) memcpy(histogramVec.data(), histogram.data(), histogram.byteSize()); // if the histogram is completely empty we still want to set 1 value in there. uint32_t maxval = 1; for(const uint32_t &v : histogramVec) maxval = qMax(v, maxval); if(!histogramVec.isEmpty()) { for(int i = 0; i < 4; i++) { int bucket = excludedBucket[i] * (histogramVec.size() - 1); if(bucket >= 0 && bucket < histogramVec.size()) histogramVec[bucket] = maxval; } } GUIInvoke::call(this, [this, histogramVec]() { ui->rangeHistogram->setHistogramRange(ui->rangeHistogram->rangeMin(), ui->rangeHistogram->rangeMax()); ui->rangeHistogram->setHistogramData(histogramVec); }); } } void TextureViewer::UI_UpdateStatusText() { TextureDescription *texptr = GetCurrentTexture(); if(texptr == NULL) return; TextureDescription &tex = *texptr; CompType compType = tex.format.compType; const bool yuv = (tex.format.type == ResourceFormatType::YUV8 || tex.format.type == ResourceFormatType::YUV10 || tex.format.type == ResourceFormatType::YUV12 || tex.format.type == ResourceFormatType::YUV16); if(tex.format.compType != m_TexDisplay.typeCast && m_TexDisplay.typeCast != CompType::Typeless && !yuv) compType = m_TexDisplay.typeCast; bool dsv = (tex.creationFlags & TextureCategory::DepthTarget) || (compType == CompType::Depth); bool uintTex = (compType == CompType::UInt); bool sintTex = (compType == CompType::SInt); if(m_TexDisplay.overlay == DebugOverlay::QuadOverdrawPass || m_TexDisplay.overlay == DebugOverlay::QuadOverdrawDraw || m_TexDisplay.overlay == DebugOverlay::TriangleSizePass || m_TexDisplay.overlay == DebugOverlay::TriangleSizeDraw) { dsv = false; uintTex = false; sintTex = false; } QColor swatchColor; if(dsv || uintTex || sintTex) { swatchColor = QColor(0, 0, 0); } else { float r = qBound(0.0f, m_CurHoverValue.floatValue[0], 1.0f); float g = qBound(0.0f, m_CurHoverValue.floatValue[1], 1.0f); float b = qBound(0.0f, m_CurHoverValue.floatValue[2], 1.0f); if(tex.format.SRGBCorrected() || (tex.creationFlags & TextureCategory::SwapBuffer)) { r = powf(r, 1.0f / 2.2f); g = powf(g, 1.0f / 2.2f); b = powf(b, 1.0f / 2.2f); } swatchColor = QColor(int(255.0f * r), int(255.0f * g), int(255.0f * b)); } { QPalette Pal(palette()); Pal.setColor(QPalette::Background, swatchColor); ui->pickSwatch->setAutoFillBackground(true); ui->pickSwatch->setPalette(Pal); } int y = m_CurHoverPixel.y() >> (int)m_TexDisplay.subresource.mip; uint32_t mipWidth = qMax(1U, tex.width >> (int)m_TexDisplay.subresource.mip); uint32_t mipHeight = qMax(1U, tex.height >> (int)m_TexDisplay.subresource.mip); if(m_Ctx.APIProps().pipelineType == GraphicsAPI::OpenGL) y = (int)(mipHeight - 1) - y; if(m_TexDisplay.flipY) y = (int)(mipHeight - 1) - y; y = qMax(0, y); int x = m_CurHoverPixel.x() >> (int)m_TexDisplay.subresource.mip; float invWidth = 1.0f / mipWidth; float invHeight = 1.0f / mipHeight; QString hoverCoords = QFormatStr("%1, %2 (%3, %4)") .arg(x, 4) .arg(y, 4) .arg((x * invWidth), 5, 'f', 4) .arg((y * invHeight), 5, 'f', 4); QString hoverText; uint32_t hoverX = (uint32_t)m_CurHoverPixel.x(); uint32_t hoverY = (uint32_t)m_CurHoverPixel.y(); if(hoverX > tex.width || hoverY > tex.height) hoverText = tr("Hover - [%1] - ").arg(hoverCoords); else hoverText = tr("Hover - %1 - ").arg(hoverCoords); ui->hoverText->setText(hoverText); QString pickedText; if(m_PickedPoint.x() >= 0) { x = m_PickedPoint.x() >> (int)m_TexDisplay.subresource.mip; y = m_PickedPoint.y() >> (int)m_TexDisplay.subresource.mip; if(m_Ctx.APIProps().pipelineType == GraphicsAPI::OpenGL) y = (int)(mipHeight - 1) - y; if(m_TexDisplay.flipY) y = (int)(mipHeight - 1) - y; y = qMax(0, y); pickedText = tr("Right click - %1, %2: ").arg(x, 4).arg(y, 4); PixelValue val = m_CurPixelValue; if(m_TexDisplay.customShaderId != ResourceId()) { pickedText += QFormatStr("%1, %2, %3, %4") .arg(Formatter::Format(val.floatValue[0])) .arg(Formatter::Format(val.floatValue[1])) .arg(Formatter::Format(val.floatValue[2])) .arg(Formatter::Format(val.floatValue[3])); val = m_CurRealValue; pickedText += tr(" (Real: "); } if(tex.format.type == ResourceFormatType::A8) val.floatValue[0] = val.floatValue[3]; if(dsv) { pickedText += tr("Depth "); if(uintTex) { pickedText += Formatter::Format(val.uintValue[0]); } else { pickedText += Formatter::Format(val.floatValue[0]); } int stencil = (int)(255.0f * val.floatValue[1]); pickedText += tr(", Stencil %1 / 0x%2").arg(stencil).arg(Formatter::Format(uint8_t(stencil & 0xff), true)); } else { // Restrict the number of components displayed to the component count of the resource format if(uintTex) { pickedText += QFormatStr("%1").arg(Formatter::Format(val.uintValue[0])); if(tex.format.compCount > 1) pickedText += QFormatStr(", %1").arg(Formatter::Format(val.uintValue[1])); if(tex.format.compCount > 2) pickedText += QFormatStr(", %1").arg(Formatter::Format(val.uintValue[2])); if(tex.format.compCount > 3) pickedText += QFormatStr(", %1").arg(Formatter::Format(val.uintValue[3])); } else if(sintTex) { pickedText += QFormatStr("%1").arg(Formatter::Format(val.intValue[0])); if(tex.format.compCount > 1) pickedText += QFormatStr(", %1").arg(Formatter::Format(val.intValue[1])); if(tex.format.compCount > 2) pickedText += QFormatStr(", %1").arg(Formatter::Format(val.intValue[2])); if(tex.format.compCount > 3) pickedText += QFormatStr(", %1").arg(Formatter::Format(val.intValue[3])); } else { pickedText += QFormatStr("%1").arg(Formatter::Format(val.floatValue[0])); if(tex.format.compCount > 1) pickedText += QFormatStr(", %1").arg(Formatter::Format(val.floatValue[1])); if(tex.format.compCount > 2) pickedText += QFormatStr(", %1").arg(Formatter::Format(val.floatValue[2])); if(tex.format.compCount > 3) pickedText += QFormatStr(", %1").arg(Formatter::Format(val.floatValue[3])); } } if(m_TexDisplay.customShaderId != ResourceId()) pickedText += lit(")"); } else { pickedText += tr("Right click to pick a pixel"); } // try and keep status text consistent by sticking to the high water mark // of length (prevents nasty oscillation when the length of the string is // just popping over/under enough to overflow onto the next line). if(pickedText.length() > m_HighWaterStatusLength) m_HighWaterStatusLength = pickedText.length(); if(pickedText.length() < m_HighWaterStatusLength) pickedText += QString(m_HighWaterStatusLength - pickedText.length(), QLatin1Char(' ')); ui->pickedText->setText(pickedText); } void TextureViewer::UI_UpdateTextureDetails() { QString status; TextureDescription *texptr = GetCurrentTexture(); if(texptr == NULL) { ui->texStatusName->setText(status); ui->texStatusDim->setText(status); ui->texStatusFormat->setText(status); ui->renderContainer->setWindowTitle(tr("Unbound")); return; } TextureDescription &current = *texptr; ResourceId followID = m_Following.GetResourceId(m_Ctx); { TextureDescription *followtex = m_Ctx.GetTexture(followID); BufferDescription *followbuf = m_Ctx.GetBuffer(followID); QString title; if(followID == ResourceId()) { title = tr("Unbound"); } else if(followtex || followbuf) { QString name = m_Ctx.GetResourceName(followID); switch(m_Following.Type) { case FollowType::OutputColour: title = QString(tr("Cur Output %1 - %2")).arg(m_Following.index).arg(name); break; case FollowType::OutputDepth: title = QString(tr("Cur Depth Output - %1")).arg(name); break; case FollowType::ReadWrite: title = QString(tr("Cur RW Output %1 - %2")).arg(m_Following.index).arg(name); break; case FollowType::ReadOnly: title = QString(tr("Cur Input %1 - %2")).arg(m_Following.index).arg(name); break; } } else { switch(m_Following.Type) { case FollowType::OutputColour: title = QString(tr("Cur Output %1")).arg(m_Following.index); break; case FollowType::OutputDepth: title = QString(tr("Cur Depth Output")); break; case FollowType::ReadWrite: title = QString(tr("Cur RW Output %1")).arg(m_Following.index); break; case FollowType::ReadOnly: title = QString(tr("Cur Input %1")).arg(m_Following.index); break; } } ui->renderContainer->setWindowTitle(title); } ui->texStatusName->setText(m_Ctx.GetResourceName(current.resourceId) + lit(" - ")); status = QString(); if(current.dimension >= 1) status += QString::number(current.width); if(current.dimension >= 2) status += lit("x") + QString::number(current.height); if(current.dimension >= 3) status += lit("x") + QString::number(current.depth); if(current.arraysize > 1) status += QFormatStr("[%1]").arg(QString::number(current.arraysize)); if(current.msQual > 0 || current.msSamp > 1) status += QFormatStr(" MS{%1x %2Q}").arg(current.msSamp).arg(current.msQual); status += QFormatStr(" %1 mips").arg(current.mips); status += lit(" - "); ui->texStatusDim->setText(status); status = current.format.Name(); const bool yuv = (current.format.type == ResourceFormatType::YUV8 || current.format.type == ResourceFormatType::YUV10 || current.format.type == ResourceFormatType::YUV12 || current.format.type == ResourceFormatType::YUV16); CompType viewCast = CompType::Typeless; if(current.format.compType != m_TexDisplay.typeCast && m_TexDisplay.typeCast != CompType::Typeless && !yuv) { viewCast = m_TexDisplay.typeCast; } else if(current.format.compType == CompType::Typeless && m_TexDisplay.typeCast == CompType::Typeless && !yuv) { // if it's a typeless texture and we don't have a hint, ensure the user knows it's being viewed // as unorm as a fallback viewCast = CompType::UNorm; } if(viewCast != CompType::Typeless) status += tr(" Viewed as %1").arg(ToQStr(viewCast)); ui->texStatusFormat->setText(status); } void TextureViewer::UI_OnTextureSelectionChanged(bool newdraw) { TextureDescription *texptr = GetCurrentTexture(); // reset high-water mark m_HighWaterStatusLength = 0; if(texptr == NULL) return; TextureDescription &tex = *texptr; bool newtex = (m_TexDisplay.resourceId != tex.resourceId); // save settings for this current texture if(m_Ctx.Config().TextureViewer_PerTexSettings) { m_TextureSettings[m_TexDisplay.resourceId].r = ui->channelRed->isChecked(); m_TextureSettings[m_TexDisplay.resourceId].g = ui->channelGreen->isChecked(); m_TextureSettings[m_TexDisplay.resourceId].b = ui->channelBlue->isChecked(); m_TextureSettings[m_TexDisplay.resourceId].a = ui->channelAlpha->isChecked(); // save state regardless, we just don't apply it without the setting m_TextureSettings[m_TexDisplay.resourceId].flip_y = ui->flip_y->isChecked(); m_TextureSettings[m_TexDisplay.resourceId].displayType = qMax(0, ui->channels->currentIndex()); m_TextureSettings[m_TexDisplay.resourceId].customShader = ui->customShader->currentText(); m_TextureSettings[m_TexDisplay.resourceId].depth = ui->depthDisplay->isChecked(); m_TextureSettings[m_TexDisplay.resourceId].stencil = ui->stencilDisplay->isChecked(); m_TextureSettings[m_TexDisplay.resourceId].mip = qMax(0, ui->mipLevel->currentIndex()); m_TextureSettings[m_TexDisplay.resourceId].slice = qMax(0, ui->sliceFace->currentIndex()); m_TextureSettings[m_TexDisplay.resourceId].minrange = ui->rangeHistogram->blackPoint(); m_TextureSettings[m_TexDisplay.resourceId].maxrange = ui->rangeHistogram->whitePoint(); if(m_TexDisplay.typeCast != CompType::Typeless) m_TextureSettings[m_TexDisplay.resourceId].typeCast = m_TexDisplay.typeCast; } m_TexDisplay.resourceId = tex.resourceId; // interpret the texture according to the currently following type. if(!currentTextureIsLocked()) m_TexDisplay.typeCast = m_Following.GetTypeHint(m_Ctx); else m_TexDisplay.typeCast = CompType::Typeless; // if there is no such type or it isn't being followed, use the last seen interpretation if(m_TexDisplay.typeCast == CompType::Typeless && m_TextureSettings.contains(m_TexDisplay.resourceId)) m_TexDisplay.typeCast = m_TextureSettings[m_TexDisplay.resourceId].typeCast; // try to maintain the pan in the new texture. If the new texture // is approx an integer multiple of the old texture, just changing // the scale will keep everything the same. This is useful for // downsample chains and things where you're flipping back and forth // between overlapping textures, but even in the non-integer case // pan will be kept approximately the same. QSizeF curSize((float)tex.width, (float)tex.height); float curArea = area(curSize); float prevArea = area(m_PrevSize); if(prevArea > 0.0f && m_PrevSize.width() > 0.0f) { float prevX = m_TexDisplay.xOffset; float prevY = m_TexDisplay.yOffset; // allow slight difference in aspect ratio for rounding errors // in downscales (e.g. 1680x1050 -> 840x525 -> 420x262 in the // last downscale the ratios are 1.6 and 1.603053435). if(qAbs(aspect(curSize) - aspect(m_PrevSize)) < 0.01f) { m_TexDisplay.scale *= m_PrevSize.width() / curSize.width(); setCurrentZoomValue(m_TexDisplay.scale); } else { // this scale factor is arbitrary really, only intention is to have // integer scales come out precisely, other 'similar' sizes will be // similar ish float scaleFactor = (float)(sqrt(curArea) / sqrt(prevArea)); m_TexDisplay.xOffset = prevX * scaleFactor; m_TexDisplay.yOffset = prevY * scaleFactor; } } m_PrevSize = curSize; // refresh scroll position setScrollPosition(getScrollPosition()); UI_UpdateStatusText(); // block signals for mipLevel and sliceFace comboboxes while editing them ui->mipLevel->blockSignals(true); ui->sliceFace->blockSignals(true); ui->mipLevel->clear(); m_TexDisplay.subresource.mip = 0; m_TexDisplay.subresource.slice = 0; bool usemipsettings = true; bool useslicesettings = true; if(tex.msSamp > 1) { for(uint32_t i = 0; i < tex.msSamp; i++) ui->mipLevel->addItem(tr("Sample %1").arg(i)); // add an option to display unweighted average resolved value, // to get an idea of how the samples average if(tex.format.compType != CompType::UInt && tex.format.compType != CompType::SInt && tex.format.compType != CompType::Depth && !(tex.creationFlags & TextureCategory::DepthTarget)) ui->mipLevel->addItem(tr("Average val")); ui->mipLabel->setText(tr("Sample")); ui->mipLevel->setCurrentIndex(0); } else { for(uint32_t i = 0; i < tex.mips; i++) ui->mipLevel->addItem( QFormatStr("%1 - %2x%3").arg(i).arg(qMax(1U, tex.width >> i)).arg(qMax(1U, tex.height >> i))); ui->mipLabel->setText(tr("Mip")); } if(tex.mips == 1 && tex.msSamp <= 1) ui->mipLevel->setEnabled(false); else ui->mipLevel->setEnabled(true); ui->sliceFace->clear(); uint32_t numSlices = 1; if(tex.arraysize == 1 && tex.depth <= 1) { ui->sliceFace->setEnabled(false); } else { ui->sliceFace->setEnabled(true); QString cubeFaces[] = {lit("X+"), lit("X-"), lit("Y+"), lit("Y-"), lit("Z+"), lit("Z-")}; numSlices = tex.arraysize; // for 3D textures, display the number of slices at this mip if(tex.depth > 1) numSlices = qMax(1u, tex.depth >> (int)ui->mipLevel->currentIndex()); for(uint32_t i = 0; i < numSlices; i++) { if(tex.cubemap) { QString name = cubeFaces[i % 6]; if(numSlices > 6) name = QFormatStr("[%1] %2").arg(i / 6).arg( cubeFaces[i % 6]); // Front 1, Back 2, 3, 4 etc for cube arrays ui->sliceFace->addItem(name); } else { ui->sliceFace->addItem(tr("Slice %1").arg(i)); } } } // enable signals for mipLevel and sliceFace ui->mipLevel->blockSignals(false); ui->sliceFace->blockSignals(false); { int highestMip = -1; // only switch to the selected mip for outputs, and when changing drawcall if(!currentTextureIsLocked() && m_Following.Type != FollowType::ReadOnly && newdraw) highestMip = m_Following.GetHighestMip(m_Ctx); // assuming we get a valid mip for the highest mip, only switch to it // if we've selected a new texture, or if it's different than the last mip. // This prevents the case where the user has clicked on another mip and // we don't want to snap their view back when stepping between events with the // same mip used. But it does mean that if they are stepping between // events with different mips used, then we will update in that case. if(highestMip >= 0 && (newtex || highestMip != m_PrevHighestMip)) { usemipsettings = false; ui->mipLevel->setCurrentIndex(qBound(0, highestMip, (int)tex.mips - 1)); } if(ui->mipLevel->currentIndex() == -1) ui->mipLevel->setCurrentIndex(qBound(0, m_PrevHighestMip, (int)tex.mips - 1)); m_PrevHighestMip = highestMip; } { int firstArraySlice = -1; // only switch to the selected mip for outputs, and when changing drawcall if(!currentTextureIsLocked() && m_Following.Type != FollowType::ReadOnly && newdraw) firstArraySlice = m_Following.GetFirstArraySlice(m_Ctx); // see above with highestMip and prevHighestMip for the logic behind this if(firstArraySlice >= 0 && (newtex || firstArraySlice != m_PrevFirstArraySlice)) { useslicesettings = false; ui->sliceFace->setCurrentIndex(qBound(0, firstArraySlice, (int)numSlices - 1)); } if(ui->sliceFace->currentIndex() == -1) ui->sliceFace->setCurrentIndex(qBound(0, m_PrevFirstArraySlice, (int)numSlices - 1)); m_PrevFirstArraySlice = firstArraySlice; } // because slice and mip are specially set above, we restore any per-tex settings to apply // even if we don't switch to a new texture. // Note that if the slice or mip was changed because that slice or mip is the selected one // at the API level, we leave this alone. if(m_Ctx.Config().TextureViewer_PerTexSettings && m_TextureSettings.contains(tex.resourceId)) { if(usemipsettings) ui->mipLevel->setCurrentIndex(m_TextureSettings[tex.resourceId].mip); if(useslicesettings) ui->sliceFace->setCurrentIndex(m_TextureSettings[tex.resourceId].slice); if(m_Ctx.Config().TextureViewer_PerTexYFlip) ui->flip_y->setChecked(m_TextureSettings[tex.resourceId].flip_y); } // handling for if we've switched to a new texture if(newtex) { // if we save certain settings per-texture, restore them (if we have any) if(m_Ctx.Config().TextureViewer_PerTexSettings && m_TextureSettings.contains(tex.resourceId)) { ui->channels->setCurrentIndex(m_TextureSettings[tex.resourceId].displayType); ui->customShader->setCurrentText(m_TextureSettings[tex.resourceId].customShader); ui->channelRed->setChecked(m_TextureSettings[tex.resourceId].r); ui->channelGreen->setChecked(m_TextureSettings[tex.resourceId].g); ui->channelBlue->setChecked(m_TextureSettings[tex.resourceId].b); ui->channelAlpha->setChecked(m_TextureSettings[tex.resourceId].a); ui->depthDisplay->setChecked(m_TextureSettings[tex.resourceId].depth); ui->stencilDisplay->setChecked(m_TextureSettings[tex.resourceId].stencil); if(m_Ctx.Config().TextureViewer_PerTexYFlip) ui->flip_y->setChecked(m_TextureSettings[tex.resourceId].flip_y); m_NoRangePaint = true; ui->rangeHistogram->setRange(m_TextureSettings[m_TexDisplay.resourceId].minrange, m_TextureSettings[m_TexDisplay.resourceId].maxrange); m_NoRangePaint = false; } else if(m_Ctx.Config().TextureViewer_PerTexSettings) { // if we are using per-tex settings, reset back to RGB ui->channels->setCurrentIndex(0); ui->customShader->setCurrentText(QString()); ui->channelRed->setChecked(true); ui->channelGreen->setChecked(true); ui->channelBlue->setChecked(true); ui->channelAlpha->setChecked(false); ui->depthDisplay->setChecked(true); ui->stencilDisplay->setChecked(false); if(m_Ctx.Config().TextureViewer_PerTexYFlip) ui->flip_y->setChecked(false); m_NoRangePaint = true; UI_SetHistogramRange(texptr, m_TexDisplay.typeCast); m_NoRangePaint = false; } // reset the range if desired if(m_Ctx.Config().TextureViewer_ResetRange) { UI_SetHistogramRange(texptr, m_TexDisplay.typeCast); } } UI_UpdateFittedScale(); UI_UpdateTextureDetails(); UI_UpdateChannels(); if(ui->autoFit->isChecked()) AutoFitRange(); m_Ctx.Replay().AsyncInvoke([this](IReplayController *r) { RT_UpdateVisualRange(r); RT_UpdateAndDisplay(r); if(m_Output != NULL) RT_PickPixelsAndUpdate(r); }); HighlightUsage(); } void TextureViewer::UI_SetHistogramRange(const TextureDescription *tex, CompType typeCast) { if(tex != NULL && (tex->format.compType == CompType::SNorm || typeCast == CompType::SNorm)) ui->rangeHistogram->setRange(-1.0f, 1.0f); else ui->rangeHistogram->setRange(0.0f, 1.0f); } void TextureViewer::UI_UpdateChannels() { TextureDescription *tex = GetCurrentTexture(); #define SHOW(widget) widget->setVisible(true) #define HIDE(widget) widget->setVisible(false) #define ENABLE(widget) widget->setEnabled(true) #define DISABLE(widget) widget->setEnabled(false) if(tex != NULL && (tex->creationFlags & TextureCategory::SwapBuffer)) { // swapbuffer is always srgb for 8-bit types, linear for 16-bit types DISABLE(ui->gammaDisplay); if(tex->format.compByteWidth == 2 && tex->format.type == ResourceFormatType::Regular) m_TexDisplay.linearDisplayAsGamma = false; else m_TexDisplay.linearDisplayAsGamma = true; } else { if(tex != NULL && !tex->format.SRGBCorrected()) ENABLE(ui->gammaDisplay); else DISABLE(ui->gammaDisplay); m_TexDisplay.linearDisplayAsGamma = !ui->gammaDisplay->isEnabled() || ui->gammaDisplay->isChecked(); } if(tex != NULL && tex->format.SRGBCorrected()) m_TexDisplay.linearDisplayAsGamma = false; bool dsv = false; if(tex != NULL) dsv = (tex->creationFlags & TextureCategory::DepthTarget) || (tex->format.compType == CompType::Depth); bool yuv = false; if(tex != NULL) yuv = (tex->format.type == ResourceFormatType::YUV8 || tex->format.type == ResourceFormatType::YUV10 || tex->format.type == ResourceFormatType::YUV12 || tex->format.type == ResourceFormatType::YUV16); const bool defaultDisplay = ui->channels->currentIndex() == 0; const bool rgbmDisplay = ui->channels->currentIndex() == 1; const bool yuvDecodeDisplay = ui->channels->currentIndex() == 2; const bool customDisplay = ui->channels->currentIndex() == 3; if(customDisplay && m_NeedCustomReload) { m_NeedCustomReload = false; reloadCustomShaders(QString()); } ui->channels->setItemText(0, yuv ? lit("YUVA") : lit("RGBA")); ui->channelRed->setText(lit("R")); ui->channelGreen->setText(lit("G")); ui->channelBlue->setText(lit("B")); if(dsv && !customDisplay) { // Depth display (when not using custom) HIDE(ui->channelRed); HIDE(ui->channelGreen); HIDE(ui->channelBlue); HIDE(ui->channelAlpha); HIDE(ui->mulSep); HIDE(ui->mulLabel); HIDE(ui->hdrMul); HIDE(ui->customShader); HIDE(ui->customCreate); HIDE(ui->customEdit); HIDE(ui->customDelete); SHOW(ui->depthDisplay); SHOW(ui->stencilDisplay); m_TexDisplay.red = ui->depthDisplay->isChecked(); m_TexDisplay.green = ui->stencilDisplay->isChecked(); m_TexDisplay.blue = false; m_TexDisplay.alpha = false; if(m_TexDisplay.red == m_TexDisplay.green && !m_TexDisplay.red) { m_TexDisplay.red = true; ui->depthDisplay->setChecked(true); } m_TexDisplay.decodeYUV = false; m_TexDisplay.hdrMultiplier = -1.0f; if(m_TexDisplay.customShaderId != ResourceId()) { memset(m_CurPixelValue.floatValue, 0, sizeof(float) * 4); memset(m_CurRealValue.floatValue, 0, sizeof(float) * 4); UI_UpdateStatusText(); } m_TexDisplay.customShaderId = ResourceId(); } else if(defaultDisplay || yuvDecodeDisplay || !m_Ctx.IsCaptureLoaded()) { // RGBA. YUV Decode is almost identical but we set decodeYUV SHOW(ui->channelRed); SHOW(ui->channelGreen); SHOW(ui->channelBlue); SHOW(ui->channelAlpha); HIDE(ui->mulSep); HIDE(ui->mulLabel); HIDE(ui->hdrMul); HIDE(ui->customShader); HIDE(ui->customCreate); HIDE(ui->customEdit); HIDE(ui->customDelete); HIDE(ui->depthDisplay); HIDE(ui->stencilDisplay); m_TexDisplay.red = ui->channelRed->isChecked(); m_TexDisplay.green = ui->channelGreen->isChecked(); m_TexDisplay.blue = ui->channelBlue->isChecked(); m_TexDisplay.alpha = ui->channelAlpha->isChecked(); if(!yuvDecodeDisplay && yuv) { ui->channelRed->setText(lit("V")); ui->channelGreen->setText(lit("Y")); ui->channelBlue->setText(lit("U")); } m_TexDisplay.decodeYUV = yuvDecodeDisplay; m_TexDisplay.hdrMultiplier = -1.0f; if(m_TexDisplay.customShaderId != ResourceId()) { memset(m_CurPixelValue.floatValue, 0, sizeof(float) * 4); memset(m_CurRealValue.floatValue, 0, sizeof(float) * 4); UI_UpdateStatusText(); } m_TexDisplay.customShaderId = ResourceId(); } else if(rgbmDisplay) { // RGBM SHOW(ui->channelRed); SHOW(ui->channelGreen); SHOW(ui->channelBlue); HIDE(ui->channelAlpha); SHOW(ui->mulSep); SHOW(ui->mulLabel); SHOW(ui->hdrMul); HIDE(ui->customShader); HIDE(ui->customCreate); HIDE(ui->customEdit); HIDE(ui->customDelete); HIDE(ui->depthDisplay); HIDE(ui->stencilDisplay); m_TexDisplay.red = ui->channelRed->isChecked(); m_TexDisplay.green = ui->channelGreen->isChecked(); m_TexDisplay.blue = ui->channelBlue->isChecked(); m_TexDisplay.alpha = false; bool ok = false; float mul = ui->hdrMul->currentText().toFloat(&ok); if(!ok) { mul = 32.0f; ui->hdrMul->setCurrentText(lit("32")); } m_TexDisplay.decodeYUV = false; m_TexDisplay.hdrMultiplier = mul; if(m_TexDisplay.customShaderId != ResourceId()) { memset(m_CurPixelValue.floatValue, 0, sizeof(float) * 4); memset(m_CurRealValue.floatValue, 0, sizeof(float) * 4); UI_UpdateStatusText(); } m_TexDisplay.customShaderId = ResourceId(); } else if(customDisplay) { // custom shaders SHOW(ui->channelRed); SHOW(ui->channelGreen); SHOW(ui->channelBlue); SHOW(ui->channelAlpha); HIDE(ui->mulSep); HIDE(ui->mulLabel); HIDE(ui->hdrMul); SHOW(ui->customShader); SHOW(ui->customCreate); SHOW(ui->customEdit); SHOW(ui->customDelete); HIDE(ui->depthDisplay); HIDE(ui->stencilDisplay); m_TexDisplay.red = ui->channelRed->isChecked(); m_TexDisplay.green = ui->channelGreen->isChecked(); m_TexDisplay.blue = ui->channelBlue->isChecked(); m_TexDisplay.alpha = ui->channelAlpha->isChecked(); m_TexDisplay.decodeYUV = false; m_TexDisplay.hdrMultiplier = -1.0f; m_TexDisplay.customShaderId = ResourceId(); QString shaderName = ui->customShader->currentText().toUpper(); if(m_CustomShaders.contains(shaderName)) { if(m_TexDisplay.customShaderId == ResourceId()) { memset(m_CurPixelValue.floatValue, 0, sizeof(float) * 4); memset(m_CurRealValue.floatValue, 0, sizeof(float) * 4); UI_UpdateStatusText(); } m_TexDisplay.customShaderId = m_CustomShaders[shaderName]; ui->customDelete->setEnabled(true); ui->customEdit->setEnabled(true); } else { ui->customDelete->setEnabled(false); ui->customEdit->setEnabled(false); } } #undef HIDE #undef SHOW #undef ENABLE #undef DISABLE m_TexDisplay.flipY = ui->flip_y->isChecked(); INVOKE_MEMFN(RT_UpdateAndDisplay); INVOKE_MEMFN(RT_UpdateVisualRange); } void TextureViewer::SetupTextureTabs() { ToolWindowManagerArea *textureTabs = ui->dockarea->areaOf(ui->renderContainer); if(!textureTabs) return; QIcon tabIcon; tabIcon.addFile(QStringLiteral(":/logo.svg"), QSize(), QIcon::Normal, QIcon::Off); textureTabs->setTabIcon(0, tabIcon); textureTabs->setElideMode(Qt::ElideRight); QObject::connect(textureTabs, &QTabWidget::currentChanged, this, &TextureViewer::textureTab_Changed); QObject::connect(textureTabs, &QTabWidget::tabCloseRequested, this, &TextureViewer::textureTab_Closing); textureTabs->disableUserDrop(); textureTabs->tabBar()->setContextMenuPolicy(Qt::CustomContextMenu); QObject::connect(textureTabs->tabBar(), &QTabBar::customContextMenuRequested, this, &TextureViewer::textureTab_Menu); } void TextureViewer::textureTab_Menu(const QPoint &pos) { ToolWindowManagerArea *textureTabs = ui->dockarea->areaOf(ui->renderContainer); int tabIndex = textureTabs->tabBar()->tabAt(pos); if(tabIndex == -1) return; QAction closeTab(tr("Close tab"), this); QAction closeOtherTabs(tr("Close other tabs"), this); QAction closeRightTabs(tr("Close tabs to the right"), this); if(textureTabs->widget(tabIndex) == ui->renderContainer) closeTab.setEnabled(false); QMenu contextMenu(this); contextMenu.addAction(&closeTab); contextMenu.addAction(&closeOtherTabs); contextMenu.addAction(&closeRightTabs); QObject::connect(&closeTab, &QAction::triggered, [textureTabs, tabIndex]() { // remove the tab at this index textureTabs->removeTab(tabIndex); }); QObject::connect(&closeRightTabs, &QAction::triggered, [textureTabs, tabIndex]() { // remove all tabs with a greater index while(textureTabs->count() > tabIndex + 1) textureTabs->removeTab(tabIndex + 1); }); QObject::connect(&closeOtherTabs, &QAction::triggered, [textureTabs, tabIndex]() { // remove all tabs with a greater index while(textureTabs->count() > tabIndex + 1) textureTabs->removeTab(tabIndex + 1); // remove all tabs at index 1 until there's only two, these are the ones between the locked tab // 0 and the tabIndex while(textureTabs->count() > 2) textureTabs->removeTab(1); }); RDDialog::show(&contextMenu, QCursor::pos()); } void TextureViewer::textureTab_Changed(int index) { ToolWindowManagerArea *textureTabs = ui->dockarea->areaOf(ui->renderContainer); if(!textureTabs) return; QWidget *w = textureTabs->widget(index); if(w) { w->setLayout(ui->renderLayout); if(w == ui->renderContainer) m_LockedId = ResourceId(); else m_LockedId = w->property("id").value<ResourceId>(); UI_UpdateCachedTexture(); } UI_OnTextureSelectionChanged(false); } void TextureViewer::textureTab_Closing(int index) { ToolWindowManagerArea *textureTabs = ui->dockarea->areaOf(ui->renderContainer); if(index > 0) { // this callback happens AFTER the widget has already been removed unfortunately, so // we need to search through the locked tab list to see which one was removed to be // able to delete it properly. QList<ResourceId> ids = m_LockedTabs.keys(); for(int i = 0; i < textureTabs->count(); i++) { QWidget *w = textureTabs->widget(i); ResourceId id = w->property("id").value<ResourceId>(); ids.removeOne(id); } if(ids.count() != 1) qWarning() << "Expected only one removed tab, got " << ids.count(); for(ResourceId id : ids) m_LockedTabs.remove(id); textureTabs->setCurrentIndex(index - 1); textureTabs->widget(index - 1)->show(); return; } // should never get here - tab 0 is the dynamic tab which is uncloseable. qCritical() << "Somehow closing dynamic tab?"; if(textureTabs->count() > 1) { textureTabs->setCurrentIndex(1); textureTabs->widget(1)->show(); } } ResourcePreview *TextureViewer::UI_CreateThumbnail(ThumbnailStrip *strip) { ResourcePreview *prev = new ResourcePreview(m_Ctx, m_Output); QObject::connect(prev, &ResourcePreview::clicked, this, &TextureViewer::thumb_clicked); QObject::connect(prev, &ResourcePreview::doubleClicked, this, &TextureViewer::thumb_doubleClicked); prev->setActive(false); strip->addThumb(prev); return prev; } void TextureViewer::UI_CreateThumbnails() { if(!ui->outputThumbs->thumbs().isEmpty()) return; // these will expand, but we make sure that there is a good set reserved for(int i = 0; i < 9; i++) { ResourcePreview *prev = UI_CreateThumbnail(ui->outputThumbs); if(i == 0) prev->setSelected(true); } for(int i = 0; i < 128; i++) UI_CreateThumbnail(ui->inputThumbs); } void TextureViewer::GotoLocation(int x, int y) { if(!m_Ctx.IsCaptureLoaded()) return; TextureDescription *tex = GetCurrentTexture(); if(tex == NULL) return; x = qMin(x << m_TexDisplay.subresource.mip, int(tex->width - 1)); y = qMin(y << m_TexDisplay.subresource.mip, int(tex->height - 1)); m_PickedPoint = QPoint(x, y); if(m_Ctx.APIProps().pipelineType == GraphicsAPI::OpenGL) m_PickedPoint.setY((int)(tex->height - 1) - m_PickedPoint.y()); if(m_TexDisplay.flipY) m_PickedPoint.setY((int)(tex->height - 1) - m_PickedPoint.x()); // centre the picked point. QPoint scrollPos; scrollPos.setX(-m_PickedPoint.x() * m_TexDisplay.scale + realRenderWidth() / 2); scrollPos.setY(-m_PickedPoint.y() * m_TexDisplay.scale + realRenderHeight() / 2); setScrollPosition(scrollPos); if(m_Output != NULL) INVOKE_MEMFN(RT_PickPixelsAndUpdate); INVOKE_MEMFN(RT_UpdateAndDisplay); UI_UpdateStatusText(); } void TextureViewer::ViewTexture(ResourceId ID, bool focus) { if(QThread::currentThread() != QCoreApplication::instance()->thread()) { GUIInvoke::call(this, [this, ID, focus] { this->ViewTexture(ID, focus); }); return; } if(m_LockedTabs.contains(ID)) { if(focus) ToolWindowManager::raiseToolWindow(this); QWidget *w = m_LockedTabs[ID]; ToolWindowManagerArea *textureTabs = ui->dockarea->areaOf(ui->renderContainer); int idx = textureTabs->indexOf(w); if(idx >= 0) textureTabs->setCurrentIndex(idx); INVOKE_MEMFN(RT_UpdateAndDisplay); return; } TextureDescription *tex = m_Ctx.GetTexture(ID); if(tex) { QWidget *lockedContainer = new QWidget(this); lockedContainer->setWindowTitle(m_Ctx.GetResourceName(ID)); lockedContainer->setProperty("id", QVariant::fromValue(ID)); ToolWindowManagerArea *textureTabs = ui->dockarea->areaOf(ui->renderContainer); ToolWindowManager::AreaReference ref(ToolWindowManager::AddTo, textureTabs); ui->dockarea->addToolWindow(lockedContainer, ref); ui->dockarea->setToolWindowProperties( lockedContainer, ToolWindowManager::DisallowUserDocking | ToolWindowManager::AlwaysDisplayFullTabs); lockedContainer->setLayout(ui->renderLayout); int idx = textureTabs->indexOf(lockedContainer); if(idx >= 0) textureTabs->setTabIcon(idx, Icons::page_go()); else qCritical() << "Couldn't get tab index of new tab to set icon"; // newPanel.DockHandler.TabPageContextMenuStrip = tabContextMenu; if(focus) ToolWindowManager::raiseToolWindow(this); m_LockedTabs[ID] = lockedContainer; INVOKE_MEMFN(RT_UpdateAndDisplay); return; } BufferDescription *buf = m_Ctx.GetBuffer(ID); if(buf) { IBufferViewer *viewer = m_Ctx.ViewBuffer(0, ~0ULL, ID); m_Ctx.AddDockWindow(viewer->Widget(), DockReference::AddTo, this); } } void TextureViewer::texContextItem_triggered() { QAction *act = qobject_cast<QAction *>(QObject::sender()); QVariant eid = act->property("eid"); if(eid.isValid()) { m_Ctx.SetEventID({}, eid.toUInt(), eid.toUInt()); return; } QVariant id = act->property("id"); if(id.isValid()) { ViewTexture(id.value<ResourceId>(), false); return; } } void TextureViewer::showUnused_triggered() { m_ShowUnused = !m_ShowUnused; if(m_Ctx.IsCaptureLoaded()) m_Ctx.RefreshStatus(); } void TextureViewer::showEmpty_triggered() { m_ShowEmpty = !m_ShowEmpty; if(m_Ctx.IsCaptureLoaded()) m_Ctx.RefreshStatus(); } void TextureViewer::AddResourceUsageEntry(QMenu &menu, uint32_t start, uint32_t end, ResourceUsage usage) { QAction *item = NULL; if(start == end) item = new QAction( QFormatStr("EID %1: %2").arg(start).arg(ToQStr(usage, m_Ctx.APIProps().pipelineType)), this); else item = new QAction( QFormatStr("EID %1-%2: %3").arg(start).arg(end).arg(ToQStr(usage, m_Ctx.APIProps().pipelineType)), this); QObject::connect(item, &QAction::triggered, this, &TextureViewer::texContextItem_triggered); item->setProperty("eid", QVariant(end)); menu.addAction(item); } void TextureViewer::OpenResourceContextMenu(ResourceId id, bool input, const rdcarray<EventUsage> &usage) { QMenu contextMenu(this); QAction showUnused(tr("Show Unused"), this); QAction showEmpty(tr("Show Empty"), this); QAction openLockedTab(tr("Open new Locked Tab"), this); QAction openResourceInspector(tr("Open in Resource Inspector"), this); QAction usageTitle(tr("Used:"), this); QAction imageLayout(this); openLockedTab.setIcon(Icons::action_hover()); openResourceInspector.setIcon(Icons::link()); showUnused.setChecked(m_ShowUnused); showUnused.setChecked(m_ShowEmpty); contextMenu.addAction(&showUnused); contextMenu.addAction(&showEmpty); QObject::connect(&showUnused, &QAction::triggered, this, &TextureViewer::showUnused_triggered); QObject::connect(&showEmpty, &QAction::triggered, this, &TextureViewer::showEmpty_triggered); if(m_Ctx.CurPipelineState().SupportsBarriers()) { contextMenu.addSeparator(); imageLayout.setText(tr("Image is in layout ") + m_Ctx.CurPipelineState().GetResourceLayout(id)); contextMenu.addAction(&imageLayout); } if(id != ResourceId()) { contextMenu.addSeparator(); contextMenu.addAction(&openLockedTab); contextMenu.addAction(&openResourceInspector); contextMenu.addSeparator(); m_Ctx.Extensions().MenuDisplaying(input ? ContextMenu::TextureViewer_InputThumbnail : ContextMenu::TextureViewer_OutputThumbnail, &contextMenu, {{"resourceId", id}}); contextMenu.addSeparator(); contextMenu.addAction(&usageTitle); openLockedTab.setProperty("id", QVariant::fromValue(id)); QObject::connect(&openLockedTab, &QAction::triggered, this, &TextureViewer::texContextItem_triggered); QObject::connect(&openResourceInspector, &QAction::triggered, [this, id]() { m_Ctx.ShowResourceInspector(); m_Ctx.GetResourceInspector()->Inspect(id); }); CombineUsageEvents(m_Ctx, usage, [this, &contextMenu](uint32_t start, uint32_t end, ResourceUsage use) { AddResourceUsageEntry(contextMenu, start, end, use); }); RDDialog::show(&contextMenu, QCursor::pos()); } else { contextMenu.addSeparator(); m_Ctx.Extensions().MenuDisplaying(input ? ContextMenu::TextureViewer_InputThumbnail : ContextMenu::TextureViewer_OutputThumbnail, &contextMenu, {}); RDDialog::show(&contextMenu, QCursor::pos()); } } void TextureViewer::InitResourcePreview(ResourcePreview *prev, BoundResource res, bool force, Following &follow, const QString &bindName, const QString &slotName) { if(res.resourceId != ResourceId() || force) { QString fullname = bindName; if(!m_Ctx.IsAutogeneratedName(res.resourceId)) { if(!fullname.isEmpty()) fullname += lit(" = "); fullname += m_Ctx.GetResourceName(res.resourceId); } if(fullname.isEmpty()) fullname = m_Ctx.GetResourceName(res.resourceId); prev->setResourceName(fullname); WindowingData winData = m_Ctx.CreateWindowingData(prev->thumbWidget()); prev->setProperty("f", QVariant::fromValue(follow)); prev->setSlotName(slotName); prev->setActive(true); prev->setSelected(m_Following == follow); if(m_Ctx.GetTexture(res.resourceId)) { m_Ctx.Replay().AsyncInvoke([this, winData, res](IReplayController *) { Subresource sub = {0, 0, ~0U}; if(res.firstMip >= 0) sub.mip = res.firstMip; if(res.firstSlice >= 0) sub.slice = res.firstSlice; m_Output->AddThumbnail(winData, res.resourceId, sub, res.typeCast); }); } else { m_Ctx.Replay().AsyncInvoke([this, winData](IReplayController *) { m_Output->AddThumbnail(winData, ResourceId(), {0, 0, ~0U}, CompType::Typeless); }); } } else if(m_Following == follow) { prev->setResourceName(tr("Unused")); prev->setActive(true); prev->setSelected(true); WindowingData winData = m_Ctx.CreateWindowingData(prev->thumbWidget()); m_Ctx.Replay().AsyncInvoke([this, winData](IReplayController *) { m_Output->AddThumbnail(winData, ResourceId(), {0, 0, ~0U}, CompType::Typeless); }); } else { prev->setResourceName(QString()); prev->setActive(false); prev->setSelected(false); } } void TextureViewer::InitStageResourcePreviews(ShaderStage stage, const rdcarray<ShaderResource> &resourceDetails, const rdcarray<Bindpoint> &mapping, rdcarray<BoundResourceArray> &ResList, ThumbnailStrip *prevs, int &prevIndex, bool copy, bool rw) { for(int idx = 0; idx < mapping.count(); idx++) { const Bindpoint &key = mapping[idx]; const rdcarray<BoundResource> *resArray = NULL; uint32_t dynamicallyUsedResCount = 1; int residx = ResList.indexOf(key); if(residx >= 0) { resArray = &ResList[residx].resources; dynamicallyUsedResCount = ResList[residx].dynamicallyUsedCount; } const bool collapseArray = dynamicallyUsedResCount > 20; int arrayLen = resArray != NULL ? resArray->count() : 1; // Too many resources to draw can cause a full-OS hang. // For now, limit the number displayed per resource array. arrayLen = qMin(arrayLen, 8); for(int arrayIdx = 0; arrayIdx < arrayLen; arrayIdx++) { if(resArray && !resArray->at(arrayIdx).dynamicallyUsed) continue; BoundResource res = {}; if(resArray) res = resArray->at(arrayIdx); bool used = key.used; QString bindName; for(const ShaderResource &bind : resourceDetails) { if(bind.bindPoint == idx) { bindName = bind.name; break; } } if(copy) { used = true; bindName = tr("Source"); } Following follow(rw ? FollowType::ReadWrite : FollowType::ReadOnly, stage, idx, arrayIdx); follow.SetResources(m_ReadOnlyResources[(uint32_t)follow.Stage], m_ReadWriteResources[(uint32_t)follow.Stage]); QString slotName = QFormatStr("%1 %2%3") .arg(m_Ctx.CurPipelineState().Abbrev(stage)) .arg(rw ? lit("RW ") : lit("")) .arg(idx); if(collapseArray) slotName += QFormatStr(" Arr[%1]").arg(arrayLen); else slotName += QFormatStr("[%1]").arg(arrayIdx); if(copy) slotName = tr("SRC"); // show if it's referenced by the shader - regardless of empty or not bool show = used; // it's bound, but not referenced, and we have "show disabled" show = show || (m_ShowUnused && res.resourceId != ResourceId()); // it's empty, and we have "show empty" show = show || (m_ShowEmpty && res.resourceId == ResourceId()); // it's the one we're following show = show || (follow == m_Following); ResourcePreview *prev = NULL; if(prevIndex < prevs->thumbs().size()) { prev = prevs->thumbs()[prevIndex]; // don't use it if we're not actually going to show it if(!show && !prev->isActive()) continue; } else { // don't create it if we're not actually going to show it if(!show) continue; prev = UI_CreateThumbnail(prevs); } prevIndex++; InitResourcePreview(prev, show ? res : BoundResource(), show, follow, bindName, slotName); if(collapseArray) break; } } } void TextureViewer::thumb_doubleClicked(QMouseEvent *e) { if(e->buttons() & Qt::LeftButton) { ResourceId id = m_Following.GetResourceId(m_Ctx); if(id != ResourceId()) ViewTexture(id, false); } } void TextureViewer::thumb_clicked(QMouseEvent *e) { if(e->buttons() & Qt::LeftButton) { ResourcePreview *prev = qobject_cast<ResourcePreview *>(QObject::sender()); Following follow = prev->property("f").value<Following>(); follow.SetResources(m_ReadOnlyResources[(uint32_t)follow.Stage], m_ReadWriteResources[(uint32_t)follow.Stage]); for(ResourcePreview *p : ui->outputThumbs->thumbs()) p->setSelected(false); for(ResourcePreview *p : ui->inputThumbs->thumbs()) p->setSelected(false); m_Following = follow; prev->setSelected(true); UI_UpdateCachedTexture(); ResourceId id = m_Following.GetResourceId(m_Ctx); if(id != ResourceId()) { UI_OnTextureSelectionChanged(false); ui->renderContainer->show(); } } if(e->buttons() & Qt::RightButton) { ResourcePreview *prev = qobject_cast<ResourcePreview *>(QObject::sender()); Following follow = prev->property("f").value<Following>(); follow.SetResources(m_ReadOnlyResources[(uint32_t)follow.Stage], m_ReadWriteResources[(uint32_t)follow.Stage]); ResourceId id = follow.GetResourceId(m_Ctx); if(id == ResourceId() && follow == m_Following) id = m_TexDisplay.resourceId; rdcarray<EventUsage> empty; bool input = follow.Type == FollowType::ReadOnly; if(id == ResourceId()) { OpenResourceContextMenu(id, input, empty); } else { m_Ctx.Replay().AsyncInvoke([this, id, input](IReplayController *r) { rdcarray<EventUsage> usage = r->GetUsage(id); GUIInvoke::call(this, [this, id, input, usage]() { OpenResourceContextMenu(id, input, usage); }); }); } } } void TextureViewer::render_mouseWheel(QWheelEvent *e) { QPoint cursorPos = e->pos(); setFitToWindow(false); // scroll in logarithmic scale double logScale = logf(m_TexDisplay.scale); logScale += e->delta() / 2500.0; UI_SetScale((float)expf(logScale), cursorPos.x() * ui->render->devicePixelRatio(), cursorPos.y() * ui->render->devicePixelRatio()); e->accept(); } void TextureViewer::render_mouseMove(QMouseEvent *e) { if(m_Output == NULL) return; m_CurHoverPixel.setX(int((float(e->x() * ui->render->devicePixelRatio()) - m_TexDisplay.xOffset) / m_TexDisplay.scale)); m_CurHoverPixel.setY(int((float(e->y() * ui->render->devicePixelRatio()) - m_TexDisplay.yOffset) / m_TexDisplay.scale)); if(m_TexDisplay.resourceId != ResourceId()) { TextureDescription *texptr = GetCurrentTexture(); if(texptr != NULL) { if(e->buttons() & Qt::RightButton) { ui->render->setCursor(QCursor(Qt::CrossCursor)); m_PickedPoint = m_CurHoverPixel; m_PickedPoint.setX(qBound(0, m_PickedPoint.x(), (int)texptr->width - 1)); m_PickedPoint.setY(qBound(0, m_PickedPoint.y(), (int)texptr->height - 1)); m_Ctx.Replay().AsyncInvoke(lit("PickPixelClick"), [this](IReplayController *r) { RT_PickPixelsAndUpdate(r); }); } else if(e->buttons() == Qt::NoButton) { m_Ctx.Replay().AsyncInvoke(lit("PickPixelHover"), [this](IReplayController *r) { RT_PickHoverAndUpdate(r); }); } } } QPoint curpos = QCursor::pos(); if(e->buttons() & Qt::LeftButton) { if(qAbs(m_DragStartPos.x() - curpos.x()) > ui->renderHScroll->singleStep() || qAbs(m_DragStartPos.y() - curpos.y()) > ui->renderVScroll->singleStep()) { setScrollPosition(QPoint(m_DragStartScroll.x() + (curpos.x() - m_DragStartPos.x()), m_DragStartScroll.y() + (curpos.y() - m_DragStartPos.y()))); } ui->render->setCursor(QCursor(Qt::SizeAllCursor)); } if(e->buttons() == Qt::NoButton) { ui->render->unsetCursor(); } UI_UpdateStatusText(); } void TextureViewer::render_mouseClick(QMouseEvent *e) { ui->render->setFocus(); if(e->buttons() & Qt::RightButton) render_mouseMove(e); if(e->buttons() & Qt::LeftButton) { m_DragStartPos = QCursor::pos(); m_DragStartScroll = getScrollPosition(); ui->render->setCursor(QCursor(Qt::SizeAllCursor)); } } void TextureViewer::render_resize(QResizeEvent *e) { UI_UpdateFittedScale(); UI_CalcScrollbars(); INVOKE_MEMFN(RT_UpdateAndDisplay); } void TextureViewer::render_keyPress(QKeyEvent *e) { TextureDescription *texptr = GetCurrentTexture(); if(texptr == NULL) return; if(e->matches(QKeySequence::Copy)) { QClipboard *clipboard = QApplication::clipboard(); clipboard->setText(ui->texStatusName->text() + ui->texStatusDim->text() + ui->texStatusFormat->text() + lit(" | ") + ui->hoverText->text() + ui->pickedText->text()); } if(!m_Ctx.IsCaptureLoaded()) return; if((e->modifiers() & Qt::ControlModifier) && e->key() == Qt::Key_G) { ShowGotoPopup(); } bool nudged = false; int increment = 1 << (int)m_TexDisplay.subresource.mip; if(e->key() == Qt::Key_Up && m_PickedPoint.y() > 0) { m_PickedPoint -= QPoint(0, increment); nudged = true; } else if(e->key() == Qt::Key_Down && m_PickedPoint.y() < (int)texptr->height - 1) { m_PickedPoint += QPoint(0, increment); nudged = true; } else if(e->key() == Qt::Key_Left && m_PickedPoint.x() > 0) { m_PickedPoint -= QPoint(increment, 0); nudged = true; } else if(e->key() == Qt::Key_Right && m_PickedPoint.x() < (int)texptr->width - 1) { m_PickedPoint += QPoint(increment, 0); nudged = true; } if(nudged) { m_PickedPoint = QPoint(qBound(0, m_PickedPoint.x(), (int)texptr->width - 1), qBound(0, m_PickedPoint.y(), (int)texptr->height - 1)); e->accept(); m_Ctx.Replay().AsyncInvoke([this](IReplayController *r) { RT_PickPixelsAndUpdate(r); RT_UpdateAndDisplay(r); }); UI_UpdateStatusText(); } } float TextureViewer::CurMaxScrollX() { TextureDescription *texptr = GetCurrentTexture(); QSizeF size(1.0f, 1.0f); if(texptr != NULL) size = QSizeF(texptr->width, texptr->height); return realRenderWidth() - size.width() * m_TexDisplay.scale; } float TextureViewer::CurMaxScrollY() { TextureDescription *texptr = GetCurrentTexture(); QSizeF size(1.0f, 1.0f); if(texptr != NULL) size = QSizeF(texptr->width, texptr->height); return realRenderHeight() - size.height() * m_TexDisplay.scale; } QPoint TextureViewer::getScrollPosition() { return QPoint((int)m_TexDisplay.xOffset, m_TexDisplay.yOffset); } void TextureViewer::setScrollPosition(const QPoint &pos) { m_TexDisplay.xOffset = qMax(CurMaxScrollX(), (float)pos.x()); m_TexDisplay.yOffset = qMax(CurMaxScrollY(), (float)pos.y()); m_TexDisplay.xOffset = qMin(0.0f, m_TexDisplay.xOffset); m_TexDisplay.yOffset = qMin(0.0f, m_TexDisplay.yOffset); if(ScrollUpdateScrollbars) { ScrollUpdateScrollbars = false; if(ui->renderHScroll->isEnabled()) ui->renderHScroll->setValue(qBound(0, -int(m_TexDisplay.xOffset), ui->renderHScroll->maximum())); if(ui->renderVScroll->isEnabled()) ui->renderVScroll->setValue(qBound(0, -int(m_TexDisplay.yOffset), ui->renderVScroll->maximum())); ScrollUpdateScrollbars = true; } INVOKE_MEMFN(RT_UpdateAndDisplay); } void TextureViewer::UI_CalcScrollbars() { TextureDescription *texptr = GetCurrentTexture(); QSizeF size(1.0f, 1.0f); if(texptr != NULL) { size = QSizeF(texptr->width, texptr->height); } if((int)floor(size.width() * m_TexDisplay.scale) <= realRenderWidth()) { ui->renderHScroll->setEnabled(false); } else { ui->renderHScroll->setEnabled(true); ui->renderHScroll->setMaximum((int)ceil(size.width() * m_TexDisplay.scale - realRenderWidth())); ui->renderHScroll->setPageStep(qMax(1, ui->renderHScroll->maximum() / 6)); ui->renderHScroll->setSingleStep(int(m_TexDisplay.scale)); } if((int)floor(size.height() * m_TexDisplay.scale) <= realRenderHeight()) { ui->renderVScroll->setEnabled(false); } else { ui->renderVScroll->setEnabled(true); ui->renderVScroll->setMaximum((int)ceil(size.height() * m_TexDisplay.scale - realRenderHeight())); ui->renderVScroll->setPageStep(qMax(1, ui->renderVScroll->maximum() / 6)); ui->renderVScroll->setSingleStep(int(m_TexDisplay.scale)); } } void TextureViewer::on_renderHScroll_valueChanged(int position) { if(!ScrollUpdateScrollbars) return; ScrollUpdateScrollbars = false; { float delta = (float)position / (float)ui->renderHScroll->maximum(); setScrollPosition(QPoint((int)(CurMaxScrollX() * delta), getScrollPosition().y())); } ScrollUpdateScrollbars = true; } void TextureViewer::on_renderVScroll_valueChanged(int position) { if(!ScrollUpdateScrollbars) return; ScrollUpdateScrollbars = false; { float delta = (float)position / (float)ui->renderVScroll->maximum(); setScrollPosition(QPoint(getScrollPosition().x(), (int)(CurMaxScrollY() * delta))); } ScrollUpdateScrollbars = true; } void TextureViewer::UI_RecreatePanels() { ICaptureContext *ctx = &m_Ctx; // while a capture is loaded, pass NULL into the widget if(!m_Ctx.IsCaptureLoaded()) ctx = NULL; { CustomPaintWidget *render = new CustomPaintWidget(ctx, ui->renderContainer); render->setObjectName(ui->render->objectName()); render->setSizePolicy(ui->render->sizePolicy()); delete ui->render; ui->render = render; ui->gridLayout->addWidget(render, 1, 0, 1, 1); } { CustomPaintWidget *pixelContext = new CustomPaintWidget(ctx, ui->pixelContextLayout); pixelContext->setObjectName(ui->pixelContext->objectName()); pixelContext->setSizePolicy(ui->pixelContext->sizePolicy()); delete ui->pixelContext; ui->pixelContext = pixelContext; ui->pixelcontextgrid->addWidget(pixelContext, 0, 0, 1, 2); } updateBackgroundColors(); QObject::connect(ui->render, &CustomPaintWidget::clicked, this, &TextureViewer::render_mouseClick); QObject::connect(ui->render, &CustomPaintWidget::mouseMove, this, &TextureViewer::render_mouseMove); QObject::connect(ui->render, &CustomPaintWidget::mouseWheel, this, &TextureViewer::render_mouseWheel); QObject::connect(ui->render, &CustomPaintWidget::resize, this, &TextureViewer::render_resize); QObject::connect(ui->render, &CustomPaintWidget::keyPress, this, &TextureViewer::render_keyPress); QObject::connect(ui->pixelContext, &CustomPaintWidget::keyPress, this, &TextureViewer::render_keyPress); } void TextureViewer::updateBackgroundColors() { if(backCol.isValid()) { ui->render->setColours(backCol, backCol); ui->pixelContext->setColours(backCol, backCol); } else { ui->render->setColours(Formatter::DarkCheckerColor(), Formatter::LightCheckerColor()); ui->pixelContext->setColours(Formatter::DarkCheckerColor(), Formatter::LightCheckerColor()); } } void TextureViewer::OnCaptureLoaded() { Reset(); WindowingData renderData = m_Ctx.CreateWindowingData(ui->render); WindowingData contextData = m_Ctx.CreateWindowingData(ui->pixelContext); ui->saveTex->setEnabled(true); ui->locationGoto->setEnabled(true); ui->viewTexBuffer->setEnabled(true); ui->pixelHistory->setEnabled(false); ui->pixelHistory->setToolTip(QString()); ui->debugPixelContext->setEnabled(false); ui->pixelHistory->setToolTip(QString()); TextureListItemModel *model = (TextureListItemModel *)ui->textureList->model(); model->reset(TextureListItemModel::String, QString()); m_TexDisplay.backgroundColor = backCol.isValid() ? FloatVector(backCol.redF(), backCol.greenF(), backCol.blueF(), 1.0f) : FloatVector(); m_Ctx.Replay().BlockInvoke([renderData, contextData, this](IReplayController *r) { m_Output = r->CreateOutput(renderData, ReplayOutputType::Texture); m_Output->SetPixelContext(contextData); ui->render->setOutput(m_Output); ui->pixelContext->setOutput(m_Output); RT_UpdateAndDisplay(r); GUIInvoke::call(this, [this]() { OnEventChanged(m_Ctx.CurEvent()); }); }); m_Watcher = new QFileSystemWatcher({configFilePath(QString())}, this); QObject::connect(m_Watcher, &QFileSystemWatcher::fileChanged, this, &TextureViewer::customShaderModified); QObject::connect(m_Watcher, &QFileSystemWatcher::directoryChanged, this, &TextureViewer::customShaderModified); m_NeedCustomReload = true; } void TextureViewer::Reset() { m_CachedTexture = NULL; m_PickedPoint.setX(-1); m_PickedPoint.setY(-1); memset(&m_TexDisplay, 0, sizeof(m_TexDisplay)); m_TexDisplay.backgroundColor = backCol.isValid() ? FloatVector(backCol.redF(), backCol.greenF(), backCol.blueF(), 1.0f) : FloatVector(); m_Output = NULL; m_TextureSettings.clear(); m_PrevSize = QSizeF(); m_HighWaterStatusLength = 0; ui->rangeHistogram->setRange(0.0f, 1.0f); ui->textureListFilter->setCurrentIndex(0); ui->renderHScroll->setEnabled(false); ui->renderVScroll->setEnabled(false); ui->pixelHistory->setEnabled(false); ui->pixelHistory->setToolTip(QString()); ui->debugPixelContext->setEnabled(false); ui->debugPixelContext->setToolTip(QString()); ui->texStatusName->setText(QString()); ui->texStatusDim->setText(QString()); ui->texStatusFormat->setText(QString()); ui->hoverText->setText(QString()); ui->pickedText->setText(QString()); ui->renderContainer->setWindowTitle(tr("Current")); ui->mipLevel->clear(); ui->sliceFace->clear(); UI_SetScale(1.0f); ui->channels->setCurrentIndex(0); ui->overlay->setCurrentIndex(0); { QPalette Pal(palette()); Pal.setColor(QPalette::Background, Qt::black); ui->pickSwatch->setAutoFillBackground(true); ui->pickSwatch->setPalette(Pal); } ui->customShader->clear(); UI_RecreatePanels(); ui->inputThumbs->clearThumbs(); ui->outputThumbs->clearThumbs(); UI_UpdateTextureDetails(); UI_UpdateChannels(); } void TextureViewer::OnCaptureClosed() { Reset(); refreshTextureList(); delete m_Watcher; m_Watcher = NULL; ToolWindowManagerArea *textureTabs = ui->dockarea->areaOf(ui->renderContainer); while(textureTabs->count() > 1) textureTabs->removeTab(1); m_LockedTabs.clear(); ui->customShader->clear(); m_CustomShaders.clear(); ui->saveTex->setEnabled(false); ui->locationGoto->setEnabled(false); ui->viewTexBuffer->setEnabled(false); UI_UpdateChannels(); } void TextureViewer::OnEventChanged(uint32_t eventId) { UI_UpdateCachedTexture(); TextureDescription *CurrentTexture = GetCurrentTexture(); if(!currentTextureIsLocked() || (CurrentTexture != NULL && m_TexDisplay.resourceId != CurrentTexture->resourceId)) UI_OnTextureSelectionChanged(true); if(m_Output == NULL) return; UI_CreateThumbnails(); UI_UpdateTextureDetails(); refreshTextureList(); // iterate over locked tabs, and update the name if it's changed for(QWidget *w : m_LockedTabs.values()) { ResourceId id = w->property("id").value<ResourceId>(); w->setWindowTitle(m_Ctx.GetResourceName(id)); } rdcarray<BoundResource> RTs = Following::GetOutputTargets(m_Ctx); BoundResource Depth = Following::GetDepthTarget(m_Ctx); int outIndex = 0; int inIndex = 0; bool copy = false, clear = false, compute = false; Following::GetDrawContext(m_Ctx, copy, clear, compute); for(int rt = 0; rt < RTs.count(); rt++) { ResourcePreview *prev; if(outIndex < ui->outputThumbs->thumbs().size()) prev = ui->outputThumbs->thumbs()[outIndex]; else prev = UI_CreateThumbnail(ui->outputThumbs); outIndex++; Following follow(FollowType::OutputColour, ShaderStage::Pixel, rt, 0); QString bindName = (copy || clear) ? tr("Destination") : QString(); QString slotName = (copy || clear) ? tr("DST") : QString(m_Ctx.CurPipelineState().OutputAbbrev() + QString::number(rt)); InitResourcePreview(prev, RTs[rt], false, follow, bindName, slotName); } // depth { ResourcePreview *prev; if(outIndex < ui->outputThumbs->thumbs().size()) prev = ui->outputThumbs->thumbs()[outIndex]; else prev = UI_CreateThumbnail(ui->outputThumbs); outIndex++; Following follow(FollowType::OutputDepth, ShaderStage::Pixel, 0, 0); InitResourcePreview(prev, Depth, false, follow, QString(), tr("DS")); } ShaderStage stages[] = {ShaderStage::Vertex, ShaderStage::Hull, ShaderStage::Domain, ShaderStage::Geometry, ShaderStage::Pixel}; int count = 5; if(compute) { stages[0] = ShaderStage::Compute; count = 1; } const rdcarray<ShaderResource> empty; // display resources used for all stages for(int i = 0; i < count; i++) { ShaderStage stage = stages[i]; m_ReadWriteResources[(uint32_t)stage] = Following::GetReadWriteResources(m_Ctx, stage); m_ReadOnlyResources[(uint32_t)stage] = Following::GetReadOnlyResources(m_Ctx, stage); const ShaderReflection *details = Following::GetReflection(m_Ctx, stage); const ShaderBindpointMapping &mapping = Following::GetMapping(m_Ctx, stage); InitStageResourcePreviews(stage, details != NULL ? details->readWriteResources : empty, mapping.readWriteResources, m_ReadWriteResources[(uint32_t)stage], ui->outputThumbs, outIndex, copy, true); InitStageResourcePreviews(stage, details != NULL ? details->readOnlyResources : empty, mapping.readOnlyResources, m_ReadOnlyResources[(uint32_t)stage], ui->inputThumbs, inIndex, copy, false); } // hide others const QVector<ResourcePreview *> &outThumbs = ui->outputThumbs->thumbs(); for(; outIndex < outThumbs.size(); outIndex++) { ResourcePreview *prev = outThumbs[outIndex]; prev->setResourceName(QString()); prev->setActive(false); prev->setSelected(false); } ui->outputThumbs->refreshLayout(); const QVector<ResourcePreview *> &inThumbs = ui->inputThumbs->thumbs(); for(; inIndex < inThumbs.size(); inIndex++) { ResourcePreview *prev = inThumbs[inIndex]; prev->setResourceName(QString()); prev->setActive(false); prev->setSelected(false); } ui->inputThumbs->refreshLayout(); INVOKE_MEMFN(RT_UpdateAndDisplay); if(ui->autoFit->isChecked()) AutoFitRange(); } QVariant TextureViewer::persistData() { QVariantMap state = ui->dockarea->saveState(); state[lit("backCol")] = backCol; state[lit("checker")] = !backCol.isValid(); return state; } void TextureViewer::setPersistData(const QVariant &persistData) { QVariantMap state = persistData.toMap(); backCol = state[lit("backCol")].value<QColor>(); bool checker = state[lit("checker")].value<bool>(); if(checker) backCol = QColor(); ui->backcolorPick->setChecked(!checker); ui->checkerBack->setChecked(checker); m_TexDisplay.backgroundColor = checker ? FloatVector() : FloatVector(backCol.redF(), backCol.greenF(), backCol.blueF(), 1.0f); ToolWindowManagerArea *textureTabs = ui->dockarea->areaOf(ui->renderContainer); while(textureTabs->count() > 1) textureTabs->removeTab(1); m_LockedTabs.clear(); updateBackgroundColors(); ui->dockarea->restoreState(state); SetupTextureTabs(); } float TextureViewer::GetFitScale() { TextureDescription *texptr = GetCurrentTexture(); if(texptr == NULL) return 1.0f; float xscale = (float)realRenderWidth() / (float)texptr->width; float yscale = (float)realRenderHeight() / (float)texptr->height; return qMin(xscale, yscale); } int TextureViewer::realRenderWidth() const { return ui->render->width() * ui->render->devicePixelRatio(); } int TextureViewer::realRenderHeight() const { return ui->render->height() * ui->render->devicePixelRatio(); } void TextureViewer::UI_UpdateFittedScale() { if(ui->fitToWindow->isChecked()) UI_SetScale(1.0f); } void TextureViewer::UI_SetScale(float s) { UI_SetScale(s, ui->render->width() / 2, ui->render->height() / 2); } void TextureViewer::UI_SetScale(float s, int x, int y) { if(ui->fitToWindow->isChecked()) s = GetFitScale(); float prevScale = m_TexDisplay.scale; m_TexDisplay.scale = qBound(0.1f, s, 256.0f); INVOKE_MEMFN(RT_UpdateAndDisplay); float scaleDelta = (m_TexDisplay.scale / prevScale); QPoint newPos = getScrollPosition(); newPos -= QPoint(x, y); newPos = QPoint((int)(newPos.x() * scaleDelta), (int)(newPos.y() * scaleDelta)); newPos += QPoint(x, y); setScrollPosition(newPos); setCurrentZoomValue(m_TexDisplay.scale); UI_CalcScrollbars(); } void TextureViewer::setCurrentZoomValue(float zoom) { ui->zoomOption->setCurrentText(QString::number(ceil(zoom * 100)) + lit("%")); } float TextureViewer::getCurrentZoomValue() { if(ui->fitToWindow->isChecked()) return m_TexDisplay.scale; QString zoomText = ui->zoomOption->currentText().replace(QLatin1Char('%'), QLatin1Char(' ')); bool ok = false; int zoom = zoomText.toInt(&ok); if(!ok) zoom = 100; return (float)(zoom) / 100.0f; } void TextureViewer::setFitToWindow(bool checked) { if(checked) { UI_UpdateFittedScale(); ui->fitToWindow->setChecked(true); } else if(!checked) { ui->fitToWindow->setChecked(false); float curScale = m_TexDisplay.scale; ui->zoomOption->setCurrentText(QString()); setCurrentZoomValue(curScale); } } void TextureViewer::on_fitToWindow_toggled(bool checked) { UI_UpdateFittedScale(); } void TextureViewer::on_zoomExactSize_clicked() { ui->fitToWindow->setChecked(false); UI_SetScale(1.0f); } void TextureViewer::on_zoomOption_currentIndexChanged(int index) { if(index >= 0) { setFitToWindow(false); ui->zoomOption->setCurrentText(ui->zoomOption->itemText(index)); UI_SetScale(getCurrentZoomValue()); } } void TextureViewer::zoomOption_returnPressed() { UI_SetScale(getCurrentZoomValue()); } void TextureViewer::on_overlay_currentIndexChanged(int index) { m_TexDisplay.overlay = DebugOverlay::NoOverlay; if(ui->overlay->currentIndex() > 0) m_TexDisplay.overlay = (DebugOverlay)ui->overlay->currentIndex(); #define ANALYTICS_OVERLAY(name) \ case DebugOverlay::name: ANALYTIC_SET(TextureOverlays.name, true); break; switch(m_TexDisplay.overlay) { ANALYTICS_OVERLAY(Drawcall); ANALYTICS_OVERLAY(Wireframe); ANALYTICS_OVERLAY(Depth); ANALYTICS_OVERLAY(Stencil); ANALYTICS_OVERLAY(BackfaceCull); ANALYTICS_OVERLAY(ViewportScissor); ANALYTICS_OVERLAY(NaN); ANALYTICS_OVERLAY(Clipping); ANALYTICS_OVERLAY(ClearBeforePass); ANALYTICS_OVERLAY(ClearBeforeDraw); ANALYTICS_OVERLAY(QuadOverdrawPass); ANALYTICS_OVERLAY(QuadOverdrawDraw); ANALYTICS_OVERLAY(TriangleSizePass); ANALYTICS_OVERLAY(TriangleSizeDraw); default: break; } #undef ANALYTICS_OVERLAY INVOKE_MEMFN(RT_UpdateAndDisplay); if(m_Output != NULL && m_PickedPoint.x() >= 0 && m_PickedPoint.y() >= 0) { INVOKE_MEMFN(RT_PickPixelsAndUpdate); } } void TextureViewer::channelsWidget_mouseClicked(QMouseEvent *event) { RDToolButton *s = qobject_cast<RDToolButton *>(QObject::sender()); if(event->button() == Qt::RightButton && s) { bool checkd = false; RDToolButton *butts[] = {ui->channelRed, ui->channelGreen, ui->channelBlue, ui->channelAlpha}; for(RDToolButton *b : butts) { if(b->isChecked() && b != s) checkd = true; if(!b->isChecked() && b == s) checkd = true; } ui->channelRed->setChecked(!checkd); ui->channelGreen->setChecked(!checkd); ui->channelBlue->setChecked(!checkd); ui->channelAlpha->setChecked(!checkd); s->setChecked(checkd); } } void TextureViewer::range_rangeUpdated() { m_TexDisplay.rangeMin = ui->rangeHistogram->blackPoint(); m_TexDisplay.rangeMax = ui->rangeHistogram->whitePoint(); ui->rangeBlack->setText(Formatter::Format(m_TexDisplay.rangeMin)); ui->rangeWhite->setText(Formatter::Format(m_TexDisplay.rangeMax)); if(m_NoRangePaint) return; INVOKE_MEMFN(RT_UpdateAndDisplay); if(m_Output == NULL) { ui->render->update(); ui->pixelContext->update(); } } void TextureViewer::rangePoint_textChanged(QString text) { m_RangePoint_Dirty = true; } void TextureViewer::rangePoint_Update() { float black = ui->rangeHistogram->blackPoint(); float white = ui->rangeHistogram->whitePoint(); bool ok = false; double d = ui->rangeBlack->text().toDouble(&ok); if(ok) black = d; d = ui->rangeWhite->text().toDouble(&ok); if(ok) white = d; ui->rangeHistogram->setRange(black, white); INVOKE_MEMFN(RT_UpdateVisualRange); } void TextureViewer::rangePoint_leave() { if(!m_RangePoint_Dirty) return; rangePoint_Update(); m_RangePoint_Dirty = false; } void TextureViewer::rangePoint_keyPress(QKeyEvent *e) { // escape key if(e->key() == Qt::Key_Escape) { m_RangePoint_Dirty = false; ui->rangeHistogram->setRange(ui->rangeHistogram->blackPoint(), ui->rangeHistogram->whitePoint()); } if(e->key() == Qt::Key_Return || e->key() == Qt::Key_Enter) { rangePoint_Update(); } } void TextureViewer::on_zoomRange_clicked() { float black = ui->rangeHistogram->blackPoint(); float white = ui->rangeHistogram->whitePoint(); ui->autoFit->setChecked(false); ui->rangeHistogram->setRange(black, white); INVOKE_MEMFN(RT_UpdateVisualRange); } void TextureViewer::on_autoFit_clicked() { AutoFitRange(); ui->autoFit->setChecked(false); } void TextureViewer::on_autoFit_mouseClicked(QMouseEvent *e) { if(e->buttons() & Qt::RightButton) ui->autoFit->setChecked(!ui->autoFit->isChecked()); } void TextureViewer::on_reset01_clicked() { UI_SetHistogramRange(GetCurrentTexture(), m_TexDisplay.typeCast); ui->autoFit->setChecked(false); INVOKE_MEMFN(RT_UpdateVisualRange); } void TextureViewer::on_visualiseRange_clicked() { if(ui->visualiseRange->isChecked()) { ui->rangeHistogram->setMinimumSize(QSize(300, 90)); m_Visualise = true; INVOKE_MEMFN(RT_UpdateVisualRange); } else { m_Visualise = false; ui->rangeHistogram->setMinimumSize(QSize(200, 0)); ui->rangeHistogram->setHistogramData({}); } } void TextureViewer::AutoFitRange() { // no capture loaded or buffer/empty texture currently being viewed - don't autofit if(!m_Ctx.IsCaptureLoaded() || GetCurrentTexture() == NULL || m_Output == NULL) return; m_Ctx.Replay().AsyncInvoke([this](IReplayController *r) { ResourceId textureId = m_TexDisplay.resourceId; Subresource sub = m_TexDisplay.subresource; CompType typeCast = m_TexDisplay.typeCast; if(m_TexDisplay.customShaderId != ResourceId() && m_Output->GetCustomShaderTexID() != ResourceId()) { textureId = m_Output->GetCustomShaderTexID(); sub.slice = sub.sample = 0; typeCast = CompType::Typeless; } PixelValue min, max; rdctie(min, max) = r->GetMinMax(textureId, sub, typeCast); { float minval = FLT_MAX; float maxval = -FLT_MAX; bool changeRange = false; ResourceFormat fmt = GetCurrentTexture()->format; if(m_TexDisplay.customShaderId != ResourceId()) { fmt.compType = CompType::Float; } if(fmt.compType == CompType::Typeless && m_TexDisplay.typeCast == CompType::UInt) fmt.compType = CompType::UInt; if(fmt.compType == CompType::Typeless && m_TexDisplay.typeCast == CompType::SInt) fmt.compType = CompType::SInt; for(int i = 0; i < 4; i++) { if(fmt.compType == CompType::UInt) { min.floatValue[i] = min.uintValue[i]; max.floatValue[i] = max.uintValue[i]; } else if(fmt.compType == CompType::SInt) { min.floatValue[i] = min.intValue[i]; max.floatValue[i] = max.intValue[i]; } } if(m_TexDisplay.red) { minval = qMin(minval, min.floatValue[0]); maxval = qMax(maxval, max.floatValue[0]); changeRange = true; } if(m_TexDisplay.green && fmt.compCount > 1) { minval = qMin(minval, min.floatValue[1]); maxval = qMax(maxval, max.floatValue[1]); changeRange = true; } if(m_TexDisplay.blue && fmt.compCount > 2) { minval = qMin(minval, min.floatValue[2]); maxval = qMax(maxval, max.floatValue[2]); changeRange = true; } if(m_TexDisplay.alpha && fmt.compCount > 3) { minval = qMin(minval, min.floatValue[3]); maxval = qMax(maxval, max.floatValue[3]); changeRange = true; } if(changeRange) { GUIInvoke::call(this, [this, minval, maxval]() { ui->rangeHistogram->setRange(minval, maxval); INVOKE_MEMFN(RT_UpdateVisualRange); }); } } }); } void TextureViewer::on_backcolorPick_clicked() { QColor col = QColorDialog::getColor(Qt::black, this, tr("Choose background colour")); if(!col.isValid()) return; col = col.toRgb(); m_TexDisplay.backgroundColor = FloatVector(col.redF(), col.greenF(), col.blueF(), 1.0f); backCol = col; updateBackgroundColors(); ui->backcolorPick->setChecked(true); ui->checkerBack->setChecked(false); INVOKE_MEMFN(RT_UpdateAndDisplay); if(m_Output == NULL) { ui->render->update(); ui->pixelContext->update(); } } void TextureViewer::on_checkerBack_clicked() { ui->checkerBack->setChecked(true); ui->backcolorPick->setChecked(false); backCol = QColor(); m_TexDisplay.backgroundColor = FloatVector(); updateBackgroundColors(); INVOKE_MEMFN(RT_UpdateAndDisplay); if(m_Output == NULL) { ui->render->update(); ui->pixelContext->update(); } } void TextureViewer::on_mipLevel_currentIndexChanged(int index) { TextureDescription *texptr = GetCurrentTexture(); if(texptr == NULL) return; TextureDescription &tex = *texptr; uint32_t prevSlice = m_TexDisplay.subresource.slice; if(tex.mips > 1) { m_TexDisplay.subresource.mip = (uint32_t)qMax(0, index); m_TexDisplay.subresource.sample = 0; } else { m_TexDisplay.subresource.mip = 0; m_TexDisplay.subresource.sample = (uint32_t)qMax(0, index); if(m_TexDisplay.subresource.sample == tex.msSamp) m_TexDisplay.subresource.sample = ~0U; } // For 3D textures, update the slice list for this mip if(tex.depth > 1) { uint32_t newSlice = prevSlice >> (int)m_TexDisplay.subresource.mip; uint32_t numSlices = qMax(1U, tex.depth >> (int)m_TexDisplay.subresource.mip); ui->sliceFace->clear(); for(uint32_t i = 0; i < numSlices; i++) ui->sliceFace->addItem(tr("Slice %1").arg(i)); // changing sliceFace index will handle updating range & re-picking ui->sliceFace->setCurrentIndex((int)qBound(0U, newSlice, numSlices - 1)); return; } INVOKE_MEMFN(RT_UpdateVisualRange); if(m_Output != NULL && m_PickedPoint.x() >= 0 && m_PickedPoint.y() >= 0) { INVOKE_MEMFN(RT_PickPixelsAndUpdate); } INVOKE_MEMFN(RT_UpdateAndDisplay); } void TextureViewer::on_sliceFace_currentIndexChanged(int index) { TextureDescription *texptr = GetCurrentTexture(); if(texptr == NULL) return; TextureDescription &tex = *texptr; m_TexDisplay.subresource.slice = (uint32_t)qMax(0, index); INVOKE_MEMFN(RT_UpdateVisualRange); if(m_Output != NULL && m_PickedPoint.x() >= 0 && m_PickedPoint.y() >= 0) { INVOKE_MEMFN(RT_PickPixelsAndUpdate); } INVOKE_MEMFN(RT_UpdateAndDisplay); } void TextureViewer::on_locationGoto_clicked() { ShowGotoPopup(); } void TextureViewer::ShowGotoPopup() { TextureDescription *texptr = GetCurrentTexture(); if(texptr) { QPoint p = m_PickedPoint; p.setX(p.x() >> (int)m_TexDisplay.subresource.mip); p.setY(p.y() >> (int)m_TexDisplay.subresource.mip); uint32_t mipHeight = qMax(1U, texptr->height >> (int)m_TexDisplay.subresource.mip); if(m_Ctx.APIProps().pipelineType == GraphicsAPI::OpenGL) p.setY((int)(mipHeight - 1) - p.y()); if(m_TexDisplay.flipY) p.setY((int)(mipHeight - 1) - p.y()); m_Goto->show(ui->render, p); } } void TextureViewer::on_viewTexBuffer_clicked() { TextureDescription *texptr = GetCurrentTexture(); if(texptr) { IBufferViewer *viewer = m_Ctx.ViewTextureAsBuffer(texptr->resourceId, m_TexDisplay.subresource, BufferFormatter::GetTextureFormatString(*texptr)); viewer->ScrollToRow(m_PickedPoint.y()); viewer->ScrollToColumn(m_PickedPoint.x() * texptr->format.compCount + 1); m_Ctx.AddDockWindow(viewer->Widget(), DockReference::AddTo, this); } } void TextureViewer::on_resourceDetails_clicked() { TextureDescription *texptr = GetCurrentTexture(); if(texptr) { if(!m_Ctx.HasResourceInspector()) m_Ctx.ShowResourceInspector(); m_Ctx.GetResourceInspector()->Inspect(texptr->resourceId); ToolWindowManager::raiseToolWindow(m_Ctx.GetResourceInspector()->Widget()); } } void TextureViewer::on_saveTex_clicked() { TextureDescription *texptr = GetCurrentTexture(); if(!texptr || !m_Output) return; // overwrite save params with current texture display settings m_SaveConfig.resourceId = m_TexDisplay.resourceId; m_SaveConfig.typeCast = m_TexDisplay.typeCast; m_SaveConfig.slice.sliceIndex = (int)m_TexDisplay.subresource.slice; m_SaveConfig.mip = (int)m_TexDisplay.subresource.mip; m_SaveConfig.channelExtract = -1; if(m_TexDisplay.red && !m_TexDisplay.green && !m_TexDisplay.blue && !m_TexDisplay.alpha) m_SaveConfig.channelExtract = 0; if(!m_TexDisplay.red && m_TexDisplay.green && !m_TexDisplay.blue && !m_TexDisplay.alpha) m_SaveConfig.channelExtract = 1; if(!m_TexDisplay.red && !m_TexDisplay.green && m_TexDisplay.blue && !m_TexDisplay.alpha) m_SaveConfig.channelExtract = 2; if(!m_TexDisplay.red && !m_TexDisplay.green && !m_TexDisplay.blue && m_TexDisplay.alpha) m_SaveConfig.channelExtract = 3; m_SaveConfig.comp.blackPoint = m_TexDisplay.rangeMin; m_SaveConfig.comp.whitePoint = m_TexDisplay.rangeMax; m_SaveConfig.alphaCol = m_TexDisplay.backgroundColor; if(m_TexDisplay.customShaderId != ResourceId()) { ResourceId id; m_Ctx.Replay().BlockInvoke( [this, &id](IReplayController *r) { id = m_Output->GetCustomShaderTexID(); }); if(id != ResourceId()) { m_SaveConfig.resourceId = id; m_SaveConfig.typeCast = CompType::Typeless; } } ResourceId overlayTexID; if(m_TexDisplay.overlay != DebugOverlay::NoOverlay) { m_Ctx.Replay().BlockInvoke([this, &overlayTexID](IReplayController *r) { overlayTexID = m_Output->GetDebugOverlayTexID(); }); } const bool hasSelectedOverlay = (m_TexDisplay.overlay != DebugOverlay::NoOverlay); const bool hasOverlay = (hasSelectedOverlay && overlayTexID != ResourceId()); TextureSaveDialog saveDialog(*texptr, hasOverlay, m_SaveConfig, this); int res = RDDialog::show(&saveDialog); m_SaveConfig = saveDialog.config(); if(saveDialog.saveOverlayInstead()) { m_SaveConfig.resourceId = overlayTexID; m_SaveConfig.typeCast = CompType::Typeless; if(m_TexDisplay.overlay == DebugOverlay::QuadOverdrawDraw || m_TexDisplay.overlay == DebugOverlay::QuadOverdrawPass || m_TexDisplay.overlay == DebugOverlay::TriangleSizeDraw || m_TexDisplay.overlay == DebugOverlay::TriangleSizePass) { m_SaveConfig.comp.blackPoint = 0.0f; m_SaveConfig.comp.whitePoint = 255.0f; } } if(res) { ANALYTIC_SET(Export.Texture, true); bool ret = false; QString fn = saveDialog.filename(); m_Ctx.Replay().BlockInvoke([this, &ret, fn](IReplayController *r) { ret = r->SaveTexture(m_SaveConfig, fn.toUtf8().data()); }); if(!ret) { RDDialog::critical( NULL, tr("Error saving texture"), tr("Error saving texture %1.\n\nCheck diagnostic log in Help menu for more details.").arg(fn)); } } } void TextureViewer::on_debugPixelContext_clicked() { if(m_PickedPoint.x() < 0 || m_PickedPoint.y() < 0) return; int x = m_PickedPoint.x() >> (int)m_TexDisplay.subresource.mip; int y = m_PickedPoint.y() >> (int)m_TexDisplay.subresource.mip; TextureDescription *texptr = GetCurrentTexture(); uint32_t mipHeight = qMax(1U, texptr->height >> (int)m_TexDisplay.subresource.mip); if(m_TexDisplay.flipY) y = (int)(mipHeight - 1) - y; bool done = false; ShaderDebugTrace *trace = NULL; m_Ctx.Replay().AsyncInvoke([this, &trace, &done, x, y](IReplayController *r) { trace = r->DebugPixel((uint32_t)x, (uint32_t)y, m_TexDisplay.subresource.sample, ~0U); if(trace->debugger == NULL) { r->FreeTrace(trace); trace = NULL; } done = true; }); QString debugContext = tr("Pixel %1,%2").arg(x).arg(y); // wait a short while before displaying the progress dialog (which won't show if we're already // done by the time we reach it) for(int i = 0; !done && i < 100; i++) QThread::msleep(5); ShowProgressDialog(this, tr("Debugging %1").arg(debugContext), [&done]() { return done; }); // if we couldn't debug the pixel on this event, open up a pixel history if(!trace) { if(m_Ctx.APIProps().pixelHistory) on_pixelHistory_clicked(); else RDDialog::critical(this, tr("Debug Error"), tr("Error debugging pixel.")); return; } const ShaderReflection *shaderDetails = m_Ctx.CurPipelineState().GetShaderReflection(ShaderStage::Pixel); const ShaderBindpointMapping &bindMapping = m_Ctx.CurPipelineState().GetBindpointMapping(ShaderStage::Pixel); ResourceId pipeline = m_Ctx.CurPipelineState().GetGraphicsPipelineObject(); // viewer takes ownership of the trace IShaderViewer *s = m_Ctx.DebugShader(&bindMapping, shaderDetails, pipeline, trace, debugContext); m_Ctx.AddDockWindow(s->Widget(), DockReference::AddTo, this); } void TextureViewer::on_pixelHistory_clicked() { TextureDescription *texptr = GetCurrentTexture(); if(!texptr || !m_Output) return; ANALYTIC_SET(UIFeatures.PixelHistory, true); int x = m_PickedPoint.x() >> (int)m_TexDisplay.subresource.mip; int y = m_PickedPoint.y() >> (int)m_TexDisplay.subresource.mip; uint32_t mipHeight = qMax(1U, texptr->height >> (int)m_TexDisplay.subresource.mip); if(m_TexDisplay.flipY) y = (int)(mipHeight - 1) - y; IPixelHistoryView *hist = m_Ctx.ViewPixelHistory(texptr->resourceId, x, y, m_TexDisplay); m_Ctx.AddDockWindow(hist->Widget(), DockReference::TransientPopupArea, this, 0.3f); // we use this pointer to ensure that the history viewer is still visible (and hasn't been closed) // by the time we want to set the results. QPointer<QWidget> histWidget = hist->Widget(); // add a short delay so that controls repainting after a new panel appears can get at the // render thread before we insert the long blocking pixel history task LambdaThread *thread = new LambdaThread([this, texptr, x, y, hist, histWidget]() { QThread::msleep(150); m_Ctx.Replay().AsyncInvoke([this, texptr, x, y, hist, histWidget](IReplayController *r) { rdcarray<PixelModification> history = r->PixelHistory(texptr->resourceId, (uint32_t)x, (int32_t)y, m_TexDisplay.subresource, m_TexDisplay.typeCast); GUIInvoke::call(this, [hist, histWidget, history] { if(histWidget) hist->SetHistory(history); }); }); }); thread->selfDelete(true); thread->start(); } void TextureViewer::on_texListShow_clicked() { if(ui->textureListFrame->isVisible()) { ui->dockarea->moveToolWindow(ui->textureListFrame, ToolWindowManager::NoArea); } else { ui->textureListFilter->setCurrentText(QString()); ui->dockarea->moveToolWindow( ui->textureListFrame, ToolWindowManager::AreaReference(ToolWindowManager::LeftOf, ui->dockarea->areaOf(ui->renderContainer), 0.2f)); ui->dockarea->setToolWindowProperties(ui->textureListFrame, ToolWindowManager::HideOnClose); } } void TextureViewer::on_cancelTextureListFilter_clicked() { ui->textureListFilter->setCurrentText(QString()); } void TextureViewer::on_textureListFilter_editTextChanged(const QString &text) { TextureListItemModel *model = (TextureListItemModel *)ui->textureList->model(); if(model == NULL) return; model->reset(TextureListItemModel::String, text); } void TextureViewer::on_textureListFilter_currentIndexChanged(int index) { refreshTextureList(); } void TextureViewer::refreshTextureList() { TextureListItemModel *model = (TextureListItemModel *)ui->textureList->model(); if(model == NULL) return; if(ui->textureListFilter->currentIndex() == 1) model->reset(TextureListItemModel::Textures, QString()); else if(ui->textureListFilter->currentIndex() == 2) model->reset(TextureListItemModel::RenderTargets, QString()); else model->reset(TextureListItemModel::String, ui->textureListFilter->currentText()); } void TextureViewer::on_textureList_clicked(const QModelIndex &index) { ResourceId id = index.model()->data(index, Qt::UserRole).value<ResourceId>(); ViewTexture(id, false); } bool TextureViewer::canCompileCustomShader(ShaderEncoding encoding) { rdcarray<ShaderEncoding> supported = m_Ctx.CustomShaderEncodings(); // if it's directly supported, we can trivially compile it if(supported.contains(encoding)) return true; // otherwise see if we have a tool that can compile it for us for(const ShaderProcessingTool &tool : m_Ctx.Config().ShaderProcessors) { // if this tool transforms from the encoding to one we support, we can compile a shader of this // encoding if(tool.input == encoding && supported.contains(tool.output)) return true; } // all options exhausted, we can't compile this return false; } void TextureViewer::reloadCustomShaders(const QString &filter) { if(!m_Ctx.IsCaptureLoaded()) return; if(filter.isEmpty()) { QString prevtext = ui->customShader->currentText(); QList<ResourceId> shaders = m_CustomShaders.values(); m_Ctx.Replay().AsyncInvoke([shaders](IReplayController *r) { for(ResourceId s : shaders) r->FreeCustomShader(s); }); ui->customShader->clear(); m_CustomShaders.clear(); ui->customShader->setCurrentText(prevtext); } else { QString fn = QFileInfo(filter).fileName(); QString key = fn.toUpper(); if(m_CustomShaders.contains(key)) { if(m_CustomShadersBusy.contains(key)) return; ResourceId freed = m_CustomShaders[key]; m_Ctx.Replay().AsyncInvoke([freed](IReplayController *r) { r->FreeCustomShader(freed); }); m_CustomShaders.remove(key); QString text = ui->customShader->currentText(); for(int i = 0; i < ui->customShader->count(); i++) { if(ui->customShader->itemText(i).compare(fn, Qt::CaseInsensitive) == 0) { ui->customShader->removeItem(i); break; } } ui->customShader->setCurrentText(text); } } QStringList filters; for(auto it = encodingExtensions.begin(); it != encodingExtensions.end(); ++it) { if(!canCompileCustomShader(it.value())) continue; filters.push_back(lit("*.") + it.key()); } QStringList files; QList<QDir> shaderDirectories = getShaderDirectories(); for(const QDir &dir : shaderDirectories) { QStringList currentDirFiles = dir.entryList(filters, QDir::Files | QDir::NoDotAndDotDot, QDir::Name | QDir::IgnoreCase); for(const QString &f : currentDirFiles) { files.append(QDir::cleanPath(dir.absoluteFilePath(f))); } } QStringList watchedFiles = m_Watcher->files(); if(!watchedFiles.isEmpty()) m_Watcher->removePaths(watchedFiles); for(const QString &f : files) { QFileInfo fileInfo(f); QString fn = fileInfo.fileName(); QString key = fn.toUpper(); ShaderEncoding encoding = encodingExtensions[fileInfo.completeSuffix()]; if(!filter.isEmpty() && filter.toUpper() != key) continue; m_Watcher->addPath(f); if(!m_CustomShaders.contains(key) && !m_CustomShadersBusy.contains(key)) { QFile fileHandle(f); if(fileHandle.open(QFile::ReadOnly | QFile::Text)) { QTextStream stream(&fileHandle); QString source = stream.readAll(); bytebuf shaderBytes(source.toUtf8()); rdcarray<ShaderEncoding> supported = m_Ctx.TargetShaderEncodings(); rdcstr errors; // we don't accept this encoding directly, need to compile if(!supported.contains(encoding)) { for(const ShaderProcessingTool &tool : m_Ctx.Config().ShaderProcessors) { // pick the first tool that can convert to an accepted format if(tool.input == encoding && supported.contains(tool.output)) { ShaderToolOutput out = tool.CompileShader(this, source, "main", ShaderStage::Pixel, ""); errors = out.log; if(m_CustomShaderEditor.contains(key)) m_CustomShaderEditor[key]->ShowErrors(errors); if(out.result.isEmpty()) break; encoding = tool.output; shaderBytes = out.result; break; } } } // if the encoding still isn't supported, all tools failed. Bail out now if(!supported.contains(encoding)) { if(m_CustomShaderEditor.contains(key)) m_CustomShaderEditor[key]->ShowErrors(errors); m_CustomShaders[key] = ResourceId(); QString prevtext = ui->customShader->currentText(); ui->customShader->addItem(fn); ui->customShader->setCurrentText(prevtext); continue; } ANALYTIC_SET(UIFeatures.CustomTextureVisualise, true); fileHandle.close(); m_CustomShaders[key] = ResourceId(); m_CustomShadersBusy.push_back(key); m_Ctx.Replay().AsyncInvoke( [this, fn, key, shaderBytes, encoding, errors](IReplayController *r) { rdcstr buildErrors; ResourceId id; rdctie(id, buildErrors) = r->BuildCustomShader( "main", encoding, shaderBytes, ShaderCompileFlags(), ShaderStage::Pixel); if(!errors.empty()) buildErrors = errors + "\n\n" + buildErrors; if(m_CustomShaderEditor.contains(key)) { IShaderViewer *editor = m_CustomShaderEditor[key]; GUIInvoke::call(editor->Widget(), [editor, buildErrors]() { editor->ShowErrors(buildErrors); }); } GUIInvoke::call(this, [this, fn, key, id]() { QString prevtext = ui->customShader->currentText(); ui->customShader->addItem(fn); ui->customShader->setCurrentText(prevtext); m_CustomShaders[key] = id; m_CustomShadersBusy.removeOne(key); UI_UpdateChannels(); }); }); } } } } QList<QDir> TextureViewer::getShaderDirectories() const { QList<QDir> dirs; dirs.reserve(int(m_Ctx.Config().TextureViewer_ShaderDirs.size() + 1u)); dirs.append(QDir(configFilePath(QString()))); for(const rdcstr &dir : m_Ctx.Config().TextureViewer_ShaderDirs) { dirs.append(QDir(dir)); } return dirs; } QString TextureViewer::getShaderPath(const QString &filename) const { QString path; QList<QDir> directories = getShaderDirectories(); for(const QDir &dir : directories) { QStringList currentDirFiles = dir.entryList(QDir::Files | QDir::NoDotAndDotDot, QDir::Name | QDir::IgnoreCase); if(currentDirFiles.contains(filename, Qt::CaseInsensitive)) { path = QDir::cleanPath(dir.absoluteFilePath(filename)); break; } } return path; } void TextureViewer::on_customCreate_clicked() { QString filename = ui->customShader->currentText(); if(filename.isEmpty()) { RDDialog::critical(this, tr("Error Creating Shader"), tr("No shader name specified.\nEnter a new name in the textbox")); return; } if(m_CustomShaders.contains(filename.toUpper())) { RDDialog::critical(this, tr("Error Creating Shader"), tr("Selected shader already exists.\nEnter a new name in the textbox.")); ui->customShader->setCurrentText(QString()); UI_UpdateChannels(); return; } ShaderEncoding enc = encodingExtensions[QFileInfo(filename).completeSuffix()]; if(enc == ShaderEncoding::Unknown) { QString extString; for(auto it = encodingExtensions.begin(); it != encodingExtensions.end(); ++it) { if(!canCompileCustomShader(it.value())) continue; if(!extString.isEmpty()) extString += lit(", "); extString += it.key(); } RDDialog::critical(this, tr("Error Creating Shader"), tr("No file extension specified, unknown shading language.\n" "Filename must contain one of: %1") .arg(extString)); return; } QString src; if(enc == ShaderEncoding::HLSL) { src = lit("float4 main(float4 pos : SV_Position, float4 uv : TEXCOORD0) : SV_Target0\n" "{\n" " return float4(0,0,0,1);\n" "}\n"); } else if(enc == ShaderEncoding::GLSL) { src = lit("#version 420 core\n\n" "layout (location = 0) in vec2 uv;\n\n" "layout (location = 0) out vec4 color_out;\n\n" "void main()\n" "{\n" " color_out = vec4(0,0,0,1);\n" "}\n"); } else if(enc == ShaderEncoding::SPIRVAsm) { src = lit("; SPIR-V"); } else { src = tr("Unknown format - no template available"); } QString path = QDir::cleanPath(QDir(configFilePath(QString())).absoluteFilePath(filename)); QFile fileHandle(path); if(fileHandle.open(QFile::WriteOnly | QIODevice::Truncate | QIODevice::Text)) { fileHandle.write(src.toUtf8()); fileHandle.close(); } else { RDDialog::critical( this, tr("Cannot create shader"), tr("Couldn't create file for shader %1\n%2").arg(filename).arg(fileHandle.errorString())); } // auto-open edit window on_customEdit_clicked(); reloadCustomShaders(filename); } void TextureViewer::on_customEdit_clicked() { QString filename = ui->customShader->currentText(); QString key = filename.toUpper(); if(filename.isEmpty()) { RDDialog::critical(this, tr("Error Editing Shader"), tr("No shader selected.\nSelect a custom shader from the drop-down")); return; } QString path = getShaderPath(filename); QString src; QFile fileHandle(path); if(fileHandle.open(QFile::ReadOnly | QFile::Text)) { QTextStream stream(&fileHandle); src = stream.readAll(); fileHandle.close(); } else { RDDialog::critical( this, tr("Cannot open shader"), tr("Couldn't open file for shader %1\n%2").arg(filename).arg(fileHandle.errorString())); return; } rdcstrpairs files; files.push_back({filename, src}); QPointer<TextureViewer> thisPointer(this); IShaderViewer *s = m_Ctx.EditShader( ResourceId(), ShaderStage::Fragment, lit("main"), files, encodingExtensions[QFileInfo(filename).completeSuffix()], ShaderCompileFlags(), // Save Callback [thisPointer, key, filename, path](ICaptureContext *ctx, IShaderViewer *viewer, ShaderEncoding, ShaderCompileFlags, rdcstr, bytebuf bytes) { { // don't trigger a full refresh if(thisPointer) thisPointer->m_CustomShaderWriteTime = thisPointer->m_CustomShaderTimer.elapsed(); QFile fileHandle(path); if(fileHandle.open(QFile::WriteOnly | QIODevice::Truncate | QIODevice::Text)) { fileHandle.write(QByteArray(bytes)); fileHandle.close(); // watcher doesn't trigger on internal modifications if(thisPointer) thisPointer->reloadCustomShaders(filename); } else { if(thisPointer) { RDDialog::critical( thisPointer, tr("Cannot save shader"), tr("Couldn't save file for shader %1\n%2").arg(filename).arg(fileHandle.errorString())); } } } }, [thisPointer, key](ICaptureContext *ctx) { if(thisPointer) thisPointer->m_CustomShaderEditor.remove(key); }); m_CustomShaderEditor[key] = s; m_Ctx.AddDockWindow(s->Widget(), DockReference::AddTo, this); } void TextureViewer::on_customDelete_clicked() { QString shaderName = ui->customShader->currentText(); if(shaderName.isEmpty()) { RDDialog::critical(this, tr("Error Deleting Shader"), tr("No shader selected.\nSelect a custom shader from the drop-down")); return; } if(!m_CustomShaders.contains(shaderName.toUpper())) { RDDialog::critical( this, tr("Error Deleting Shader"), tr("Selected shader doesn't exist.\nSelect a custom shader from the drop-down")); return; } QMessageBox::StandardButton res = RDDialog::question(this, tr("Deleting Custom Shader"), tr("Really delete %1?").arg(shaderName), RDDialog::YesNoCancel); if(res == QMessageBox::Yes) { QString path = getShaderPath(shaderName); if(!QFileInfo::exists(path)) { RDDialog::critical( this, tr("Error Deleting Shader"), tr("Shader file %1 can't be found.\nSelect a custom shader from the drop-down") .arg(shaderName)); return; } if(!QFile::remove(path)) { RDDialog::critical(this, tr("Error Deleting Shader"), tr("Error deleting shader %1 from disk").arg(shaderName)); return; } ui->customShader->setCurrentText(QString()); UI_UpdateChannels(); reloadCustomShaders(QString()); } } void TextureViewer::customShaderModified(const QString &path) { static bool recurse = false; if(recurse) return; // if we just wrote a shader less than 100ms ago, don't refresh - this will have been handled // internally at a finer granularity than 'all shaders' if(m_CustomShaderWriteTime > m_CustomShaderTimer.elapsed() - 100) return; recurse = true; // allow time for modifications to finish QThread::msleep(15); reloadCustomShaders(QString()); recurse = false; }
/* * Copyright (c) 2021 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "ipc_stream_operator_fuzzer.h" #include "fuzz_base.h" #include <cstddef> #include <cstdint> class IPCStreamOperatorFuzzer : public StreamOperatorStub { public: CamRetCode IsStreamsSupported( OperationMode mode, const std::shared_ptr<CameraStandard::CameraMetadata> &modeSetting, const std::vector<std::shared_ptr<StreamInfo>> &info, StreamSupportType &type) override { return OHOS::Camera::NO_ERROR; } CamRetCode IsStreamsSupported( OperationMode mode, const std::shared_ptr<CameraStandard::CameraMetadata> &modeSetting, const std::shared_ptr<StreamInfo> &info, StreamSupportType &type) override { return OHOS::Camera::NO_ERROR; } CamRetCode CreateStreams(const std::vector<std::shared_ptr<StreamInfo>> &streamInfos) override { return OHOS::Camera::NO_ERROR; } CamRetCode ReleaseStreams(const std::vector<int>& streamIds) override { return OHOS::Camera::NO_ERROR; } CamRetCode CommitStreams(OperationMode mode, const std::shared_ptr<CameraStandard::CameraMetadata>& modeSetting) override { return OHOS::Camera::NO_ERROR; } CamRetCode GetStreamAttributes(std::vector<std::shared_ptr<StreamAttribute>>& attributes) override { return OHOS::Camera::NO_ERROR; } CamRetCode AttachBufferQueue(int streamId, const OHOS::sptr<OHOS::IBufferProducer>& producer) override { return OHOS::Camera::NO_ERROR; } CamRetCode DetachBufferQueue(int streamId) override { return OHOS::Camera::NO_ERROR; } CamRetCode Capture(int captureId, const std::shared_ptr<CaptureInfo>& captureInfo, bool isStreaming) override {} { return OHOS::Camera::NO_ERROR; } CamRetCode CancelCapture(int captureId) override { return OHOS::Camera::NO_ERROR; } CamRetCode ChangeToOfflineStream(const std::vector<int>& streamIds, OHOS::sptr<IStreamOperatorCallback>& callback, OHOS::sptr<IOfflineStreamOperator>& offlineOperator) override { return OHOS::Camera::NO_ERROR; } }; static uint32_t U32_AT(const uint8_t *ptr) { return (ptr[0] << 24) | (ptr[1] << 16) | (ptr[2] << 8) | ptr[3]; } static int32_t onRemoteRequest(uint32_t code, MessageParcel &data) { MessageParcel reply; MessageOption option; IPCStreamOperatorFuzzer IPCStreamSer; auto ret = IPCStreamSer.OnRemoteRequest(code, data, reply, option); return ret; } static void IpcFuzzService(const uint8_t *data, size_t size) { MessageParcel reply; MessageOption option; MessageParcel dataMessageParcel; if (size > sizeof(uint32_t)) { uint32_t code = U32_AT(data); uint8_t *number = data; number = number + sizeof(uint32_t); if (code == 7) { // 7:code size return; } size_t length = size; length = length - sizeof(uint32_t); dataMessageParcel.WriteInterfaceToken(StreamOperatorStub::GetDescriptor()); dataMessageParcel.WriteBuffer(number, length); dataMessageParcel.RewindRead(0); onRemoteRequest(code, dataMessageParcel); } } static void OnRemoteRequestFunc(const uint8_t *data, size_t size) { IpcFuzzService(data, size); } extern "C" int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size) { OnRemoteRequestFunc(data, size); return 0; }
#include <stdio.h> #include <pthread.h> #include <math.h> #define NUM_THREAD 10 int thread_ret[NUM_THREAD]; int range_start; int range_end; bool IsPrime(int n) { if (n < 2) { return false; } for (int i = 2; i <= sqrt(n); i++) { if (n % i == 0) { return false; } } return true; } void* ThreadFunc(void* arg) { long tid = (long)arg; // Split range for this thread int start = range_start + ((range_end - range_start) / NUM_THREAD) * tid; int end = range_start + ((range_end - range_start) / NUM_THREAD) * (tid+1); if (tid == NUM_THREAD - 1) { end = range_end + 1; } long cnt_prime = 0; for (int i = start; i < end; i++) { if (IsPrime(i)) { cnt_prime++; } } thread_ret[tid] = cnt_prime; return NULL; } int main(void) { pthread_t threads[NUM_THREAD]; while (1) { // Input range scanf("%d", &range_start); if (range_start == -1) { break; } scanf("%d", &range_end); // Create threads to work for (long i = 0; i < NUM_THREAD; i++) { if (pthread_create(&threads[i], 0, ThreadFunc, (void*)i) < 0) { printf("pthread_create error!\n"); return 0; } } // Wait threads end for (int i = 0; i < NUM_THREAD; i++) { pthread_join(threads[i], NULL); } // Collect results int cnt_prime = 0; for (int i = 0; i < NUM_THREAD; i++) { cnt_prime += thread_ret[i]; } printf("number of prime: %d\n", cnt_prime); } return 0; }
// TODO re-implement on new API #include "opencv2/imgproc/imgproc.hpp" #include "opencv2/imgcodecs.hpp" #include "opencv2/highgui/highgui.hpp" #include "GradientModule.hpp" using namespace std; using namespace uipf; /** @runs the module **/ /** data DataManager handles the input and output of this module **/ void GradientModule::run( DataManager& data) const { using namespace cv; // print params for debugging data.listParams(); // Declaring the variables to use for simple Edge detector int scale = 1; int delta = 0; int ddepth = CV_16S; int c; // read the params (window size and sigma) given for this step int nWindowSize = data.getParam<int>("windowSize",-1); double dSigma = data.getParam<double>("sigma",0.0); // get a pointer to the "image" input data Matrix::c_ptr oMatrix = data.getInputData<Matrix>("image"); // get the actual opencv matrix of the input data Mat m = oMatrix->getContent(); // do gaussian blur using opencv GaussianBlur(m,m,Size( nWindowSize, nWindowSize ), dSigma, dSigma ); // Declare the new source for the grayscale data Mat m_gray; // convert the filtered image to grayscale cvtColor(m,m_gray, CV_RGB2GRAY); //Declare the gradient image source Mat grad; /// Generate grad_x and grad_y Mat grad_x, grad_y; Mat abs_grad_x, abs_grad_y; /// Gradient X //Scharr( src_gray, grad_x, ddepth, 1, 0, scale, delta, BORDER_DEFAULT ); Sobel( m_gray, grad_x, ddepth, 1, 0, 3, scale, delta, BORDER_DEFAULT ); convertScaleAbs( grad_x, abs_grad_x ); /// Gradient Y //Scharr( src_gray, grad_y, ddepth, 0, 1, scale, delta, BORDER_DEFAULT ); Sobel( m_gray, grad_y, ddepth, 0, 1, 3, scale, delta, BORDER_DEFAULT ); convertScaleAbs( grad_y, abs_grad_y ); /// Total Gradient (approximate) addWeighted( abs_grad_x, 0.5, abs_grad_y, 0.5, 0, grad ); // set the result (output) on the datamanager data.setOutputData("image",new Matrix(m_gray)); } // returns the meta data of this module MetaData GaussianModule::getMetaData() const { map<string, DataDescription> input = { {"image", DataDescription(MATRIX, "the image to apply the filter and convert to grayscale on.") } }; map<string, DataDescription> output = { {"image", DataDescription(MATRIX, "the result image.") } }; map<string, ParamDescription> params = { {"windowSize", ParamDescription("window size of the kernel.") }, {"sigma", ParamDescription("variance of the gaussian kernel.") } }; return MetaData( "Applies Gaussian blurring to an image. Then converts the image into grayscale", input, output, params ); }
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/renderer/external_extension.h" #include <stdint.h> #include "base/macros.h" #include "chrome/common/render_messages.h" #include "chrome/common/search_provider.h" #include "content/public/renderer/render_view.h" #include "third_party/WebKit/public/web/WebDocument.h" #include "third_party/WebKit/public/web/WebLocalFrame.h" #include "third_party/WebKit/public/web/WebView.h" #include "v8/include/v8.h" using blink::WebLocalFrame; using blink::WebView; using content::RenderView; namespace extensions_v8 { namespace { const char* const kSearchProviderApi = "var external;" "if (!external)" " external = {};" "external.IsSearchProviderInstalled = function(name) {" " native function NativeIsSearchProviderInstalled();" " return NativeIsSearchProviderInstalled(name);" "};"; const char kExternalExtensionName[] = "v8/External"; } // namespace class ExternalExtensionWrapper : public v8::Extension { public: ExternalExtensionWrapper(); // Allows v8's javascript code to call the native functions defined // in this class for window.external. v8::Local<v8::FunctionTemplate> GetNativeFunctionTemplate( v8::Isolate* isolate, v8::Local<v8::String> name) override; // Helper function to find the RenderView. May return NULL. static RenderView* GetRenderView(); // Implementation of window.external.IsSearchProviderInstalled. static void IsSearchProviderInstalled( const v8::FunctionCallbackInfo<v8::Value>& args); private: DISALLOW_COPY_AND_ASSIGN(ExternalExtensionWrapper); }; ExternalExtensionWrapper::ExternalExtensionWrapper() : v8::Extension(kExternalExtensionName, kSearchProviderApi) { } v8::Local<v8::FunctionTemplate> ExternalExtensionWrapper::GetNativeFunctionTemplate( v8::Isolate* isolate, v8::Local<v8::String> name) { if (name->Equals(v8::String::NewFromUtf8( isolate, "NativeIsSearchProviderInstalled"))) { return v8::FunctionTemplate::New(isolate, IsSearchProviderInstalled); } return v8::Local<v8::FunctionTemplate>(); } // static RenderView* ExternalExtensionWrapper::GetRenderView() { WebLocalFrame* webframe = WebLocalFrame::frameForCurrentContext(); DCHECK(webframe) << "There should be an active frame since we just got " "a native function called."; if (!webframe) return NULL; WebView* webview = webframe->view(); if (!webview) return NULL; // can happen during closing return RenderView::FromWebView(webview); } // static void ExternalExtensionWrapper::IsSearchProviderInstalled( const v8::FunctionCallbackInfo<v8::Value>& args) { if (!args.Length() || !args[0]->IsString()) return; v8::String::Utf8Value utf8name(args[0]); if (!utf8name.length()) return; std::string name(*utf8name); RenderView* render_view = GetRenderView(); if (!render_view) return; WebLocalFrame* webframe = WebLocalFrame::frameForCurrentContext(); if (!webframe) return; search_provider::InstallState install = search_provider::DENIED; GURL inquiry_url = GURL(webframe->document().url()).Resolve(name); if (!inquiry_url.is_empty()) { webframe->didCallIsSearchProviderInstalled(); render_view->Send(new ChromeViewHostMsg_GetSearchProviderInstallState( render_view->GetRoutingID(), webframe->document().url(), inquiry_url, &install)); } if (install == search_provider::DENIED) { // FIXME: throw access denied exception. v8::Isolate* isolate = args.GetIsolate(); isolate->ThrowException(v8::Exception::Error(v8::String::Empty(isolate))); return; } args.GetReturnValue().Set(static_cast<int32_t>(install)); } v8::Extension* ExternalExtension::Get() { return new ExternalExtensionWrapper(); } } // namespace extensions_v8
//------------------------------------------------------------------------------ /* This file is part of rippled: https://github.com/ripple/rippled Copyright (c) 2014 Ripple Labs Inc. Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL , DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ //============================================================================== #include <BeastConfig.h> #include <ripple/app/ledger/Ledger.h> #include <ripple/app/tx/impl/SetSignerList.h> #include <ripple/app/tx/impl/SignerEntries.h> #include <ripple/protocol/STObject.h> #include <ripple/protocol/STArray.h> #include <ripple/protocol/STTx.h> #include <ripple/protocol/STAccount.h> #include <ripple/protocol/Indexes.h> #include <ripple/basics/Log.h> #include <cstdint> #include <algorithm> namespace ripple { TER SetSignerList::doApply () { // All operations require our ledger index. Compute that once and pass it // to our handlers. uint256 const index = getSignerListIndex (account_); // Perform the operation preCheck() decided on. switch (do_) { case set: return replaceSignerList (index); case destroy: return destroySignerList (index); default: // Fall through intentionally break; } assert (false); // Should not be possible to get here. return temMALFORMED; } TER SetSignerList::preCheck() { #if ! RIPPLE_ENABLE_MULTI_SIGN if (! (view().flags() & tapENABLE_TESTING)) return temDISABLED; #endif // We need the account ID later, so do this check first. preCheckAccount (); // Check the quorum. A non-zero quorum means we're creating or replacing // the list. A zero quorum means we're destroying the list. quorum_ = (mTxn.getFieldU32 (sfSignerQuorum)); bool const hasSignerEntries (mTxn.isFieldPresent (sfSignerEntries)); if (quorum_ && hasSignerEntries) { SignerEntries::Decoded signers ( SignerEntries::deserialize (mTxn, j_, "transaction")); if (signers.ter != tesSUCCESS) return signers.ter; // Validate our settings. if (TER const ter = validateQuorumAndSignerEntries (quorum_, signers.vec)) { return ter; } // Save deserialized and validated list for later. signers_ = std::move (signers.vec); do_ = set; } else if ((quorum_ == 0) && !hasSignerEntries) { do_ = destroy; } else { // Neither a set nor a destroy. Malformed. if (j_.trace) j_.trace << "Malformed transaction: Invalid signer set list format."; return temMALFORMED; } return preCheckSigningKey (); } TER SetSignerList::validateQuorumAndSignerEntries ( std::uint32_t quorum, std::vector<SignerEntries::SignerEntry>& signers) const { // Reject if there are too many or too few entries in the list. { std::size_t const signerCount = signers.size (); if ((signerCount < SignerEntries::minEntries) || (signerCount > SignerEntries::maxEntries)) { if (j_.trace) j_.trace << "Too many or too few signers in signer list."; return temMALFORMED; } } // Make sure there are no duplicate signers. std::sort (signers.begin (), signers.end ()); if (std::adjacent_find ( signers.begin (), signers.end ()) != signers.end ()) { if (j_.trace) j_.trace << "Duplicate signers in signer list"; return temBAD_SIGNER; } // Make sure no signers reference this account. Also make sure the // quorum can be reached. std::uint64_t allSignersWeight (0); for (auto const& signer : signers) { allSignersWeight += signer.weight; if (signer.account == account_) { if (j_.trace) j_.trace << "A signer may not self reference account."; return temBAD_SIGNER; } // Don't verify that the signer accounts exist. Non-existent accounts // may be phantom accounts (which are permitted). } if ((quorum <= 0) || (allSignersWeight < quorum)) { if (j_.trace) j_.trace << "Quorum is unreachable"; return temBAD_QUORUM; } return tesSUCCESS; } TER SetSignerList::replaceSignerList (uint256 const& index) { // This may be either a create or a replace. Preemptively destroy any // old signer list. May reduce the reserve, so this is done before // checking the reserve. if (TER const ter = destroySignerList (index)) return ter; auto const sle = view().peek( keylet::account(account_)); // Compute new reserve. Verify the account has funds to meet the reserve. std::uint32_t const oldOwnerCount = sle->getFieldU32 (sfOwnerCount); std::uint32_t const addedOwnerCount = ownerCountDelta (signers_.size ()); auto const newReserve = view().fees().accountReserve( oldOwnerCount + addedOwnerCount); // We check the reserve against the starting balance because we want to // allow dipping into the reserve to pay fees. This behavior is consistent // with CreateTicket. if (mPriorBalance < newReserve) return tecINSUFFICIENT_RESERVE; // Everything's ducky. Add the ltSIGNER_LIST to the ledger. auto signerList = std::make_shared<SLE>(ltSIGNER_LIST, index); view().insert (signerList); writeSignersToLedger (signerList); // Lambda for call to dirAdd. auto describer = [&] (SLE::ref sle, bool dummy) { ownerDirDescriber (sle, dummy, account_); }; // Add the signer list to the account's directory. std::uint64_t hint; TER result = dirAdd(ctx_.view (), hint, getOwnerDirIndex (account_), index, describer); if (j_.trace) j_.trace << "Create signer list for account " << account_ << ": " << transHuman (result); if (result != tesSUCCESS) return result; signerList->setFieldU64 (sfOwnerNode, hint); // If we succeeded, the new entry counts against the creator's reserve. adjustOwnerCount(view(), sle, addedOwnerCount); return result; } TER SetSignerList::destroySignerList (uint256 const& index) { // See if there's an ltSIGNER_LIST for this account. SLE::pointer signerList = view().peek (keylet::signers(index)); // If the signer list doesn't exist we've already succeeded in deleting it. if (!signerList) return tesSUCCESS; // We have to examine the current SignerList so we know how much to // reduce the OwnerCount. std::uint32_t removeFromOwnerCount = 0; auto const k = keylet::signers(account_); SLE::pointer accountSignersList = view().peek (k); if (accountSignersList) { STArray const& actualList = accountSignersList->getFieldArray (sfSignerEntries); removeFromOwnerCount = ownerCountDelta (actualList.size ()); } // Remove the node from the account directory. std::uint64_t const hint (signerList->getFieldU64 (sfOwnerNode)); TER const result = dirDelete(ctx_.view (), false, hint, getOwnerDirIndex (account_), index, false, (hint == 0)); if (result == tesSUCCESS) adjustOwnerCount(view(), view().peek(keylet::account(account_)), removeFromOwnerCount); ctx_.view ().erase (signerList); return result; } // VFALCO NOTE This name is misleading, the signers // are not written to the ledger they are // added to the SLE. void SetSignerList::writeSignersToLedger (SLE::pointer ledgerEntry) { // Assign the quorum. ledgerEntry->setFieldU32 (sfSignerQuorum, quorum_); // Create the SignerListArray one SignerEntry at a time. STArray toLedger (signers_.size ()); for (auto const& entry : signers_) { toLedger.emplace_back(sfSignerEntry); STObject& obj = toLedger.back(); obj.reserve (2); obj.setAccountID (sfAccount, entry.account); obj.setFieldU16 (sfSignerWeight, entry.weight); } // Assign the SignerEntries. ledgerEntry->setFieldArray (sfSignerEntries, toLedger); } std::size_t SetSignerList::ownerCountDelta (std::size_t entryCount) { // We always compute the full change in OwnerCount, taking into account: // o The fact that we're adding/removing a SignerList and // o Accounting for the number of entries in the list. // We can get away with that because lists are not adjusted incrementally; // we add or remove an entire list. // The wiki (https://wiki.ripple.com/Multisign#Fees_2) currently says // (December 2014) the reserve should be // Reserve * (N + 1) / 2 // That's not making sense to me right now, since I'm working in // integral OwnerCount units. If, say, N is 4 I don't know how to return // 4.5 units as an integer. // // So, just to get started, I'm saying that: // o Simply having a SignerList costs 2 OwnerCount units. // o And each signer in the list costs 1 more OwnerCount unit. // So, at a minimum, adding a SignerList with 2 entries costs 4 OwnerCount // units. A SignerList with 8 entries would cost 10 OwnerCount units. // // It's worth noting that once this reserve policy has gotten into the // wild it will be very difficult to change. So think hard about what // we want for the long term. return 2 + entryCount; } } // namespace ripple
#include <common.h> #include <interception_macros.h> #include <pickups/pickups.h> #include <csharp_bridge.h> // Taken from dump.cs enum class WorldMapIconType : int32_t { value__, Keystone = 0, Mapstone = 1, BreakableWall = 2, BreakableWallBroken = 3, StompableFloor = 4, StompableFloorBroken = 5, EnergyGateTwo = 6, EnergyGateOpen = 7, KeystoneDoorFour = 8, KeystoneDoorOpen = 9, AbilityPedestal = 10, HealthUpgrade = 11, EnergyUpgrade = 12, SavePedestal = 13, AbilityPoint = 14, KeystoneDoorTwo = 15, Invisible = 16, Experience = 17, MapstonePickup = 18, EnergyGateTwelve = 19, EnergyGateTen = 20, EnergyGateEight = 21, EnergyGateSix = 22, EnergyGateFour = 23, SpiritShard = 24, NPC = 25, QuestItem = 26, ShardSlotUpgrade = 27, Teleporter = 28, Ore = 29, HealthFragment = 33, EnergyFragment = 34, Seed = 35, QuestStart = 30, QuestEnd = 31, RaceStart = 32, RaceEnd = 36, Eyestone = 37, WatermillDoor = 40, TempleDoor = 41, SmallDoor = 42, Shrine = 43, Loremaster = 50, Weaponmaster = 51, Gardener = 52, Mapmaker = 53, Shardtrader = 54, Wanderer = 55, Treekeeper = 56, Builder = 57, Kwolok = 58, Statistician = 59, CreepHeart = 60, Miner = 61, Spiderling = 62, Moki = 63, MokiBrave = 64, MokiAdventurer = 65, MokiArtist = 66, MokiDarkness = 67, MokiFashionable = 68, MokiFisherman = 69, MokiFrozen = 70, MokiKwolokAmulet = 71, MokiSpyglass = 72, Ku = 73, IceFisher = 74, Siira = 75 }; INTERCEPT(4093520, int32_t, GameWorld__GetCollectedIconTypeCount, (app::GameWorld* this_ptr, app::WorldMapIconType__Enum type)) { auto value = GameWorld__GetCollectedIconTypeCount(this_ptr, type); if (static_cast<int32_t>(type) == static_cast<int32_t>(WorldMapIconType::Ore)) value = csharp_bridge::ore_count(); return value; } INTERCEPT(5814720, void, SeinPickupProcessor__OnCollectOrePickup, (app::SeinPickupProcessor* this_ptr, app::OrePickup* orePickup)) { collecting_pickup = true; SeinPickupProcessor__OnCollectOrePickup(this_ptr, orePickup); collecting_pickup = false; } INTERCEPT(8453568, void, SeinLevel__set_Ore, (app::SeinLevel* this_ptr, int32_t value)) { if(collecting_pickup) return; SeinLevel__set_Ore(this_ptr, value); }
// RUN: %clangxx -fsycl %s -o %t.out // RUN: %RUN_ON_HOST %t.out // This test performs basic check of supporting user defined class that are // implicitly converted from sycl::item/sycl::nd_item in parallel_for. #include <CL/sycl.hpp> #include <iostream> template <int Dimensions> class item_wrapper { public: item_wrapper(sycl::item<Dimensions> it) : m_item(it) {} private: sycl::item<Dimensions> m_item; }; template <int Dimensions> class nd_item_wrapper { public: nd_item_wrapper(sycl::nd_item<Dimensions> it) : m_item(it) {} private: sycl::nd_item<Dimensions> m_item; }; template <int Dimensions, typename T> class item_wrapper2 { public: item_wrapper2(sycl::item<Dimensions> it) : m_item(it), m_value(T()) {} private: sycl::item<Dimensions> m_item; T m_value; }; template <int Dimensions, typename T> class nd_item_wrapper2 { public: nd_item_wrapper2(sycl::nd_item<Dimensions> it) : m_item(it), m_value(T()) {} private: sycl::nd_item<Dimensions> m_item; T m_value; }; int main() { sycl::queue q; q.parallel_for(sycl::range<1>{1}, [=](item_wrapper<1> item) {}); q.parallel_for(sycl::nd_range<1>{1, 1}, [=](nd_item_wrapper<1> item) {}); q.parallel_for(sycl::range<1>{1}, [=](item_wrapper2<1, int> item) {}); q.parallel_for(sycl::nd_range<1>{1, 1}, [=](nd_item_wrapper2<1, int> item) {}); return 0; }
#include "stddefx.h" #ifndef INCLUDED_CALC_TSSINPUTLEAF #include "calc_tssinputleaf.h" #define INCLUDED_CALC_TSSINPUTLEAF #endif #ifndef INCLUDED_CALC_TSSINPUTPARAMETER #include "calc_tssinputparameter.h" #define INCLUDED_CALC_TSSINPUTPARAMETER #endif #ifndef INCLUDED_CALC_INDEXSELECTED #include "calc_indexselected.h" #define INCLUDED_CALC_INDEXSELECTED #endif #ifndef INCLUDED_CALC_TIMETABLE #include "calc_timetable.h" #define INCLUDED_CALC_TIMETABLE #endif #ifndef INCLUDED_CALC_USEPAR # include "calc_usepar.h" #define INCLUDED_CALC_USEPAR #endif #ifndef INCLUDED_CALC_INFOSCRIPT #include "calc_infoscript.h" #define INCLUDED_CALC_INFOSCRIPT #endif #ifndef INCLUDED_CALC_ISCRIPT #include "calc_iscript.h" #define INCLUDED_CALC_ISCRIPT #endif #ifndef INCLUDED_COM_EXCEPTION #include "com_exception.h" #define INCLUDED_COM_EXCEPTION #endif const calc::TimeTable *calc::TssInputLeaf::execute() { return d_par->value(select()); } size_t calc::TssInputLeaf::select() const { return d_index->select(); } void calc::TssInputLeaf::print(calc::InfoScript& i)const { i.parTag(name()); } //! ctor, modifies \a par for inputFilePath /*! \todo reverse of pcrcalc/test44: first input then output */ calc::TssInputLeaf::TssInputLeaf( UsePar& par, VS vsOfResult): Symbol(par),d_index(par.createSelector()) { if (par.isArray()) posError("Array of tss not yet implemented"); // first cast to more generic TssParameter *p = dynamic_cast<TssParameter *>(script().findRightParameter(par,VS_TSS)); d_par = dynamic_cast<TssInputParameter *>(p); if (d_par) // found return; if (p) // it is a tss but not an input! pcrcalc/test44 posError(p->userName()+"\n is already defined as an timeoutput" " on "+p->definitionPoint()+"\n" "can not mix timeinput and timeoutput\n"); // load value par.setInputFilePath(); std::vector <TimeTable *>tss(1); try { expectedFileType(par.externalName(),VS_TSS); tss[0] = new TimeTable(par.externalName(), vsOfResult,scriptConst().nrTimeSteps()); } catch (com::Exception& msg) { // pcrcalc/test45 // pcrcalc/test226 par.symError(msg); } d_par = new TssInputParameter(par,true, tss); script().addSymbol(d_par); } calc::TssInputLeaf::~TssInputLeaf() { }
#ifndef _CUDA_ANALYZE_INSTRUCTION_H_ #define _CUDA_ANALYZE_INSTRUCTION_H_ #include <map> #include <vector> #include <string> #include <CodeObject.h> namespace CudaParse { class Function; class Instruction; struct InstructionStat { enum PredicateFlag { PREDICATE_NONE = 0, PREDICATE_TRUE = 1, PREDICATE_FALSE = 2, }; static int const WAIT_BITS = 6; static int const BARRIER_NONE = 7; struct Control { uint8_t reuse; uint8_t wait; uint8_t read; uint8_t write; uint8_t yield; uint8_t stall; Control() : reuse(0), wait(0), read(7), write(7), yield(0), stall(1) {} }; std::string op; int pc; int predicate; // P0-P6 PredicateFlag predicate_flag; std::vector<int> predicate_assign_pcs; std::vector<int> dsts; // R0-R255: only records normal registers std::vector<int> srcs; // R0-R255: only records normal registers std::vector<int> pdsts; // P0-P6: only records predicate registers std::vector<int> psrcs; // P0-P6: only records predicate registers std::vector<int> bdsts; // B1-B6: only records barriers std::vector<int> bsrcs; // B1-B6: only records barriers std::vector<int> udsts; // UR0-UR63: only records uniform regsters std::vector<int> usrcs; // UR0-UR63: only records uniform regsters std::vector<int> updsts; // UP0-UP?: only records uniform predicate regsters std::vector<int> upsrcs; // UP0-UP?: only records uniform predicate regsters std::map<int, std::vector<int> > assign_pcs; std::map<int, std::vector<int> > passign_pcs; std::map<int, std::vector<int> > bassign_pcs; std::map<int, std::vector<int> > uassign_pcs; std::map<int, std::vector<int> > upassign_pcs; Control control; InstructionStat() {} explicit InstructionStat(Instruction *inst); InstructionStat(const std::string &op, int pc, int predicate, PredicateFlag predicate_flag, std::vector<int> &predicate_assign_pcs, std::vector<int> &dsts, std::vector<int> &srcs, std::vector<int> &pdsts, std::vector<int> &psrcs, std::vector<int> &bdsts, std::vector<int> &bsrcs) : op(op), pc(pc), predicate(predicate), predicate_flag(predicate_flag), predicate_assign_pcs(predicate_assign_pcs), dsts(dsts), srcs(srcs), pdsts(pdsts), psrcs(psrcs), bdsts(bdsts), bsrcs(bsrcs) {} InstructionStat(const std::string &op, int pc, int predicate, PredicateFlag predicate_flag, std::vector<int> &predicate_assign_pcs, std::vector<int> &dsts, std::vector<int> &srcs, std::vector<int> &pdsts, std::vector<int> &psrcs, std::vector<int> &bdsts, std::vector<int> &bsrcs, std::vector<int> &udsts, std::vector<int> &usrcs, std::vector<int> &updsts, std::vector<int> &upsrcs, std::map<int, std::vector<int> > &assign_pcs, std::map<int, std::vector<int> > &passign_pcs, std::map<int, std::vector<int> > &bassign_pcs, std::map<int, std::vector<int> > &uassign_pcs, std::map<int, std::vector<int> > &upassign_pcs) : op(op), pc(pc), predicate(predicate), predicate_flag(predicate_flag), predicate_assign_pcs(predicate_assign_pcs), dsts(dsts), srcs(srcs), pdsts(pdsts), psrcs(psrcs), bdsts(bdsts), bsrcs(bsrcs), udsts(udsts), usrcs(usrcs), updsts(updsts), upsrcs(upsrcs), assign_pcs(assign_pcs), passign_pcs(passign_pcs), bassign_pcs(bassign_pcs), uassign_pcs(uassign_pcs), upassign_pcs(upassign_pcs) {} InstructionStat(const std::string &op, int pc, int predicate, PredicateFlag predicate_flag, std::vector<int> &predicate_assign_pcs, std::vector<int> &dsts, std::vector<int> &srcs, std::vector<int> &pdsts, std::vector<int> &psrcs, std::vector<int> &bdsts, std::vector<int> &bsrcs, std::vector<int> &udsts, std::vector<int> &usrcs, std::vector<int> &updsts, std::vector<int> &upsrcs, std::map<int, std::vector<int> > &assign_pcs, std::map<int, std::vector<int> > &passign_pcs, std::map<int, std::vector<int> > &bassign_pcs, std::map<int, std::vector<int> > &uassign_pcs, std::map<int, std::vector<int> > &upassign_pcs, Control &control) : op(op), pc(pc), predicate(predicate), predicate_flag(predicate_flag), predicate_assign_pcs(predicate_assign_pcs), dsts(dsts), srcs(srcs), pdsts(pdsts), psrcs(psrcs), bdsts(bdsts), bsrcs(bsrcs), udsts(udsts), usrcs(usrcs), updsts(updsts), upsrcs(upsrcs), assign_pcs(assign_pcs), passign_pcs(passign_pcs), bassign_pcs(bassign_pcs), uassign_pcs(uassign_pcs), upassign_pcs(upassign_pcs), control(control) {} bool operator < (const InstructionStat &other) const { return this->pc < other.pc; } bool find_src_reg(int reg) { return std::find(srcs.begin(), srcs.end(), reg) != srcs.end(); } bool find_src_pred_reg(int pred_reg) { return std::find(psrcs.begin(), psrcs.end(), pred_reg) != psrcs.end(); } bool find_src_barrier(int barrier) { return std::find(bsrcs.begin(), bsrcs.end(), barrier) != bsrcs.end(); } }; void relocateCudaInstructionStats(std::vector<Function *> &functions); void flatCudaInstructionStats(const std::vector<Function *> &functions, std::vector<InstructionStat *> &inst_stats); void controlCudaInstructions(const char *cubin, std::vector<Function *> &functions); void sliceCudaInstructions(const Dyninst::ParseAPI::CodeObject::funclist &func_set, int threads, std::vector<Function *> &functions); void processLivenessCudaInstructions(const Dyninst::ParseAPI::CodeObject::funclist &func_set, std::vector<Function *> &functions); bool dumpCudaInstructions(const std::string &file_path, const std::vector<Function *> &functions); bool readCudaInstructions(const std::string &file_path, std::vector<Function *> &Function_stats); } // namespace CudaParse #endif
/* * Copyright (c) 2020 Andreas Pohl * Licensed under MIT (https://github.com/apohl79/audiogridder/blob/master/COPYING) * * Author: Andreas Pohl */ #ifndef ProcessorChain_hpp #define ProcessorChain_hpp #include <JuceHeader.h> #include "Utils.hpp" #include "Defaults.hpp" namespace e47 { class ProcessorChain; class AGProcessor : public LogTagDelegate, public AudioProcessorParameter::Listener { public: static std::atomic_uint32_t loadedCount; AGProcessor(ProcessorChain& chain, const String& id, double sampleRate, int blockSize); ~AGProcessor() override; static String createPluginID(const PluginDescription& d); static String convertJUCEtoAGPluginID(const String& id); inline static String createString(const PluginDescription& d) { json j = {{"name", d.name.toStdString()}, {"company", d.manufacturerName.toStdString()}, {"id", createPluginID(d).toStdString()}, {"type", d.pluginFormatName.toStdString()}, {"category", d.category.toStdString()}, {"isInstrument", d.isInstrument}}; return String(j.dump()) + "\n"; } static std::unique_ptr<PluginDescription> findPluginDescritpion(const String& id); std::shared_ptr<AudioPluginInstance> getPlugin() { traceScope(); std::lock_guard<std::mutex> lock(m_pluginMtx); return m_plugin; } void updateScreenCaptureArea(int val) { traceScope(); if (val == Defaults::SCAREA_FULLSCREEN) { m_fullscreen = !m_fullscreen; } else { m_additionalScreenSpace = m_additionalScreenSpace + val > 0 ? m_additionalScreenSpace + val : 0; } } int getAdditionalScreenCapturingSpace() { traceScope(); return m_additionalScreenSpace; } bool isFullscreen() { traceScope(); return m_fullscreen; } static std::shared_ptr<AudioPluginInstance> loadPlugin(PluginDescription& plugdesc, double sampleRate, int blockSize, String& err); static std::shared_ptr<AudioPluginInstance> loadPlugin(const String& fileOrIdentifier, double sampleRate, int blockSize, String& err); bool load(String& err); void unload(); void setChainIndex(int idx) { m_chainIdx = idx; } template <typename T> bool processBlock(AudioBuffer<T>& buffer, MidiBuffer& midiMessages) { traceScope(); auto p = getPlugin(); if (nullptr != p) { if (!p->isSuspended()) { p->processBlock(buffer, midiMessages); } else { if (m_lastKnownLatency > 0) { processBlockBypassed(buffer); } } return true; } return false; } void processBlockBypassed(AudioBuffer<float>& buffer); void processBlockBypassed(AudioBuffer<double>& buffer); void prepareToPlay(double sampleRate, int maximumExpectedSamplesPerBlock) { traceScope(); auto p = getPlugin(); if (nullptr != p) { p->prepareToPlay(sampleRate, maximumExpectedSamplesPerBlock); m_prepared = true; } } void releaseResources() { traceScope(); auto p = getPlugin(); if (nullptr != p) { p->releaseResources(); m_prepared = false; } } int getLatencySamples() { traceScope(); auto p = getPlugin(); if (nullptr != p) { int latency = p->getLatencySamples(); if (latency != m_lastKnownLatency) { m_lastKnownLatency = latency; updateLatencyBuffers(); } return latency; } return 0; } const String getName() { traceScope(); auto p = getPlugin(); if (nullptr != p) { return p->getName(); } return ""; } bool hasEditor() { traceScope(); auto p = getPlugin(); if (nullptr != p) { return p->hasEditor(); } return false; } bool isSuspended() { traceScope(); auto p = getPlugin(); if (nullptr != p) { return p->isSuspended(); } return true; } double getTailLengthSeconds() { traceScope(); auto p = getPlugin(); if (nullptr != p) { return p->getTailLengthSeconds(); } return 0.0; } AudioProcessorEditor* createEditorIfNeeded() { traceScope(); auto p = getPlugin(); if (nullptr != p) { return p->createEditorIfNeeded(); } return nullptr; } AudioProcessorEditor* getActiveEditor() { traceScope(); auto p = getPlugin(); if (nullptr != p) { return p->getActiveEditor(); } return nullptr; } void getStateInformation(juce::MemoryBlock& destData) { traceScope(); auto p = getPlugin(); if (nullptr != p) { p->getStateInformation(destData); } } void setStateInformation(const void* data, int sizeInBytes) { traceScope(); auto p = getPlugin(); if (nullptr != p) { p->setStateInformation(data, sizeInBytes); } } void suspendProcessing(const bool shouldBeSuspended); void updateLatencyBuffers(); int getExtraInChannels() const { return m_extraInChannels; } int getExtraOutChannels() const { return m_extraOutChannels; } void setExtraChannels(int in, int out) { m_extraInChannels = in; m_extraOutChannels = out; } bool getNeedsDisabledSidechain() const { return m_needsDisabledSidechain; } void setNeedsDisabledSidechain(bool b) { m_needsDisabledSidechain = b; } Point<int> getLastPosition() const { return m_lastPosition; } void setLastPosition(Point<int> p) { m_lastPosition = p; } // AudioProcessorParameter::Listener std::function<void(int idx, int paramIdx, float val)> onParamValueChange; std::function<void(int idx, int paramIdx, bool gestureIsStarting)> onParamGestureChange; void parameterValueChanged(int parameterIndex, float newValue) override { traceScope(); if (onParamValueChange) { onParamValueChange(m_chainIdx, parameterIndex, newValue); } } void parameterGestureChanged(int parameterIndex, bool gestureIsStarting) override { traceScope(); if (onParamGestureChange) { onParamGestureChange(m_chainIdx, parameterIndex, gestureIsStarting); } } private: ProcessorChain& m_chain; int m_chainIdx = -1; String m_id; double m_sampleRate; int m_blockSize; bool m_parallelLoadAllowed; static std::mutex m_pluginLoaderMtx; std::shared_ptr<AudioPluginInstance> m_plugin; std::mutex m_pluginMtx; int m_additionalScreenSpace = 0; bool m_fullscreen = false; bool m_prepared = false; int m_extraInChannels = 0; int m_extraOutChannels = 0; bool m_needsDisabledSidechain = false; Array<Array<float>> m_bypassBufferF; Array<Array<double>> m_bypassBufferD; int m_lastKnownLatency = 0; Point<int> m_lastPosition = {0, 0}; }; class ProcessorChain : public AudioProcessor, public LogTagDelegate { public: class PlayHead : public AudioPlayHead { public: PlayHead(AudioPlayHead::CurrentPositionInfo* posInfo) : m_posInfo(posInfo) {} bool getCurrentPosition(CurrentPositionInfo& result) { result = *m_posInfo; return true; } private: AudioPlayHead::CurrentPositionInfo* m_posInfo; }; ProcessorChain(const BusesProperties& props) : AudioProcessor(props) {} static BusesProperties createBussesProperties(int in, int out, int sc) { setLogTagStatic("processorchain"); traceScope(); auto props = BusesProperties().withOutput("Output", AudioChannelSet::discreteChannels(out), false); if (in > 0) { props = props.withInput("Input", AudioChannelSet::discreteChannels(in), false); } if (sc > 0) { props = props.withInput("Sidechain", AudioChannelSet::discreteChannels(sc), false); } return props; } bool isSidechainDisabled() const { return m_sidechainDisabled; } void prepareToPlay(double sampleRate, int maximumExpectedSamplesPerBlock) override; void releaseResources() override; void processBlock(AudioBuffer<float>& buffer, MidiBuffer& midiMessages) override; void processBlock(AudioBuffer<double>& buffer, MidiBuffer& midiMessages) override; const String getName() const override { return "ProcessorChain"; } double getTailLengthSeconds() const override; bool supportsDoublePrecisionProcessing() const override; bool isBusesLayoutSupported(const BusesLayout& /*layouts*/) const override { return true; } bool updateChannels(int channelsIn, int channelsOut, int channelsSC); bool setProcessorBusesLayout(AGProcessor* proc); int getExtraChannels(); bool acceptsMidi() const override { return false; } bool producesMidi() const override { return false; } AudioProcessorEditor* createEditor() override { return nullptr; } bool hasEditor() const override { return false; } int getNumPrograms() override { return 0; } int getCurrentProgram() override { return 0; } void setCurrentProgram(int /* index */) override {} const String getProgramName(int /* index */) override { return ""; } void changeProgramName(int /* index */, const String& /* newName */) override {} void getStateInformation(juce::MemoryBlock& /* destData */) override {} void setStateInformation(const void* /* data */, int /* sizeInBytes */) override {} bool initPluginInstance(AGProcessor* proc, String& err); bool addPluginProcessor(const String& id, String& err); void addProcessor(std::shared_ptr<AGProcessor> processor); size_t getSize() const { return m_processors.size(); } std::shared_ptr<AGProcessor> getProcessor(int index); void delProcessor(int idx); void exchangeProcessors(int idxA, int idxB); float getParameterValue(int idx, int paramIdx); void update(); void clear(); String toString(); private: std::vector<std::shared_ptr<AGProcessor>> m_processors; std::mutex m_processors_mtx; std::atomic_bool m_supportsDoublePrecission{true}; std::atomic<double> m_tailSecs{0.0}; int m_extraChannels = 0; bool m_hasSidechain = false; bool m_sidechainDisabled = false; template <typename T> void processBlockReal(AudioBuffer<T>& buffer, MidiBuffer& midiMessages) { traceScope(); int latency = 0; if (getBusCount(true) > 1 && m_sidechainDisabled) { auto sidechainBuffer = getBusBuffer(buffer, true, 1); sidechainBuffer.clear(); } std::lock_guard<std::mutex> lock(m_processors_mtx); for (auto& proc : m_processors) { if (proc->processBlock(buffer, midiMessages)) { latency += proc->getLatencySamples(); } } if (latency != getLatencySamples()) { logln("updating latency samples to " << latency); setLatencySamples(latency); } } template <typename T> void preProcessBlocks(std::shared_ptr<AudioPluginInstance> inst) { traceScope(); MidiBuffer midi; int channels = jmax(getTotalNumInputChannels(), getTotalNumOutputChannels()) + m_extraChannels; AudioBuffer<T> buf(channels, getBlockSize()); buf.clear(); int samplesProcessed = 0; do { inst->processBlock(buf, midi); samplesProcessed += getBlockSize(); } while (samplesProcessed < 16384); } void updateNoLock(); void printBusesLayout(const AudioProcessor::BusesLayout& l) const { logln("input buses: " << l.inputBuses.size()); for (int i = 0; i < l.inputBuses.size(); i++) { logln(" [" << i << "] " << l.inputBuses[i].size() << " channel(s)"); for (auto ct : l.inputBuses[i].getChannelTypes()) { logln(" <- " << AudioChannelSet::getAbbreviatedChannelTypeName(ct)); } } logln("output buses: " << l.outputBuses.size()); for (int i = 0; i < l.outputBuses.size(); i++) { logln(" [" << i << "] " << l.outputBuses[i].size() << " channel(s)"); for (auto ct : l.outputBuses[i].getChannelTypes()) { logln(" -> " << AudioChannelSet::getAbbreviatedChannelTypeName(ct)); } } } }; } // namespace e47 #endif /* ProcessorChain_hpp */
/****************************************************************************** * The MIT License (MIT) * * Copyright (c) 2019-2022 Baldur Karlsson * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. ******************************************************************************/ #include "RDSplitter.h" #include <QPaintEvent> #include <QPainter> RDSplitterHandle::RDSplitterHandle(Qt::Orientation orientation, QSplitter *parent) : QSplitterHandle(orientation, parent), m_index(-1), m_isCollapsed(false) { } void RDSplitterHandle::setIndex(int index) { m_index = index; } int RDSplitterHandle::index() const { return m_index; } void RDSplitterHandle::setTitle(const QString &title) { m_title = title; } const QString &RDSplitterHandle::title() const { return m_title; } void RDSplitterHandle::setCollapsed(bool collapsed) { m_isCollapsed = collapsed; } bool RDSplitterHandle::collapsed() const { return m_isCollapsed; } void RDSplitterHandle::paintEvent(QPaintEvent *event) { QPainter painter(this); QColor col = palette().color(QPalette::WindowText); painter.setPen(col); painter.setBrush(QBrush(col)); int w = width(); int h = height(); if(orientation() == Qt::Vertical) { painter.drawText(QRect(0, 0, w, 25), Qt::AlignHCenter, m_title); } else { painter.drawText(QRect(0, h / 2 - 12, w, 25), Qt::AlignHCenter, m_title); } painter.setRenderHint(QPainter::Antialiasing, true); // draw the arrow if(orientation() == Qt::Vertical) { if(m_isCollapsed) { m_arrowPoints[0] = QPoint(w / 2, h - 9); m_arrowPoints[1] = QPoint(w / 2 - 10, h - 1); m_arrowPoints[2] = QPoint(w / 2 + 10, h - 1); } else { m_arrowPoints[0] = QPoint(w / 2, h - 1); m_arrowPoints[1] = QPoint(w / 2 - 10, h - 9); m_arrowPoints[2] = QPoint(w / 2 + 10, h - 9); } } else { if(m_isCollapsed) { m_arrowPoints[0] = QPoint(w - 9, h / 2 + 15); m_arrowPoints[1] = QPoint(w - 1, h / 2 + 5); m_arrowPoints[2] = QPoint(w - 1, h / 2 + 20); } else { m_arrowPoints[0] = QPoint(w - 1, h / 2 + 15); m_arrowPoints[1] = QPoint(w - 9, h / 2 + 5); m_arrowPoints[2] = QPoint(w - 9, h / 2 + 25); } } painter.drawPolygon(m_arrowPoints, 3); // draw the bullets if(orientation() == Qt::Vertical) { painter.drawEllipse(QPoint(w / 4 - 10, h - 10), 3, 3); painter.drawEllipse(QPoint(w / 4, h - 10), 3, 3); painter.drawEllipse(QPoint(w / 4 + 10, h - 10), 3, 3); painter.drawEllipse(QPoint(3 * w / 4 - 10, h - 10), 3, 3); painter.drawEllipse(QPoint(3 * w / 4, h - 10), 3, 3); painter.drawEllipse(QPoint(3 * w / 4 + 10, h - 10), 3, 3); } else { painter.drawEllipse(QPoint(w - 10, h / 4 - 10), 3, 3); painter.drawEllipse(QPoint(w - 10, h / 4), 3, 3); painter.drawEllipse(QPoint(w - 10, h / 4 + 10), 3, 3); painter.drawEllipse(QPoint(w - 10, 3 * h / 4 - 10), 3, 3); painter.drawEllipse(QPoint(w - 10, 3 * h / 4), 3, 3); painter.drawEllipse(QPoint(w - 10, 3 * h / 4 + 10), 3, 3); } } void RDSplitterHandle::mouseDoubleClickEvent(QMouseEvent *event) { RDSplitter *par = (RDSplitter *)splitter(); par->handleDoubleClicked(m_index); } RDSplitter::RDSplitter(Qt::Orientation orientation, QWidget *parent) : QSplitter(orientation, parent) { initialize(); } RDSplitter::RDSplitter(QWidget *parent) : QSplitter(parent) { initialize(); } void RDSplitter::handleDoubleClicked(int index) { if(index < 0 || index >= count()) return; RDSplitterHandle *rdHandle = (RDSplitterHandle *)handle(index); QList<int> totalSizes = sizes(); if(totalSizes[index] > 0) { // add to the previous handle the size of the current one totalSizes[index - 1] += totalSizes[index]; // set the current handle's size to 0 totalSizes[index] = 0; rdHandle->setCollapsed(true); } else { // split the sizes in half int s = totalSizes[index - 1] / 2; totalSizes[index] = totalSizes[index - 1] = s; rdHandle->setCollapsed(false); } setSizes(totalSizes); } void RDSplitter::setHandleCollapsed(int pos, int index) { QList<int> totalSizes = sizes(); RDSplitterHandle *rdHandle = (RDSplitterHandle *)handle(index); if(totalSizes[index] == 0) rdHandle->setCollapsed(true); else rdHandle->setCollapsed(false); } void RDSplitter::initialize() { connect(this, &RDSplitter::splitterMoved, this, &RDSplitter::setHandleCollapsed); } QSplitterHandle *RDSplitter::createHandle() { return new RDSplitterHandle(orientation(), this); }
/** * VKTS - VulKan ToolS. * * The MIT License (MIT) * * Copyright (c) since 2014 Norbert Nopper * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ #include "UpdateThreadExecutor.hpp" namespace vkts { UpdateThreadExecutor::UpdateThreadExecutor(const int32_t index, ExecutorSync& executorSync, const IUpdateThreadSP& updateThread, const UpdateThreadContextSP& updateThreadContext, const PFN_dispatchFunction dispatchFunction) : index(index), executorSync(executorSync), updateThread(updateThread), updateThreadContext(updateThreadContext), dispatchFunction(dispatchFunction) { } UpdateThreadExecutor::~UpdateThreadExecutor() { } int32_t UpdateThreadExecutor::getIndex() const { return index; } void UpdateThreadExecutor::run() const { // Initialization. VkBool32 doRun = VK_TRUE; if (!updateThread->init(*updateThreadContext)) { logPrint(VKTS_LOG_ERROR, __FILE__, __LINE__, "UpdateThreadExecutor %d run failed! Update thread Initialize failed.", index); doRun = VK_FALSE; executorSync.setDoAllRunFalse(); logPrint(VKTS_LOG_SEVERE, __FILE__, __LINE__, "UpdateThreadExecutor %d killing barrier.", index); barrierKill(); } else { logPrint(VKTS_LOG_SEVERE, __FILE__, __LINE__, "UpdateThreadExecutor %d initialized.", index); } // Update loop. while (doRun && executorSync.doAllRun()) { doRun = updateThread->update(*updateThreadContext); if (!doRun) { logPrint(VKTS_LOG_INFO, __FILE__, __LINE__, "UpdateThreadExecutor %d update ended.", index); doRun = VK_FALSE; executorSync.setDoAllRunFalse(); logPrint(VKTS_LOG_SEVERE, __FILE__, __LINE__, "UpdateThreadExecutor %d killing barrier.", index); barrierKill(); logPrint(VKTS_LOG_SEVERE, __FILE__, __LINE__, "UpdateThreadExecutor %d disabling task queue.", index); updateThreadContext->sendTask(ITaskSP()); break; } updateThreadContext->update(); if (dispatchFunction != nullptr) { if (!dispatchFunction()) { logPrint(VKTS_LOG_INFO, __FILE__, __LINE__, "UpdateThreadExecutor %d received quit message.", index); doRun = VK_FALSE; executorSync.setDoAllRunFalse(); logPrint(VKTS_LOG_SEVERE, __FILE__, __LINE__, "UpdateThreadExecutor %d killing barrier.", index); barrierKill(); logPrint(VKTS_LOG_SEVERE, __FILE__, __LINE__, "UpdateThreadExecutor %d disabling task queue.", index); updateThreadContext->sendTask(ITaskSP(nullptr)); break; } } std::this_thread::yield(); } // Blocking call, that all executors have finished their update thread. executorSync.updateDone(); // Termination. updateThread->terminate(*updateThreadContext); logPrint(VKTS_LOG_SEVERE, __FILE__, __LINE__, "UpdateThreadExecutor %d terminated.", index); } } /* namespace vkts */
// Copyright 2018 PDFium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // Original code copyright 2014 Foxit Software Inc. http://www.foxitsoftware.com #include "fxjs/xfa/fxjse.h" namespace pdfium { namespace fxjse { const char kFuncTag[] = "function descriptor tag"; const char kClassTag[] = "class descriptor tag"; } // namespace fxjse } // namespace pdfium CFXJSE_HostObject::CFXJSE_HostObject() = default; CFXJSE_HostObject::~CFXJSE_HostObject() = default; CFXJSE_FormCalcContext* CFXJSE_HostObject::AsFormCalcContext() { return nullptr; } CXFA_Object* CFXJSE_HostObject::AsCXFAObject() { return nullptr; }