text stringlengths 1 1.05M |
|---|
;
;==================================================================================================
; ROMWBW 2.X CONFIGURATION DEFAULTS FOR UNA
;==================================================================================================
;
; THIS FILE CONTAINS THE FULL SET OF DEFAULT CONFIGURATION SETTINGS FOR THE PLATFORM
; INDICATED ABOVE. THIS FILE SHOULD *NOT* NORMALLY BE CHANGED. INSTEAD, YOU SHOULD
; OVERRIDE ANY SETTINGS YOU WANT USING A CONFIGURATION FILE IN THE CONFIG DIRECTORY
; UNDER THIS DIRECTORY.
;
; THIS FILE CAN BE CONSIDERED A REFERENCE THAT LISTS ALL POSSIBLE CONFIGURATION SETTINGS
; FOR THE PLATFORM.
;
#DEFINE PLATFORM_NAME "UNA"
;
PLATFORM .EQU PLT_UNA ; PLT_[SBC|ZETA|ZETA2|N8|MK4|UNA|RCZ80|RCZ180|EZZ80|SCZ180|DYNO|RCZ280|MBC]
BIOS .EQU BIOS_UNA ; HARDWARE BIOS: BIOS_[WBW|UNA]
;
BOOT_TIMEOUT .EQU -1 ; AUTO BOOT TIMEOUT IN SECONDS, -1 TO DISABLE, 0 FOR IMMEDIATE
;
CPUSPDCAP .EQU SPD_FIXED ; CPU SPEED CHANGE CAPABILITY SPD_FIXED|SPD_HILO
CPUSPDDEF .EQU SPD_HIGH ; CPU SPEED DEFAULT SPD_UNSUP|SPD_HIGH|SPD_LOW
CPUOSC .EQU 18432000 ; CPU OSC FREQ IN MHZ
INTMODE .EQU 0 ; INTERRUPTS: 0=NONE, 1=MODE 1, 2=MODE 2, 3=MODE 3 (Z280)
;
RAMSIZE .EQU 512 ; SIZE OF RAM IN KB (MUST MATCH YOUR HARDWARE!!!)
PLT_RAM_R .EQU 0 ; RESERVE FIRST N KB OF RAM (USUALLY 0)
PLT_ROM_R .EQU 0 ; RESERVE FIRST N KB OR ROM (USUALLY 0)
;
RTCIO .EQU $70 ; RTC LATCH REGISTER ADR
;
DSKYENABLE .EQU FALSE ; ENABLES DSKY (DO NOT COMBINE WITH PPIDE)
|
; A253947: a(n) = 6*binomial(n+1,7).
; 6,48,216,720,1980,4752,10296,20592,38610,68640,116688,190944,302328,465120,697680,1023264,1470942,2076624,2884200,3946800,5328180,7104240,9364680,12214800,15777450,20195136,25632288,32277696,40347120,50086080,61772832,75721536,92285622,111861360,134891640,161869968,193344684,229923408,272277720,321148080,377348994,441774432,515403504,599306400,694650600,802707360,924858480,1062603360,1217566350,1391504400,1586315016,1804044528,2046896676,2317241520,2617624680,2950776912,3319624026,3727297152,4177143360,4672736640,5217889248,5816663424,6473383488,7192648320,7979344230,8838658224,9776091672,10797474384,11908979100,13117136400,14428850040,15851412720,17392522290,19060298400,20863299600,22810540896,24911511768,27176194656,29615083920,32239205280,35060135742,38090024016,41341611432,44828253360,48563941140,52563324528,56841734664,61415207568,66300508170,71515154880,77077444704,83006478912,89322189264,96045364800,103197679200,110801718720,118881010710,127460052720,136564342200,146220406800,156455835276,167299309008,178780634136,190930774320,203781884130,217367343072,231721790256,246881159712,262882716360,279765092640,297568325808,316333895904,336104764398,356925413520,378841886280,401901827184,426154523652,451650948144,478443801000,506587554000,536138494650,567154771200,599696438400,633825504000,669605976000,707103910656,746387461248,787526927616,830594806470,875665842480,922817080152,972127916496,1023680154492,1077558057360,1133848403640,1192640543088,1254026453394,1318100797728,1384960983120,1454707219680,1527442580664,1603273063392,1682307651024,1764658375200,1850440379550,1939771984080,2032774750440,2129573548080,2230296621300,2335075657200,2444045854536,2557345993488,2675118506346,2797509549120,2924669074080,3056750903232,3193912802736,3336316558272,3484128051360,3637517336640,3796658720118,3961730838384,4132916738808,4310403960720,4494384617580,4685055480144,4882618060632,5087278697904,5299248643650,5518744149600,5745986555760,5981202379680,6224623406760,6476486781600,6737035100400,7006516504416,7285184774478,7573299426576,7871125808520,8178935197680,8497004899812,8825618348976,9165065208552,9515641473360,9877649572890,10251398475648,10637203794624,11035387893888,11446279996320,11870216292480,12307540050624,12758601727872,13223759082534,13703377287600,14197829045400,14707494703440,15232762371420,15774028039440,16331695697400,16906177455600,17497893666546,18107273047968,18734752807056,19380778765920,20045805488280,20730296407392,21434723955216,22159569692832,22905324442110,23672488418640,24461571365928,25273092690864,26107581600468,26965577239920,27847628831880,28754295817104,29686147996362,30643765673664,31627739800800,32638672123200,33677175327120,34743873188160,35839400721120,36964404331200,38119541966550,39305483272176,40522909745208,41772514891536,43055004383820,44371096220880,45721520888472,47107021521456,48528354067362,49986287451360,51481603742640,53015098322208,54587580052104,56199871446048,57852808841520,59547242573280,61284037148334,63064071422352,64888238777544,66757447302000,68672619970500,70634694826800,72644625167400,74703379726800,76811942864250,78971314752000
add $0,7
bin $0,7
mov $1,$0
mul $1,6
|
//===--- MetadataRequest.cpp - IR generation for metadata requests --------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
//
// This file implements IR generation for accessing metadata.
//
//===----------------------------------------------------------------------===//
#include "MetadataRequest.h"
#include "Callee.h"
#include "ConstantBuilder.h"
#include "Explosion.h"
#include "FixedTypeInfo.h"
#include "GenArchetype.h"
#include "GenClass.h"
#include "GenMeta.h"
#include "GenPointerAuth.h"
#include "GenProto.h"
#include "GenType.h"
#include "GenericArguments.h"
#include "GenericRequirement.h"
#include "IRGenDebugInfo.h"
#include "IRGenFunction.h"
#include "IRGenMangler.h"
#include "IRGenModule.h"
#include "swift/AST/ASTContext.h"
#include "swift/AST/CanTypeVisitor.h"
#include "swift/AST/ExistentialLayout.h"
#include "swift/AST/GenericEnvironment.h"
#include "swift/AST/IRGenOptions.h"
#include "swift/AST/SubstitutionMap.h"
#include "swift/ClangImporter/ClangModule.h"
#include "swift/IRGen/Linking.h"
#include "swift/SIL/FormalLinkage.h"
#include "swift/SIL/TypeLowering.h"
#include "llvm/ADT/SmallSet.h"
#include "llvm/ADT/STLExtras.h"
#include "llvm/IR/Constant.h"
#include "llvm/IR/GlobalVariable.h"
#include "llvm/Support/Debug.h"
#include "llvm/Support/FormatVariadic.h"
#include <algorithm>
using namespace swift;
using namespace irgen;
llvm::Value *DynamicMetadataRequest::get(IRGenFunction &IGF) const {
if (isStatic()) {
return IGF.IGM.getSize(Size(StaticRequest.getOpaqueValue()));
} else {
return DynamicRequest;
}
}
llvm::Value *DynamicMetadataRequest::getRequiredState(IRGenFunction &IGF) const{
if (isStatic()) {
return IGF.IGM.getSize(Size(size_t(StaticRequest.getState())));
}
auto request = DynamicRequest;
static_assert(MetadataRequest::State_bit == 0,
"code below is not doing any shifts");
uint32_t mask =
((uint32_t(1) << MetadataRequest::State_width) - 1);
auto requiredState =
IGF.Builder.CreateAnd(request,
llvm::ConstantInt::get(IGF.IGM.SizeTy, mask));
return requiredState;
}
MetadataResponse MetadataResponse::getUndef(IRGenFunction &IGF) {
return forComplete(llvm::UndefValue::get(IGF.IGM.TypeMetadataPtrTy));
}
MetadataResponse
MetadataResponse::handle(IRGenFunction &IGF, DynamicMetadataRequest request,
llvm::Value *pair) {
assert(pair->getType() == IGF.IGM.TypeMetadataResponseTy);
// If the request is statically known to produce a complete result,
// we never even need to extract the status value.
if (request.isStaticallyBlockingComplete()) {
auto value = IGF.Builder.CreateExtractValue(pair, 0);
return MetadataResponse::forComplete(value);
}
// Otherwise, split the response.
auto split = IGF.Builder.CreateSplit<2>(pair);
// If the request has a collector installed, check the dependency now.
if (auto collector = request.getDependencyCollector()) {
collector->checkDependency(IGF, request, split[0], split[1]);
}
// Compute the static lower bound on the metadata's dynamic state.
// This will include any refinements from having branched for the
// dependency collector.
auto staticBound = request.getStaticLowerBoundOnResponseState();
auto response = MetadataResponse(split[0], split[1], staticBound);
return response;
}
llvm::Value *MetadataResponse::combine(IRGenFunction &IGF) const {
assert(isValid());
assert(hasDynamicState() && "cannot combine response without dynamic state");
return IGF.Builder.CreateCombine(IGF.IGM.TypeMetadataResponseTy,
{Metadata, getDynamicState()});
}
void MetadataResponse::ensureDynamicState(IRGenFunction &IGF) & {
assert(isValid());
// If we already have a dynamic state, bail out.
if (hasDynamicState()) return;
// If we're statically known complete, we can just fill in
// MetadataState::Complete.
if (isStaticallyKnownComplete()) {
DynamicState = getCompletedState(IGF.IGM);
return;
}
// Otherwise, we need to check the state dynamically. Do a non-blocking
// request for complete metadata.
auto request = MetadataRequest(MetadataState::Complete,
/*non-blocking*/ true);
*this = emitGetTypeMetadataDynamicState(IGF, request, Metadata);
}
llvm::Constant *MetadataResponse::getCompletedState(IRGenModule &IGM) {
return IGM.getSize(Size(size_t(MetadataState::Complete)));
}
llvm::Value *MetadataDependency::combine(IRGenFunction &IGF) const {
if (isTrivial()) {
return getTrivialCombinedDependency(IGF.IGM);
}
return IGF.Builder.CreateCombine(IGF.IGM.TypeMetadataDependencyTy,
{RequiredMetadata, RequiredState});
}
llvm::Constant *
MetadataDependency::getTrivialCombinedDependency(IRGenModule &IGM) {
return llvm::ConstantAggregateZero::get(IGM.TypeMetadataDependencyTy);
}
void MetadataDependencyCollector::checkDependency(IRGenFunction &IGF,
DynamicMetadataRequest request,
llvm::Value *metadata,
llvm::Value *metadataState) {
// Having either both or neither of the PHIs is normal.
// Having just RequiredState means that we already finalized this collector
// and shouldn't be using it anymore.
assert((!RequiredMetadata || RequiredState) &&
"checking dependencies on a finished collector");
// If the request is statically always satisfied, the operation cannot
// have failed.
if (request.isStaticallyAlwaysSatisfied())
return;
// Otherwise, we need to pull out the response state and compare it against
// the request state.
llvm::Value *requiredState = request.getRequiredState(IGF);
// More advanced metadata states are lower numbers.
static_assert(MetadataStateIsReverseOrdered,
"relying on the ordering of MetadataState here");
auto satisfied = IGF.Builder.CreateICmpULE(metadataState, requiredState);
emitCheckBranch(IGF, satisfied, metadata, requiredState);
}
void MetadataDependencyCollector::collect(IRGenFunction &IGF,
llvm::Value *dependency) {
// Having either both or neither of the PHIs is normal.
// Having just RequiredState means that we already finalized this collector
// and shouldn't be using it anymore.
assert((!RequiredMetadata || RequiredState) &&
"checking dependencies on a finished collector");
assert(dependency->getType() == IGF.IGM.TypeMetadataDependencyTy);
// Split the dependency.
auto metadata = IGF.Builder.CreateExtractValue(dependency, 0);
auto requiredState = IGF.Builder.CreateExtractValue(dependency, 1);
// We have a dependency if the metadata is non-null; otherwise we're
// satisfied and can continue.
auto satisfied = IGF.Builder.CreateIsNull(metadata);
emitCheckBranch(IGF, satisfied, metadata, requiredState);
}
void MetadataDependencyCollector::emitCheckBranch(IRGenFunction &IGF,
llvm::Value *satisfied,
llvm::Value *metadata,
llvm::Value *requiredState) {
// Lazily create the final continuation block and phis.
if (!RequiredMetadata) {
auto contBB = IGF.createBasicBlock("metadata-dependencies.cont");
RequiredMetadata =
llvm::PHINode::Create(IGF.IGM.TypeMetadataPtrTy, 4, "", contBB);
RequiredState = llvm::PHINode::Create(IGF.IGM.SizeTy, 4, "", contBB);
}
// Conditionally branch to the final continuation block.
auto satisfiedBB = IGF.createBasicBlock("dependency-satisfied");
auto curBB = IGF.Builder.GetInsertBlock();
RequiredMetadata->addIncoming(metadata, curBB);
RequiredState->addIncoming(requiredState, curBB);
IGF.Builder.CreateCondBr(satisfied, satisfiedBB,
RequiredMetadata->getParent());
// Otherwise resume emitting code on the main path.
IGF.Builder.emitBlock(satisfiedBB);
}
MetadataDependency MetadataDependencyCollector::finish(IRGenFunction &IGF) {
assert((!RequiredMetadata || RequiredState) &&
"finishing an already-finished collector");
// If we never branched with a dependency, the result is trivial.
if (RequiredMetadata == nullptr)
return MetadataDependency();
llvm::BasicBlock *curBB = IGF.Builder.GetInsertBlock();
assert(curBB);
auto contBB = RequiredMetadata->getParent();
IGF.Builder.CreateBr(contBB);
RequiredMetadata->addIncoming(
llvm::ConstantPointerNull::get(IGF.IGM.TypeMetadataPtrTy),
curBB);
RequiredState->addIncoming(llvm::ConstantInt::get(IGF.IGM.SizeTy, 0), curBB);
IGF.Builder.emitBlock(contBB);
auto result = MetadataDependency(RequiredMetadata, RequiredState);
// Clear RequiredMetadata to tell the destructor that we finished.
// We leave RequiredState in place so that we can detect attempts to
// add
RequiredMetadata = nullptr;
return result;
}
llvm::Constant *IRGenModule::getAddrOfStringForMetadataRef(
StringRef symbolName,
unsigned alignment,
bool shouldSetLowBit,
llvm::function_ref<ConstantInitFuture (ConstantInitBuilder &)> body) {
// Call this to form the return value.
auto returnValue = [&](llvm::Constant *addr) {
if (!shouldSetLowBit)
return addr;
auto bitConstant = llvm::ConstantInt::get(IntPtrTy, 1);
return llvm::ConstantExpr::getGetElementPtr(nullptr, addr, bitConstant);
};
// Check whether we already have an entry with this name.
auto &entry = StringsForTypeRef[symbolName];
if (entry.second) {
return returnValue(entry.second);
}
// Construct the initializer.
ConstantInitBuilder builder(*this);
auto finished = body(builder);
auto var = new llvm::GlobalVariable(Module, finished.getType(),
/*constant*/ true,
llvm::GlobalValue::LinkOnceODRLinkage,
nullptr,
symbolName);
ApplyIRLinkage(IRLinkage::InternalLinkOnceODR).to(var);
if (alignment)
var->setAlignment(llvm::MaybeAlign(alignment));
setTrueConstGlobal(var);
var->setSection(getReflectionTypeRefSectionName());
finished.installInGlobal(var);
// Drill down to the i8* at the beginning of the constant.
auto addr = llvm::ConstantExpr::getBitCast(var, Int8PtrTy);
StringsForTypeRef[symbolName] = { var, addr };
return returnValue(addr);
}
llvm::Constant *IRGenModule::getAddrOfStringForTypeRef(StringRef str,
MangledTypeRefRole role){
return getAddrOfStringForTypeRef(SymbolicMangling{str.str(), {}}, role);
}
llvm::Constant *IRGenModule::getAddrOfStringForTypeRef(
const SymbolicMangling &mangling,
MangledTypeRefRole role) {
// Create a symbol name for the symbolic mangling. This is used as the
// uniquing key both for ODR coalescing and within this TU.
IRGenMangler mangler;
std::string symbolName =
mangler.mangleSymbolNameForSymbolicMangling(mangling, role);
// See if we emitted the constant already.
auto &entry = StringsForTypeRef[symbolName];
if (entry.second) {
return entry.second;
}
ConstantInitBuilder B(*this);
auto S = B.beginStruct();
S.setPacked(true);
switch (role) {
case MangledTypeRefRole::DefaultAssociatedTypeWitness:
// The 0xFF prefix identifies a default associated type witness.
S.addInt(Int8Ty,
ProtocolRequirementFlags::AssociatedTypeInProtocolContextByte);
break;
case MangledTypeRefRole::Metadata:
case MangledTypeRefRole::Reflection:
break;
}
unsigned pos = 0;
for (auto &symbolic : mangling.SymbolicReferences) {
assert(symbolic.second >= pos
&& "references should be ordered");
if (symbolic.second != pos) {
// Emit the preceding literal chunk.
auto literalChunk = StringRef(mangling.String.data() + pos,
symbolic.second - pos);
auto literal = llvm::ConstantDataArray::getString(getLLVMContext(),
literalChunk,
/*null*/ false);
S.add(literal);
}
ConstantReference ref;
unsigned char baseKind;
if (auto ctype = symbolic.first.dyn_cast<const NominalTypeDecl*>()) {
auto type = const_cast<NominalTypeDecl*>(ctype);
if (auto proto = dyn_cast<ProtocolDecl>(type)) {
// The symbolic reference is to the protocol descriptor of the
// referenced protocol.
ref = getAddrOfLLVMVariableOrGOTEquivalent(
LinkEntity::forProtocolDescriptor(proto));
} else {
// The symbolic reference is to the type context descriptor of the
// referenced type.
IRGen.noteUseOfTypeContextDescriptor(type, DontRequireMetadata);
ref = getAddrOfLLVMVariableOrGOTEquivalent(
LinkEntity::forNominalTypeDescriptor(type));
}
// \1 - direct reference, \2 - indirect reference
baseKind = 1;
} else if (auto copaque = symbolic.first.dyn_cast<const OpaqueTypeDecl*>()){
auto opaque = const_cast<OpaqueTypeDecl*>(copaque);
IRGen.noteUseOfOpaqueTypeDescriptor(opaque);
ref = getAddrOfLLVMVariableOrGOTEquivalent(
LinkEntity::forOpaqueTypeDescriptor(opaque));
baseKind = 1;
} else {
llvm_unreachable("unhandled symbolic referent");
}
// add kind byte. indirect kinds are the direct kind + 1
unsigned char kind = ref.isIndirect() ? baseKind + 1 : baseKind;
S.add(llvm::ConstantInt::get(Int8Ty, kind));
// add relative reference
S.addRelativeAddress(ref.getValue());
pos = symbolic.second + 5;
}
// Add the last literal bit, if any.
if (pos != mangling.String.size()) {
auto literalChunk = StringRef(mangling.String.data() + pos,
mangling.String.size() - pos);
auto literal = llvm::ConstantDataArray::getString(getLLVMContext(),
literalChunk,
/*null*/ false);
S.add(literal);
}
// And a null terminator!
S.addInt(Int8Ty, 0);
auto finished = S.finishAndCreateFuture();
auto var = new llvm::GlobalVariable(Module, finished.getType(),
/*constant*/ true,
llvm::GlobalValue::LinkOnceODRLinkage,
nullptr,
symbolName);
ApplyIRLinkage(IRLinkage::InternalLinkOnceODR).to(var);
var->setAlignment(llvm::MaybeAlign(2));
setTrueConstGlobal(var);
var->setSection(getReflectionTypeRefSectionName());
finished.installInGlobal(var);
// Drill down to the i8* at the beginning of the constant.
auto addr = llvm::ConstantExpr::getBitCast(var, Int8PtrTy);
entry = {var, addr};
return addr;
}
llvm::Value *irgen::emitObjCMetadataRefForMetadata(IRGenFunction &IGF,
llvm::Value *classPtr) {
assert(IGF.IGM.Context.LangOpts.EnableObjCInterop);
classPtr = IGF.Builder.CreateBitCast(classPtr, IGF.IGM.ObjCClassPtrTy);
// Fetch the metadata for that class.
auto call = IGF.Builder.CreateCall(IGF.IGM.getGetObjCClassMetadataFn(),
classPtr);
call->setDoesNotThrow();
call->setDoesNotAccessMemory();
return call;
}
/// Emit a reference to the Swift metadata for an Objective-C class.
static llvm::Value *emitObjCMetadataRef(IRGenFunction &IGF,
ClassDecl *theClass) {
// Derive a pointer to the Objective-C class.
auto classPtr = emitObjCHeapMetadataRef(IGF, theClass);
return emitObjCMetadataRefForMetadata(IGF, classPtr);
}
// Get the type that exists at runtime to represent a compile-time type.
CanType IRGenModule::getRuntimeReifiedType(CanType type) {
// Leave type-erased ObjC generics with their generic arguments unbound, since
// the arguments do not exist at runtime.
return CanType(type.transform([&](Type t) -> Type {
if (CanType(t).isTypeErasedGenericClassType()) {
return t->getAnyNominal()->getDeclaredType()->getCanonicalType();
}
return t;
}));
}
CanType IRGenModule::substOpaqueTypesWithUnderlyingTypes(CanType type) {
// Substitute away opaque types whose underlying types we're allowed to
// assume are constant.
if (type->hasOpaqueArchetype()) {
ReplaceOpaqueTypesWithUnderlyingTypes replacer(
getSwiftModule(), ResilienceExpansion::Maximal,
getSILModule().isWholeModule());
auto underlyingTy =
type.subst(replacer, replacer, SubstFlags::SubstituteOpaqueArchetypes)
->getCanonicalType();
return underlyingTy;
}
return type;
}
SILType IRGenModule::substOpaqueTypesWithUnderlyingTypes(
SILType type, CanGenericSignature genericSig) {
// Substitute away opaque types whose underlying types we're allowed to
// assume are constant.
if (type.getASTType()->hasOpaqueArchetype()) {
ReplaceOpaqueTypesWithUnderlyingTypes replacer(
getSwiftModule(), ResilienceExpansion::Maximal,
getSILModule().isWholeModule());
auto underlyingTy =
type.subst(getSILModule(), replacer, replacer, genericSig,
/*substitute opaque*/ true);
return underlyingTy;
}
return type;
}
std::pair<CanType, ProtocolConformanceRef>
IRGenModule::substOpaqueTypesWithUnderlyingTypes(CanType type,
ProtocolConformanceRef conformance) {
// Substitute away opaque types whose underlying types we're allowed to
// assume are constant.
if (type->hasOpaqueArchetype()) {
ReplaceOpaqueTypesWithUnderlyingTypes replacer(
getSwiftModule(), ResilienceExpansion::Maximal,
getSILModule().isWholeModule());
auto substConformance = conformance.subst(
type, replacer, replacer, SubstFlags::SubstituteOpaqueArchetypes);
auto underlyingTy =
type.subst(replacer, replacer, SubstFlags::SubstituteOpaqueArchetypes)
->getCanonicalType();
return std::make_pair(underlyingTy, substConformance);
}
return std::make_pair(type, conformance);
}
/// Attempts to return a constant heap metadata reference for a
/// class type. This is generally only valid for specific kinds of
/// ObjC reference, like superclasses or category references.
llvm::Constant *
irgen::tryEmitConstantHeapMetadataRef(IRGenModule &IGM,
CanType type,
bool allowDynamicUninitialized) {
auto theDecl = type->getClassOrBoundGenericClass();
assert(theDecl && "emitting constant heap metadata ref for non-class type?");
switch (IGM.getClassMetadataStrategy(theDecl)) {
case ClassMetadataStrategy::Resilient:
case ClassMetadataStrategy::Singleton:
if (!allowDynamicUninitialized)
return nullptr;
break;
case ClassMetadataStrategy::Update:
case ClassMetadataStrategy::FixedOrUpdate:
case ClassMetadataStrategy::Fixed:
break;
}
// For imported classes, use the ObjC class symbol.
if (!hasKnownSwiftMetadata(IGM, theDecl))
return IGM.getAddrOfObjCClass(theDecl, NotForDefinition);
return IGM.getAddrOfTypeMetadata(type);
}
/// Attempts to return a constant type metadata reference for a
/// nominal type.
ConstantReference
irgen::tryEmitConstantTypeMetadataRef(IRGenModule &IGM, CanType type,
SymbolReferenceKind refKind) {
if (IGM.isStandardLibrary())
return ConstantReference();
if (isCanonicalCompleteTypeMetadataStaticallyAddressable(IGM, type))
return ConstantReference();
return IGM.getAddrOfTypeMetadata(type, refKind);
}
/// Emit a reference to an ObjC class. In general, the only things
/// you're allowed to do with the address of an ObjC class symbol are
/// (1) send ObjC messages to it (in which case the message will be
/// forwarded to the real class, if one exists) or (2) put it in
/// various data sections where the ObjC runtime will properly arrange
/// things. Therefore, we must typically force the initialization of
/// a class when emitting a reference to it.
llvm::Value *irgen::emitObjCHeapMetadataRef(IRGenFunction &IGF,
ClassDecl *theClass,
bool allowUninitialized) {
// If the class is visible only through the Objective-C runtime, form the
// appropriate runtime call.
if (theClass->getForeignClassKind() == ClassDecl::ForeignKind::RuntimeOnly) {
SmallString<64> scratch;
auto className =
IGF.IGM.getAddrOfGlobalString(theClass->getObjCRuntimeName(scratch));
return IGF.Builder.CreateCall(IGF.IGM.getLookUpClassFn(), className);
}
assert(!theClass->isForeign());
Address classRef = IGF.IGM.getAddrOfObjCClassRef(theClass);
auto classObject = IGF.Builder.CreateLoad(classRef);
if (allowUninitialized) return classObject;
// TODO: memoize this the same way that we memoize Swift type metadata?
return IGF.Builder.CreateCall(IGF.IGM.getFixedClassInitializationFn(),
classObject);
}
static MetadataResponse emitNominalPrespecializedGenericMetadataRef(
IRGenFunction &IGF, NominalTypeDecl *theDecl, CanType theType,
DynamicMetadataRequest request,
SpecializedMetadataCanonicality canonicality) {
assert(isCompleteSpecializedNominalTypeMetadataStaticallyAddressable(
IGF.IGM, *theDecl, theType, canonicality));
// We are applying generic parameters to a generic type.
assert(theType->getAnyNominal() == theDecl);
// Check to see if we've maybe got a local reference already.
if (auto cache = IGF.tryGetLocalTypeMetadata(theType, request))
return cache;
switch (canonicality) {
case CanonicalSpecializedMetadata: {
auto metadata = IGF.IGM.getAddrOfTypeMetadata(theType);
return MetadataResponse::forComplete(metadata);
}
case NoncanonicalSpecializedMetadata: {
auto cacheVariable =
IGF.IGM.getAddrOfNoncanonicalSpecializedGenericTypeMetadataCacheVariable(theType);
auto call = IGF.Builder.CreateCall(
IGF.IGM.getGetCanonicalSpecializedMetadataFn(),
{request.get(IGF),
IGF.IGM.getAddrOfTypeMetadata(theType,
TypeMetadataCanonicality::Noncanonical),
cacheVariable});
call->setDoesNotThrow();
call->setCallingConv(IGF.IGM.SwiftCC);
call->addAttribute(llvm::AttributeList::FunctionIndex,
llvm::Attribute::ReadNone);
return MetadataResponse::handle(IGF, request, call);
}
}
llvm_unreachable("unhandled metadata canonicality");
}
static llvm::Value *
emitIdempotentClassMetadataInitialization(IRGenFunction &IGF,
llvm::Value *metadata) {
if (IGF.IGM.ObjCInterop) {
metadata = IGF.Builder.CreateBitCast(metadata, IGF.IGM.ObjCClassPtrTy);
metadata = IGF.Builder.CreateCall(IGF.IGM.getFixedClassInitializationFn(),
metadata);
metadata = IGF.Builder.CreateBitCast(metadata, IGF.IGM.TypeMetadataPtrTy);
}
return metadata;
}
/// Returns a metadata reference for a nominal type.
///
/// This is only valid in a couple of special cases:
/// 1) The nominal type is generic, in which case we emit a call to the
/// generic metadata accessor function, which must be defined separately.
/// 2) The nominal type is a value type with a fixed size from this
/// resilience domain, in which case we can reference the constant
/// metadata directly.
/// 3) The nominal type is a class with known Swift metadata and
/// a fixed layout from this resilience domain, in which case we only
/// need perform idempotent class initialization to realize it
/// in the ObjC runtime.
///
/// In any other case, a metadata accessor should be called instead.
static MetadataResponse emitNominalMetadataRef(IRGenFunction &IGF,
NominalTypeDecl *theDecl,
CanType theType,
DynamicMetadataRequest request) {
assert(!isa<ProtocolDecl>(theDecl));
if (!theDecl->isGenericContext()) {
assert(!IGF.IGM.isResilient(theDecl, ResilienceExpansion::Maximal));
if (auto response = IGF.tryGetLocalTypeMetadata(theType, request)) {
return response;
}
llvm::Value *metadata = IGF.IGM.getAddrOfTypeMetadata(theType);
// We need to realize classes with the ObjC runtime.
if (auto c = dyn_cast<ClassDecl>(theDecl)) {
assert(hasKnownSwiftMetadata(IGF.IGM, c));
metadata = emitIdempotentClassMetadataInitialization(IGF, metadata);
}
auto response = MetadataResponse::forComplete(metadata);
IGF.setScopedLocalTypeMetadata(theType, response);
return response;
}
// We are applying generic parameters to a generic type.
assert(theType->isSpecialized() &&
theType->getAnyNominal() == theDecl);
// Check to see if we've maybe got a local reference already.
if (auto cache = IGF.tryGetLocalTypeMetadata(theType, request))
return cache;
// Grab the substitutions.
GenericArguments genericArgs;
genericArgs.collect(IGF, theType);
assert((!genericArgs.Values.empty() ||
theDecl->getGenericSignature()->areAllParamsConcrete()) &&
"no generic args?!");
MetadataResponse response;
if (isCompleteSpecializedNominalTypeMetadataStaticallyAddressable(
IGF.IGM, *theDecl, theType, CanonicalSpecializedMetadata)) {
response = emitNominalPrespecializedGenericMetadataRef(
IGF, theDecl, theType, request, CanonicalSpecializedMetadata);
} else if (isCompleteSpecializedNominalTypeMetadataStaticallyAddressable(
IGF.IGM, *theDecl, theType, NoncanonicalSpecializedMetadata)) {
response = emitNominalPrespecializedGenericMetadataRef(
IGF, theDecl, theType, request, NoncanonicalSpecializedMetadata);
} else if (auto theClass = dyn_cast<ClassDecl>(theDecl)) {
if (isSpecializedNominalTypeMetadataStaticallyAddressable(
IGF.IGM, *theClass, theType, CanonicalSpecializedMetadata,
ForUseOnlyFromAccessor)) {
llvm::Function *accessor =
IGF.IGM
.getAddrOfCanonicalSpecializedGenericTypeMetadataAccessFunction(
theType, NotForDefinition);
response =
IGF.emitGenericTypeMetadataAccessFunctionCall(accessor, {}, request);
}
}
if (!response.isValid()) {
// Call the generic metadata accessor function.
llvm::Function *accessor =
IGF.IGM.getAddrOfGenericTypeMetadataAccessFunction(
theDecl, genericArgs.Types, NotForDefinition);
response = IGF.emitGenericTypeMetadataAccessFunctionCall(
accessor, genericArgs.Values, request);
}
IGF.setScopedLocalTypeMetadata(theType, response);
return response;
}
bool irgen::isSpecializedNominalTypeMetadataStaticallyAddressable(
IRGenModule &IGM, NominalTypeDecl &nominal, CanType type,
SpecializedMetadataCanonicality canonicality,
SpecializedMetadataUsageIsOnlyFromAccessor onlyFromAccessor) {
assert(nominal.isGenericContext());
if (!IGM.shouldPrespecializeGenericMetadata()) {
return false;
}
if (type->hasArchetype()) {
return false;
}
switch (canonicality) {
case CanonicalSpecializedMetadata:
if (IGM.getSILModule().isWholeModule()) {
// Canonical prespecializations can only be emitted within the module
// where the generic type is itself defined, since it is the module where
// the metadata accessor is defined.
if (IGM.getSwiftModule() != nominal.getModuleContext()) {
return false;
}
} else {
// If whole module optimization is not enabled, we can only construct a
// canonical prespecialization if the usage is in the same *file* as that
// containing the type's decl! The reason is that the generic metadata
// accessor is defined in the IRGenModule corresponding to the source file
// containing the type's decl.
SourceFile *nominalFile = nominal.getDeclContext()->getParentSourceFile();
if (auto *moduleFile = IGM.IRGen.getSourceFile(&IGM)) {
if (nominalFile != moduleFile) {
return false;
}
}
}
break;
case NoncanonicalSpecializedMetadata:
// Non-canonical metadata prespecializations for a type cannot be formed
// within the module that defines that type.
if (IGM.getSwiftModule() == nominal.getModuleContext()) {
return false;
}
if (nominal.isResilient(IGM.getSwiftModule(),
ResilienceExpansion::Maximal)) {
return false;
}
break;
}
if (auto *theClass = dyn_cast<ClassDecl>(&nominal)) {
if (theClass->hasResilientMetadata(IGM.getSwiftModule(),
ResilienceExpansion::Maximal)) {
return false;
}
AncestryOptions flags = theClass->checkAncestry();
if (flags & (AncestryOptions(AncestryFlags::ResilientOther) |
AncestryOptions(AncestryFlags::ClangImported))) {
return false;
}
if (auto *theSuperclass = theClass->getSuperclassDecl()) {
auto superclassType =
type->getSuperclass(/*useArchetypes=*/false)->getCanonicalType();
if (!isCanonicalInitializableTypeMetadataStaticallyAddressable(
IGM, superclassType) &&
!tryEmitConstantHeapMetadataRef(
IGM, superclassType,
/*allowDynamicUninitialized=*/false)) {
return false;
}
}
}
auto *generic = type.getAnyGeneric();
assert(generic);
auto *environment = generic->getGenericEnvironment();
assert(environment);
auto substitutions =
type->getContextSubstitutionMap(IGM.getSwiftModule(), &nominal);
auto allArgumentsAreStaticallyAddressable =
llvm::all_of(environment->getGenericParams(), [&](auto parameter) {
auto signature = environment->getGenericSignature();
const auto protocols = signature->getRequiredProtocols(parameter);
auto argument = ((Type *)parameter)->subst(substitutions);
auto canonicalType = argument->getCanonicalType();
auto witnessTablesAreReferenceable = [&]() {
return llvm::all_of(protocols, [&](ProtocolDecl *protocol) {
auto conformance =
signature->lookupConformance(canonicalType, protocol);
if (!conformance.isConcrete()) {
return false;
}
auto rootConformance =
conformance.getConcrete()->getRootConformance();
return !IGM.isDependentConformance(rootConformance) &&
!IGM.isResilientConformance(rootConformance);
});
};
// TODO: Once witness tables are statically specialized, check whether
// the
// ConformanceInfo returns nullptr from tryGetConstantTable.
auto isGenericWithoutPrespecializedConformance = [&]() {
auto genericArgument = argument->getAnyGeneric();
return genericArgument && genericArgument->isGenericContext() &&
(protocols.size() > 0);
};
auto metadataAccessIsTrivial = [&]() {
if (onlyFromAccessor) {
// If an accessor is being used, then the accessor will be able to
// initialize the arguments, i.e. register classes with the ObjC
// runtime.
return irgen::
isCanonicalInitializableTypeMetadataStaticallyAddressable(
IGM, canonicalType);
} else {
return irgen::isCanonicalCompleteTypeMetadataStaticallyAddressable(
IGM, canonicalType);
}
};
return !isGenericWithoutPrespecializedConformance() &&
metadataAccessIsTrivial() && witnessTablesAreReferenceable();
});
return allArgumentsAreStaticallyAddressable &&
IGM.getTypeInfoForUnlowered(type).isFixedSize(
ResilienceExpansion::Maximal);
}
bool irgen::isCompleteSpecializedNominalTypeMetadataStaticallyAddressable(
IRGenModule &IGM, NominalTypeDecl &nominal, CanType type,
SpecializedMetadataCanonicality canonicality) {
if (isa<ClassType>(type) || isa<BoundGenericClassType>(type)) {
// TODO: On platforms without ObjC interop, we can do direct access to
// class metadata.
return false;
}
// Prespecialized struct/enum metadata gets no dedicated accessor yet and so
// cannot do the work of registering the generic arguments which are classes
// with the ObjC runtime. Concretely, the following cannot be prespecialized
// yet:
// Struct<Klass<Int>>
// Enum<Klass<Int>>
return isSpecializedNominalTypeMetadataStaticallyAddressable(
IGM, nominal, type, canonicality, NotForUseOnlyFromAccessor);
}
/// Is there a known address for canonical specialized metadata? The metadata
/// there may need initialization before it is complete.
bool irgen::isCanonicalInitializableTypeMetadataStaticallyAddressable(
IRGenModule &IGM, CanType type) {
if (isCanonicalCompleteTypeMetadataStaticallyAddressable(IGM, type)) {
// The address of the complete metadata is the address of the abstract
// metadata.
return true;
}
NominalTypeDecl *nominal;
if ((nominal = type->getAnyNominal()) && nominal->isGenericContext()) {
// Prespecialized class metadata gets a dedicated accessor which can do
// the work of registering the class and its arguments with the ObjC
// runtime.
// Concretely, Clazz<Klass<Int>> can be prespecialized.
return isSpecializedNominalTypeMetadataStaticallyAddressable(
IGM, *nominal, type, CanonicalSpecializedMetadata,
ForUseOnlyFromAccessor);
}
return false;
}
bool irgen::isNoncanonicalCompleteTypeMetadataStaticallyAddressable(
IRGenModule &IGM, CanType type) {
// If the canonical metadata record can be statically addressed, then there
// should be no visible non-canonical metadata record to address.
if (isCanonicalCompleteTypeMetadataStaticallyAddressable(IGM, type)) {
return false;
}
if (isa<BoundGenericStructType>(type) || isa<BoundGenericEnumType>(type)) {
auto nominalType = cast<BoundGenericType>(type);
auto *nominalDecl = nominalType->getDecl();
// Imported type metadata always requires an accessor.
if (isa<ClangModuleUnit>(nominalDecl->getModuleScopeContext()))
return false;
return isCompleteSpecializedNominalTypeMetadataStaticallyAddressable(
IGM, *nominalDecl, type, NoncanonicalSpecializedMetadata);
}
return false;
}
/// Is complete metadata for the given type available at a fixed address?
bool irgen::isCanonicalCompleteTypeMetadataStaticallyAddressable(
IRGenModule &IGM, CanType type) {
assert(!type->hasArchetype());
// Value type metadata only requires dynamic initialization on first
// access if it contains a resilient type.
if (isa<StructType>(type) || isa<EnumType>(type)) {
auto nominalType = cast<NominalType>(type);
auto *nominalDecl = nominalType->getDecl();
// Imported type metadata always requires an accessor.
if (isa<ClangModuleUnit>(nominalDecl->getModuleScopeContext()))
return false;
if (nominalDecl->isGenericContext())
return isCompleteSpecializedNominalTypeMetadataStaticallyAddressable(
IGM, *nominalDecl, type, CanonicalSpecializedMetadata);
auto expansion = ResilienceExpansion::Maximal;
// Resiliently-sized metadata access always requires an accessor.
return IGM.getTypeInfoForUnlowered(type).isFixedSize(expansion);
}
// The empty tuple type has a singleton metadata.
if (auto tuple = dyn_cast<TupleType>(type))
return tuple->getNumElements() == 0;
// Any and AnyObject have singleton metadata.
if (type->isAny() || type->isAnyObject())
return true;
// The builtin types generally don't require metadata, but some of them
// have nodes in the runtime anyway.
if (isa<BuiltinType>(type))
return true;
// SIL box types are artificial, but for the purposes of dynamic layout,
// we use the NativeObject metadata.
if (isa<SILBoxType>(type))
return true;
if (isa<BoundGenericStructType>(type) || isa<BoundGenericEnumType>(type)) {
auto nominalType = cast<BoundGenericType>(type);
auto *nominalDecl = nominalType->getDecl();
// Imported type metadata always requires an accessor.
if (isa<ClangModuleUnit>(nominalDecl->getModuleScopeContext()))
return false;
return isCompleteSpecializedNominalTypeMetadataStaticallyAddressable(
IGM, *nominalDecl, type, CanonicalSpecializedMetadata);
}
return false;
}
/// Should requests for the given type's metadata be cached?
bool irgen::shouldCacheTypeMetadataAccess(IRGenModule &IGM, CanType type) {
// DynamicSelfType is actually local.
if (type->hasDynamicSelfType())
return false;
// Nongeneric, nonresilient classes with known Swift metadata need to be
// realized with the Objective-C runtime, but that only requires a single
// runtime call that already has a fast path exit for already-realized
// classes, so we don't need to put up another layer of caching in front.
//
// TODO: On platforms without ObjC interop, we can do direct access to
// Swift metadata without a runtime call at all.
if (auto classDecl = type.getClassOrBoundGenericClass()) {
if (!hasKnownSwiftMetadata(IGM, classDecl))
return true;
if (classDecl->isGenericContext() &&
isSpecializedNominalTypeMetadataStaticallyAddressable(
IGM, *classDecl, type, CanonicalSpecializedMetadata,
ForUseOnlyFromAccessor))
return false;
auto strategy = IGM.getClassMetadataStrategy(classDecl);
return strategy != ClassMetadataStrategy::Fixed;
}
// Trivially accessible metadata does not need a cache.
if (isCanonicalCompleteTypeMetadataStaticallyAddressable(IGM, type))
return false;
if (isNoncanonicalCompleteTypeMetadataStaticallyAddressable(IGM, type))
return false;
return true;
}
/// Should requests for the given type's metadata go through an accessor?
static bool shouldTypeMetadataAccessUseAccessor(IRGenModule &IGM, CanType type){
// Anything that requires caching should go through an accessor to outline
// the cache check.
if (shouldCacheTypeMetadataAccess(IGM, type))
return true;
// Fixed-metadata classes don't require caching, but we still want to go
// through the accessor to outline the ObjC realization.
// TODO: On non-Apple platforms, fixed classes should not need any
// initialization so should be directly addressable.
if (isa<ClassType>(type)) {
return true;
}
return false;
}
/// Return the standard access strategy for getting a non-dependent
/// type metadata object.
MetadataAccessStrategy irgen::getTypeMetadataAccessStrategy(CanType type) {
// We should not be emitting accessors for partially-substituted
// generic types.
assert(!type->hasArchetype());
// Non-generic structs, enums, and classes are special cases.
//
// Note that while protocol types don't have a metadata pattern,
// we still require an accessor since we actually want to get
// the metadata for the existential type.
//
// This needs to kept in sync with hasRequiredTypeMetadataAccessPattern.
auto nominal = type->getAnyNominal();
if (nominal && !isa<ProtocolDecl>(nominal)) {
// Metadata accessors for fully-substituted generic types are
// emitted with shared linkage.
if (nominal->isGenericContext() && !nominal->isObjC()) {
if (type->isSpecialized())
return MetadataAccessStrategy::NonUniqueAccessor;
assert(type->hasUnboundGenericType());
}
if (requiresForeignTypeMetadata(nominal))
return MetadataAccessStrategy::ForeignAccessor;
// If the type doesn't guarantee that it has an access function,
// we might have to use a non-unique accessor.
// Everything else requires accessors.
switch (getDeclLinkage(nominal)) {
case FormalLinkage::PublicUnique:
return MetadataAccessStrategy::PublicUniqueAccessor;
case FormalLinkage::HiddenUnique:
return MetadataAccessStrategy::HiddenUniqueAccessor;
case FormalLinkage::Private:
return MetadataAccessStrategy::PrivateAccessor;
case FormalLinkage::PublicNonUnique:
return MetadataAccessStrategy::NonUniqueAccessor;
}
llvm_unreachable("bad formal linkage");
}
// Everything else requires a shared accessor function.
return MetadataAccessStrategy::NonUniqueAccessor;
}
/// Emit a string encoding the labels in the given tuple type.
static llvm::Constant *getTupleLabelsString(IRGenModule &IGM,
CanTupleType type,
bool useLabels) {
// If we were asked to ignore the labels, do so.
if (!useLabels) {
return llvm::ConstantPointerNull::get(IGM.Int8PtrTy);
}
bool hasLabels = false;
llvm::SmallString<128> buffer;
for (auto &elt : type->getElements()) {
if (elt.hasName()) {
hasLabels = true;
buffer.append(elt.getName().str());
}
// Each label is space-terminated.
buffer += ' ';
}
// If there are no labels, use a null pointer.
if (!hasLabels) {
return llvm::ConstantPointerNull::get(IGM.Int8PtrTy);
}
// Otherwise, create a new string literal.
// This method implicitly adds a null terminator.
return IGM.getAddrOfGlobalString(buffer);
}
static llvm::Constant *emitEmptyTupleTypeMetadataRef(IRGenModule &IGM) {
llvm::Constant *fullMetadata = IGM.getEmptyTupleMetadata();
llvm::Constant *indices[] = {
llvm::ConstantInt::get(IGM.Int32Ty, 0),
llvm::ConstantInt::get(IGM.Int32Ty, 1)
};
return llvm::ConstantExpr::getInBoundsGetElementPtr(
/*Ty=*/nullptr, fullMetadata, indices);
}
using GetElementMetadataFn =
llvm::function_ref<MetadataResponse(CanType eltType,
DynamicMetadataRequest eltRequest)>;
static MetadataResponse emitTupleTypeMetadataRef(IRGenFunction &IGF,
CanTupleType type,
DynamicMetadataRequest request,
bool useLabels,
GetElementMetadataFn getMetadataRecursive) {
auto getElementMetadata = [&](CanType type) {
// Just request the elements to be abstract so that we can always build
// the metadata.
// TODO: if we have a collector, or if this is a blocking request, maybe
// we should build a stronger request?
return getMetadataRecursive(type, MetadataState::Abstract).getMetadata();
};
switch (type->getNumElements()) {
case 0:
return MetadataResponse::forComplete(
emitEmptyTupleTypeMetadataRef(IGF.IGM));
case 1:
// For metadata purposes, we consider a singleton tuple to be
// isomorphic to its element type. ???
return getMetadataRecursive(type.getElementType(0), request);
case 2: {
auto elt0Metadata = getElementMetadata(type.getElementType(0));
auto elt1Metadata = getElementMetadata(type.getElementType(1));
llvm::Value *args[] = {
request.get(IGF),
elt0Metadata, elt1Metadata,
getTupleLabelsString(IGF.IGM, type, useLabels),
llvm::ConstantPointerNull::get(IGF.IGM.WitnessTablePtrTy) // proposed
};
auto call = IGF.Builder.CreateCall(IGF.IGM.getGetTupleMetadata2Fn(),
args);
call->setCallingConv(IGF.IGM.SwiftCC);
call->setDoesNotThrow();
return MetadataResponse::handle(IGF, request, call);
}
case 3: {
auto elt0Metadata = getElementMetadata(type.getElementType(0));
auto elt1Metadata = getElementMetadata(type.getElementType(1));
auto elt2Metadata = getElementMetadata(type.getElementType(2));
llvm::Value *args[] = {
request.get(IGF),
elt0Metadata, elt1Metadata, elt2Metadata,
getTupleLabelsString(IGF.IGM, type, useLabels),
llvm::ConstantPointerNull::get(IGF.IGM.WitnessTablePtrTy) // proposed
};
auto call = IGF.Builder.CreateCall(IGF.IGM.getGetTupleMetadata3Fn(),
args);
call->setCallingConv(IGF.IGM.SwiftCC);
call->setDoesNotThrow();
return MetadataResponse::handle(IGF, request, call);
}
default:
// TODO: use a caching entrypoint (with all information
// out-of-line) for non-dependent tuples.
llvm::Value *pointerToFirst = nullptr; // appease -Wuninitialized
auto elements = type.getElementTypes();
auto arrayTy = llvm::ArrayType::get(IGF.IGM.TypeMetadataPtrTy,
elements.size());
Address buffer = IGF.createAlloca(arrayTy,IGF.IGM.getPointerAlignment(),
"tuple-elements");
IGF.Builder.CreateLifetimeStart(buffer,
IGF.IGM.getPointerSize() * elements.size());
for (auto i : indices(elements)) {
// Find the metadata pointer for this element.
llvm::Value *eltMetadata = getElementMetadata(elements[i]);
// GEP to the appropriate element and store.
Address eltPtr = IGF.Builder.CreateStructGEP(buffer, i,
IGF.IGM.getPointerSize());
IGF.Builder.CreateStore(eltMetadata, eltPtr);
// Remember the GEP to the first element.
if (i == 0) pointerToFirst = eltPtr.getAddress();
}
TupleTypeFlags flags =
TupleTypeFlags().withNumElements(elements.size());
llvm::Value *args[] = {
request.get(IGF),
llvm::ConstantInt::get(IGF.IGM.SizeTy, flags.getIntValue()),
pointerToFirst,
getTupleLabelsString(IGF.IGM, type, useLabels),
llvm::ConstantPointerNull::get(IGF.IGM.WitnessTablePtrTy) // proposed
};
auto call = IGF.Builder.CreateCall(IGF.IGM.getGetTupleMetadataFn(),
args);
call->setCallingConv(IGF.IGM.SwiftCC);
call->setDoesNotThrow();
IGF.Builder.CreateLifetimeEnd(buffer,
IGF.IGM.getPointerSize() * elements.size());
return MetadataResponse::handle(IGF, request, call);
}
}
namespace {
/// A visitor class for emitting a reference to a metatype object.
/// This implements a "raw" access, useful for implementing cache
/// functions or for implementing dependent accesses.
///
/// If the access requires runtime initialization, that initialization
/// must be dependency-ordered-before any load that carries a dependency
/// from the resulting metadata pointer.
class EmitTypeMetadataRef
: public CanTypeVisitor<EmitTypeMetadataRef, MetadataResponse,
DynamicMetadataRequest> {
private:
IRGenFunction &IGF;
public:
EmitTypeMetadataRef(IRGenFunction &IGF) : IGF(IGF) {}
MetadataResponse emitDirectMetadataRef(CanType type) {
return MetadataResponse::forComplete(IGF.IGM.getAddrOfTypeMetadata(type));
}
/// The given type should use opaque type info. We assume that
/// the runtime always provides an entry for such a type.
MetadataResponse visitBuiltinIntegerType(CanBuiltinIntegerType type,
DynamicMetadataRequest request) {
// If the size isn't a power up two, round up to the next power of two
// and use the corresponding integer type.
auto &opaqueTI = cast<FixedTypeInfo>(IGF.IGM.getTypeInfoForLowered(type));
unsigned numBits = opaqueTI.getFixedSize().getValueInBits();
if (!llvm::isPowerOf2_32(numBits)) {
numBits = llvm::NextPowerOf2(numBits);
type = CanBuiltinIntegerType(
BuiltinIntegerType::get(numBits, IGF.IGM.Context));
}
return emitDirectMetadataRef(type);
}
MetadataResponse
visitBuiltinIntegerLiteralType(CanBuiltinIntegerLiteralType type,
DynamicMetadataRequest request) {
return emitDirectMetadataRef(type);
}
MetadataResponse
visitBuiltinNativeObjectType(CanBuiltinNativeObjectType type,
DynamicMetadataRequest request) {
return emitDirectMetadataRef(type);
}
MetadataResponse
visitBuiltinBridgeObjectType(CanBuiltinBridgeObjectType type,
DynamicMetadataRequest request) {
return emitDirectMetadataRef(type);
}
MetadataResponse
visitBuiltinUnsafeValueBufferType(CanBuiltinUnsafeValueBufferType type,
DynamicMetadataRequest request) {
return emitDirectMetadataRef(type);
}
MetadataResponse
visitBuiltinRawPointerType(CanBuiltinRawPointerType type,
DynamicMetadataRequest request) {
return emitDirectMetadataRef(type);
}
MetadataResponse
visitBuiltinRawUnsafeContinuationType(CanBuiltinRawUnsafeContinuationType type,
DynamicMetadataRequest request) {
return emitDirectMetadataRef(type);
}
MetadataResponse
visitBuiltinJobType(CanBuiltinJobType type,
DynamicMetadataRequest request) {
return emitDirectMetadataRef(type);
}
MetadataResponse
visitBuiltinExecutorType(CanBuiltinExecutorType type,
DynamicMetadataRequest request) {
return emitDirectMetadataRef(type);
}
MetadataResponse
visitBuiltinFloatType(CanBuiltinFloatType type,
DynamicMetadataRequest request) {
return emitDirectMetadataRef(type);
}
MetadataResponse
visitBuiltinVectorType(CanBuiltinVectorType type,
DynamicMetadataRequest request) {
return emitDirectMetadataRef(type);
}
MetadataResponse visitNominalType(CanNominalType type,
DynamicMetadataRequest request) {
assert(!type->isExistentialType());
return emitNominalMetadataRef(IGF, type->getDecl(), type, request);
}
MetadataResponse visitBoundGenericType(CanBoundGenericType type,
DynamicMetadataRequest request) {
assert(!type->isExistentialType());
return emitNominalMetadataRef(IGF, type->getDecl(), type, request);
}
MetadataResponse visitTupleType(CanTupleType type,
DynamicMetadataRequest request) {
if (auto cached = tryGetLocal(type, request))
return cached;
auto response = emitTupleTypeMetadataRef(IGF, type, request,
/*labels*/ true,
[&](CanType eltType, DynamicMetadataRequest eltRequest) {
return IGF.emitTypeMetadataRef(eltType, eltRequest);
});
return setLocal(type, response);
}
MetadataResponse visitGenericFunctionType(CanGenericFunctionType type,
DynamicMetadataRequest request) {
IGF.unimplemented(SourceLoc(),
"metadata ref for generic function type");
return MetadataResponse::getUndef(IGF);
}
llvm::Value *getFunctionParameterRef(AnyFunctionType::CanParam ¶m) {
auto type = param.getPlainType()->getCanonicalType();
return IGF.emitAbstractTypeMetadataRef(type);
}
MetadataResponse visitFunctionType(CanFunctionType type,
DynamicMetadataRequest request) {
if (auto metatype = tryGetLocal(type, request))
return metatype;
auto result =
IGF.emitAbstractTypeMetadataRef(type->getResult()->getCanonicalType());
auto params = type.getParams();
auto numParams = params.size();
// Retrieve the ABI parameter flags from the type-level parameter
// flags.
auto getABIParameterFlags = [](ParameterTypeFlags flags) {
return ParameterFlags()
.withValueOwnership(flags.getValueOwnership())
.withVariadic(flags.isVariadic())
.withAutoClosure(flags.isAutoClosure())
.withNoDerivative(flags.isNoDerivative())
.withIsolated(flags.isIsolated());
};
bool hasParameterFlags = false;
for (auto param : params) {
if (!getABIParameterFlags(param.getParameterFlags()).isNone()) {
hasParameterFlags = true;
break;
}
}
// Map the convention to a runtime metadata value.
FunctionMetadataConvention metadataConvention;
bool isEscaping = false;
switch (type->getRepresentation()) {
case FunctionTypeRepresentation::Swift:
metadataConvention = FunctionMetadataConvention::Swift;
isEscaping = !type->isNoEscape();
break;
case FunctionTypeRepresentation::Thin:
metadataConvention = FunctionMetadataConvention::Thin;
break;
case FunctionTypeRepresentation::Block:
metadataConvention = FunctionMetadataConvention::Block;
break;
case FunctionTypeRepresentation::CFunctionPointer:
metadataConvention = FunctionMetadataConvention::CFunctionPointer;
break;
}
FunctionMetadataDifferentiabilityKind metadataDifferentiabilityKind;
switch (type->getDifferentiabilityKind()) {
case DifferentiabilityKind::NonDifferentiable:
metadataDifferentiabilityKind =
FunctionMetadataDifferentiabilityKind::NonDifferentiable;
break;
case DifferentiabilityKind::Normal:
metadataDifferentiabilityKind =
FunctionMetadataDifferentiabilityKind::Normal;
break;
case DifferentiabilityKind::Linear:
metadataDifferentiabilityKind =
FunctionMetadataDifferentiabilityKind::Linear;
break;
case DifferentiabilityKind::Forward:
metadataDifferentiabilityKind =
FunctionMetadataDifferentiabilityKind::Forward;
break;
case DifferentiabilityKind::Reverse:
metadataDifferentiabilityKind =
FunctionMetadataDifferentiabilityKind::Reverse;
break;
}
auto flags = FunctionTypeFlags()
.withNumParameters(numParams)
.withConvention(metadataConvention)
.withAsync(type->isAsync())
.withConcurrent(type->isSendable())
.withThrows(type->isThrowing())
.withParameterFlags(hasParameterFlags)
.withEscaping(isEscaping)
.withDifferentiable(type->isDifferentiable())
.withGlobalActor(!type->getGlobalActor().isNull());
auto flagsVal = llvm::ConstantInt::get(IGF.IGM.SizeTy,
flags.getIntValue());
llvm::Value *diffKindVal = nullptr;
if (type->isDifferentiable()) {
assert(metadataDifferentiabilityKind.isDifferentiable());
diffKindVal = llvm::ConstantInt::get(
IGF.IGM.SizeTy, metadataDifferentiabilityKind.getIntValue());
} else if (type->getGlobalActor()) {
diffKindVal = llvm::ConstantInt::get(
IGF.IGM.SizeTy,
FunctionMetadataDifferentiabilityKind::NonDifferentiable);
}
auto collectParameters =
[&](llvm::function_ref<void(unsigned, llvm::Value *,
ParameterFlags flags)>
processor) {
for (auto index : indices(params)) {
auto param = params[index];
auto flags = param.getParameterFlags();
auto parameterFlags = getABIParameterFlags(flags);
processor(index, getFunctionParameterRef(param), parameterFlags);
}
};
auto constructSimpleCall =
[&](llvm::SmallVectorImpl<llvm::Value *> &arguments)
-> llvm::Constant * {
arguments.push_back(flagsVal);
collectParameters([&](unsigned i, llvm::Value *typeRef,
ParameterFlags flags) {
arguments.push_back(typeRef);
if (hasParameterFlags)
arguments.push_back(
llvm::ConstantInt::get(IGF.IGM.Int32Ty, flags.getIntValue()));
});
arguments.push_back(result);
switch (params.size()) {
case 0:
return IGF.IGM.getGetFunctionMetadata0Fn();
case 1:
return IGF.IGM.getGetFunctionMetadata1Fn();
case 2:
return IGF.IGM.getGetFunctionMetadata2Fn();
case 3:
return IGF.IGM.getGetFunctionMetadata3Fn();
default:
llvm_unreachable("supports only 1/2/3 parameter functions");
}
};
switch (numParams) {
case 0:
case 1:
case 2:
case 3: {
if (!hasParameterFlags && !type->isDifferentiable() &&
!type->getGlobalActor()) {
llvm::SmallVector<llvm::Value *, 8> arguments;
auto *metadataFn = constructSimpleCall(arguments);
auto *call = IGF.Builder.CreateCall(metadataFn, arguments);
call->setDoesNotThrow();
return setLocal(CanType(type), MetadataResponse::forComplete(call));
}
// If function type has parameter flags or is differentiable or has a
// global actor, emit the most general function to retrieve them.
LLVM_FALLTHROUGH;
}
default:
assert((!params.empty() || type->isDifferentiable() ||
type->getGlobalActor()) &&
"0 parameter case should be specialized unless it is a "
"differentiable function or has a global actor");
auto *const Int32Ptr = IGF.IGM.Int32Ty->getPointerTo();
llvm::SmallVector<llvm::Value *, 8> arguments;
arguments.push_back(flagsVal);
if (diffKindVal) {
arguments.push_back(diffKindVal);
}
ConstantInitBuilder paramFlags(IGF.IGM);
auto flagsArr = paramFlags.beginArray();
Address parameters;
if (!params.empty()) {
auto arrayTy =
llvm::ArrayType::get(IGF.IGM.TypeMetadataPtrTy, numParams);
parameters = IGF.createAlloca(
arrayTy, IGF.IGM.getTypeMetadataAlignment(), "function-parameters");
IGF.Builder.CreateLifetimeStart(parameters,
IGF.IGM.getPointerSize() * numParams);
collectParameters([&](unsigned i, llvm::Value *typeRef,
ParameterFlags flags) {
auto argPtr = IGF.Builder.CreateStructGEP(parameters, i,
IGF.IGM.getPointerSize());
IGF.Builder.CreateStore(typeRef, argPtr);
if (i == 0)
arguments.push_back(argPtr.getAddress());
if (hasParameterFlags)
flagsArr.addInt32(flags.getIntValue());
});
} else {
auto parametersPtr =
llvm::ConstantPointerNull::get(
IGF.IGM.TypeMetadataPtrTy->getPointerTo());
arguments.push_back(parametersPtr);
}
if (hasParameterFlags) {
auto *flagsVar = flagsArr.finishAndCreateGlobal(
"parameter-flags", IGF.IGM.getPointerAlignment(),
/* constant */ true);
arguments.push_back(IGF.Builder.CreateBitCast(flagsVar, Int32Ptr));
} else {
flagsArr.abandon();
arguments.push_back(llvm::ConstantPointerNull::get(Int32Ptr));
}
arguments.push_back(result);
if (Type globalActor = type->getGlobalActor()) {
arguments.push_back(
IGF.emitAbstractTypeMetadataRef(globalActor->getCanonicalType()));
}
auto *getMetadataFn = type->getGlobalActor()
? (IGF.IGM.isConcurrencyAvailable()
? IGF.IGM.getGetFunctionMetadataGlobalActorFn()
: IGF.IGM.getGetFunctionMetadataGlobalActorBackDeployFn())
: type->isDifferentiable()
? IGF.IGM.getGetFunctionMetadataDifferentiableFn()
: IGF.IGM.getGetFunctionMetadataFn();
auto call = IGF.Builder.CreateCall(getMetadataFn, arguments);
call->setDoesNotThrow();
if (parameters.isValid())
IGF.Builder.CreateLifetimeEnd(parameters,
IGF.IGM.getPointerSize() * numParams);
return setLocal(type, MetadataResponse::forComplete(call));
}
}
MetadataResponse visitAnyMetatypeType(CanAnyMetatypeType type,
DynamicMetadataRequest request) {
// FIXME: We shouldn't accept a lowered metatype here, but we need to
// represent Optional<@objc_metatype T.Type> as an AST type for ABI
// reasons.
// assert(!type->hasRepresentation()
// && "should not be asking for a representation-specific metatype "
// "metadata");
if (auto metatype = tryGetLocal(type, request))
return metatype;
auto instMetadata =
IGF.emitAbstractTypeMetadataRef(type.getInstanceType());
auto fn = isa<MetatypeType>(type)
? IGF.IGM.getGetMetatypeMetadataFn()
: IGF.IGM.getGetExistentialMetatypeMetadataFn();
auto call = IGF.Builder.CreateCall(fn, instMetadata);
call->setDoesNotThrow();
return setLocal(type, MetadataResponse::forComplete(call));
}
MetadataResponse visitModuleType(CanModuleType type,
DynamicMetadataRequest request) {
IGF.unimplemented(SourceLoc(), "metadata ref for module type");
return MetadataResponse::getUndef(IGF);
}
MetadataResponse visitDynamicSelfType(CanDynamicSelfType type,
DynamicMetadataRequest request) {
return MetadataResponse::forComplete(IGF.getDynamicSelfMetadata());
}
MetadataResponse emitExistentialTypeMetadata(CanType type,
DynamicMetadataRequest request) {
if (auto metatype = tryGetLocal(type, request))
return metatype;
// Any and AnyObject have singleton metadata in the runtime.
llvm::Constant *singletonMetadata = nullptr;
if (type->isAny())
singletonMetadata = IGF.IGM.getAnyExistentialMetadata();
if (type->isAnyObject())
singletonMetadata = IGF.IGM.getAnyObjectExistentialMetadata();
if (singletonMetadata) {
llvm::Constant *indices[] = {
llvm::ConstantInt::get(IGF.IGM.Int32Ty, 0),
llvm::ConstantInt::get(IGF.IGM.Int32Ty, 1)
};
return MetadataResponse::forComplete(
llvm::ConstantExpr::getInBoundsGetElementPtr(
/*Ty=*/nullptr, singletonMetadata, indices));
}
auto layout = type.getExistentialLayout();
auto protocols = layout.getProtocols();
// Collect references to the protocol descriptors.
auto descriptorArrayTy
= llvm::ArrayType::get(IGF.IGM.ProtocolDescriptorRefTy,
protocols.size());
Address descriptorArray = IGF.createAlloca(descriptorArrayTy,
IGF.IGM.getPointerAlignment(),
"protocols");
IGF.Builder.CreateLifetimeStart(descriptorArray,
IGF.IGM.getPointerSize() * protocols.size());
descriptorArray = IGF.Builder.CreateBitCast(descriptorArray,
IGF.IGM.ProtocolDescriptorRefTy->getPointerTo());
unsigned index = 0;
for (auto *protoTy : protocols) {
auto *protoDecl = protoTy->getDecl();
llvm::Value *ref = emitProtocolDescriptorRef(IGF, protoDecl);
Address slot = IGF.Builder.CreateConstArrayGEP(descriptorArray,
index, IGF.IGM.getPointerSize());
IGF.Builder.CreateStore(ref, slot);
++index;
}
// Note: ProtocolClassConstraint::Class is 0, ::Any is 1.
auto classConstraint =
llvm::ConstantInt::get(IGF.IGM.Int1Ty,
!layout.requiresClass());
llvm::Value *superclassConstraint =
llvm::ConstantPointerNull::get(IGF.IGM.TypeMetadataPtrTy);
if (auto superclass = layout.explicitSuperclass) {
superclassConstraint = IGF.emitAbstractTypeMetadataRef(
CanType(superclass));
}
auto call = IGF.Builder.CreateCall(IGF.IGM.getGetExistentialMetadataFn(),
{classConstraint,
superclassConstraint,
IGF.IGM.getSize(Size(protocols.size())),
descriptorArray.getAddress()});
call->setDoesNotThrow();
IGF.Builder.CreateLifetimeEnd(descriptorArray,
IGF.IGM.getPointerSize() * protocols.size());
return setLocal(type, MetadataResponse::forComplete(call));
}
MetadataResponse visitProtocolType(CanProtocolType type,
DynamicMetadataRequest request) {
return emitExistentialTypeMetadata(type, request);
}
MetadataResponse
visitProtocolCompositionType(CanProtocolCompositionType type,
DynamicMetadataRequest request) {
return emitExistentialTypeMetadata(type, request);
}
MetadataResponse visitReferenceStorageType(CanReferenceStorageType type,
DynamicMetadataRequest request) {
llvm_unreachable("reference storage type should have been converted by "
"SILGen");
}
MetadataResponse visitSILFunctionType(CanSILFunctionType type,
DynamicMetadataRequest request) {
llvm_unreachable("should not be asking for metadata of a lowered SIL "
"function type--SILGen should have used the AST type");
}
MetadataResponse visitSILTokenType(CanSILTokenType type,
DynamicMetadataRequest request) {
llvm_unreachable("should not be asking for metadata of a SILToken type");
}
MetadataResponse visitArchetypeType(CanArchetypeType type,
DynamicMetadataRequest request) {
return emitArchetypeTypeMetadataRef(IGF, type, request);
}
MetadataResponse visitGenericTypeParamType(CanGenericTypeParamType type,
DynamicMetadataRequest request) {
llvm_unreachable("dependent type should have been substituted by Sema or SILGen");
}
MetadataResponse visitDependentMemberType(CanDependentMemberType type,
DynamicMetadataRequest request) {
llvm_unreachable("dependent type should have been substituted by Sema or SILGen");
}
MetadataResponse visitLValueType(CanLValueType type,
DynamicMetadataRequest request) {
llvm_unreachable("lvalue type should have been lowered by SILGen");
}
MetadataResponse visitInOutType(CanInOutType type,
DynamicMetadataRequest request) {
llvm_unreachable("inout type should have been lowered by SILGen");
}
MetadataResponse visitErrorType(CanErrorType type,
DynamicMetadataRequest request) {
llvm_unreachable("error type should not appear in IRGen");
}
// These types are artificial types used for internal purposes and
// should never appear in a metadata request.
#define INTERNAL_ONLY_TYPE(ID) \
MetadataResponse visit##ID##Type(Can##ID##Type type, \
DynamicMetadataRequest request) { \
llvm_unreachable("cannot ask for metadata of compiler-internal type"); \
}
INTERNAL_ONLY_TYPE(SILBlockStorage)
INTERNAL_ONLY_TYPE(BuiltinDefaultActorStorage)
#undef INTERNAL_ONLY_TYPE
MetadataResponse visitSILBoxType(CanSILBoxType type,
DynamicMetadataRequest request) {
// The Builtin.NativeObject metadata can stand in for boxes.
return emitDirectMetadataRef(type->getASTContext().TheNativeObjectType);
}
/// Try to find the metatype in local data.
MetadataResponse tryGetLocal(CanType type, DynamicMetadataRequest request) {
return IGF.tryGetLocalTypeMetadata(type, request);
}
/// Set the metatype in local data.
MetadataResponse setLocal(CanType type, MetadataResponse response) {
IGF.setScopedLocalTypeMetadata(type, response);
return response;
}
};
} // end anonymous namespace
/// Emit a type metadata reference without using an accessor function.
static MetadataResponse emitDirectTypeMetadataRef(IRGenFunction &IGF,
CanType type,
DynamicMetadataRequest request) {
return EmitTypeMetadataRef(IGF).visit(type, request);
}
static bool isLoadFrom(llvm::Value *value, Address address) {
if (auto load = dyn_cast<llvm::LoadInst>(value)) {
return load->getOperand(0) == address.getAddress();
}
return false;
}
/// Emit the body of a cache accessor.
///
/// If cacheVariable is null, we perform the direct access every time.
/// This is used for metadata accessors that come about due to resilience,
/// where the direct access is completely trivial.
void irgen::emitCacheAccessFunction(IRGenModule &IGM,
llvm::Function *accessor,
llvm::Constant *cacheVariable,
CacheStrategy cacheStrategy,
CacheEmitter getValue,
bool isReadNone) {
assert((cacheStrategy == CacheStrategy::None) == (cacheVariable == nullptr));
accessor->setDoesNotThrow();
// Don't inline cache functions, since doing so has little impact on
// overall performance.
accessor->addAttribute(llvm::AttributeList::FunctionIndex,
llvm::Attribute::NoInline);
// Accessor functions don't need frame pointers.
IGM.setHasNoFramePointer(accessor);
// This function is logically 'readnone': the caller does not need
// to reason about any side effects or stores it might perform.
if (isReadNone)
accessor->setDoesNotAccessMemory();
IRGenFunction IGF(IGM, accessor);
if (IGM.DebugInfo)
IGM.DebugInfo->emitArtificialFunction(IGF, accessor);
auto parameters = IGF.collectParameters();
bool returnsResponse =
(accessor->getReturnType() == IGM.TypeMetadataResponseTy);
switch (cacheStrategy) {
// If there's no cache variable, just perform the direct access.
case CacheStrategy::None: {
auto response = getValue(IGF, parameters);
llvm::Value *ret;
if (returnsResponse) {
response.ensureDynamicState(IGF);
ret = response.combine(IGF);
} else {
assert(response.isStaticallyKnownComplete());
ret = response.getMetadata();
}
IGF.Builder.CreateRet(ret);
return;
}
// For in-place initialization, drill to the first element of the cache.
case CacheStrategy::SingletonInitialization:
cacheVariable =
llvm::ConstantExpr::getBitCast(cacheVariable,
IGM.TypeMetadataPtrTy->getPointerTo());
break;
case CacheStrategy::Lazy:
break;
}
llvm::Constant *null =
llvm::ConstantPointerNull::get(
cast<llvm::PointerType>(
cacheVariable->getType()->getPointerElementType()));
Address cache(cacheVariable, IGM.getPointerAlignment());
// Okay, first thing, check the cache variable.
//
// Conceptually, this needs to establish memory ordering with the
// store we do later in the function: if the metadata value is
// non-null, we must be able to see any stores performed by the
// initialization of the metadata. However, any attempt to read
// from the metadata will be address-dependent on the loaded
// metadata pointer, which is sufficient to provide adequate
// memory ordering guarantees on all the platforms we care about:
// ARM has special rules about address dependencies, and x86's
// memory ordering is strong enough to guarantee the visibility
// even without the address dependency.
//
// And we do not need to worry about the compiler because the
// address dependency naturally forces an order to the memory
// accesses.
//
// Therefore, we can perform a completely naked load here.
// FIXME: Technically should be "consume", but that introduces barriers in the
// current LLVM ARM backend.
auto load = IGF.Builder.CreateLoad(cache);
// Make this barrier explicit when building for TSan to avoid false positives.
if (IGM.IRGen.Opts.Sanitizers & SanitizerKind::Thread)
load->setOrdering(llvm::AtomicOrdering::Acquire);
// Compare the load result against null.
auto isNullBB = IGF.createBasicBlock("cacheIsNull");
auto contBB = IGF.createBasicBlock("cont");
llvm::Value *comparison = IGF.Builder.CreateICmpEQ(load, null);
IGF.Builder.CreateCondBr(comparison, isNullBB, contBB);
auto loadBB = IGF.Builder.GetInsertBlock();
// If the load yielded null, emit the type metadata.
IGF.Builder.emitBlock(isNullBB);
MetadataResponse response = getValue(IGF, parameters);
// Ensure that we have a dynamically-correct state value.
llvm::Constant *completedState = nullptr;
if (returnsResponse) {
completedState = MetadataResponse::getCompletedState(IGM);
response.ensureDynamicState(IGF);
}
auto directResult = response.getMetadata();
// Emit a branch around the caching code if we're working with responses
// and the fetched result is not complete. We can avoid doing this if
// the response is statically known to be complete, and we don't need to
// do it if this is an in-place initiazation cache because the store
// is done within the runtime.
llvm::BasicBlock *completionCheckBB = nullptr;
llvm::Value *directState = nullptr;
if (cacheStrategy == CacheStrategy::SingletonInitialization) {
directState = response.getDynamicState();
completionCheckBB = IGF.Builder.GetInsertBlock();
} else {
if (returnsResponse &&
!response.isStaticallyKnownComplete()) {
completionCheckBB = IGF.Builder.GetInsertBlock();
directState = response.getDynamicState();
auto isCompleteBB = IGF.createBasicBlock("is_complete");
auto isComplete =
IGF.Builder.CreateICmpEQ(directState, completedState);
IGF.Builder.CreateCondBr(isComplete, isCompleteBB, contBB);
IGF.Builder.emitBlock(isCompleteBB);
}
// Store it back to the cache variable. This needs to be a store-release
// because it needs to propagate memory visibility to the other threads
// that can access the cache: the initializing stores might be visible
// to this thread, but they aren't transitively guaranteed to be visible
// to other threads unless this is a store-release.
//
// However, we can skip this if the value was actually loaded from the
// cache. This is a simple, if hacky, peephole that's useful for the
// code in emitOnceTypeMetadataAccessFunctionBody.
if (!isLoadFrom(directResult, cache)) {
IGF.Builder.CreateStore(directResult, cache)
->setAtomic(llvm::AtomicOrdering::Release);
}
}
IGF.Builder.CreateBr(contBB);
auto storeBB = IGF.Builder.GetInsertBlock();
// Emit the continuation block.
IGF.Builder.emitBlock(contBB);
// Add a phi for the metadata value.
auto phi = IGF.Builder.CreatePHI(null->getType(), 3);
phi->addIncoming(load, loadBB);
phi->addIncoming(directResult, storeBB);
// Add a phi for the metadata state if we're returning a response.
llvm::Value *stateToReturn = nullptr;
if (directState) {
if (storeBB != completionCheckBB)
phi->addIncoming(directResult, completionCheckBB);
auto completionStatePHI = IGF.Builder.CreatePHI(IGM.SizeTy, 3);
completionStatePHI->addIncoming(completedState, loadBB);
completionStatePHI->addIncoming(directState, completionCheckBB);
if (storeBB != completionCheckBB)
completionStatePHI->addIncoming(completedState, storeBB);
stateToReturn = completionStatePHI;
} else if (returnsResponse) {
stateToReturn = completedState;
}
// Build the return value.
llvm::Value *ret;
if (returnsResponse) {
ret = MetadataResponse(phi, stateToReturn, MetadataState::Abstract)
.combine(IGF);
} else {
ret = phi;
}
IGF.Builder.CreateRet(ret);
}
MetadataResponse
IRGenFunction::emitGenericTypeMetadataAccessFunctionCall(
llvm::Function *accessFunction,
ArrayRef<llvm::Value *> args,
DynamicMetadataRequest request) {
SmallVector<llvm::Value *, 8> callArgs;
// Add the metadata request argument.
callArgs.push_back(request.get(*this));
Address argsBuffer;
bool allocatedArgsBuffer = false;
if (args.size() > NumDirectGenericTypeMetadataAccessFunctionArgs) {
// Allocate an array to pass the arguments.
auto argsBufferTy = llvm::ArrayType::get(IGM.Int8PtrTy, args.size());
argsBuffer = createAlloca(argsBufferTy, IGM.getPointerAlignment());
// Mark the beginning of the array lifetime.
Builder.CreateLifetimeStart(argsBuffer,
IGM.getPointerSize() * args.size());
allocatedArgsBuffer = true;
// Fill in the buffer.
for (unsigned i : indices(args)) {
Address elt = Builder.CreateStructGEP(argsBuffer, i,
IGM.getPointerSize() * i);
auto *arg =
Builder.CreateBitCast(args[i], elt.getType()->getPointerElementType());
Builder.CreateStore(arg, elt);
}
// Add the buffer to the call arguments.
callArgs.push_back(
Builder.CreateBitCast(argsBuffer.getAddress(), IGM.Int8PtrPtrTy));
} else {
callArgs.append(args.begin(), args.end());
}
auto call = Builder.CreateCall(accessFunction, callArgs);
call->setDoesNotThrow();
call->setCallingConv(IGM.SwiftCC);
call->addAttribute(llvm::AttributeList::FunctionIndex,
allocatedArgsBuffer
? llvm::Attribute::InaccessibleMemOrArgMemOnly
: llvm::Attribute::ReadNone);
// If we allocated a buffer for the arguments, end its lifetime.
if (allocatedArgsBuffer)
Builder.CreateLifetimeEnd(argsBuffer, IGM.getPointerSize() * args.size());
return MetadataResponse::handle(*this, request, call);
}
MetadataResponse irgen::emitGenericTypeMetadataAccessFunction(
IRGenFunction &IGF, Explosion ¶ms, NominalTypeDecl *nominal,
GenericArguments &genericArgs) {
auto &IGM = IGF.IGM;
llvm::Value *descriptor =
IGM.getAddrOfTypeContextDescriptor(nominal, RequireMetadata);
// Sign the descriptor.
auto schema = IGF.IGM.getOptions().PointerAuth.TypeDescriptorsAsArguments;
if (schema) {
auto authInfo = PointerAuthInfo::emit(
IGF, schema, nullptr,
PointerAuthEntity::Special::TypeDescriptorAsArgument);
descriptor = emitPointerAuthSign(IGF, descriptor, authInfo);
}
auto request = params.claimNext();
bool checkPrespecialized =
IGM.IRGen.metadataPrespecializationsForType(nominal).size() > 0;
auto numArguments = genericArgs.Types.size();
llvm::Value *result;
if (numArguments > NumDirectGenericTypeMetadataAccessFunctionArgs) {
// swift_getGenericMetadata's calling convention is already cleverly
// laid out to minimize the assembly language size of the thunk.
// The caller passed us an appropriate buffer with the arguments.
auto argsBuffer = Address(params.claimNext(), IGM.getPointerAlignment());
llvm::Value *arguments =
IGF.Builder.CreateBitCast(argsBuffer.getAddress(), IGM.Int8PtrTy);
// Make the call.
llvm::CallInst *call;
if (checkPrespecialized) {
call = IGF.Builder.CreateCall(
IGM.getGetCanonicalPrespecializedGenericMetadataFn(),
{request, arguments, descriptor,
IGM.getAddrOfCanonicalPrespecializedGenericTypeCachingOnceToken(
nominal)});
} else {
call = IGF.Builder.CreateCall(IGM.getGetGenericMetadataFn(),
{request, arguments, descriptor});
}
call->setDoesNotThrow();
call->setCallingConv(IGM.SwiftCC);
call->addAttribute(llvm::AttributeList::FunctionIndex,
llvm::Attribute::ReadOnly);
result = call;
} else {
static_assert(NumDirectGenericTypeMetadataAccessFunctionArgs == 3,
"adjust this if you change "
"NumDirectGenericTypeMetadataAccessFunctionArgs");
// Factor out the buffer shuffling for metadata accessors that take their
// arguments directly, so that the accessor function itself only needs to
// materialize the nominal type descriptor and call this thunk.
auto generateThunkFn = [&IGM,
checkPrespecialized](IRGenFunction &subIGF) {
subIGF.CurFn->setDoesNotAccessMemory();
subIGF.CurFn->setCallingConv(IGM.SwiftCC);
IGM.setHasNoFramePointer(subIGF.CurFn);
auto params = subIGF.collectParameters();
auto request = params.claimNext();
auto arg0 = params.claimNext();
auto arg1 = params.claimNext();
auto arg2 = params.claimNext();
auto descriptor = params.claimNext();
llvm::Value *token = nullptr;
if (checkPrespecialized) {
token = params.claimNext();
}
// Allocate a buffer with enough storage for the arguments.
auto argsBufferTy =
llvm::ArrayType::get(IGM.Int8PtrTy,
NumDirectGenericTypeMetadataAccessFunctionArgs);
auto argsBuffer = subIGF.createAlloca(argsBufferTy,
IGM.getPointerAlignment(),
"generic.arguments");
subIGF.Builder.CreateLifetimeStart(argsBuffer,
IGM.getPointerSize() * NumDirectGenericTypeMetadataAccessFunctionArgs);
auto arg0Buf = subIGF.Builder.CreateConstInBoundsGEP2_32(argsBufferTy,
argsBuffer.getAddress(), 0, 0);
subIGF.Builder.CreateStore(arg0, arg0Buf, IGM.getPointerAlignment());
auto arg1Buf = subIGF.Builder.CreateConstInBoundsGEP2_32(argsBufferTy,
argsBuffer.getAddress(), 0, 1);
subIGF.Builder.CreateStore(arg1, arg1Buf, IGM.getPointerAlignment());
auto arg2Buf = subIGF.Builder.CreateConstInBoundsGEP2_32(argsBufferTy,
argsBuffer.getAddress(), 0, 2);
subIGF.Builder.CreateStore(arg2, arg2Buf, IGM.getPointerAlignment());
// Make the call.
auto argsAddr = subIGF.Builder.CreateBitCast(argsBuffer.getAddress(),
IGM.Int8PtrTy);
llvm::Value *result;
if (checkPrespecialized) {
result = subIGF.Builder.CreateCall(
IGM.getGetCanonicalPrespecializedGenericMetadataFn(),
{request, argsAddr, descriptor, token});
} else {
result = subIGF.Builder.CreateCall(IGM.getGetGenericMetadataFn(),
{request, argsAddr, descriptor});
}
subIGF.Builder.CreateRet(result);
};
llvm::Constant *thunkFn;
if (checkPrespecialized) {
thunkFn = IGM.getOrCreateHelperFunction(
"__swift_instantiateCanonicalPrespecializedGenericMetadata",
IGM.TypeMetadataResponseTy,
{
IGM.SizeTy, // request
IGM.Int8PtrTy, // arg 0
IGM.Int8PtrTy, // arg 1
IGM.Int8PtrTy, // arg 2
IGM.TypeContextDescriptorPtrTy, // type context descriptor
IGM.OnceTy->getPointerTo() // token pointer
},
generateThunkFn,
/*noinline*/ true);
} else {
thunkFn = IGM.getOrCreateHelperFunction(
"__swift_instantiateGenericMetadata", IGM.TypeMetadataResponseTy,
{
IGM.SizeTy, // request
IGM.Int8PtrTy, // arg 0
IGM.Int8PtrTy, // arg 1
IGM.Int8PtrTy, // arg 2
IGM.TypeContextDescriptorPtrTy // type context descriptor
},
generateThunkFn,
/*noinline*/ true);
}
// Call out to the helper.
auto arg0 = numArguments >= 1
? IGF.Builder.CreateBitCast(params.claimNext(), IGM.Int8PtrTy)
: llvm::UndefValue::get(IGM.Int8PtrTy);
auto arg1 = numArguments >= 2
? IGF.Builder.CreateBitCast(params.claimNext(), IGM.Int8PtrTy)
: llvm::UndefValue::get(IGM.Int8PtrTy);
auto arg2 = numArguments >= 3
? IGF.Builder.CreateBitCast(params.claimNext(), IGM.Int8PtrTy)
: llvm::UndefValue::get(IGM.Int8PtrTy);
llvm::CallInst *call;
if (checkPrespecialized) {
auto *token =
IGM.getAddrOfCanonicalPrespecializedGenericTypeCachingOnceToken(
nominal);
call = IGF.Builder.CreateCall(
thunkFn, {request, arg0, arg1, arg2, descriptor, token});
} else {
call = IGF.Builder.CreateCall(thunkFn,
{request, arg0, arg1, arg2, descriptor});
}
call->setDoesNotAccessMemory();
call->setDoesNotThrow();
call->setCallingConv(IGM.SwiftCC);
result = call;
}
return MetadataResponse::handle(IGF, DynamicMetadataRequest(request), result);
}
static void
emitIdempotentCanonicalSpecializedClassMetadataInitializationComponent(
IRGenFunction &IGF, CanType theType,
llvm::SmallSet<CanType, 16> &initializedTypes) {
if (initializedTypes.count(theType) > 0) {
return;
}
initializedTypes.insert(theType);
auto *classDecl = theType->getClassOrBoundGenericClass();
assert(classDecl);
if (classDecl->isGenericContext()) {
llvm::Function *accessor =
IGF.IGM.getAddrOfCanonicalSpecializedGenericTypeMetadataAccessFunction(
theType, NotForDefinition);
auto request = DynamicMetadataRequest(MetadataState::Complete);
IGF.emitGenericTypeMetadataAccessFunctionCall(accessor, {}, request);
} else {
llvm::Function *accessor =
IGF.IGM.getAddrOfTypeMetadataAccessFunction(theType, NotForDefinition);
auto request = DynamicMetadataRequest(MetadataState::Complete);
IGF.emitGenericTypeMetadataAccessFunctionCall(accessor, {}, request);
}
}
MetadataResponse
irgen::emitCanonicalSpecializedGenericTypeMetadataAccessFunction(
IRGenFunction &IGF, Explosion ¶ms, CanType theType) {
assert(isa<ClassDecl>(theType->getAnyNominal()));
auto request = params.claimNext();
// The metadata request that is passed to a canonical specialized generic
// metadata accessor is ignored because complete metadata is always returned.
(void)request;
llvm::SmallSet<CanType, 16> initializedTypes;
auto *nominal = theType->getAnyNominal();
assert(nominal);
assert(isa<ClassDecl>(nominal));
assert(nominal->isGenericContext());
assert(!theType->hasUnboundGenericType());
auto requirements = GenericTypeRequirements(IGF.IGM, nominal);
auto substitutions =
theType->getContextSubstitutionMap(IGF.IGM.getSwiftModule(), nominal);
for (auto requirement : requirements.getRequirements()) {
if (requirement.Protocol) {
continue;
}
auto parameter = requirement.TypeParameter;
auto noncanonicalArgument = parameter.subst(substitutions);
auto argument = noncanonicalArgument->getCanonicalType();
if (auto *classDecl = argument->getClassOrBoundGenericClass()) {
emitIdempotentCanonicalSpecializedClassMetadataInitializationComponent(
IGF, argument, initializedTypes);
}
}
Type superclassType = theType->getSuperclass(/*useArchetypes=*/false);
if (superclassType) {
emitIdempotentCanonicalSpecializedClassMetadataInitializationComponent(
IGF, superclassType->getCanonicalType(), initializedTypes);
}
auto *uninitializedMetadata = IGF.IGM.getAddrOfTypeMetadata(theType);
initializedTypes.insert(theType);
auto *initializedMetadata =
emitIdempotentClassMetadataInitialization(IGF, uninitializedMetadata);
return MetadataResponse::forComplete(initializedMetadata);
}
/// Emit the body of a metadata accessor function for the given type.
///
/// This function is appropriate for ordinary situations where the
/// construction of the metadata value just involves calling idempotent
/// metadata-construction functions. It is not used for the in-place
/// initialization of non-generic nominal type metadata.
static MetadataResponse
emitDirectTypeMetadataAccessFunctionBody(IRGenFunction &IGF,
DynamicMetadataRequest request,
CanType type) {
assert(!type->hasArchetype() &&
"cannot emit metadata accessor for context-dependent type");
// We only take this path for non-generic nominal types.
auto typeDecl = type->getAnyNominal();
if (!typeDecl)
return emitDirectTypeMetadataRef(IGF, type, request);
if (typeDecl->isGenericContext() &&
!(isa<ClassDecl>(typeDecl) &&
isa<ClangModuleUnit>(typeDecl->getModuleScopeContext()))) {
// This is a metadata accessor for a fully substituted generic type.
return emitDirectTypeMetadataRef(IGF, type, request);
}
// We should never be emitting a metadata accessor for resilient nominal
// types outside of their defining module. We'd only do that anyway for
// types that don't guarantee the existence of a non-unique access
// function, and that should never be true of a resilient type with
// external availability.
//
// (The type might still not have a statically-known layout. It just
// can't be resilient at the top level: we have to know its immediate
// members, or we can't even begin to approach the problem of emitting
// metadata for it.)
assert(!IGF.IGM.isResilient(typeDecl, ResilienceExpansion::Maximal));
// We should never be emitting a metadata accessor for foreign type
// metadata using this function.
assert(!requiresForeignTypeMetadata(typeDecl));
if (auto classDecl = dyn_cast<ClassDecl>(typeDecl)) {
// For known-Swift metadata, we can perform a direct reference with
// potentially idempotent initialization.
if (hasKnownSwiftMetadata(IGF.IGM, classDecl))
return emitDirectTypeMetadataRef(IGF, type, request);
// Classes that might not have Swift metadata use a different
// access pattern.
return MetadataResponse::forComplete(emitObjCMetadataRef(IGF, classDecl));
}
// We should not be doing more serious work along this path.
assert(isCanonicalCompleteTypeMetadataStaticallyAddressable(IGF.IGM, type));
// Okay, everything else is built from a Swift metadata object.
llvm::Constant *metadata = IGF.IGM.getAddrOfTypeMetadata(type);
return MetadataResponse::forComplete(metadata);
}
static llvm::Function *getAccessFunctionPrototype(IRGenModule &IGM,
CanType type,
ForDefinition_t forDefinition) {
assert(!type->hasArchetype());
// Type should be bound unless it's type erased.
assert(type.isTypeErasedGenericClassType()
? !isa<BoundGenericType>(type)
: !isa<UnboundGenericType>(type));
return IGM.getAddrOfTypeMetadataAccessFunction(type, forDefinition);
}
llvm::Function *
irgen::getOtherwiseDefinedTypeMetadataAccessFunction(IRGenModule &IGM,
CanType type) {
return getAccessFunctionPrototype(IGM, type, NotForDefinition);
}
/// Get or create an accessor function to the given non-dependent type.
llvm::Function *
irgen::createTypeMetadataAccessFunction(IRGenModule &IGM, CanType type,
CacheStrategy cacheStrategy,
MetadataAccessGenerator generator,
bool allowExistingDefinition) {
// Get the prototype.
auto accessor = getAccessFunctionPrototype(IGM, type, ForDefinition);
// If we're not supposed to define the accessor, or if we already
// have defined it, just return the pointer.
if (!accessor->empty()) {
assert(allowExistingDefinition &&
"repeat definition of access function!");
return accessor;
}
// Okay, define the accessor.
llvm::Constant *cacheVariable = nullptr;
// If our preferred access method is to go via an accessor, it means
// there is some non-trivial computation that needs to be cached.
if (!shouldCacheTypeMetadataAccess(IGM, type)) {
cacheStrategy = CacheStrategy::None;
} else {
switch (cacheStrategy) {
// Nothing to do.
case CacheStrategy::None:
break;
// For lazy initialization, the cache variable is just a pointer.
case CacheStrategy::Lazy:
cacheVariable = IGM.getAddrOfTypeMetadataLazyCacheVariable(type);
break;
// For in-place initialization, drill down to the first element.
case CacheStrategy::SingletonInitialization:
cacheVariable = IGM.getAddrOfTypeMetadataSingletonInitializationCache(
type->getAnyNominal(), ForDefinition);
break;
}
if (IGM.getOptions().optimizeForSize())
accessor->addFnAttr(llvm::Attribute::NoInline);
}
emitCacheAccessFunction(IGM, accessor, cacheVariable, cacheStrategy,
[&](IRGenFunction &IGF, Explosion ¶ms) {
auto request = DynamicMetadataRequest(params.claimNext());
return generator(IGF, request, cacheVariable);
});
return accessor;
}
/// Emit a standard accessor function to the given non-dependent type.
llvm::Function *
irgen::createDirectTypeMetadataAccessFunction(IRGenModule &IGM, CanType type,
bool allowExistingDefinition) {
return createTypeMetadataAccessFunction(IGM, type, CacheStrategy::Lazy,
[&](IRGenFunction &IGF,
DynamicMetadataRequest request,
llvm::Constant *cacheVariable) {
// We should not be called with ForDefinition for nominal types
// that require in-place initialization.
return emitDirectTypeMetadataAccessFunctionBody(IGF, request, type);
}, allowExistingDefinition);
}
/// Get or create an accessor function to the given generic type.
llvm::Function *
irgen::getGenericTypeMetadataAccessFunction(IRGenModule &IGM,
NominalTypeDecl *nominal,
ForDefinition_t shouldDefine) {
assert(nominal->isGenericContext());
assert(!nominal->isTypeErasedGenericClass());
GenericArguments genericArgs;
genericArgs.collectTypes(IGM, nominal);
llvm::Function *accessor =
IGM.getAddrOfGenericTypeMetadataAccessFunction(
nominal, genericArgs.Types, shouldDefine);
// If we're not supposed to define the accessor, or if we already
// have defined it, just return the pointer.
if (!shouldDefine || !accessor->empty())
return accessor;
IGM.IRGen.noteUseOfMetadataAccessor(nominal);
return accessor;
}
static bool shouldAccessByMangledName(IRGenModule &IGM, CanType type) {
// Never access by mangled name if we've been asked not to.
if (IGM.getOptions().DisableConcreteTypeMetadataMangledNameAccessors)
return false;
// Do not access by mangled name if the runtime won't understand it.
if (mangledNameIsUnknownToDeployTarget(IGM, type))
return false;
// A nongeneric nominal type with nontrivial metadata has an accessor
// already we can just call.
if (auto nom = dyn_cast<NominalType>(type)) {
if (!isa<ProtocolDecl>(nom->getDecl())
&& (!nom->getDecl()->isGenericContext()
|| nom->getDecl()->getGenericSignature()->areAllParamsConcrete())) {
return false;
}
}
return true;
// The visitor below can be used to fine-tune a heuristic to decide whether
// demangling might be better for code size than open-coding an access. In
// my experiments on the Swift standard library and Apple SDK overlays,
// always demangling seemed to have the biggest code size benefit.
#if false
// Guess the number of calls and addresses we need to materialize a
// metadata record in code.
struct OpenCodedMetadataAccessWeightVisitor
: CanTypeVisitor<OpenCodedMetadataAccessWeightVisitor>
{
IRGenModule &IGM;
unsigned NumCalls = 0, NumAddresses = 0;
OpenCodedMetadataAccessWeightVisitor(IRGenModule &IGM)
: IGM(IGM) {}
void visitBoundGenericType(CanBoundGenericType bgt) {
// Need to materialize all the arguments, then call the metadata
// accessor.
//
// TODO: Also need to count the parent type's generic arguments.
for (auto arg : bgt->getGenericArgs()) {
visit(arg);
}
NumCalls += 1;
}
void visitNominalType(CanNominalType nom) {
// Some nominal types have trivially-referenceable metadata symbols,
// others may require accessors to trigger instantiation.
//
// TODO: Also need to count the parent type's generic arguments.
if (!shouldCacheTypeMetadataAccess(IGM, nom)) {
NumAddresses += 1;
} else {
NumCalls += 1;
}
}
void visitTupleType(CanTupleType tup) {
// The empty tuple has trivial metadata.
if (tup->getNumElements() == 0) {
NumAddresses += 1;
return;
}
// Need to materialize the element types, then call the getTupleMetadata
// accessor.
for (auto elt : tup.getElementTypes()) {
visit(elt);
}
NumCalls += 1;
}
void visitAnyFunctionType(CanAnyFunctionType fun) {
// Need to materialize the arguments and return, then call the
// getFunctionMetadata accessor.
for (auto arg : fun.getParams()) {
visit(arg.getPlainType());
}
visit(fun.getResult());
NumCalls += 1;
}
void visitMetatypeType(CanMetatypeType meta) {
// Need to materialize the instance type, then call the
// getMetatypeMetadata accessor.
visit(meta.getInstanceType());
NumCalls += 1;
}
void visitProtocolType(CanProtocolType proto) {
// Need to reference the protocol descriptor, then call the
// getExistentialTypeMetadata accessor.
NumAddresses += 1;
NumCalls += 1;
}
void visitBuiltinType(CanBuiltinType b) {
// Builtins always have trivial metadata.
NumAddresses += 1;
}
void visitProtocolCompositionType(CanProtocolCompositionType comp) {
unsigned numMembers = comp->getMembers().size();
// The empty compositions Any and AnyObject are trivial.
if (numMembers == 0) {
NumAddresses += 1;
return;
}
// Need to materialize the base class, if any.
if (comp->getMembers().front()->getClassOrBoundGenericClass()) {
visit(CanType(comp->getMembers().front()));
numMembers -= 1;
}
// Need to reference the protocol descriptors for each protocol.
NumAddresses += numMembers;
// Finally, call the getExistentialTypeMetadata accessor.
NumCalls += 1;
}
void visitExistentialMetatypeType(CanExistentialMetatypeType meta) {
// The number of accesses turns out the same as the instance type,
// but instead of getExistentialTypeMetadata, we call
// getExistentialMetatypeMetadata
visit(meta.getInstanceType());
}
// Shouldn't emit metadata for other kinds of types.
void visitType(CanType t) {
llvm_unreachable("unhandled type?!");
}
};
OpenCodedMetadataAccessWeightVisitor visitor(IGM);
visitor.visit(type);
// If we need more than one accessor call, or the access requires too many
// arguments, the mangled name accessor is probably more compact.
return visitor.NumCalls > 1 || visitor.NumAddresses > 1;
#endif
}
static bool canIssueIncompleteMetadataRequests(IRGenModule &IGM) {
// We can only answer blocking complete metadata requests with the <=5.1
// runtime ABI entry points.
auto &context = IGM.getSwiftModule()->getASTContext();
auto deploymentAvailability =
AvailabilityContext::forDeploymentTarget(context);
return deploymentAvailability.isContainedIn(
context.getTypesInAbstractMetadataStateAvailability());
}
/// Emit a call to a type metadata accessor using a mangled name.
static MetadataResponse
emitMetadataAccessByMangledName(IRGenFunction &IGF, CanType type,
DynamicMetadataRequest request) {
auto &IGM = IGF.IGM;
// We can only answer blocking complete metadata requests with the <=5.1
// runtime ABI entry points.
assert((request.isStaticallyBlockingComplete() ||
(request.isStaticallyAbstract() &&
canIssueIncompleteMetadataRequests(IGM))) &&
"can only form complete metadata by mangled name");
llvm::Constant *mangledString;
unsigned mangledStringSize;
std::tie(mangledString, mangledStringSize) =
IGM.getTypeRef(type, CanGenericSignature(), MangledTypeRefRole::Metadata);
assert(mangledStringSize < 0x80000000u
&& "2GB of mangled name ought to be enough for anyone");
// Get or create the cache variable if necessary.
auto cache = IGM.getAddrOfTypeMetadataDemanglingCacheVariable(type,
ConstantInit());
if (cast<llvm::GlobalVariable>(cache->stripPointerCasts())->isDeclaration()) {
ConstantInitBuilder builder(IGM);
auto structBuilder = builder.beginStruct();
// A "negative" 64-bit value in the cache indicates the uninitialized state.
// Which word has that bit in the {i32, i32} layout depends on endianness.
if (IGM.getModule()->getDataLayout().isBigEndian()) {
structBuilder.addInt32(-mangledStringSize);
structBuilder.addRelativeAddress(mangledString);
} else {
structBuilder.addRelativeAddress(mangledString);
structBuilder.addInt32(-mangledStringSize);
}
auto init = structBuilder.finishAndCreateFuture();
cache = IGM.getAddrOfTypeMetadataDemanglingCacheVariable(type, init);
}
// Get or create a shared helper function to do the instantiation.
auto instantiationFnName =
request.isStaticallyAbstract()
? "__swift_instantiateConcreteTypeFromMangledNameAbstract"
: "__swift_instantiateConcreteTypeFromMangledName";
auto generateInstantiationFn = [&IGM, request](IRGenFunction &subIGF) {
subIGF.CurFn->setDoesNotAccessMemory();
IGM.setHasNoFramePointer(subIGF.CurFn);
auto params = subIGF.collectParameters();
auto cache = params.claimNext();
// Load the existing cache value.
// Conceptually, this needs to establish memory ordering with the
// store we do later in the function: if the metadata value is
// non-null, we must be able to see any stores performed by the
// initialization of the metadata. However, any attempt to read
// from the metadata will be address-dependent on the loaded
// metadata pointer, which is sufficient to provide adequate
// memory ordering guarantees on all the platforms we care about:
// ARM has special rules about address dependencies, and x86's
// memory ordering is strong enough to guarantee the visibility
// even without the address dependency.
//
// And we do not need to worry about the compiler because the
// address dependency naturally forces an order to the memory
// accesses.
//
// Therefore, we can perform a completely naked load here.
// FIXME: Technically should be "consume", but that introduces barriers
// in the current LLVM ARM backend.
auto cacheWordAddr = subIGF.Builder.CreateBitCast(cache,
IGM.Int64Ty->getPointerTo());
auto load = subIGF.Builder.CreateLoad(cacheWordAddr, Alignment(8));
// Make this barrier explicit when building for TSan to avoid false positives.
if (IGM.IRGen.Opts.Sanitizers & SanitizerKind::Thread)
load->setOrdering(llvm::AtomicOrdering::Acquire);
else
load->setOrdering(llvm::AtomicOrdering::Monotonic);
// Compare the load result to see if it's negative.
auto isUnfilledBB = subIGF.createBasicBlock("");
auto contBB = subIGF.createBasicBlock("");
llvm::Value *comparison = subIGF.Builder.CreateICmpSLT(load,
llvm::ConstantInt::get(IGM.Int64Ty, 0));
comparison = subIGF.Builder.CreateExpect(comparison,
llvm::ConstantInt::get(IGM.Int1Ty, 0));
subIGF.Builder.CreateCondBr(comparison, isUnfilledBB, contBB);
auto loadBB = subIGF.Builder.GetInsertBlock();
// If the load is negative, emit the call to instantiate the type
// metadata.
subIGF.Builder.SetInsertPoint(&subIGF.CurFn->back());
subIGF.Builder.emitBlock(isUnfilledBB);
// Break up the loaded value into size and relative address to the
// string.
auto size = subIGF.Builder.CreateAShr(load, 32);
size = subIGF.Builder.CreateTruncOrBitCast(size, IGM.SizeTy);
size = subIGF.Builder.CreateNeg(size);
auto stringAddrOffset = subIGF.Builder.CreateTrunc(load,
IGM.Int32Ty);
stringAddrOffset = subIGF.Builder.CreateSExtOrBitCast(stringAddrOffset,
IGM.SizeTy);
auto stringAddrBase = subIGF.Builder.CreatePtrToInt(cache, IGM.SizeTy);
if (IGM.getModule()->getDataLayout().isBigEndian()) {
stringAddrBase = subIGF.Builder.CreateAdd(stringAddrBase,
llvm::ConstantInt::get(IGM.SizeTy, 4));
}
auto stringAddr = subIGF.Builder.CreateAdd(stringAddrBase,
stringAddrOffset);
stringAddr = subIGF.Builder.CreateIntToPtr(stringAddr, IGM.Int8PtrTy);
llvm::CallInst *call;
if (request.isStaticallyAbstract()) {
call = subIGF.Builder.CreateCall(
IGM.getGetTypeByMangledNameInContextInMetadataStateFn(),
{llvm::ConstantInt::get(IGM.SizeTy, (size_t)MetadataState::Abstract),
stringAddr, size,
// TODO: Use mangled name lookup in generic
// contexts?
llvm::ConstantPointerNull::get(IGM.TypeContextDescriptorPtrTy),
llvm::ConstantPointerNull::get(IGM.Int8PtrPtrTy)});
} else {
call = subIGF.Builder.CreateCall(
IGM.getGetTypeByMangledNameInContextFn(),
{stringAddr, size,
// TODO: Use mangled name lookup in generic
// contexts?
llvm::ConstantPointerNull::get(IGM.TypeContextDescriptorPtrTy),
llvm::ConstantPointerNull::get(IGM.Int8PtrPtrTy)});
}
call->setDoesNotThrow();
call->setDoesNotAccessMemory();
call->setCallingConv(IGM.SwiftCC);
// Store the result back to the cache. Metadata instantatiation should
// already have emitted the necessary barriers to publish the instantiated
// metadata to other threads, so we only need to expose the pointer.
// Worst case, another thread might race with us and reinstantiate the
// exact same metadata pointer.
auto resultWord = subIGF.Builder.CreatePtrToInt(call, IGM.SizeTy);
resultWord = subIGF.Builder.CreateZExtOrBitCast(resultWord, IGM.Int64Ty);
auto store = subIGF.Builder.CreateStore(resultWord, cacheWordAddr,
Alignment(8));
store->setOrdering(llvm::AtomicOrdering::Monotonic);
subIGF.Builder.CreateBr(contBB);
subIGF.Builder.SetInsertPoint(loadBB);
subIGF.Builder.emitBlock(contBB);
auto phi = subIGF.Builder.CreatePHI(IGM.Int64Ty, 2);
phi->addIncoming(load, loadBB);
phi->addIncoming(resultWord, isUnfilledBB);
auto resultAddr = subIGF.Builder.CreateTruncOrBitCast(phi, IGM.SizeTy);
resultAddr = subIGF.Builder.CreateIntToPtr(resultAddr,
IGM.TypeMetadataPtrTy);
subIGF.Builder.CreateRet(resultAddr);
};
auto instantiationFn =
IGM.getOrCreateHelperFunction(instantiationFnName,
IGF.IGM.TypeMetadataPtrTy,
cache->getType(),
generateInstantiationFn,
/*noinline*/true);
auto call = IGF.Builder.CreateCall(instantiationFn, cache);
call->setDoesNotThrow();
call->setDoesNotAccessMemory();
auto response = MetadataResponse::forComplete(call);
IGF.setScopedLocalTypeMetadata(type, response);
return response;
}
/// Emit a call to the type metadata accessor for the given function.
static MetadataResponse
emitCallToTypeMetadataAccessFunction(IRGenFunction &IGF, CanType type,
DynamicMetadataRequest request) {
// If we already cached the metadata, use it.
if (auto local = IGF.tryGetLocalTypeMetadata(type, request))
return local;
// If the metadata would require multiple runtime calls to build, emit a
// single access by mangled name instead, if we're asking for complete
// metadata.
//
if ((request.isStaticallyBlockingComplete() ||
(request.isStaticallyAbstract() &&
canIssueIncompleteMetadataRequests(IGF.IGM))) &&
shouldAccessByMangledName(IGF.IGM, type)) {
return emitMetadataAccessByMangledName(IGF, type, request);
}
llvm::Constant *accessor =
getOrCreateTypeMetadataAccessFunction(IGF.IGM, type);
llvm::CallInst *call = IGF.Builder.CreateCall(accessor, { request.get(IGF) });
call->setCallingConv(IGF.IGM.SwiftCC);
call->setDoesNotAccessMemory();
call->setDoesNotThrow();
auto response = MetadataResponse::handle(IGF, request, call);
// Save the metadata for future lookups.
IGF.setScopedLocalTypeMetadata(type, response);
return response;
}
llvm::Value *IRGenFunction::emitAbstractTypeMetadataRef(CanType type) {
return emitTypeMetadataRef(type, MetadataState::Abstract).getMetadata();
}
/// Produce the type metadata pointer for the given type.
llvm::Value *IRGenFunction::emitTypeMetadataRef(CanType type) {
return emitTypeMetadataRef(type, MetadataState::Complete).getMetadata();
}
/// Produce the type metadata pointer for the given type.
MetadataResponse
IRGenFunction::emitTypeMetadataRef(CanType type,
DynamicMetadataRequest request) {
type = IGM.getRuntimeReifiedType(type);
// Look through any opaque types we're allowed to.
type = IGM.substOpaqueTypesWithUnderlyingTypes(type);
// If we're asking for the metadata of the type that dynamic Self is known
// to be equal to, we can just use the self metadata.
if (SelfTypeIsExact && SelfType == type) {
return MetadataResponse::forComplete(getDynamicSelfMetadata());
}
if (type->hasArchetype() ||
!shouldTypeMetadataAccessUseAccessor(IGM, type)) {
return emitDirectTypeMetadataRef(*this, type, request);
}
return emitCallToTypeMetadataAccessFunction(*this, type, request);
}
/// Return the address of a function that will return type metadata
/// for the given non-dependent type.
llvm::Function *irgen::getOrCreateTypeMetadataAccessFunction(IRGenModule &IGM,
CanType type) {
type = IGM.getRuntimeReifiedType(type);
assert(!type->hasArchetype() &&
"cannot create global function to return dependent type metadata");
switch (getTypeMetadataAccessStrategy(type)) {
case MetadataAccessStrategy::ForeignAccessor:
case MetadataAccessStrategy::PublicUniqueAccessor:
case MetadataAccessStrategy::HiddenUniqueAccessor:
case MetadataAccessStrategy::PrivateAccessor:
return getOtherwiseDefinedTypeMetadataAccessFunction(IGM, type);
case MetadataAccessStrategy::NonUniqueAccessor:
return createDirectTypeMetadataAccessFunction(IGM, type,
/*allow existing*/true);
}
llvm_unreachable("bad type metadata access strategy");
}
namespace {
/// A visitor class for emitting a reference to type metatype for a
/// SILType, i.e. a lowered representation type. In general, the type
/// metadata produced here might not correspond to the formal type that
/// would belong to the unlowered type. For correctness, it is important
/// not to cache the result as if it were the metadata for a formal type
/// unless the type actually cannot possibly be a formal type, e.g. because
/// it is one of the special lowered type kinds like SILFunctionType.
///
/// NOTE: If you modify the special cases in this, you should update
/// isTypeMetadataForLayoutAccessible in SIL.cpp.
class EmitTypeMetadataRefForLayout
: public CanTypeVisitor<EmitTypeMetadataRefForLayout, CanType> {
public:
EmitTypeMetadataRefForLayout() {}
/// For most types, we can just emit the usual metadata.
CanType visitType(CanType t) { return t; }
CanType visitBoundGenericEnumType(CanBoundGenericEnumType ty) {
// Optionals have a lowered payload type, so we recurse here.
if (auto objectTy = ty.getOptionalObjectType()) {
auto payloadTy = visit(objectTy);
if (payloadTy == objectTy)
return ty;
auto &C = ty->getASTContext();
auto optDecl = C.getOptionalDecl();
return CanType(BoundGenericEnumType::get(optDecl, Type(), payloadTy));
}
// Otherwise, generic arguments are not lowered.
return ty;
}
CanType visitTupleType(CanTupleType ty) {
bool changed = false;
SmallVector<TupleTypeElt, 4> loweredElts;
loweredElts.reserve(ty->getNumElements());
for (auto i : indices(ty->getElementTypes())) {
auto substEltType = ty.getElementType(i);
auto &substElt = ty->getElement(i);
// Make sure we don't have something non-materializable.
auto Flags = substElt.getParameterFlags();
assert(Flags.getValueOwnership() == ValueOwnership::Default);
assert(!Flags.isVariadic());
CanType loweredSubstEltType = visit(substEltType);
changed =
(changed || substEltType != loweredSubstEltType || !Flags.isNone());
// Note: we drop @escaping and @autoclosure which can still appear on
// materializable tuple types.
//
// FIXME: Replace this with an assertion that the original tuple element
// did not have any flags.
loweredElts.emplace_back(loweredSubstEltType, substElt.getName(),
ParameterTypeFlags());
}
if (!changed)
return ty;
// The cast should succeed, because if we end up with a one-element
// tuple type here, it must have a label.
return cast<TupleType>(
CanType(TupleType::get(loweredElts, ty->getASTContext())));
}
CanType visitAnyFunctionType(CanAnyFunctionType ty) {
llvm_unreachable("not a SIL type");
}
CanType visitSILFunctionType(CanSILFunctionType ty) {
// All function types have the same layout regardless of arguments or
// abstraction level. Use the metadata for () -> () for thick functions,
// or AnyObject for block functions.
auto &C = ty->getASTContext();
switch (ty->getRepresentation()) {
case SILFunctionType::Representation::Thin:
case SILFunctionType::Representation::Method:
case SILFunctionType::Representation::WitnessMethod:
case SILFunctionType::Representation::ObjCMethod:
case SILFunctionType::Representation::CFunctionPointer:
case SILFunctionType::Representation::Closure:
// A thin function looks like a plain pointer.
// FIXME: Except for extra inhabitants?
return C.TheRawPointerType;
case SILFunctionType::Representation::Thick: {
// All function types look like () -> ().
// FIXME: It'd be nice not to have to call through the runtime here.
//
// FIXME: Verify ExtInfo state is correct, not working by accident.
CanFunctionType::ExtInfo info;
return CanFunctionType::get({}, C.TheEmptyTupleType, info);
}
case SILFunctionType::Representation::Block:
// All block types look like AnyObject.
return C.getAnyObjectType();
}
llvm_unreachable("Not a valid SILFunctionType.");
}
CanType visitAnyMetatypeType(CanAnyMetatypeType ty) {
assert(ty->hasRepresentation() && "not a lowered metatype");
auto &C = ty->getASTContext();
switch (ty->getRepresentation()) {
case MetatypeRepresentation::Thin:
// Thin metatypes are empty, so they look like the empty tuple type.
return C.TheEmptyTupleType;
case MetatypeRepresentation::Thick:
case MetatypeRepresentation::ObjC:
// Thick and ObjC metatypes look like pointers with extra inhabitants.
// Get the metatype metadata from the runtime.
// FIXME: It'd be nice not to need a runtime call here; we should just
// have a standard aligned-pointer type metadata.
return ty;
}
llvm_unreachable("Not a valid MetatypeRepresentation.");
}
};
} // end anonymous namespace
llvm::Value *IRGenFunction::emitTypeMetadataRefForLayout(SILType type) {
return emitTypeMetadataRefForLayout(type, MetadataState::Complete);
}
llvm::Value *
IRGenFunction::emitTypeMetadataRefForLayout(SILType ty,
DynamicMetadataRequest request) {
assert(request.canResponseStatusBeIgnored());
if (auto response =
tryGetLocalTypeMetadataForLayout(ty.getObjectType(), request)) {
assert(request.canResponseStatusBeIgnored() || !response.isValid());
return response.getMetadata();
}
// Map to a layout equivalent AST type.
auto layoutEquivalentType =
EmitTypeMetadataRefForLayout().visit(ty.getASTType());
auto response = emitTypeMetadataRef(layoutEquivalentType, request);
setScopedLocalTypeMetadataForLayout(ty.getObjectType(), response);
return response.getMetadata();
}
namespace {
/// A visitor class for emitting a reference to a type layout struct.
/// There are a few ways we can emit it:
///
/// - If the type is fixed-layout and we have visibility of its value
/// witness table (or one close enough), we can project the layout struct
/// from it.
/// - If the type is fixed layout, we can emit our own copy of the layout
/// struct.
/// - If the type is dynamic-layout, we have to instantiate its metadata
/// and project out its metadata. (FIXME: This leads to deadlocks in
/// recursive cases, though we can avoid many deadlocks because most
/// valid recursive types bottom out in fixed-sized types like classes
/// or pointers.)
class EmitTypeLayoutRef
: public CanTypeVisitor<EmitTypeLayoutRef, llvm::Value *,
DynamicMetadataRequest> {
private:
IRGenFunction &IGF;
public:
EmitTypeLayoutRef(IRGenFunction &IGF) : IGF(IGF) {}
llvm::Value *emitFromValueWitnessTablePointer(llvm::Value *vwtable) {
llvm::Value *indexConstant = llvm::ConstantInt::get(IGF.IGM.Int32Ty,
(unsigned)ValueWitness::First_TypeLayoutWitness);
return IGF.Builder.CreateInBoundsGEP(IGF.IGM.Int8PtrTy, vwtable,
indexConstant);
}
/// Emit the type layout by projecting it from a value witness table to
/// which we have linkage.
llvm::Value *emitFromValueWitnessTable(CanType t) {
auto *vwtable = IGF.IGM.getAddrOfValueWitnessTable(t);
return emitFromValueWitnessTablePointer(vwtable);
}
/// Emit the type layout by projecting it from dynamic type metadata.
llvm::Value *emitFromTypeMetadata(CanType t,
DynamicMetadataRequest request) {
auto *vwtable =
IGF.emitValueWitnessTableRef(IGF.IGM.getLoweredType(t), request);
return emitFromValueWitnessTablePointer(vwtable);
}
/// Given that the type is fixed-layout, emit the type layout by
/// emitting a global layout for it.
llvm::Value *emitFromFixedLayout(CanType t) {
auto layout = tryEmitFromFixedLayout(t);
assert(layout && "type must be fixed-size to call emitFromFixedLayout");
return layout;
}
/// If the type is fixed-layout, emit the type layout by
/// emitting a global layout for it.
llvm::Value *tryEmitFromFixedLayout(CanType t) {
auto &ti = IGF.getTypeInfo(SILType::getPrimitiveObjectType(t));
if (auto fixedTI = dyn_cast<FixedTypeInfo>(&ti))
return IGF.IGM.emitFixedTypeLayout(t, *fixedTI);
return nullptr;
}
bool hasVisibleValueWitnessTable(CanType t) const {
// Some builtin and structural types have value witnesses exported from
// the runtime.
auto &C = IGF.IGM.Context;
if (t == C.TheEmptyTupleType
|| t == C.TheNativeObjectType
|| t == C.TheBridgeObjectType
|| t == C.TheRawPointerType
|| t == C.getAnyObjectType())
return true;
if (auto intTy = dyn_cast<BuiltinIntegerType>(t)) {
auto width = intTy->getWidth();
if (width.isPointerWidth())
return true;
if (width.isFixedWidth()) {
switch (width.getFixedWidth()) {
case 8:
case 16:
case 32:
case 64:
case 128:
case 256:
return true;
default:
return false;
}
}
return false;
}
// TODO: If a nominal type is in the same source file as we're currently
// emitting, we would be able to see its value witness table.
return false;
}
/// Fallback default implementation.
llvm::Value *visitType(CanType t, DynamicMetadataRequest request) {
auto silTy = IGF.IGM.getLoweredType(t);
auto &ti = IGF.getTypeInfo(silTy);
// If the type is in the same source file, or has a common value
// witness table exported from the runtime, we can project from the
// value witness table instead of emitting a new record.
if (hasVisibleValueWitnessTable(t))
return emitFromValueWitnessTable(t);
// If the type is a singleton aggregate, the field's layout is equivalent
// to the aggregate's.
if (SILType singletonFieldTy = getSingletonAggregateFieldType(IGF.IGM,
silTy, ResilienceExpansion::Maximal))
return visit(singletonFieldTy.getASTType(), request);
// If the type is fixed-layout, emit a copy of its layout.
if (auto fixed = dyn_cast<FixedTypeInfo>(&ti))
return IGF.IGM.emitFixedTypeLayout(t, *fixed);
return emitFromTypeMetadata(t, request);
}
llvm::Value *visitAnyFunctionType(CanAnyFunctionType type,
DynamicMetadataRequest request) {
llvm_unreachable("not a SIL type");
}
llvm::Value *visitSILFunctionType(CanSILFunctionType type,
DynamicMetadataRequest request) {
// All function types have the same layout regardless of arguments or
// abstraction level. Use the value witness table for
// @convention(blah) () -> () from the runtime.
auto &C = type->getASTContext();
switch (type->getRepresentation()) {
case SILFunctionType::Representation::Thin:
case SILFunctionType::Representation::Method:
case SILFunctionType::Representation::WitnessMethod:
case SILFunctionType::Representation::ObjCMethod:
case SILFunctionType::Representation::CFunctionPointer:
case SILFunctionType::Representation::Closure:
// A thin function looks like a plain pointer.
// FIXME: Except for extra inhabitants?
return emitFromValueWitnessTable(C.TheRawPointerType);
case SILFunctionType::Representation::Thick: {
// All function types look like () -> ().
// FIXME: Verify ExtInfo state is correct, not working by accident.
CanFunctionType::ExtInfo info;
return emitFromValueWitnessTable(
CanFunctionType::get({}, C.TheEmptyTupleType, info));
}
case SILFunctionType::Representation::Block:
// All block types look like AnyObject.
return emitFromValueWitnessTable(C.getAnyObjectType());
}
llvm_unreachable("Not a valid SILFunctionType.");
}
llvm::Value *visitAnyMetatypeType(CanAnyMetatypeType type,
DynamicMetadataRequest request) {
assert(type->hasRepresentation()
&& "not a lowered metatype");
switch (type->getRepresentation()) {
case MetatypeRepresentation::Thin: {
// Thin metatypes are empty, so they look like the empty tuple type.
return emitFromValueWitnessTable(IGF.IGM.Context.TheEmptyTupleType);
}
case MetatypeRepresentation::Thick:
if (isa<ExistentialMetatypeType>(type)) {
return emitFromFixedLayout(type);
}
// Otherwise, this is a metatype that looks like a pointer.
LLVM_FALLTHROUGH;
case MetatypeRepresentation::ObjC:
// Thick metatypes look like pointers with spare bits.
return emitFromValueWitnessTable(
CanMetatypeType::get(IGF.IGM.Context.TheNativeObjectType));
}
llvm_unreachable("Not a valid MetatypeRepresentation.");
}
llvm::Value *visitAnyClassType(ClassDecl *classDecl,
DynamicMetadataRequest request) {
// All class types have the same layout.
auto type = classDecl->getDeclaredType()->getCanonicalType();
switch (type->getReferenceCounting()) {
case ReferenceCounting::Native:
return emitFromValueWitnessTable(IGF.IGM.Context.TheNativeObjectType);
case ReferenceCounting::ObjC:
case ReferenceCounting::Block:
case ReferenceCounting::Unknown:
return emitFromValueWitnessTable(IGF.IGM.Context.getAnyObjectType());
case ReferenceCounting::Bridge:
case ReferenceCounting::Error:
llvm_unreachable("classes shouldn't have this kind of refcounting");
}
llvm_unreachable("Not a valid ReferenceCounting.");
}
llvm::Value *visitClassType(CanClassType type,
DynamicMetadataRequest request) {
return visitAnyClassType(type->getClassOrBoundGenericClass(), request);
}
llvm::Value *visitBoundGenericClassType(CanBoundGenericClassType type,
DynamicMetadataRequest request) {
return visitAnyClassType(type->getClassOrBoundGenericClass(), request);
}
llvm::Value *visitTupleType(CanTupleType type,
DynamicMetadataRequest request) {
// Single-element tuples have exactly the same layout as their elements.
if (type->getNumElements() == 1) {
return visit(type.getElementType(0), request);
}
// If the type is fixed-layout, use a global layout.
if (auto layout = tryEmitFromFixedLayout(type))
return layout;
// TODO: check for cached VWT / metadata for the type.
// Use swift_getTupleTypeLayout to compute a layout.
// Create a buffer to hold the result. We don't have any reasonable
// way to scope the lifetime of this.
auto resultPtr = IGF.createAlloca(IGF.IGM.FullTypeLayoutTy,
IGF.IGM.getPointerAlignment())
.getAddress();
switch (type->getNumElements()) {
case 0:
case 1:
llvm_unreachable("filtered out above");
case 2: {
auto elt0 = visit(type.getElementType(0), request);
auto elt1 = visit(type.getElementType(1), request);
// Ignore the offset.
auto call = IGF.Builder.CreateCall(IGF.IGM.getGetTupleLayout2Fn(),
{resultPtr, elt0, elt1});
call->setDoesNotThrow();
break;
}
case 3: {
auto elt0 = visit(type.getElementType(0), request);
auto elt1 = visit(type.getElementType(1), request);
auto elt2 = visit(type.getElementType(2), request);
// Ignore the offsets.
auto call = IGF.Builder.CreateCall(IGF.IGM.getGetTupleLayout3Fn(),
{resultPtr, elt0, elt1, elt2});
call->setDoesNotThrow();
break;
}
default: {
// Allocate a temporary array for the element layouts.
auto eltLayoutsArraySize =
IGF.IGM.getPointerSize() * type->getNumElements();
auto eltLayoutsArray =
IGF.createAlloca(IGF.IGM.Int8PtrPtrTy,
IGF.IGM.getSize(Size(type->getNumElements())),
IGF.IGM.getPointerAlignment());
IGF.Builder.CreateLifetimeStart(eltLayoutsArray, eltLayoutsArraySize);
// Emit layouts for all the elements and store them into the array.
for (auto i : indices(type.getElementTypes())) {
auto eltLayout = visit(type.getElementType(i), request);
auto eltLayoutSlot =
i == 0 ? eltLayoutsArray
: IGF.Builder.CreateConstArrayGEP(eltLayoutsArray, i,
IGF.IGM.getPointerSize());
IGF.Builder.CreateStore(eltLayout, eltLayoutSlot);
}
// Ignore the offsets.
auto offsetsPtr =
llvm::ConstantPointerNull::get(IGF.IGM.Int32Ty->getPointerTo());
// Flags.
auto flags = TupleTypeFlags().withNumElements(type->getNumElements());
auto flagsValue = IGF.IGM.getSize(Size(flags.getIntValue()));
// Compute the layout.
auto call = IGF.Builder.CreateCall(IGF.IGM.getGetTupleLayoutFn(),
{resultPtr, offsetsPtr, flagsValue,
eltLayoutsArray.getAddress()});
call->setDoesNotThrow();
// We're done with the buffer.
IGF.Builder.CreateLifetimeEnd(eltLayoutsArray, eltLayoutsArraySize);
break;
}
}
// Cast resultPtr to i8**, our general currency type for type layouts.
resultPtr = IGF.Builder.CreateBitCast(resultPtr, IGF.IGM.Int8PtrPtrTy);
return resultPtr;
}
};
} // end anonymous namespace
llvm::Value *irgen::emitTypeLayoutRef(IRGenFunction &IGF, SILType type,
MetadataDependencyCollector *collector) {
auto request =
DynamicMetadataRequest::getNonBlocking(MetadataState::LayoutComplete,
collector);
assert(request.canResponseStatusBeIgnored());
return EmitTypeLayoutRef(IGF).visit(type.getASTType(), request);
}
/// Given a class metatype, produce the necessary heap metadata
/// reference. This is generally the metatype pointer, but may
/// instead be a reference type.
llvm::Value *irgen::emitClassHeapMetadataRefForMetatype(IRGenFunction &IGF,
llvm::Value *metatype,
CanType type) {
// If the type is known to have Swift metadata, this is trivial.
if (hasKnownSwiftMetadata(IGF.IGM, type))
return metatype;
// Otherwise, we may have to unwrap an ObjC class wrapper.
assert(IGF.IGM.Context.LangOpts.EnableObjCInterop);
metatype = IGF.Builder.CreateBitCast(metatype, IGF.IGM.TypeMetadataPtrTy);
// Fetch the metadata for that class.
auto call = IGF.Builder.CreateCall(IGF.IGM.getGetObjCClassFromMetadataFn(),
metatype);
call->setDoesNotThrow();
call->setDoesNotAccessMemory();
return call;
}
/// Produce the heap metadata pointer for the given class type. For
/// Swift-defined types, this is equivalent to the metatype for the
/// class, but for Objective-C-defined types, this is the class
/// object.
llvm::Value *irgen::emitClassHeapMetadataRef(IRGenFunction &IGF, CanType type,
MetadataValueType desiredType,
DynamicMetadataRequest request,
bool allowUninitialized) {
assert(request.canResponseStatusBeIgnored() &&
"emitClassHeapMetadataRef only supports satisfied requests");
assert(type->mayHaveSuperclass() || type->isTypeErasedGenericClassType());
// Archetypes may or may not be ObjC classes and need unwrapping to get at
// the class object.
if (auto archetype = dyn_cast<ArchetypeType>(type)) {
// Look up the Swift metadata from context.
auto archetypeMeta = IGF.emitTypeMetadataRef(type, request).getMetadata();
// Get the class pointer.
auto classPtr = emitClassHeapMetadataRefForMetatype(IGF, archetypeMeta,
archetype);
if (desiredType == MetadataValueType::ObjCClass)
classPtr = IGF.Builder.CreateBitCast(classPtr, IGF.IGM.ObjCClassPtrTy);
return classPtr;
}
if (ClassDecl *theClass = dyn_cast_or_null<ClassDecl>(type->getAnyNominal())) {
if (!hasKnownSwiftMetadata(IGF.IGM, theClass)) {
llvm::Value *result =
emitObjCHeapMetadataRef(IGF, theClass, allowUninitialized);
if (desiredType == MetadataValueType::TypeMetadata)
result = IGF.Builder.CreateBitCast(result, IGF.IGM.TypeMetadataPtrTy);
return result;
}
}
llvm::Value *result = IGF.emitTypeMetadataRef(type, request).getMetadata();
if (desiredType == MetadataValueType::ObjCClass)
result = IGF.Builder.CreateBitCast(result, IGF.IGM.ObjCClassPtrTy);
return result;
}
/// Emit a metatype value for a known type.
void irgen::emitMetatypeRef(IRGenFunction &IGF, CanMetatypeType type,
Explosion &explosion) {
switch (type->getRepresentation()) {
case MetatypeRepresentation::Thin:
// Thin types have a trivial representation.
break;
case MetatypeRepresentation::Thick:
explosion.add(IGF.emitTypeMetadataRef(type.getInstanceType()));
break;
case MetatypeRepresentation::ObjC:
explosion.add(emitClassHeapMetadataRef(IGF, type.getInstanceType(),
MetadataValueType::ObjCClass,
MetadataState::Complete));
break;
}
}
static bool canCheckStateWithBranch(DynamicMetadataRequest request,
MetadataResponse response) {
assert(request.getDependencyCollector() == nullptr ||
(request.isStatic() && request.getStaticRequest().isNonBlocking()));
return (response.hasDynamicState() &&
request.getDependencyCollector() != nullptr);
}
MetadataResponse
irgen::emitCheckTypeMetadataState(IRGenFunction &IGF,
DynamicMetadataRequest request,
MetadataResponse response) {
// Note that the structure of this function is mirrored in
// getCheckTypeMetadataStateCost.
// If the request is already satisfied by the response, we don't need
// to check anything.
if (request.isSatisfiedBy(response))
return response;
auto metadata = response.getMetadata();
// Try to check the already-fetched dynamic state against the required state.
if (canCheckStateWithBranch(request, response)) {
auto dynamicState = response.getDynamicState();
request.getDependencyCollector()
->checkDependency(IGF, request, metadata, dynamicState);
return MetadataResponse(metadata, dynamicState,
request.getStaticRequest().getState());
}
// Otherwise, we have to ask the runtime.
return emitGetTypeMetadataDynamicState(IGF, request, metadata);
}
OperationCost
irgen::getCheckTypeMetadataStateCost(DynamicMetadataRequest request,
MetadataResponse response) {
if (request.isSatisfiedBy(response))
return OperationCost::Free;
if (canCheckStateWithBranch(request, response))
return OperationCost::Arithmetic;
return OperationCost::Call;
}
/// Call swift_checkMetadataState.
MetadataResponse
irgen::emitGetTypeMetadataDynamicState(IRGenFunction &IGF,
DynamicMetadataRequest request,
llvm::Value *metadata) {
auto call = IGF.Builder.CreateCall(IGF.IGM.getCheckMetadataStateFn(),
{ request.get(IGF), metadata });
call->setCallingConv(IGF.IGM.SwiftCC);
return MetadataResponse::handle(IGF, request, call);
}
|
#include "gbdt.h"
#include <LightGBM/utils/openmp_wrapper.h>
#include <LightGBM/utils/common.h>
#include <LightGBM/objective_function.h>
#include <LightGBM/metric.h>
#include <LightGBM/prediction_early_stop.h>
#include <ctime>
#include <sstream>
#include <chrono>
#include <string>
#include <vector>
#include <utility>
namespace LightGBM {
#ifdef TIMETAG
std::chrono::duration<double, std::milli> boosting_time;
std::chrono::duration<double, std::milli> train_score_time;
std::chrono::duration<double, std::milli> out_of_bag_score_time;
std::chrono::duration<double, std::milli> valid_score_time;
std::chrono::duration<double, std::milli> metric_time;
std::chrono::duration<double, std::milli> bagging_time;
std::chrono::duration<double, std::milli> sub_gradient_time;
std::chrono::duration<double, std::milli> tree_time;
#endif // TIMETAG
GBDT::GBDT()
:iter_(0),
train_data_(nullptr),
objective_function_(nullptr),
early_stopping_round_(0),
max_feature_idx_(0),
num_tree_per_iteration_(1),
num_class_(1),
num_iteration_for_pred_(0),
shrinkage_rate_(0.1f),
num_init_iteration_(0),
boost_from_average_(false) {
#pragma omp parallel
#pragma omp master
{
num_threads_ = omp_get_num_threads();
}
}
GBDT::~GBDT() {
#ifdef TIMETAG
Log::Info("GBDT::boosting costs %f", boosting_time * 1e-3);
Log::Info("GBDT::train_score costs %f", train_score_time * 1e-3);
Log::Info("GBDT::out_of_bag_score costs %f", out_of_bag_score_time * 1e-3);
Log::Info("GBDT::valid_score costs %f", valid_score_time * 1e-3);
Log::Info("GBDT::metric costs %f", metric_time * 1e-3);
Log::Info("GBDT::bagging costs %f", bagging_time * 1e-3);
Log::Info("GBDT::sub_gradient costs %f", sub_gradient_time * 1e-3);
Log::Info("GBDT::tree costs %f", tree_time * 1e-3);
#endif
}
void GBDT::Init(const BoostingConfig* config, const Dataset* train_data, const ObjectiveFunction* objective_function,
const std::vector<const Metric*>& training_metrics) {
iter_ = 0;
num_iteration_for_pred_ = 0;
max_feature_idx_ = 0;
num_class_ = config->num_class;
train_data_ = nullptr;
gbdt_config_ = nullptr;
tree_learner_ = nullptr;
ResetTrainingData(config, train_data, objective_function, training_metrics);
}
void GBDT::ResetTrainingData(const BoostingConfig* config, const Dataset* train_data, const ObjectiveFunction* objective_function,
const std::vector<const Metric*>& training_metrics) {
auto new_config = std::unique_ptr<BoostingConfig>(new BoostingConfig(*config));
if (train_data_ != nullptr && !train_data_->CheckAlign(*train_data)) {
Log::Fatal("cannot reset training data, since new training data has different bin mappers");
}
early_stopping_round_ = new_config->early_stopping_round;
shrinkage_rate_ = new_config->learning_rate;
objective_function_ = objective_function;
num_tree_per_iteration_ = num_class_;
if (objective_function_ != nullptr) {
is_constant_hessian_ = objective_function_->IsConstantHessian();
num_tree_per_iteration_ = objective_function_->NumTreePerIteration();
} else {
is_constant_hessian_ = false;
}
if (train_data_ != train_data && train_data != nullptr) {
if (tree_learner_ == nullptr) {
tree_learner_ = std::unique_ptr<TreeLearner>(TreeLearner::CreateTreeLearner(new_config->tree_learner_type, new_config->device_type, &new_config->tree_config));
}
// init tree learner
tree_learner_->Init(train_data, is_constant_hessian_);
// push training metrics
training_metrics_.clear();
for (const auto& metric : training_metrics) {
training_metrics_.push_back(metric);
}
training_metrics_.shrink_to_fit();
// not same training data, need reset score and others
// create score tracker
train_score_updater_.reset(new ScoreUpdater(train_data, num_tree_per_iteration_));
// update score
for (int i = 0; i < iter_; ++i) {
for (int cur_tree_id = 0; cur_tree_id < num_tree_per_iteration_; ++cur_tree_id) {
auto curr_tree = (i + num_init_iteration_) * num_tree_per_iteration_ + cur_tree_id;
train_score_updater_->AddScore(models_[curr_tree].get(), cur_tree_id);
}
}
num_data_ = train_data->num_data();
// create buffer for gradients and hessians
if (objective_function_ != nullptr) {
size_t total_size = static_cast<size_t>(num_data_) * num_tree_per_iteration_;
gradients_.resize(total_size);
hessians_.resize(total_size);
}
// get max feature index
max_feature_idx_ = train_data->num_total_features() - 1;
// get label index
label_idx_ = train_data->label_idx();
// get feature names
feature_names_ = train_data->feature_names();
feature_infos_ = train_data->feature_infos();
}
if ((train_data_ != train_data && train_data != nullptr)
|| (gbdt_config_ != nullptr && gbdt_config_->bagging_fraction != new_config->bagging_fraction)) {
// if need bagging, create buffer
if (new_config->bagging_fraction < 1.0 && new_config->bagging_freq > 0) {
bag_data_cnt_ =
static_cast<data_size_t>(new_config->bagging_fraction * num_data_);
bag_data_indices_.resize(num_data_);
tmp_indices_.resize(num_data_);
offsets_buf_.resize(num_threads_);
left_cnts_buf_.resize(num_threads_);
right_cnts_buf_.resize(num_threads_);
left_write_pos_buf_.resize(num_threads_);
right_write_pos_buf_.resize(num_threads_);
double average_bag_rate = new_config->bagging_fraction / new_config->bagging_freq;
is_use_subset_ = false;
if (average_bag_rate <= 0.5) {
tmp_subset_.reset(new Dataset(bag_data_cnt_));
tmp_subset_->CopyFeatureMapperFrom(train_data);
is_use_subset_ = true;
Log::Debug("use subset for bagging");
}
} else {
bag_data_cnt_ = num_data_;
bag_data_indices_.clear();
tmp_indices_.clear();
is_use_subset_ = false;
}
}
train_data_ = train_data;
if (train_data_ != nullptr) {
// reset config for tree learner
tree_learner_->ResetConfig(&new_config->tree_config);
class_need_train_ = std::vector<bool>(num_tree_per_iteration_, true);
if (objective_function_ != nullptr && objective_function_->SkipEmptyClass()) {
CHECK(num_tree_per_iteration_ == num_class_);
// + 1 here for the binary classification
class_default_output_ = std::vector<double>(num_tree_per_iteration_, 0.0f);
auto label = train_data_->metadata().label();
if (num_tree_per_iteration_ > 1) {
// multi-class
std::vector<data_size_t> cnt_per_class(num_tree_per_iteration_, 0);
for (data_size_t i = 0; i < num_data_; ++i) {
int index = static_cast<int>(label[i]);
CHECK(index < num_tree_per_iteration_);
++cnt_per_class[index];
}
for (int i = 0; i < num_tree_per_iteration_; ++i) {
if (cnt_per_class[i] == num_data_) {
class_need_train_[i] = false;
class_default_output_[i] = -std::log(kEpsilon);
} else if (cnt_per_class[i] == 0) {
class_need_train_[i] = false;
class_default_output_[i] = -std::log(1.0f / kEpsilon - 1.0f);
}
}
} else {
// binary class
data_size_t cnt_pos = 0;
for (data_size_t i = 0; i < num_data_; ++i) {
if (label[i] > 0) {
++cnt_pos;
}
}
if (cnt_pos == 0) {
class_need_train_[0] = false;
class_default_output_[0] = -std::log(1.0f / kEpsilon - 1.0f);
} else if (cnt_pos == num_data_) {
class_need_train_[0] = false;
class_default_output_[0] = -std::log(kEpsilon);
}
}
}
}
gbdt_config_.reset(new_config.release());
}
void GBDT::AddValidDataset(const Dataset* valid_data,
const std::vector<const Metric*>& valid_metrics) {
if (!train_data_->CheckAlign(*valid_data)) {
Log::Fatal("cannot add validation data, since it has different bin mappers with training data");
}
// for a validation dataset, we need its score and metric
auto new_score_updater = std::unique_ptr<ScoreUpdater>(new ScoreUpdater(valid_data, num_tree_per_iteration_));
// update score
for (int i = 0; i < iter_; ++i) {
for (int cur_tree_id = 0; cur_tree_id < num_tree_per_iteration_; ++cur_tree_id) {
auto curr_tree = (i + num_init_iteration_) * num_tree_per_iteration_ + cur_tree_id;
new_score_updater->AddScore(models_[curr_tree].get(), cur_tree_id);
}
}
valid_score_updater_.push_back(std::move(new_score_updater));
valid_metrics_.emplace_back();
if (early_stopping_round_ > 0) {
best_iter_.emplace_back();
best_score_.emplace_back();
best_msg_.emplace_back();
}
for (const auto& metric : valid_metrics) {
valid_metrics_.back().push_back(metric);
if (early_stopping_round_ > 0) {
best_iter_.back().push_back(0);
best_score_.back().push_back(kMinScore);
best_msg_.back().emplace_back();
}
}
valid_metrics_.back().shrink_to_fit();
}
data_size_t GBDT::BaggingHelper(Random& cur_rand, data_size_t start, data_size_t cnt, data_size_t* buffer) {
if (cnt <= 0) {
return 0;
}
data_size_t bag_data_cnt =
static_cast<data_size_t>(gbdt_config_->bagging_fraction * cnt);
data_size_t cur_left_cnt = 0;
data_size_t cur_right_cnt = 0;
auto right_buffer = buffer + bag_data_cnt;
// random bagging, minimal unit is one record
for (data_size_t i = 0; i < cnt; ++i) {
float prob =
(bag_data_cnt - cur_left_cnt) / static_cast<float>(cnt - i);
if (cur_rand.NextFloat() < prob) {
buffer[cur_left_cnt++] = start + i;
} else {
right_buffer[cur_right_cnt++] = start + i;
}
}
CHECK(cur_left_cnt == bag_data_cnt);
return cur_left_cnt;
}
void GBDT::Bagging(int iter) {
// if need bagging
if (bag_data_cnt_ < num_data_ && iter % gbdt_config_->bagging_freq == 0) {
const data_size_t min_inner_size = 1000;
data_size_t inner_size = (num_data_ + num_threads_ - 1) / num_threads_;
if (inner_size < min_inner_size) { inner_size = min_inner_size; }
OMP_INIT_EX();
#pragma omp parallel for schedule(static,1)
for (int i = 0; i < num_threads_; ++i) {
OMP_LOOP_EX_BEGIN();
left_cnts_buf_[i] = 0;
right_cnts_buf_[i] = 0;
data_size_t cur_start = i * inner_size;
if (cur_start > num_data_) { continue; }
data_size_t cur_cnt = inner_size;
if (cur_start + cur_cnt > num_data_) { cur_cnt = num_data_ - cur_start; }
Random cur_rand(gbdt_config_->bagging_seed + iter * num_threads_ + i);
data_size_t cur_left_count = BaggingHelper(cur_rand, cur_start, cur_cnt, tmp_indices_.data() + cur_start);
offsets_buf_[i] = cur_start;
left_cnts_buf_[i] = cur_left_count;
right_cnts_buf_[i] = cur_cnt - cur_left_count;
OMP_LOOP_EX_END();
}
OMP_THROW_EX();
data_size_t left_cnt = 0;
left_write_pos_buf_[0] = 0;
right_write_pos_buf_[0] = 0;
for (int i = 1; i < num_threads_; ++i) {
left_write_pos_buf_[i] = left_write_pos_buf_[i - 1] + left_cnts_buf_[i - 1];
right_write_pos_buf_[i] = right_write_pos_buf_[i - 1] + right_cnts_buf_[i - 1];
}
left_cnt = left_write_pos_buf_[num_threads_ - 1] + left_cnts_buf_[num_threads_ - 1];
#pragma omp parallel for schedule(static, 1)
for (int i = 0; i < num_threads_; ++i) {
OMP_LOOP_EX_BEGIN();
if (left_cnts_buf_[i] > 0) {
std::memcpy(bag_data_indices_.data() + left_write_pos_buf_[i],
tmp_indices_.data() + offsets_buf_[i], left_cnts_buf_[i] * sizeof(data_size_t));
}
if (right_cnts_buf_[i] > 0) {
std::memcpy(bag_data_indices_.data() + left_cnt + right_write_pos_buf_[i],
tmp_indices_.data() + offsets_buf_[i] + left_cnts_buf_[i], right_cnts_buf_[i] * sizeof(data_size_t));
}
OMP_LOOP_EX_END();
}
OMP_THROW_EX();
bag_data_cnt_ = left_cnt;
Log::Debug("Re-bagging, using %d data to train", bag_data_cnt_);
// set bagging data to tree learner
if (!is_use_subset_) {
tree_learner_->SetBaggingData(bag_data_indices_.data(), bag_data_cnt_);
} else {
// get subset
tmp_subset_->ReSize(bag_data_cnt_);
tmp_subset_->CopySubset(train_data_, bag_data_indices_.data(), bag_data_cnt_, false);
tree_learner_->ResetTrainingData(tmp_subset_.get());
}
}
}
void GBDT::UpdateScoreOutOfBag(const Tree* tree, const int cur_tree_id) {
#ifdef TIMETAG
auto start_time = std::chrono::steady_clock::now();
#endif
// we need to predict out-of-bag scores of data for boosting
if (num_data_ - bag_data_cnt_ > 0 && !is_use_subset_) {
train_score_updater_->AddScore(tree, bag_data_indices_.data() + bag_data_cnt_, num_data_ - bag_data_cnt_, cur_tree_id);
}
#ifdef TIMETAG
out_of_bag_score_time += std::chrono::steady_clock::now() - start_time;
#endif
}
bool GBDT::TrainOneIter(const score_t* gradient, const score_t* hessian, bool is_eval) {
// boosting from average prediction. It doesn't work well for classification, remove it for now.
if (models_.empty()
&& gbdt_config_->boost_from_average
&& !train_score_updater_->has_init_score()
&& num_class_ <= 1
&& objective_function_ != nullptr
&& objective_function_->BoostFromAverage()) {
double init_score = 0.0f;
auto label = train_data_->metadata().label();
#pragma omp parallel for schedule(static) reduction(+:init_score)
for (data_size_t i = 0; i < num_data_; ++i) {
init_score += label[i];
}
init_score /= num_data_;
std::unique_ptr<Tree> new_tree(new Tree(2));
new_tree->Split(0, 0, BinType::NumericalBin, 0, 0, 0, init_score, init_score, 0, num_data_, -1, 0, 0, 0);
train_score_updater_->AddScore(init_score, 0);
for (auto& score_updater : valid_score_updater_) {
score_updater->AddScore(init_score, 0);
}
models_.push_back(std::move(new_tree));
boost_from_average_ = true;
}
// boosting first
if (gradient == nullptr || hessian == nullptr) {
#ifdef TIMETAG
auto start_time = std::chrono::steady_clock::now();
#endif
Boosting();
gradient = gradients_.data();
hessian = hessians_.data();
#ifdef TIMETAG
boosting_time += std::chrono::steady_clock::now() - start_time;
#endif
}
#ifdef TIMETAG
auto start_time = std::chrono::steady_clock::now();
#endif
// bagging logic
Bagging(iter_);
#ifdef TIMETAG
bagging_time += std::chrono::steady_clock::now() - start_time;
#endif
if (is_use_subset_ && bag_data_cnt_ < num_data_) {
#ifdef TIMETAG
start_time = std::chrono::steady_clock::now();
#endif
if (gradients_.empty()) {
size_t total_size = static_cast<size_t>(num_data_) * num_tree_per_iteration_;
gradients_.resize(total_size);
hessians_.resize(total_size);
}
// get sub gradients
for (int cur_tree_id = 0; cur_tree_id < num_tree_per_iteration_; ++cur_tree_id) {
size_t bias = static_cast<size_t>(cur_tree_id)* num_data_;
// cannot multi-threading here.
for (int i = 0; i < bag_data_cnt_; ++i) {
gradients_[bias + i] = gradient[bias + bag_data_indices_[i]];
hessians_[bias + i] = hessian[bias + bag_data_indices_[i]];
}
}
gradient = gradients_.data();
hessian = hessians_.data();
#ifdef TIMETAG
sub_gradient_time += std::chrono::steady_clock::now() - start_time;
#endif
}
bool should_continue = false;
for (int cur_tree_id = 0; cur_tree_id < num_tree_per_iteration_; ++cur_tree_id) {
#ifdef TIMETAG
start_time = std::chrono::steady_clock::now();
#endif
std::unique_ptr<Tree> new_tree(new Tree(2));
if (class_need_train_[cur_tree_id]) {
size_t bias = static_cast<size_t>(cur_tree_id)* num_data_;
new_tree.reset(
tree_learner_->Train(gradient + bias, hessian + bias, is_constant_hessian_));
}
#ifdef TIMETAG
tree_time += std::chrono::steady_clock::now() - start_time;
#endif
if (new_tree->num_leaves() > 1) {
should_continue = true;
// shrinkage by learning rate
new_tree->Shrinkage(shrinkage_rate_);
// update score
UpdateScore(new_tree.get(), cur_tree_id);
UpdateScoreOutOfBag(new_tree.get(), cur_tree_id);
} else {
// only add default score one-time
if (!class_need_train_[cur_tree_id] && models_.size() < static_cast<size_t>(num_tree_per_iteration_)) {
auto output = class_default_output_[cur_tree_id];
new_tree->Split(0, 0, BinType::NumericalBin, 0, 0, 0,
output, output, 0, num_data_, -1, 0, 0, 0);
train_score_updater_->AddScore(output, cur_tree_id);
for (auto& score_updater : valid_score_updater_) {
score_updater->AddScore(output, cur_tree_id);
}
}
}
// add model
models_.push_back(std::move(new_tree));
}
if (!should_continue) {
Log::Warning("Stopped training because there are no more leaves that meet the split requirements.");
for (int cur_tree_id = 0; cur_tree_id < num_tree_per_iteration_; ++cur_tree_id) {
models_.pop_back();
}
return true;
}
++iter_;
if (is_eval) {
return EvalAndCheckEarlyStopping();
} else {
return false;
}
}
void GBDT::RollbackOneIter() {
if (iter_ <= 0) { return; }
int cur_iter = iter_ + num_init_iteration_ - 1;
// reset score
for (int cur_tree_id = 0; cur_tree_id < num_tree_per_iteration_; ++cur_tree_id) {
auto curr_tree = cur_iter * num_tree_per_iteration_ + cur_tree_id;
models_[curr_tree]->Shrinkage(-1.0);
train_score_updater_->AddScore(models_[curr_tree].get(), cur_tree_id);
for (auto& score_updater : valid_score_updater_) {
score_updater->AddScore(models_[curr_tree].get(), cur_tree_id);
}
}
// remove model
for (int cur_tree_id = 0; cur_tree_id < num_tree_per_iteration_; ++cur_tree_id) {
models_.pop_back();
}
--iter_;
}
bool GBDT::EvalAndCheckEarlyStopping() {
bool is_met_early_stopping = false;
#ifdef TIMETAG
auto start_time = std::chrono::steady_clock::now();
#endif
// print message for metric
auto best_msg = OutputMetric(iter_);
#ifdef TIMETAG
metric_time += std::chrono::steady_clock::now() - start_time;
#endif
is_met_early_stopping = !best_msg.empty();
if (is_met_early_stopping) {
Log::Info("Early stopping at iteration %d, the best iteration round is %d",
iter_, iter_ - early_stopping_round_);
Log::Info("Output of best iteration round:\n%s", best_msg.c_str());
// pop last early_stopping_round_ models
for (int i = 0; i < early_stopping_round_ * num_tree_per_iteration_; ++i) {
models_.pop_back();
}
}
return is_met_early_stopping;
}
void GBDT::UpdateScore(const Tree* tree, const int cur_tree_id) {
#ifdef TIMETAG
auto start_time = std::chrono::steady_clock::now();
#endif
// update training score
if (!is_use_subset_) {
train_score_updater_->AddScore(tree_learner_.get(), tree, cur_tree_id);
} else {
train_score_updater_->AddScore(tree, cur_tree_id);
}
#ifdef TIMETAG
train_score_time += std::chrono::steady_clock::now() - start_time;
#endif
#ifdef TIMETAG
start_time = std::chrono::steady_clock::now();
#endif
// update validation score
for (auto& score_updater : valid_score_updater_) {
score_updater->AddScore(tree, cur_tree_id);
}
#ifdef TIMETAG
valid_score_time += std::chrono::steady_clock::now() - start_time;
#endif
}
std::string GBDT::OutputMetric(int iter) {
bool need_output = (iter % gbdt_config_->output_freq) == 0;
std::string ret = "";
std::stringstream msg_buf;
std::vector<std::pair<size_t, size_t>> meet_early_stopping_pairs;
// print training metric
if (need_output) {
for (auto& sub_metric : training_metrics_) {
auto name = sub_metric->GetName();
auto scores = sub_metric->Eval(train_score_updater_->score(), objective_function_);
for (size_t k = 0; k < name.size(); ++k) {
std::stringstream tmp_buf;
tmp_buf << "Iteration:" << iter
<< ", training " << name[k]
<< " : " << scores[k];
Log::Info(tmp_buf.str().c_str());
if (early_stopping_round_ > 0) {
msg_buf << tmp_buf.str() << std::endl;
}
}
}
}
// print validation metric
if (need_output || early_stopping_round_ > 0) {
for (size_t i = 0; i < valid_metrics_.size(); ++i) {
for (size_t j = 0; j < valid_metrics_[i].size(); ++j) {
auto test_scores = valid_metrics_[i][j]->Eval(valid_score_updater_[i]->score(),
objective_function_);
auto name = valid_metrics_[i][j]->GetName();
for (size_t k = 0; k < name.size(); ++k) {
std::stringstream tmp_buf;
tmp_buf << "Iteration:" << iter
<< ", valid_" << i + 1 << " " << name[k]
<< " : " << test_scores[k];
if (need_output) {
Log::Info(tmp_buf.str().c_str());
}
if (early_stopping_round_ > 0) {
msg_buf << tmp_buf.str() << std::endl;
}
}
if (ret.empty() && early_stopping_round_ > 0) {
auto cur_score = valid_metrics_[i][j]->factor_to_bigger_better() * test_scores.back();
if (cur_score > best_score_[i][j]) {
best_score_[i][j] = cur_score;
best_iter_[i][j] = iter;
meet_early_stopping_pairs.emplace_back(i, j);
} else {
if (iter - best_iter_[i][j] >= early_stopping_round_) { ret = best_msg_[i][j]; }
}
}
}
}
}
for (auto& pair : meet_early_stopping_pairs) {
best_msg_[pair.first][pair.second] = msg_buf.str();
}
return ret;
}
/*! \brief Get eval result */
std::vector<double> GBDT::GetEvalAt(int data_idx) const {
CHECK(data_idx >= 0 && data_idx <= static_cast<int>(valid_score_updater_.size()));
std::vector<double> ret;
if (data_idx == 0) {
for (auto& sub_metric : training_metrics_) {
auto scores = sub_metric->Eval(train_score_updater_->score(), objective_function_);
for (auto score : scores) {
ret.push_back(score);
}
}
} else {
auto used_idx = data_idx - 1;
for (size_t j = 0; j < valid_metrics_[used_idx].size(); ++j) {
auto test_scores = valid_metrics_[used_idx][j]->Eval(valid_score_updater_[used_idx]->score(),
objective_function_);
for (auto score : test_scores) {
ret.push_back(score);
}
}
}
return ret;
}
/*! \brief Get training scores result */
const double* GBDT::GetTrainingScore(int64_t* out_len) {
*out_len = static_cast<int64_t>(train_score_updater_->num_data()) * num_class_;
return train_score_updater_->score();
}
void GBDT::GetPredictAt(int data_idx, double* out_result, int64_t* out_len) {
CHECK(data_idx >= 0 && data_idx <= static_cast<int>(valid_score_updater_.size()));
const double* raw_scores = nullptr;
data_size_t num_data = 0;
if (data_idx == 0) {
raw_scores = GetTrainingScore(out_len);
num_data = train_score_updater_->num_data();
} else {
auto used_idx = data_idx - 1;
raw_scores = valid_score_updater_[used_idx]->score();
num_data = valid_score_updater_[used_idx]->num_data();
*out_len = static_cast<int64_t>(num_data) * num_class_;
}
if (objective_function_ != nullptr) {
#pragma omp parallel for schedule(static)
for (data_size_t i = 0; i < num_data; ++i) {
std::vector<double> tree_pred(num_tree_per_iteration_);
for (int j = 0; j < num_tree_per_iteration_; ++j) {
tree_pred[j] = raw_scores[j * num_data + i];
}
std::vector<double> tmp_result(num_class_);
objective_function_->ConvertOutput(tree_pred.data(), tmp_result.data());
for (int j = 0; j < num_class_; ++j) {
out_result[j * num_data + i] = static_cast<double>(tmp_result[j]);
}
}
} else {
#pragma omp parallel for schedule(static)
for (data_size_t i = 0; i < num_data; ++i) {
std::vector<double> tmp_result(num_tree_per_iteration_);
for (int j = 0; j < num_tree_per_iteration_; ++j) {
out_result[j * num_data + i] = static_cast<double>(raw_scores[j * num_data + i]);
}
}
}
}
void GBDT::Boosting() {
if (objective_function_ == nullptr) {
Log::Fatal("No object function provided");
}
// objective function will calculate gradients and hessians
int64_t num_score = 0;
objective_function_->
GetGradients(GetTrainingScore(&num_score), gradients_.data(), hessians_.data());
}
std::string GBDT::DumpModel(int num_iteration) const {
std::stringstream str_buf;
str_buf << "{";
str_buf << "\"name\":\"" << SubModelName() << "\"," << std::endl;
str_buf << "\"num_class\":" << num_class_ << "," << std::endl;
str_buf << "\"num_tree_per_iteration\":" << num_tree_per_iteration_ << "," << std::endl;
str_buf << "\"label_index\":" << label_idx_ << "," << std::endl;
str_buf << "\"max_feature_idx\":" << max_feature_idx_ << "," << std::endl;
str_buf << "\"feature_names\":[\""
<< Common::Join(feature_names_, "\",\"") << "\"],"
<< std::endl;
str_buf << "\"tree_info\":[";
int num_used_model = static_cast<int>(models_.size());
if (num_iteration > 0) {
num_iteration += boost_from_average_ ? 1 : 0;
num_used_model = std::min(num_iteration * num_tree_per_iteration_, num_used_model);
}
for (int i = 0; i < num_used_model; ++i) {
if (i > 0) {
str_buf << ",";
}
str_buf << "{";
str_buf << "\"tree_index\":" << i << ",";
str_buf << models_[i]->ToJSON();
str_buf << "}";
}
str_buf << "]" << std::endl;
str_buf << "}" << std::endl;
return str_buf.str();
}
std::string GBDT::ModelToIfElse(int num_iteration) const {
std::stringstream str_buf;
str_buf << "#include \"gbdt.h\"" << std::endl;
str_buf << "#include <LightGBM/utils/common.h>" << std::endl;
str_buf << "#include <LightGBM/objective_function.h>" << std::endl;
str_buf << "#include <LightGBM/metric.h>" << std::endl;
str_buf << "#include <LightGBM/prediction_early_stop.h>" << std::endl;
str_buf << "#include <ctime>" << std::endl;
str_buf << "#include <sstream>" << std::endl;
str_buf << "#include <chrono>" << std::endl;
str_buf << "#include <string>" << std::endl;
str_buf << "#include <vector>" << std::endl;
str_buf << "#include <utility>" << std::endl;
str_buf << "namespace LightGBM {" << std::endl;
int num_used_model = static_cast<int>(models_.size());
if (num_iteration > 0) {
num_iteration += boost_from_average_ ? 1 : 0;
num_used_model = std::min(num_iteration * num_tree_per_iteration_, num_used_model);
}
// PredictRaw
for (int i = 0; i < num_used_model; ++i) {
str_buf << models_[i]->ToIfElse(i, false) << std::endl;
}
str_buf << "double (*PredictTreePtr[])(const double*) = { ";
for (int i = 0; i < num_used_model; ++i) {
if (i > 0) {
str_buf << " , ";
}
str_buf << "PredictTree" << i;
}
str_buf << " };" << std::endl << std::endl;
std::stringstream pred_str_buf;
pred_str_buf << "\t" << "int early_stop_round_counter = 0;" << std::endl;
pred_str_buf << "\t" << "for (int i = 0; i < num_iteration_for_pred_; ++i) {" << std::endl;
pred_str_buf << "\t\t" << "for (int k = 0; k < num_tree_per_iteration_; ++k) {" << std::endl;
pred_str_buf << "\t\t\t" << "output[k] += (*PredictTreePtr[i * num_tree_per_iteration_ + k])(features);" << std::endl;
pred_str_buf << "\t\t" << "}" << std::endl;
pred_str_buf << "\t\t" << "++early_stop_round_counter;" << std::endl;
pred_str_buf << "\t\t" << "if (early_stop->round_period == early_stop_round_counter) {" << std::endl;
pred_str_buf << "\t\t\t" << "if (early_stop->callback_function(output, num_tree_per_iteration_))" << std::endl;
pred_str_buf << "\t\t\t\t" << "return;" << std::endl;
pred_str_buf << "\t\t\t" << "early_stop_round_counter = 0;" << std::endl;
pred_str_buf << "\t\t" << "}" << std::endl;
pred_str_buf << "\t" << "}" << std::endl;
str_buf << "void GBDT::PredictRaw(const double* features, double *output, const PredictionEarlyStopInstance* early_stop) const {" << std::endl;
str_buf << pred_str_buf.str();
str_buf << "}" << std::endl;
str_buf << std::endl;
// Predict
str_buf << "void GBDT::Predict(const double* features, double *output, const PredictionEarlyStopInstance* early_stop) const {" << std::endl;
str_buf << "\t" << "PredictRaw(features, output, early_stop);" << std::endl;
str_buf << "\t" << "if (objective_function_ != nullptr) {" << std::endl;
str_buf << "\t\t" << "objective_function_->ConvertOutput(output, output);" << std::endl;
str_buf << "\t" << "}" << std::endl;
str_buf << "}" << std::endl;
str_buf << std::endl;
// PredictLeafIndex
for (int i = 0; i < num_used_model; ++i) {
str_buf << models_[i]->ToIfElse(i, true) << std::endl;
}
str_buf << "double (*PredictTreeLeafPtr[])(const double*) = { ";
for (int i = 0; i < num_used_model; ++i) {
if (i > 0) {
str_buf << " , ";
}
str_buf << "PredictTree" << i << "Leaf";
}
str_buf << " };" << std::endl << std::endl;
str_buf << "void GBDT::PredictLeafIndex(const double* features, double *output) const {" << std::endl;
str_buf << "\t" << "int total_tree = num_iteration_for_pred_ * num_tree_per_iteration_;" << std::endl;
str_buf << "\t" << "for (int i = 0; i < total_tree; ++i) {" << std::endl;
str_buf << "\t\t" << "output[i] = (*PredictTreeLeafPtr[i])(features);" << std::endl;
str_buf << "\t" << "}" << std::endl;
str_buf << "}" << std::endl;
str_buf << "} // namespace LightGBM" << std::endl;
return str_buf.str();
}
bool GBDT::SaveModelToIfElse(int num_iteration, const char* filename) const {
/*! \brief File to write models */
std::ofstream output_file;
std::ifstream ifs(filename);
if (ifs.good()) {
std::string origin((std::istreambuf_iterator<char>(ifs)),
(std::istreambuf_iterator<char>()));
output_file.open(filename);
output_file << "#define USE_HARD_CODE 0" << std::endl;
output_file << "#ifndef USE_HARD_CODE" << std::endl;
output_file << origin << std::endl;
output_file << "#else" << std::endl;
output_file << ModelToIfElse(num_iteration);
output_file << "#endif" << std::endl;
} else {
output_file.open(filename);
output_file << ModelToIfElse(num_iteration);
}
ifs.close();
output_file.close();
return (bool)output_file;
}
std::string GBDT::SaveModelToString(int num_iteration) const {
std::stringstream ss;
// output model type
ss << SubModelName() << std::endl;
// output number of class
ss << "num_class=" << num_class_ << std::endl;
ss << "num_tree_per_iteration=" << num_tree_per_iteration_ << std::endl;
// output label index
ss << "label_index=" << label_idx_ << std::endl;
// output max_feature_idx
ss << "max_feature_idx=" << max_feature_idx_ << std::endl;
// output objective
if (objective_function_ != nullptr) {
ss << "objective=" << objective_function_->ToString() << std::endl;
}
if (boost_from_average_) {
ss << "boost_from_average" << std::endl;
}
ss << "feature_names=" << Common::Join(feature_names_, " ") << std::endl;
ss << "feature_infos=" << Common::Join(feature_infos_, " ") << std::endl;
ss << std::endl;
int num_used_model = static_cast<int>(models_.size());
if (num_iteration > 0) {
num_iteration += boost_from_average_ ? 1 : 0;
num_used_model = std::min(num_iteration * num_tree_per_iteration_, num_used_model);
}
// output tree models
for (int i = 0; i < num_used_model; ++i) {
ss << "Tree=" << i << std::endl;
ss << models_[i]->ToString() << std::endl;
}
std::vector<std::pair<size_t, std::string>> pairs = FeatureImportance();
ss << std::endl << "feature importances:" << std::endl;
for (size_t i = 0; i < pairs.size(); ++i) {
ss << pairs[i].second << "=" << std::to_string(pairs[i].first) << std::endl;
}
return ss.str();
}
bool GBDT::SaveModelToFile(int num_iteration, const char* filename) const {
/*! \brief File to write models */
std::ofstream output_file;
output_file.open(filename);
output_file << SaveModelToString(num_iteration);
output_file.close();
return (bool)output_file;
}
bool GBDT::LoadModelFromString(const std::string& model_str) {
// use serialized string to restore this object
models_.clear();
std::vector<std::string> lines = Common::Split(model_str.c_str(), '\n');
// get number of classes
auto line = Common::FindFromLines(lines, "num_class=");
if (line.size() > 0) {
Common::Atoi(Common::Split(line.c_str(), '=')[1].c_str(), &num_class_);
} else {
Log::Fatal("Model file doesn't specify the number of classes");
return false;
}
line = Common::FindFromLines(lines, "num_tree_per_iteration=");
if (line.size() > 0) {
Common::Atoi(Common::Split(line.c_str(), '=')[1].c_str(), &num_tree_per_iteration_);
} else {
num_tree_per_iteration_ = num_class_;
}
// get index of label
line = Common::FindFromLines(lines, "label_index=");
if (line.size() > 0) {
Common::Atoi(Common::Split(line.c_str(), '=')[1].c_str(), &label_idx_);
} else {
Log::Fatal("Model file doesn't specify the label index");
return false;
}
// get max_feature_idx first
line = Common::FindFromLines(lines, "max_feature_idx=");
if (line.size() > 0) {
Common::Atoi(Common::Split(line.c_str(), '=')[1].c_str(), &max_feature_idx_);
} else {
Log::Fatal("Model file doesn't specify max_feature_idx");
return false;
}
// get boost_from_average_
line = Common::FindFromLines(lines, "boost_from_average");
if (line.size() > 0) {
boost_from_average_ = true;
}
// get feature names
line = Common::FindFromLines(lines, "feature_names=");
if (line.size() > 0) {
feature_names_ = Common::Split(line.substr(std::strlen("feature_names=")).c_str(), " ");
if (feature_names_.size() != static_cast<size_t>(max_feature_idx_ + 1)) {
Log::Fatal("Wrong size of feature_names");
return false;
}
} else {
Log::Fatal("Model file doesn't contain feature names");
return false;
}
line = Common::FindFromLines(lines, "feature_infos=");
if (line.size() > 0) {
feature_infos_ = Common::Split(line.substr(std::strlen("feature_infos=")).c_str(), " ");
if (feature_infos_.size() != static_cast<size_t>(max_feature_idx_ + 1)) {
Log::Fatal("Wrong size of feature_infos");
return false;
}
} else {
Log::Fatal("Model file doesn't contain feature infos");
return false;
}
line = Common::FindFromLines(lines, "objective=");
if (line.size() > 0) {
auto str = Common::Split(line.c_str(), '=')[1];
loaded_objective_.reset(ObjectiveFunction::CreateObjectiveFunction(str));
objective_function_ = loaded_objective_.get();
}
// get tree models
size_t i = 0;
while (i < lines.size()) {
size_t find_pos = lines[i].find("Tree=");
if (find_pos != std::string::npos) {
++i;
int start = static_cast<int>(i);
while (i < lines.size() && lines[i].find("Tree=") == std::string::npos) { ++i; }
int end = static_cast<int>(i);
std::string tree_str = Common::Join<std::string>(lines, start, end, "\n");
models_.emplace_back(new Tree(tree_str));
} else {
++i;
}
}
Log::Info("Finished loading %d models", models_.size());
num_iteration_for_pred_ = static_cast<int>(models_.size()) / num_tree_per_iteration_;
num_init_iteration_ = num_iteration_for_pred_;
iter_ = 0;
return true;
}
std::vector<std::pair<size_t, std::string>> GBDT::FeatureImportance() const {
std::vector<size_t> feature_importances(max_feature_idx_ + 1, 0);
for (size_t iter = 0; iter < models_.size(); ++iter) {
for (int split_idx = 0; split_idx < models_[iter]->num_leaves() - 1; ++split_idx) {
if (models_[iter]->split_gain(split_idx) > 0) {
++feature_importances[models_[iter]->split_feature(split_idx)];
}
}
}
// store the importance first
std::vector<std::pair<size_t, std::string>> pairs;
for (size_t i = 0; i < feature_importances.size(); ++i) {
if (feature_importances[i] > 0) {
pairs.emplace_back(feature_importances[i], feature_names_[i]);
}
}
// sort the importance
std::sort(pairs.begin(), pairs.end(),
[](const std::pair<size_t, std::string>& lhs,
const std::pair<size_t, std::string>& rhs) {
return lhs.first > rhs.first;
});
return pairs;
}
} // namespace LightGBM
|
;
; Generic game device library
; Stefano Bodrato - 20/8/2001
;
; $Id: joystick.asm,v 1.3 2009/01/23 08:22:27 stefano Exp $
;
XLIB joystick
LIB getk
.joystick
;__FASTALL__ : joystick no. in HL
ld a,l
cp 1 ; Stick emulation 1 (qaop-mn)
jr nz,j_no1
call getk
ld a,l
ld l,0
or @00100000 ; TO_LOWER
cp 'm'
jr nz,no_fire1
set 4,l
jr j_done
.no_fire1
cp 'n'
jr nz,no_fire2
set 5,l
jr j_done
.no_fire2
cp 'q'
jr nz,no_up
set 3,l
jr j_done
.no_up
cp 'a'
jr nz,no_down
set 2,l
jr j_done
.no_down
cp 'o'
jr nz,no_left
set 1,l
jr j_done
.no_left
cp 'p'
jr nz,no_right
set 0,l
.no_right
jr j_done
.j_no1
cp 2 ; Stick emulation 2 (8246-05)
jr nz,j_no2
call getk
ld a,l
ld l,0
cp '0'
jr nz,no_fire1_a
set 4,l
jr j_done
.no_fire1_a
cp '5'
jr nz,no_fire2_a
set 5,l
jr j_done
.no_fire2_a
cp '8'
jr nz,no_up_a
set 3,l
jr j_done
.no_up_a
cp '2'
jr nz,no_down_a
set 2,l
jr j_done
.no_down_a
cp '4'
jr nz,no_left_a
set 1,l
jr j_done
.no_left_a
cp '6'
jr nz,no_right_a
set 0,l
.no_right_a
jr j_done
.j_no2
xor a
.j_done
ret
|
; A160938: a(n)= n * digital sum(n+1)
; 2,6,12,20,30,42,56,72,9,20,33,48,65,84,105,128,153,180,38,60,84,110,138,168,200,234,270,308,87,120,155,192,231,272,315,360,407,456,156,200,246,294,344,396,450,506,564,624,245,300,357,416,477,540,605,672,741
add $0,5
mov $2,-3
lpb $0,1
add $0,$2
mov $2,$0
mod $2,10
mov $3,$0
div $0,10
add $2,$0
mov $0,1
add $3,1
mov $1,$3
sub $1,2
mul $1,$2
lpe
|
//-----------------------------------------------------------------------------
// Copyright (c) 2012 GarageGames, LLC
//
// 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 "platform/platform.h"
#include "console/console.h"
#include "gfx/bitmap/gBitmap.h"
#include "SDL.h"
#include "windowManager/sdl/sdlWindow.h"
static SDL_Window* gSplashWindow = nullptr;
static SDL_Surface* gSplashImage = nullptr;
static SDL_Texture* gSplashTexture = nullptr;
static SDL_Renderer* gSplashRenderer = nullptr;
bool Platform::displaySplashWindow( String path )
{
if(path.isEmpty())
return false;
Torque::Path iconPath = Torque::Path(path);
if (iconPath.getExtension() == String("bmp"))
{
Con::errorf("Unable to use bmp format images for the splash screen. Please use a different format.");
return false;
}
Resource<GBitmap> img = GBitmap::load(iconPath);
if (img != NULL)
{
U32 pitch;
U32 width = img->getWidth();
bool hasAlpha = img->getHasTransparency();
U32 depth;
if (hasAlpha)
{
pitch = 4 * width;
depth = 32;
}
else
{
pitch = 3 * width;
depth = 24;
}
Uint32 rmask, gmask, bmask, amask;
if (SDL_BYTEORDER == SDL_BIG_ENDIAN)
{
S32 shift = hasAlpha ? 8 : 0;
rmask = 0xff000000 >> shift;
gmask = 0x00ff0000 >> shift;
bmask = 0x0000ff00 >> shift;
amask = 0x000000ff >> shift;
}
else
{
rmask = 0x000000ff;
gmask = 0x0000ff00;
bmask = 0x00ff0000;
amask = hasAlpha ? 0xff000000 : 0;
}
gSplashImage = SDL_CreateRGBSurfaceFrom(img->getAddress(0, 0), img->getWidth(), img->getHeight(), depth, pitch, rmask, gmask, bmask, amask);
}
//now the pop-up window
if (gSplashImage)
{
gSplashWindow = SDL_CreateWindow("", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED,
gSplashImage->w, gSplashImage->h, SDL_WINDOW_BORDERLESS | SDL_WINDOW_SHOWN);
gSplashRenderer = SDL_CreateRenderer(gSplashWindow, -1, SDL_RENDERER_ACCELERATED);
gSplashTexture = SDL_CreateTextureFromSurface(gSplashRenderer, gSplashImage);
SDL_RenderCopy(gSplashRenderer, gSplashTexture, NULL, NULL);
SDL_RenderPresent(gSplashRenderer);
}
return true;
}
bool Platform::closeSplashWindow()
{
if (gSplashTexture != nullptr)
{
SDL_DestroyTexture(gSplashTexture);
gSplashTexture = nullptr;
}
if (gSplashImage != nullptr)
{
SDL_FreeSurface(gSplashImage);
gSplashImage = nullptr;
}
if (gSplashRenderer != nullptr)
{
SDL_DestroyRenderer(gSplashRenderer);
gSplashRenderer = nullptr;
}
if (gSplashWindow != nullptr)
{
SDL_DestroyWindow(gSplashWindow);
gSplashWindow = nullptr;
}
return true;
} |
; int ungetc_unlocked(int c, FILE *stream)
SECTION code_clib
SECTION code_stdio
PUBLIC _ungetc_unlocked
EXTERN l0_ungetc_unlocked_callee
_ungetc_unlocked:
pop af
pop hl
pop bc
push bc
push hl
push af
jp l0_ungetc_unlocked_callee
|
.model small
.stack
.data
PA EQU 01190H
PB EQU 01191H
PC EQU 01192H
CR EQU 01193H
table db 80h,96h,0abh,0c0h,0d2h,0e2h,0eeh,0f8h,0feh,0ffh,
0feh,0f8h,0eeh,0e2h,0d2h,0c0h,0abh,96h,80h,
69h,54h,3fh,2dh,1dh,1dh,11h,07h,01h,00h,
01h,07h,011h,1dh,2dh,3fh,54h,69h
count equ 36d
.code
mov ax,@data
mov ds,ax
mov dx,CR
mov al,80h
out dx,al
lp1: lea si,table
mov cx,count
lp2: mov dx,PA
mov al,[si]
out dx,al
inc si
call delay
loop lp2
mov ah,01h
int 16h
jz lp1
mov ah,4ch
int 21h
delay proc
mov ax,0ffffh
lp3: dec ax
jnz lp3
ret
delay endp
end |
;*=$C800
; UP9600 KERNAL ADAPTER
; ORIGINALLY BY DANIAL DALLMAN
; ADAPTED 2017 FOR KERNAL BY BO ZIMMERMAN
; MODIFIED ON 2/14/2017 1:26A
; .D @0:UP9600.BIN
; PROVIDED FUNCTIONS
JMP UP9600.INIT
JMP UP9600.INSTALL; INSTALL AND (PROBE FOR) UP9600 (C=ERROR)
JMP UP9600.ENABLE; (RE-)ENABLE INTERFACE
JMP UP9600.DISABLE; DISABLE INTERFACE (EG. FOR FLOPPY ACCESSES)
; RSOUT AND RSIN BOTH MODIFY A AND X REGISTER
JMP UP9600.RSOUT; PUT BYTE TO RS232 (BLOCKING)
JMP UP9600.RSIN; READ BYTE FROM RS232 (C=TRYAGAIN)
UP9600.IRQVECT = 788
UP9600.JIFFIES = $A2; LOWEST BYTE OF SYSTEM'S JIFFIE COUNTER
UP9600.ORIGIRQ = $EA31; (MUST INCEASE JIFFIE-COUNTER !)
UP9600.ORIGNMI = $FE47
UP9600.NMIVECT = 792
UP9600.WRSPTR = 670; WRITE-POINTER INTO SEND BUFFER
UP9600.RDSPTR = 669; READ-POINTER INTO SEND BUFFER
UP9600.WRRPTR = 667; WRITE-POINTER INTO RECEIVE BUFFER
UP9600.RDRPTR = 668; READ-POINTER INTO RECEIVE BUFFER
; STATIC VARIABLES
UP9600.STIME
BYTE 0;; COPY OF $A2=JIFFIES TO DETECT TIMEOUTS
UP9600.OUTSTAT = 169
UP9600.UPFLAG
BYTE 0
UP9600.SAVBYTE
BYTE 0,0,0,0
; JIFFIES .BYTE 0
UP9600.RECPTR = 247; RECBUF = $CB00;; 247 - 248
UP9600.SNDPTR = 249; SNDBUF = $CC00;; 249 - 250
;
;
UP9600.INIT
SEI
LDA #<UP9600.DOOPEN
STA $031A
LDA #>UP9600.DOOPEN
STA $031B
LDA #<UP9600.DOCLOSE
STA $031C
LDA #>UP9600.DOCLOSE
STA $031D
LDA #<UP9600.DOCHKIN
STA $031E
LDA #>UP9600.DOCHKIN
STA $031F
LDA #<UP9600.DOCHKOUT
STA $0320
LDA #>UP9600.DOCHKOUT
STA $0321
LDA #<UP9600.DOCHRIN
STA $0324
LDA #>UP9600.DOCHRIN
STA $0325
LDA #<UP9600.DOGETIN
STA $032A
LDA #>UP9600.DOGETIN
STA $032B
LDA #<UP9600.DOPUT
STA $0326
LDA #>UP9600.DOPUT
STA $0327
CLI
RTS
; *******************************
UP9600.DOOPEN
PHA
TYA
PHA
JSR UP9600.DISABLE
JSR $F34A; CALL IOPEN
LDY #$00
LDA $BA
CMP #$02
BNE UP9600.EOPEN
LDY #$00
LDA ($BB),Y
CMP #$0C
BCC UP9600.EOPEN
LDA #$01
STA UP9600.UPFLAG
JSR UP9600.INSTALL
UP9600.EOPEN
PLA
TAY
PLA
LDX #$00
CLC
RTS
; *******************************
UP9600.DOCHRIN
LDA UP9600.UPFLAG
BEQ UP9600.NOCHRIN
LDA $99
CMP #$02
BEQ UP9600.DOGET2
UP9600.NOCHRIN
JMP $F157
UP9600.DOGETIN
LDA UP9600.UPFLAG
BEQ UP9600.NOGETIN
LDA $99
CMP #$02
BEQ UP9600.DOGET2
UP9600.NOGETIN
JMP $F13E
UP9600.DOGET2
TYA
PHA
TXA
PHA
LDA #$00
STA UP9600.SAVBYTE
STA $0297
JSR UP9600.RSIN
BCC UP9600.DOGOTIN
PLA
TAX
PLA
TAY
LDA #$08
STA $0297
LDA #$00
CLC
RTS
UP9600.DOGOTIN
STA UP9600.SAVBYTE
UP9600.DOGET4
PLA
TAX
PLA
TAY
LDA UP9600.SAVBYTE
CLC
RTS
; *******************************
UP9600.DOPUT
PHA
LDA UP9600.UPFLAG
BEQ UP9600.NOPUT1
LDA $9A
CMP #$02
BEQ UP9600.DOPUT2
UP9600.NOPUT1
PLA
JMP $F1CA
UP9600.DOPUT2
CLC
PLA
JSR UP9600.RSOUT
LDA #$00
STA $0297
CLC
UP9600.DOPUT4
RTS
; *******************************
; ;;;;;;;;;;;;;;;;
nop
nop
UP9600.DOCLOSE
PHA
JSR UP9600.DISABLE
JSR $F314
BEQ UP9600.DOCLO2
PLA
CLC
RTS
UP9600.DOCLO2
JSR $F31F; SET BA
LDA $BA
CMP #$02
BEQ UP9600.DOCLO4
UP9600.DOCLO3
PLA
JMP $F291
UP9600.DOCLO4
LDA #$00
STA UP9600.UPFLAG
PLA
LDX #$00
CLC
RTS
; *******************************
UP9600.DOCHKIN
PHA
LDA UP9600.UPFLAG
BNE UP9600.DOCHKI1
PLA
JMP $F20E
UP9600.DOCHKI1
PLA
JSR $F30F
BEQ UP9600.DOCHKI2
JMP $F701
UP9600.DOCHKI2
JSR $F31F
LDA $BA
CMP #$02
BEQ UP9600.DOCHKI4
CMP #$04
BCC UP9600.NOCHKIN
UP9600.DOCHKI3
JSR UP9600.DISABLE
JMP UP9600.NOCHKIN
UP9600.DOCHKI4
STA $99
JSR UP9600.ENABLE
CLC
RTS
UP9600.NOCHKIN
JMP $F219
;
UP9600.DOCHKOUT
PHA
LDA UP9600.UPFLAG
BNE UP9600.DOCHKO1
PLA
JMP $F250
UP9600.DOCHKO1
PLA
JSR $F30F
BEQ UP9600.DOCHKO2
JMP $F701
UP9600.DOCHKO2
JSR $F31F
LDA $BA
CMP #$02
BEQ UP9600.DOCHKO4
CMP #$04
BCC UP9600.NOCHKOUT
UP9600.DOCHKO3
JSR UP9600.DISABLE
JMP UP9600.NOCHKOUT
UP9600.DOCHKO4
STA $9A
JSR UP9600.ENABLE
CLC
RTS
UP9600.NOCHKOUT
JMP $F25B
; *******************************
UP9600.NMIDOBIT
PHA
BIT $DD0D; CHECK BIT 7 (STARTBIT PRINT)
BPL UP9600.NMIDOBI2; NO STARTBIT RECEIVED, THEN SKIP
LDA #$13
STA $DD0F; START TIMER B (FORCED RELOAD, SIGNAL AT PB7)
STA $DD0D; DISABLE TIMER AND FLAG INTERRUPTS
LDA #<UP9600.NMIBYTRY; ON NEXT NMI CALL NMIBYTRY
STA UP9600.NMIVECT; (TRIGGERED BY SDR FULL)
LDA #>UP9600.NMIBYTRY
STA UP9600.NMIVECT+1
UP9600.NMIDOBI2
PLA; IGNORE, IF NMI WAS TRIGGERED BY RESTORE-KEY
RTI
;
UP9600.NMIBYTRY
PHA
BIT $DD0D; CHECK BIT 7 (SDR FULL PRINT)
BPL UP9600.NMIDOBI2; SDR NOT FULL, THEN SKIP (EG. RESTORE-KEY)
LDA #$92
STA $DD0F; STOP TIMER B (KEEP SIGNALLING AT PB7!)
STA $DD0D; ENABLE FLAG (AND TIMER) INTERRUPTS
LDA #<UP9600.NMIDOBIT; ON NEXT NMI CALL NMIDOBIT
STA UP9600.NMIVECT; (TRIGGERED BY A STARTBIT)
LDA #>UP9600.NMIDOBIT
STA UP9600.NMIVECT+1
TXA
PHA
TYA
PHA
LDA $DD0C; READ SDR (BIT0=DATABIT7,...,BIT7=DATABIT0)
CMP #128; MOVE BIT7 INTO CARRY-FLAG
AND #127
TAX
LDA UP9600.REVTAB,X; READ DATABITS 1-7 FROM LOOKUP TABLE
ADC #0; ADD DATABIT0
LDY UP9600.WRRPTR; AND WRITE IT INTO THE RECEIVE BUFFER
STA (UP9600.RECPTR),Y
INY
STY UP9600.WRRPTR
SEC;;START BUFFER FULL CHK
TYA
SBC UP9600.RDRPTR
CMP #200
BCC UP9600.NMIBYTR2
LDA $DD01;; MORE THAN 200 BYTES IN THE RECEIVE BUFFER
AND #$FD;; THEN DISABLE RTS
STA $DD01
UP9600.NMIBYTR2
PLA
TAY
PLA
TAX
PLA
RTI
; *******************************************************
; IRQ PART
UP9600.NEWIRQ
LDA $DC0D
UP9600.NEWIRQ1
LSR; READ IRQ-MASK
LSR; MOVE BIT1 INTO CARRY-FLAG (TIMER B - FLAG)
AND #$02; TEST BIT3 (SDR - FLAG)
BEQ UP9600.NEWIRQ3; SDR NOT EMPTY, THEN SKIP THE FIRST PART
LDX UP9600.OUTSTAT
BEQ UP9600.NEWIRQ2; SKIP, IF WE'RE NOT WAITING FOR AN EMPTY SDR
DEX
STX UP9600.OUTSTAT
UP9600.NEWIRQ2
;BCC UP9600.NEWIRQ6
bcs UP9600.NEWIRQ3
jmp UP9600.NEWIRQ6
UP9600.NEWIRQ3
CLI
JSR $FFEA
LDA $CC
;BNE UP9600.NEWIRQ5
beq UP9600.NEWIRQ3_1
jmp UP9600.NEWIRQ5
UP9600.NEWIRQ3_1
DEC $CD
;BNE UP9600.NEWIRQ5
beq UP9600.NEWIRQ3_2
jmp UP9600.NEWIRQ5
UP9600.NEWIRQ3_2
LDA #$14
STA $CD
LDY $D3
LSR $CF
LDX $0287
LDA ($D1),Y
BCS UP9600.NEWIRQ4
INC $CF
STA $CE
JSR $EA24
LDA ($F3),Y
STA $0287
LDX $0286
LDA $CE
UP9600.NEWIRQ4
EOR #$80
JSR $EA1C
UP9600.NEWIRQ5
JSR $EA87
UP9600.NEWIRQ6
JMP $EA81
; *******************************
; GET BYTE FROM SERIAL INTERFACE
UP9600.RSIN
LDY UP9600.RDRPTR
CPY UP9600.WRRPTR
BEQ UP9600.RSIN3; SKIP (EMPTY BUFFER, RETURN WITH CARRY SET)
LDA (UP9600.RECPTR),Y
INY
STY UP9600.RDRPTR
PHA;;BEGIN BUFFER EMPTYING CHK
TYA
SEC
SBC UP9600.WRRPTR
CMP #206;;256-50
BCC UP9600.RSIN2
LDA #2
ORA $DD01
STA $DD01;; ENABLE RTS
CLC
UP9600.RSIN2
PLA
UP9600.RSIN3
RTS
; ******************************
; PUT BYTE TO SERIAL INTERFACE
UP9600.RSOUT
PHA
STA $9E
CMP #$80
AND #$7F
STX $A8
STY $A7
TAX
JSR UP9600.RSOUTX
UP9600.RSOUT3
LDA UP9600.REVTAB,X
ADC #$00
LSR
SEI
STA $DC0C
LDA #$02
STA UP9600.OUTSTAT
ROR
ORA #$7F
STA $DC0C
CLI
LDX $A8
LDY $A7
PLA
RTS
UP9600.RSOUTX
CLI
LDA #$FD
STA $A2
UP9600.RSOUTX2
LDA UP9600.OUTSTAT
BEQ UP9600.RSOUTX3
BIT $A2
BMI UP9600.RSOUTX2
UP9600.RSOUTX3
JMP $F490
; ******************************
; INSTALL (AND PROBE FOR) SERIAL INTERFACE
; RETURN WITH CARRY SET IF THERE WAS AN ERROR
UP9600.INSTERR
CLI
SEC
RTS
UP9600.INSTALL
SEI
LDA UP9600.IRQVECT
CMP #<UP9600.ORIGIRQ
BNE UP9600.INSTERR; IRQ-VECTOR ALREADY CHANGED
LDA UP9600.IRQVECT+1
CMP #>UP9600.ORIGIRQ
BNE UP9600.INSTERR; IRQ-VECTOR ALREADY CHANGED
LDA UP9600.NMIVECT
CMP #<UP9600.ORIGNMI
BNE UP9600.INSTERR; NMI-VECTOR ALREADY CHANGED
LDA UP9600.NMIVECT+1
CMP #>UP9600.ORIGNMI
BNE UP9600.INSTERR; NMI-VECTOR ALREADY CHANGED
LDY #0
STY UP9600.WRSPTR
STY UP9600.RDSPTR
STY UP9600.WRRPTR
STY UP9600.RDRPTR
; PROBE FOR RS232 INTERFACE
CLI
LDA #$7F
STA $DD0D; DISABLE ALL NMIS
LDA #$80
STA $DD03; PB7 USED AS OUTPUT
STA $DD0E; STOP TIMERA
STA $DD0F; STOP TIMERB
BIT $DD0D; CLEAR PENDING INTERRUPTS
LDX #8
UP9600.INSTALL2
STX $DD01; TOGGLE TXD
STA $DD01; AND LOOK IF IT TRIGGERS AN
DEX; SHIFT-REGISTER INTERRUPT
BNE UP9600.INSTALL2
LDA $DD0D; CHECK FOR BIT3 (SDR-FLAG)
AND #8
BEQ UP9600.INSTERR; NO INTERFACE DETECTED
; GENERATE LOOKUP TABLE
LDX #0
UP9600.INSTALL3
STX UP9600.OUTSTAT; OUTSTAT USED AS TEMPORARY VARIABLE
LDY #8
UP9600.INSTALL4
ASL UP9600.OUTSTAT
ROR
DEY
BNE UP9600.INSTALL4
STA UP9600.REVTAB,X
INX
BPL UP9600.INSTALL3
; ******************************
; ENABLE SERIAL INTERFACE (IRQ+NMI)
UP9600.ENABLE
PHA
TXA
PHA
TYA
PHA
LDA UP9600.IRQVECT
CMP #<UP9600.NEWIRQ
;BNE UP9600.ENABL2
beq UP9600.ENABLE_1
jmp UP9600.ENABL2
nop
nop
nop
nop
UP9600.ENABLE_1
LDA UP9600.IRQVECT+1
CMP #>UP9600.NEWIRQ
;BNE UP9600.ENABL2
beq UP9600.ENABLE_2
jmp UP9600.ENABL2
UP9600.ENABLE_2
PLA
TAY
PLA
TAX
PLA
RTS
UP9600.ENABL2
SEI
LDX #<UP9600.NEWIRQ; INSTALL NEW IRQ-HANDLER
LDY #>UP9600.NEWIRQ
STX UP9600.IRQVECT
STY UP9600.IRQVECT+1
LDX #<UP9600.NMIDOBIT; INSTALL NEW NMI-HANDLER
LDY #>UP9600.NMIDOBIT
STX UP9600.NMIVECT
STY UP9600.NMIVECT+1
LDX $2A6; PAL OR NTSC VERSION PRINT
LDA UP9600.ILOTAB,X; (KEYSCAN INTERRUPT ONCE EVERY 1/64 SECOND)
STA $DC06; (SORRY THIS WILL BREAK CODE, THAT USES
LDA UP9600.IHITAB,X; THE TI$ - VARIABLE)
STA $DC07; START VALUE FOR TIMER B (OF CIA1)
TXA
ASL
EOR #$33; ** TIME CONSTANT FOR SENDER **
LDX #0; 51 OR 55 DEPENDING ON PAL/NTSC VERSION
STA $DC04; START VALUE FOR TIMERA (OF CIA1)
STX $DC05; (TIME IS AROUND 1/(2*BAUDRATE) )
ASL; ** TIME CONSTANT FOR RECEIVER **
ORA #1; 103 OR 111 DEPENDING ON PAL/NTSC VERSION
STA $DD06; START VALUE FOR TIMERB (OF CIA2)
STX $DD07; (TIME IS AROUND 1/BAUDRATE )
LDA #$41; START TIMERA OF CIA1, SP1 USED AS OUTPUT
STA $DC0E; GENERATES THE SENDER'S BIT CLOCK
LDA #1
STA UP9600.OUTSTAT
STA $DC0D; DISABLE TIMERA (CIA1) INTERRUPT
STA $DC0F; START TIMERB OF CIA1 (GENERATES KEYSCAN IRQ)
LDA #$92; STOP TIMERB OF CIA2 (ENABLE SIGNAL AT PB7)
STA $DD0F
LDA #$98
BIT $DD0D; CLEAR PENDING NMIS
STA $DD0D; ENABLE NMI (SDR AND FLAG) (CIA2)
LDA #$8A
STA $DC0D; ENABLE IRQ (TIMERB AND SDR) (CIA1)
LDA #$FF
STA $DD01; PB0-7 DEFAULT TO 1
STA $DC0C; SP1 DEFAULTS TO 1
SEC
LDA UP9600.WRRPTR
SBC UP9600.RDRPTR
CMP #200
BCS UP9600.ENABLE2;; DON'T ENABLE RTS IF REC-BUFFER IS FULL
LDA #2;; ENABLE RTS
STA $DD03;; (THE RTS LINE IS THE ONLY OUTPUT)
UP9600.ENABLE2
CLI
PLA
TAY
PLA
TAX
PLA
RTS
; TABLE OF TIMER VALUES FOR PAL AND NTSC VERSION
UP9600.ILOTAB
BYTE 149,37
;
UP9600.IHITAB
BYTE 66,64
; *******************************************************
; DISABLE SERIAL INTERFACE
UP9600.DISABLE
PHA
TXA
PHA
TYA
PHA
LDA UP9600.IRQVECT
CMP #<UP9600.NEWIRQ
BNE UP9600.NODIS
LDA UP9600.IRQVECT+1
CMP #>UP9600.NEWIRQ
BEQ UP9600.DISABL2
UP9600.NODIS
PLA
TAY
PLA
TAX
PLA
RTS
UP9600.DISABL2
SEI
LDA $DD01; DISABLE RTS
AND #$FD
STA $DD01
LDA #$7F
STA $DD0D; DISABLE ALL CIA INTERRUPTS
STA $DC0D
LDA #$41; QUICK (AND DIRTY) HACK TO SWITCH BACK
STA $DC05; TO THE DEFAULT CIA1 CONFIGURATION
LDA #$81
STA $DC0D; ENABLE TIMER1 (THIS IS DEFAULT)
LDA #<UP9600.ORIGIRQ; RESTORE OLD IRQ-HANDLER
STA UP9600.IRQVECT
LDA #>UP9600.ORIGIRQ
STA UP9600.IRQVECT+1
LDA #<UP9600.ORIGNMI; RESTORE OLD NMI-HANDLER
STA UP9600.NMIVECT
LDA #>UP9600.ORIGNMI
STA UP9600.NMIVECT+1
CLI
PLA
TAY
PLA
TAX
PLA
RTS
;
;
UP9600.REVTAB
; .BUF 128
UP9600.PRINT
NOP; :F$="UP9600.BAS":OPEN1,8,15,"S0:UP9600*":CLOSE1:SAVEF$,8
|
; ==================================================================
; MichalOS Icons
; ==================================================================
bomblogo db 9, 16
db 00000000b, 00000000b, 00000000b, 00000000b, 00000000b, 00100000b, 00000000b, 01100000b, 00000000b
db 00000000b, 00000000b, 00000000b, 00000000b, 00000100b, 00000010b, 00000001b, 10000000b, 00000000b
db 00000000b, 00000000b, 00000000b, 00000000b, 00000000b, 10000100b, 10000000b, 00000000b, 00000000b
db 00000000b, 00000000b, 00000000b, 01101010b, 10100101b, 00000001b, 01010000b, 10001000b, 10000000b
db 00000000b, 00000000b, 00000011b, 00000000b, 00000000b, 10101000b, 00000000b, 01000000b, 00000000b
db 00000000b, 00000000b, 01010111b, 01010100b, 00000000b, 00011000b, 00100000b, 00100100b, 00000000b
db 00000000b, 00000000b, 11111111b, 11111100b, 00000000b, 10000000b, 00100000b, 00000010b, 00000000b
db 00000000b, 01011111b, 11111111b, 11111111b, 11010100b, 00000000b, 00100000b, 00000000b, 00000000b
db 00000001b, 11111111b, 11111111b, 11111111b, 11111101b, 00000000b, 00000000b, 00000000b, 00000000b
db 00000111b, 11111111b, 11111111b, 11111111b, 11111111b, 01000000b, 00000000b, 00000000b, 00000000b
db 00001111b, 11111111b, 11111111b, 11111111b, 11111111b, 11000000b, 00000000b, 00000000b, 00000000b
db 00001111b, 11111111b, 11111111b, 11111111b, 11111111b, 11000000b, 00000000b, 00000000b, 00000000b
db 00001111b, 11111111b, 11111111b, 11111111b, 11111111b, 11000000b, 00000000b, 00000000b, 00000000b
db 00000011b, 11111111b, 11111111b, 11111111b, 11111111b, 00000000b, 00000000b, 00000000b, 00000000b
db 00000000b, 11111111b, 11111111b, 11111111b, 11111100b, 00000000b, 00000000b, 00000000b, 00000000b
db 00000000b, 00001010b, 11111111b, 11111110b, 10000000b, 00000000b, 00000000b, 00000000b, 00000000b
filelogo db 4, 8
db 00001110b, 10101010b, 11010000b, 00000000b
db 00001100b, 00000000b, 11001001b, 00000000b
db 00001100b, 00000000b, 10101010b, 11000000b
db 00001100b, 00000000b, 00000000b, 11000000b
db 00001100b, 00000000b, 00000000b, 11000000b
db 00001100b, 00000000b, 00000000b, 11000000b
db 00001100b, 00000000b, 00000000b, 11000000b
db 00001101b, 01010101b, 01010101b, 11000000b
logo db 18, 7
db 00000000b, 00000000b, 00001110b, 11101010b, 10101010b, 10101100b, 01000000b, 00000100b, 00000000b, 00000000b, 01000000b, 00000000b, 00000000b, 00010011b, 11101010b, 10111111b, 10101010b, 10110000b
db 00000000b, 00000000b, 00001100b, 11101010b, 10101010b, 11101100b, 11100100b, 01101100b, 00000000b, 00000000b, 11000000b, 00000000b, 00000000b, 00110011b, 00111111b, 11001100b, 11111111b, 11110000b
db 00000000b, 00000000b, 00001100b, 11000000b, 00000000b, 11001100b, 11000010b, 00001100b, 10000000b, 00000000b, 11000000b, 00000000b, 00000000b, 00110011b, 00111111b, 11001100b, 11111111b, 11110000b
db 00000000b, 00000000b, 00001100b, 11000000b, 00000000b, 11001100b, 11000000b, 00001100b, 11000110b, 10101000b, 11011010b, 10010010b, 10101001b, 00110011b, 00111111b, 11001111b, 01010101b, 10110000b
db 00000000b, 00000000b, 00001100b, 11000000b, 00000000b, 11001100b, 11000000b, 00001100b, 11001100b, 00000000b, 11000000b, 00110001b, 10101011b, 00110011b, 00111111b, 11001111b, 11111111b, 00110000b
db 00000000b, 00000000b, 00001110b, 10101010b, 10101010b, 11001100b, 11000000b, 00001100b, 11001001b, 01010100b, 11000000b, 00110010b, 01010110b, 00110011b, 01101010b, 10011110b, 10101010b, 01110000b
db 00000000b, 00000000b, 00001010b, 10101010b, 10101010b, 10101000b, 00000000b, 00000000b, 00000000b, 00000000b, 00000000b, 00000000b, 00000000b, 00000010b, 10101010b, 10101010b, 10101010b, 10100000b
|
; A197354: a(n) = Sum_{k>=0} A030308(n,k)*(2k+1).
; Submitted by Jamie Morken(s3)
; 0,1,3,4,5,6,8,9,7,8,10,11,12,13,15,16,9,10,12,13,14,15,17,18,16,17,19,20,21,22,24,25,11,12,14,15,16,17,19,20,18,19,21,22,23,24,26,27,20,21,23,24,25,26,28,29,27,28,30,31,32,33,35,36,13,14,16,17,18,19,21,22,20,21,23,24,25,26,28,29,22,23,25,26,27,28,30,31,29,30,32,33,34,35,37,38,24,25,27,28
mov $2,1
lpb $0
mov $3,$0
div $0,2
mod $3,2
mul $3,$2
add $1,$3
add $2,2
lpe
mov $0,$1
|
drawIntroFrame:
push es
push 0xb800
pop es
; Increase the frame tick counter to make the intro run faster
mov byte [frameTickCounter], 5
; Check if message is already fully displayed
cmp si, messageLength
jae .end
mov di, si
imul di, 2
mov byte al, [si+message]
mov byte [es:di], al
mov byte [es:di+1], 0xf0
inc si
mov [frameIndex], si
.end:
pop es
ret
|
/*
grabber.cpp
Screen grabber
*/
/*
Copyright © 1996 Eugene Roshal
Copyright © 2000 Far Group
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. The name of the authors may not be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
IN NO EVENT SHALL THE AUTHOR 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.
*/
// BUGBUG
#include "platform.headers.hpp"
// Self:
#include "grabber.hpp"
// Internal:
#include "keyboard.hpp"
#include "keys.hpp"
#include "savescr.hpp"
#include "ctrlobj.hpp"
#include "manager.hpp"
#include "interf.hpp"
#include "clipboard.hpp"
#include "config.hpp"
#include "help.hpp"
#include "string_utils.hpp"
#include "global.hpp"
#include "colormix.hpp"
#include "eol.hpp"
// Platform:
// Common:
#include "common/string_utils.hpp"
// External:
//----------------------------------------------------------------------------
Grabber::Grabber(private_tag)
{
ScreenObject::SetPosition({ 0, 0, ScrX, ScrY });
}
grabber_ptr Grabber::create()
{
auto GrabberPtr = std::make_shared<Grabber>(private_tag());
GrabberPtr->init();
return GrabberPtr;
}
void Grabber::init()
{
SetMacroMode(MACROAREA_GRABBER);
SaveScr = std::make_unique<SaveScreen>();
bool Visible=false;
size_t Size = 0;
GetCursorType(Visible,Size);
if (Visible)
GArea.Current = GetCursorPos();
else
GArea.Current = {};
GArea.Begin.x = -1;
Process();
SaveScr.reset();
Global->WindowManager->RefreshWindow();
}
std::tuple<point&, point&> Grabber::GetSelection()
{
auto& SelectionBegin = GArea.Begin.y == GArea.End.y?
GArea.Begin.x < GArea.End.x? GArea.Begin : GArea.End :
GArea.Begin.y < GArea.End.y? GArea.Begin : GArea.End;
auto& SelectionEnd = &SelectionBegin == &GArea.Begin? GArea.End : GArea.Begin;
return std::tie(SelectionBegin, SelectionEnd);
}
void Grabber::CopyGrabbedArea(bool Append, bool VerticalBlock)
{
if (GArea.Begin.x < 0)
return;
const auto X1 = std::min(GArea.Begin.x, GArea.End.x);
const auto X2 = std::max(GArea.Begin.x, GArea.End.x);
const auto Y1 = std::min(GArea.Begin.y, GArea.End.y);
const auto Y2 = std::max(GArea.Begin.y, GArea.End.y);
auto FromX = X1;
auto ToX = X2;
const auto FromY = Y1;
const auto ToY = Y2;
if (m_StreamSelection)
{
FromX = 0;
ToX = ScrX;
}
matrix<FAR_CHAR_INFO> CharBuf(ToY - FromY + 1, ToX - FromX + 1);
GetText({ FromX, FromY, ToX, ToY }, CharBuf);
string CopyBuf;
CopyBuf.reserve(CharBuf.height() * (CharBuf.width() + 2));
string Line;
Line.reserve(CharBuf.width());
const auto& [SelectionBegin, SelectionEnd] = GetSelection();
const auto Eol = eol::system.str();
for (size_t i = 0; i != CharBuf.height(); ++i)
{
const auto& MatrixLine = CharBuf[i];
auto Begin = MatrixLine.cbegin(), End = MatrixLine.cend();
const auto IsFirstLine = i == 0;
const auto IsLastLine = i == CharBuf.height() - 1;
if (m_StreamSelection)
{
Begin += IsFirstLine? SelectionBegin.x : 0;
End -= IsLastLine? ScrX - SelectionEnd.x : 0;
}
Line.clear();
std::transform(Begin, End, std::back_inserter(Line), [](const FAR_CHAR_INFO& Char) { return Char.Char; });
bool AddEol = !IsLastLine;
if (m_StreamSelection)
{
// in stream mode we want to preserve existing line breaks,
// but at the same time join lines that were split because of the text wrapping.
// The Windows console doesn't keep EOL characters at all, so we will try to guess.
// If the line ends with an alphanumeric character, it's probably has been wrapped.
// TODO: consider analysing the beginning of the next line too.
AddEol = !is_alphanumeric(Line.back());
}
else
{
inplace::trim_right(Line);
}
CopyBuf += Line;
if (AddEol)
{
CopyBuf += Eol;
}
}
clipboard_accessor Clip;
if (Clip->Open())
{
if (Append)
{
string OldData;
if (Clip->GetText(OldData))
{
if (!OldData.empty() && OldData.back() != L'\n')
{
OldData += Eol;
}
CopyBuf.insert(0, OldData);
}
}
if (VerticalBlock)
Clip->SetVText(CopyBuf);
else
Clip->SetText(CopyBuf);
}
}
void Grabber::DisplayObject()
{
MoveCursor({ GArea.Current.x, GArea.Current.y });
const auto X1 = std::min(GArea.Begin.x, GArea.End.x);
const auto X2 = std::max(GArea.Begin.x, GArea.End.x);
const auto Y1 = std::min(GArea.Begin.y, GArea.End.y);
const auto Y2 = std::max(GArea.Begin.y, GArea.End.y);
m_StreamSelection.forget();
if (GArea.Begin.x != -1)
{
auto FromX = X1;
auto ToX = X2;
const auto FromY = Y1;
const auto ToY = Y2;
if (m_StreamSelection)
{
FromX = 0;
ToX = ScrX;
}
matrix<FAR_CHAR_INFO> CharBuf(ToY - FromY + 1, ToX - FromX + 1);
GetText({ FromX, FromY, ToX, ToY }, CharBuf);
for (int Y = FromY; Y <= ToY; Y++)
{
for (int X = FromX; X <= ToX; X++)
{
const auto& CurColor = SaveScr->ScreenBuf[Y][X].Attributes;
auto& Destination = CharBuf[Y - Y1][X - FromX].Attributes;
Destination = CurColor;
if (m_StreamSelection)
{
const auto ToUp = GArea.Begin.y < GArea.End.y;
const auto ToDown = !ToUp;
const auto FirstLine = Y == FromY;
const auto LastLine = Y == ToY;
if (ToDown)
{
if (FirstLine && LastLine)
{
if (X < X1 || X > X2)
{
continue;
}
}
else if ((FirstLine && X < GArea.End.x) || (LastLine && X > GArea.Begin.x))
continue;
}
else
{
if ((FirstLine && X < GArea.Begin.x) || (LastLine && X > GArea.End.x))
continue;
}
}
Destination.BackgroundColor = colors::alpha_value(CurColor.BackgroundColor) | (
CurColor.IsBg4Bit()?
colors::index_value(~colors::index_value(CurColor.BackgroundColor)) :
colors::color_value(~colors::color_value(CurColor.BackgroundColor))
);
Destination.ForegroundColor = colors::alpha_value(CurColor.ForegroundColor) | (
CurColor.IsFg4Bit()?
colors::index_value(~colors::index_value(CurColor.ForegroundColor)) :
colors::color_value(~colors::color_value(CurColor.ForegroundColor))
);
}
}
PutText({ FromX, FromY, ToX, ToY }, CharBuf.data());
}
SetCursorType(true, 60);
}
bool Grabber::ProcessKey(const Manager::Key& Key)
{
auto LocalKey = Key();
if(Global->CloseFAR)
{
LocalKey = KEY_ESC;
}
/* $ 14.03.2001 SVS
[-] Неправильно воспроизводился макрос в режиме грабления экрана.
При воспроизведении клавиша Home перемещала курсор в координаты
0,0 консоли.
Не было учтено режима выполнения макроса.
*/
if (Global->CtrlObject->Macro.IsExecuting())
{
if ((LocalKey&KEY_SHIFT) && LocalKey!=KEY_NONE && ResetArea)
Reset();
else if (none_of(LocalKey, KEY_IDLE, KEY_NONE) && !(LocalKey&KEY_SHIFT) && !IntKeyState.ShiftPressed() && !IntKeyState.AltPressed())
ResetArea = true;
}
else
{
if ((IntKeyState.ShiftPressed() || LocalKey!=KEY_SHIFT) && (LocalKey&KEY_SHIFT) && none_of(LocalKey, KEY_NONE, KEY_CTRLA, KEY_RCTRLA) && !IntKeyState.AltPressed() && ResetArea)
Reset();
else if (none_of(LocalKey, KEY_IDLE, KEY_NONE, KEY_SHIFT, KEY_CTRLA, KEY_RCTRLA, KEY_F1, KEY_SPACE) && !IntKeyState.ShiftPressed() && !IntKeyState.AltPressed() && !(LocalKey&KEY_SHIFT))
ResetArea = true;
}
const auto Move = [](point& What, int Count, int Direction, int LimitX, int LimitY, int NewX)
{
for (; Count; --Count)
{
if (What.x != LimitX)
{
What.x += Direction;
}
else if (m_StreamSelection)
{
if (What.y != LimitY)
{
What.y += Direction;
What.x = NewX;
}
else
{
return false;
}
}
else
{
return false;
}
}
return true;
};
const auto MovePointLeft = [&](point& What, int Count)
{
return Move(What, Count, -1, 0, 0, ScrX);
};
const auto MovePointRight = [&](point& What, int Count)
{
return Move(What, Count, 1, ScrX, ScrY, 0);
};
const auto MoveLeft = [&](int Count)
{
return MovePointLeft(GArea.Current, Count);
};
const auto MoveRight = [&](int Count)
{
return MovePointRight(GArea.Current, Count);
};
switch (LocalKey)
{
case KEY_F1:
help::show(L"Grabber"sv);
break;
case KEY_CTRLU:
case KEY_RCTRLU:
Reset();
GArea.Begin.x = -1;
break;
case KEY_ESC:
case KEY_F10:
Close(0);
break;
case KEY_SPACE:
m_StreamSelection = !m_StreamSelection;
break;
case KEY_NUMENTER:
case KEY_ENTER:
case KEY_CTRLINS: case KEY_CTRLNUMPAD0:
case KEY_RCTRLINS: case KEY_RCTRLNUMPAD0:
case KEY_CTRLADD:
case KEY_RCTRLADD:
CopyGrabbedArea(any_of(LocalKey, KEY_CTRLADD, KEY_RCTRLADD), m_VerticalBlock);
Close(1);
break;
case KEY_LEFT: case KEY_NUMPAD4: case L'4':
MoveLeft(1);
break;
case KEY_RIGHT: case KEY_NUMPAD6: case L'6':
MoveRight(1);
break;
case KEY_UP: case KEY_NUMPAD8: case L'8':
if (GArea.Current.y > 0)
--GArea.Current.y;
break;
case KEY_DOWN: case KEY_NUMPAD2: case L'2':
if (GArea.Current.y < ScrY)
++GArea.Current.y;
break;
case KEY_HOME: case KEY_NUMPAD7: case L'7':
GArea.Current.x = 0;
break;
case KEY_END: case KEY_NUMPAD1: case L'1':
GArea.Current.x = ScrX;
break;
case KEY_PGUP: case KEY_NUMPAD9: case L'9':
GArea.Current.y = 0;
break;
case KEY_PGDN: case KEY_NUMPAD3: case L'3':
GArea.Current.y = ScrY;
break;
case KEY_CTRLHOME: case KEY_CTRLNUMPAD7:
case KEY_RCTRLHOME: case KEY_RCTRLNUMPAD7:
GArea.Current = {};
break;
case KEY_CTRLEND: case KEY_CTRLNUMPAD1:
case KEY_RCTRLEND: case KEY_RCTRLNUMPAD1:
GArea.Current = { ScrX, ScrY };
break;
case KEY_CTRLLEFT: case KEY_CTRLNUMPAD4:
case KEY_RCTRLLEFT: case KEY_RCTRLNUMPAD4:
case KEY_CTRLSHIFTLEFT: case KEY_CTRLSHIFTNUMPAD4:
case KEY_RCTRLSHIFTLEFT: case KEY_RCTRLSHIFTNUMPAD4:
MoveLeft(10);
if (any_of(LocalKey, KEY_CTRLSHIFTLEFT, KEY_RCTRLSHIFTLEFT, KEY_CTRLSHIFTNUMPAD4, KEY_RCTRLSHIFTNUMPAD4))
{
GArea.Begin = GArea.Current;
}
break;
case KEY_CTRLRIGHT: case KEY_CTRLNUMPAD6:
case KEY_RCTRLRIGHT: case KEY_RCTRLNUMPAD6:
case KEY_CTRLSHIFTRIGHT: case KEY_CTRLSHIFTNUMPAD6:
case KEY_RCTRLSHIFTRIGHT: case KEY_RCTRLSHIFTNUMPAD6:
MoveRight(10);
if (any_of(LocalKey, KEY_CTRLSHIFTRIGHT, KEY_RCTRLSHIFTRIGHT, KEY_CTRLSHIFTNUMPAD6, KEY_RCTRLSHIFTNUMPAD6))
{
GArea.Begin = GArea.Current;
}
break;
case KEY_CTRLUP: case KEY_CTRLNUMPAD8:
case KEY_RCTRLUP: case KEY_RCTRLNUMPAD8:
case KEY_CTRLSHIFTUP: case KEY_CTRLSHIFTNUMPAD8:
case KEY_RCTRLSHIFTUP: case KEY_RCTRLSHIFTNUMPAD8:
GArea.Current.y = std::max(GArea.Current.y - 5, 0);
if (any_of(LocalKey, KEY_CTRLSHIFTUP, KEY_RCTRLSHIFTUP, KEY_CTRLSHIFTNUMPAD8, KEY_RCTRLSHIFTNUMPAD8))
GArea.Begin.y = GArea.Current.y;
break;
case KEY_CTRLDOWN: case KEY_CTRLNUMPAD2:
case KEY_RCTRLDOWN: case KEY_RCTRLNUMPAD2:
case KEY_CTRLSHIFTDOWN: case KEY_CTRLSHIFTNUMPAD2:
case KEY_RCTRLSHIFTDOWN: case KEY_RCTRLSHIFTNUMPAD2:
GArea.Current.y = std::min(static_cast<int>(ScrY), GArea.Current.y + 5);
if (any_of(LocalKey, KEY_CTRLSHIFTDOWN, KEY_RCTRLSHIFTDOWN, KEY_CTRLSHIFTNUMPAD2, KEY_RCTRLSHIFTNUMPAD2))
GArea.Begin.y = GArea.Current.y;
break;
case KEY_SHIFTLEFT: case KEY_SHIFTNUMPAD4:
MoveLeft(1);
GArea.Begin = GArea.Current;
break;
case KEY_SHIFTRIGHT: case KEY_SHIFTNUMPAD6:
MoveRight(1);
GArea.Begin = GArea.Current;
break;
case KEY_SHIFTUP: case KEY_SHIFTNUMPAD8:
if (GArea.Begin.y > 0)
--GArea.Begin.y;
GArea.Current = GArea.Begin;
break;
case KEY_SHIFTDOWN: case KEY_SHIFTNUMPAD2:
if (GArea.Begin.y < ScrY)
++GArea.Begin.y;
GArea.Current = GArea.Begin;
break;
case KEY_SHIFTHOME: case KEY_SHIFTNUMPAD7:
GArea.Current.x = GArea.Begin.x = 0;
break;
case KEY_SHIFTEND: case KEY_SHIFTNUMPAD1:
GArea.Current.x = GArea.Begin.x = ScrX;
break;
case KEY_SHIFTPGUP: case KEY_SHIFTNUMPAD9:
GArea.Current.y = GArea.Begin.y = 0;
break;
case KEY_SHIFTPGDN: case KEY_SHIFTNUMPAD3:
GArea.Current.y = GArea.Begin.y = ScrY;
break;
case KEY_ALTSHIFTHOME: case KEY_ALTSHIFTNUMPAD7:
case KEY_RALTSHIFTHOME: case KEY_RALTSHIFTNUMPAD7:
GArea.End.x = 0;
break;
case KEY_ALTSHIFTEND: case KEY_ALTSHIFTNUMPAD1:
case KEY_RALTSHIFTEND: case KEY_RALTSHIFTNUMPAD1:
GArea.End.x = ScrX;
break;
case KEY_ALTSHIFTPGUP: case KEY_ALTSHIFTNUMPAD9:
case KEY_RALTSHIFTPGUP: case KEY_RALTSHIFTNUMPAD9:
GArea.End.y = 0;
break;
case KEY_ALTSHIFTPGDN: case KEY_ALTSHIFTNUMPAD3:
case KEY_RALTSHIFTPGDN: case KEY_RALTSHIFTNUMPAD3:
GArea.End.y = ScrY;
break;
case KEY_ALTSHIFTLEFT: case KEY_ALTSHIFTNUMPAD4:
case KEY_RALTSHIFTLEFT: case KEY_RALTSHIFTNUMPAD4:
MovePointLeft(GArea.End, 1);
break;
case KEY_ALTSHIFTRIGHT: case KEY_ALTSHIFTNUMPAD6:
case KEY_RALTSHIFTRIGHT: case KEY_RALTSHIFTNUMPAD6:
MovePointRight(GArea.End, 1);
break;
case KEY_ALTSHIFTUP: case KEY_ALTSHIFTNUMPAD8:
case KEY_RALTSHIFTUP: case KEY_RALTSHIFTNUMPAD8:
if (GArea.End.y > 0)
--GArea.End.y;
break;
case KEY_ALTSHIFTDOWN: case KEY_ALTSHIFTNUMPAD2:
case KEY_RALTSHIFTDOWN: case KEY_RALTSHIFTNUMPAD2:
if (GArea.End.y < ScrY)
++GArea.End.y;
break;
case KEY_CTRLA:
case KEY_RCTRLA:
GArea.Begin.x = ScrX;
GArea.Begin.y = ScrY;
GArea.End.x = 0;
GArea.End.y = 0;
GArea.Current = GArea.Begin;
break;
case KEY_ALTLEFT:
case KEY_RALTLEFT:
{
const auto& [SelectionBegin, SelectionEnd] = GetSelection();
if (MovePointLeft(SelectionBegin, 1))
{
MovePointLeft(SelectionEnd, 1);
GArea.Current = GArea.Begin;
}
}
break;
case KEY_ALTRIGHT:
case KEY_RALTRIGHT:
{
const auto& [SelectionBegin, SelectionEnd] = GetSelection();
if (MovePointRight(SelectionEnd, 1))
{
MovePointRight(SelectionBegin, 1);
GArea.Current = GArea.Begin;
}
}
break;
case KEY_ALTUP:
case KEY_RALTUP:
if (GArea.Begin.y && GArea.End.y)
{
--GArea.Begin.y;
--GArea.End.y;
GArea.Current = GArea.Begin;
}
break;
case KEY_ALTDOWN:
case KEY_RALTDOWN:
if (GArea.Begin.y < ScrY && GArea.End.y < ScrY)
{
++GArea.Begin.y;
++GArea.End.y;
GArea.Current = GArea.Begin;
}
break;
case KEY_ALTHOME:
case KEY_RALTHOME:
GArea.Begin.x = GArea.Current.x = abs(GArea.Begin.x - GArea.End.x);
GArea.End.x = 0;
break;
case KEY_ALTEND:
case KEY_RALTEND:
GArea.End.x = ScrX - abs(GArea.Begin.x - GArea.End.x);
GArea.Begin.x = GArea.Current.x = ScrX;
break;
case KEY_ALTPGUP:
case KEY_RALTPGUP:
GArea.Begin.y = GArea.Current.y = abs(GArea.Begin.y - GArea.End.y);
GArea.End.y = 0;
break;
case KEY_ALTPGDN:
case KEY_RALTPGDN:
GArea.End.y = ScrY - abs(GArea.Begin.y - GArea.End.y);
GArea.Begin.y = GArea.Current.y = ScrY;
break;
}
Global->WindowManager->RefreshWindow();
return true;
}
bool Grabber::ProcessMouse(const MOUSE_EVENT_RECORD *MouseEvent)
{
if (MouseEvent->dwEventFlags==DOUBLE_CLICK ||
(!MouseEvent->dwEventFlags && (MouseEvent->dwButtonState & RIGHTMOST_BUTTON_PRESSED)))
{
ProcessKey(Manager::Key(KEY_ENTER));
return true;
}
if (IntKeyState.MouseButtonState!=FROM_LEFT_1ST_BUTTON_PRESSED)
return false;
if (!MouseEvent->dwEventFlags)
{
ResetArea = true;
}
else if (MouseEvent->dwEventFlags == MOUSE_MOVED && ResetArea)
{
GArea.End = GArea.Current;
ResetArea = false;
}
GArea.Current.x = std::clamp(IntKeyState.MousePos.x, 0, int(ScrX));
GArea.Current.y = std::clamp(IntKeyState.MousePos.y, 0, int(ScrY));
if (MouseEvent->dwEventFlags == MOUSE_MOVED)
{
GArea.Begin = GArea.Current;
}
Global->WindowManager->RefreshWindow();
return true;
}
void Grabber::Reset()
{
GArea.Begin = GArea.End = GArea.Current;
ResetArea = false;
}
void Grabber::ResizeConsole()
{
Close(0);
}
bool RunGraber()
{
static bool InGrabber=false;
if (!InGrabber)
{
InGrabber=true;
FlushInputBuffer();
Grabber::create();
InGrabber=false;
return true;
}
return false;
}
|
; A161370: a(n) = 2*A010844(n) + 1.
; 3,7,27,159,1267,12663,151947,2127247,34035939,612646887,12252937723,269564629887,6469551117267,168208329048919,4709833213369707,141294996401091183,4521439884834917827,153728956084387206087
mul $0,2
mov $2,$0
lpb $0
sub $0,2
add $1,$2
mul $2,$0
lpe
mul $1,2
add $1,3
mov $0,$1
|
@256
D=A
@SP
M=D
@5
D=A
@R13
M=D
@Sys.init
D=A
@R14
M=D
@Sys.init$ret0
D=A
@VM$CALL
0;JMP
(Sys.init$ret0)
(VM$STOP)
@VM$STOP
0;JMP
(VM$CALL)
@SP
AM=M+1
A=A-1
M=D
@LCL
D=M
@SP
AM=M+1
A=A-1
M=D
@ARG
D=M
@SP
AM=M+1
A=A-1
M=D
@THIS
D=M
@SP
AM=M+1
A=A-1
M=D
@THAT
D=M
@SP
AM=M+1
A=A-1
M=D
@R13
D=M
@SP
D=M-D
@ARG
M=D
@R14
A=M
0;JMP
(VM$RETURN)
@5
D=A
@LCL
A=M-D
D=M
@R13
M=D
@SP
AM=M-1
D=M
@ARG
A=M
M=D
D=A
@SP
M=D+1
@LCL
D=M
@R14
AM=D-1
D=M
@THAT
M=D
@R14
AM=M-1
D=M
@THIS
M=D
@R14
AM=M-1
D=M
@ARG
M=D
@R14
AM=M-1
D=M
@LCL
M=D
@R13
A=M
0;JMP
// function Main.fibonacci 0
(Main.fibonacci)
@SP
D=M
@LCL
M=D
// push argument 0
@ARG
A=M
D=M
@SP
AM=M+1
A=A-1
M=D
// push constant 2
@2
D=A
@SP
AM=M+1
A=A-1
M=D
// lt
@SP
AM=M-1
D=M
@SP
AM=M-1
D=M-D
@Main.JLT_true1
D;JLT
@Main.JLT_false2
D=0;JMP
(Main.JLT_true1)
D=-1
(Main.JLT_false2)
@SP
AM=M+1
A=A-1
M=D
// if-goto IF_TRUE
@SP
AM=M-1
D=M
@Main.fibonacci$IF_TRUE
D;JNE
// goto IF_FALSE
@Main.fibonacci$IF_FALSE
0;JMP
// label IF_TRUE
(Main.fibonacci$IF_TRUE)
// push argument 0
@ARG
A=M
D=M
@SP
AM=M+1
A=A-1
M=D
// return
@VM$RETURN
0;JMP
// label IF_FALSE
(Main.fibonacci$IF_FALSE)
// push argument 0
@ARG
A=M
D=M
@SP
AM=M+1
A=A-1
M=D
// push constant 2
@2
D=A
@SP
AM=M+1
A=A-1
M=D
// sub
@SP
AM=M-1
D=M
@SP
A=M-1
M=M-D
// call Main.fibonacci 1
@6
D=A
@R13
M=D
@Main.fibonacci
D=A
@R14
M=D
@Main.fibonacci$ret3
D=A
@VM$CALL
0;JMP
(Main.fibonacci$ret3)
// push argument 0
@ARG
A=M
D=M
@SP
AM=M+1
A=A-1
M=D
// push constant 1
@1
D=A
@SP
AM=M+1
A=A-1
M=D
// sub
@SP
AM=M-1
D=M
@SP
A=M-1
M=M-D
// call Main.fibonacci 1
@6
D=A
@R13
M=D
@Main.fibonacci
D=A
@R14
M=D
@Main.fibonacci$ret4
D=A
@VM$CALL
0;JMP
(Main.fibonacci$ret4)
// add
@SP
AM=M-1
D=M
@SP
A=M-1
M=D+M
// return
@VM$RETURN
0;JMP
// function Sys.init 0
(Sys.init)
@SP
D=M
@LCL
M=D
// push constant 4
@4
D=A
@SP
AM=M+1
A=A-1
M=D
// call Main.fibonacci 1
@6
D=A
@R13
M=D
@Main.fibonacci
D=A
@R14
M=D
@Main.fibonacci$ret5
D=A
@VM$CALL
0;JMP
(Main.fibonacci$ret5)
// label WHILE
(Sys.init$WHILE)
// goto WHILE
@Sys.init$WHILE
0;JMP |
.global s_prepare_buffers
s_prepare_buffers:
push %r12
push %r13
push %rax
push %rbx
push %rcx
push %rdi
push %rdx
push %rsi
lea addresses_WT_ht+0x3f93, %rsi
lea addresses_WC_ht+0x993f, %rdi
clflush (%rdi)
nop
nop
nop
add %r12, %r12
mov $5, %rcx
rep movsw
nop
nop
xor %rbx, %rbx
lea addresses_UC_ht+0xf87b, %rsi
lea addresses_normal_ht+0x1eedf, %rdi
nop
nop
nop
nop
sub $7556, %r13
mov $31, %rcx
rep movsw
nop
nop
dec %r12
lea addresses_A_ht+0x58df, %rsi
lea addresses_D_ht+0x1c05f, %rdi
dec %rax
mov $48, %rcx
rep movsw
nop
nop
nop
and %rcx, %rcx
lea addresses_WT_ht+0x15edf, %rdi
nop
nop
xor $43758, %r12
movw $0x6162, (%rdi)
nop
nop
nop
cmp %rsi, %rsi
lea addresses_UC_ht+0x1d6df, %rsi
lea addresses_D_ht+0x55bf, %rdi
clflush (%rdi)
nop
nop
add %rdx, %rdx
mov $39, %rcx
rep movsl
nop
nop
nop
add %rdi, %rdi
lea addresses_A_ht+0xb9ff, %rdi
nop
dec %rbx
movups (%rdi), %xmm6
vpextrq $0, %xmm6, %r13
xor %r13, %r13
lea addresses_UC_ht+0xacdf, %rsi
lea addresses_D_ht+0x1eedf, %rdi
nop
nop
and %rax, %rax
mov $56, %rcx
rep movsq
nop
nop
nop
cmp %r13, %r13
lea addresses_WC_ht+0x1279f, %rsi
lea addresses_A_ht+0xa6df, %rdi
nop
nop
nop
add %rax, %rax
mov $107, %rcx
rep movsb
nop
nop
nop
nop
add $11718, %r13
lea addresses_UC_ht+0x18b50, %rsi
lea addresses_A_ht+0x1b0df, %rdi
nop
nop
nop
mfence
mov $77, %rcx
rep movsw
nop
nop
add $38312, %r13
lea addresses_WC_ht+0x5a3f, %rsi
nop
nop
nop
nop
and %r12, %r12
and $0xffffffffffffffc0, %rsi
vmovntdqa (%rsi), %ymm3
vextracti128 $1, %ymm3, %xmm3
vpextrq $1, %xmm3, %rdx
nop
nop
nop
and %rdi, %rdi
lea addresses_A_ht+0x16df, %rbx
nop
nop
nop
nop
sub $21189, %rdx
movl $0x61626364, (%rbx)
nop
nop
xor $31967, %r13
pop %rsi
pop %rdx
pop %rdi
pop %rcx
pop %rbx
pop %rax
pop %r13
pop %r12
ret
.global s_faulty_load
s_faulty_load:
push %r11
push %r12
push %r8
push %r9
push %rax
push %rdx
push %rsi
// Load
lea addresses_WT+0x86df, %r9
nop
inc %r12
mov (%r9), %eax
nop
nop
and $29768, %rax
// Faulty Load
mov $0x3638e700000006df, %r8
nop
nop
nop
nop
nop
sub $65413, %rsi
vmovups (%r8), %ymm4
vextracti128 $0, %ymm4, %xmm4
vpextrq $1, %xmm4, %r11
lea oracles, %rax
and $0xff, %r11
shlq $12, %r11
mov (%rax,%r11,1), %r11
pop %rsi
pop %rdx
pop %rax
pop %r9
pop %r8
pop %r12
pop %r11
ret
/*
<gen_faulty_load>
[REF]
{'src': {'NT': False, 'AVXalign': False, 'size': 1, 'congruent': 0, 'same': False, 'type': 'addresses_NC'}, 'OP': 'LOAD'}
{'src': {'NT': False, 'AVXalign': False, 'size': 4, 'congruent': 9, 'same': False, 'type': 'addresses_WT'}, 'OP': 'LOAD'}
[Faulty Load]
{'src': {'NT': False, 'AVXalign': False, 'size': 32, 'congruent': 0, 'same': True, 'type': 'addresses_NC'}, 'OP': 'LOAD'}
<gen_prepare_buffer>
{'src': {'congruent': 1, 'same': False, 'type': 'addresses_WT_ht'}, 'dst': {'congruent': 1, 'same': False, 'type': 'addresses_WC_ht'}, 'OP': 'REPM'}
{'src': {'congruent': 1, 'same': False, 'type': 'addresses_UC_ht'}, 'dst': {'congruent': 10, 'same': False, 'type': 'addresses_normal_ht'}, 'OP': 'REPM'}
{'src': {'congruent': 8, 'same': False, 'type': 'addresses_A_ht'}, 'dst': {'congruent': 1, 'same': False, 'type': 'addresses_D_ht'}, 'OP': 'REPM'}
{'dst': {'NT': False, 'AVXalign': False, 'size': 2, 'congruent': 11, 'same': False, 'type': 'addresses_WT_ht'}, 'OP': 'STOR'}
{'src': {'congruent': 10, 'same': False, 'type': 'addresses_UC_ht'}, 'dst': {'congruent': 4, 'same': False, 'type': 'addresses_D_ht'}, 'OP': 'REPM'}
{'src': {'NT': False, 'AVXalign': False, 'size': 16, 'congruent': 5, 'same': False, 'type': 'addresses_A_ht'}, 'OP': 'LOAD'}
{'src': {'congruent': 9, 'same': False, 'type': 'addresses_UC_ht'}, 'dst': {'congruent': 8, 'same': True, 'type': 'addresses_D_ht'}, 'OP': 'REPM'}
{'src': {'congruent': 6, 'same': False, 'type': 'addresses_WC_ht'}, 'dst': {'congruent': 10, 'same': True, 'type': 'addresses_A_ht'}, 'OP': 'REPM'}
{'src': {'congruent': 0, 'same': True, 'type': 'addresses_UC_ht'}, 'dst': {'congruent': 8, 'same': False, 'type': 'addresses_A_ht'}, 'OP': 'REPM'}
{'src': {'NT': True, 'AVXalign': False, 'size': 32, 'congruent': 5, 'same': False, 'type': 'addresses_WC_ht'}, 'OP': 'LOAD'}
{'dst': {'NT': False, 'AVXalign': False, 'size': 4, 'congruent': 9, 'same': False, 'type': 'addresses_A_ht'}, 'OP': 'STOR'}
{'00': 15094, '45': 2844, '48': 3823, '49': 68}
00 00 48 00 00 00 48 00 00 00 00 00 00 48 00 00 00 00 00 00 00 00 00 00 48 00 45 00 48 00 00 00 00 00 45 00 45 48 00 48 00 48 00 48 00 00 00 00 45 00 00 00 00 48 00 00 48 00 00 00 00 00 00 45 00 45 00 00 48 00 45 00 48 00 00 00 00 00 00 00 48 48 00 45 48 00 48 00 00 00 00 00 00 00 45 00 00 48 00 00 00 48 00 48 00 48 00 00 00 00 00 48 00 00 48 00 00 48 00 00 00 00 45 48 00 00 00 48 00 00 00 00 48 00 00 00 00 48 48 48 00 00 00 45 48 00 45 48 00 45 45 00 00 45 45 00 48 45 00 48 48 00 00 00 48 00 00 00 45 00 00 00 00 00 48 00 00 48 00 45 00 48 00 00 00 00 45 45 48 00 00 00 45 00 48 00 00 48 00 48 00 00 45 00 00 00 00 00 00 45 00 00 00 45 45 48 00 00 00 48 00 00 00 45 00 48 00 00 45 00 48 00 00 00 00 00 00 48 00 45 48 00 00 00 00 45 00 45 48 48 00 48 00 00 48 00 45 48 00 00 00 00 00 00 00 45 00 00 00 45 00 00 00 48 00 00 00 00 00 00 00 00 00 00 48 00 00 00 48 00 48 00 00 00 00 00 45 00 00 00 00 00 00 00 00 00 00 00 48 00 00 45 00 45 48 45 00 00 00 48 00 48 45 48 00 00 00 00 45 00 00 00 48 00 48 00 00 00 45 45 45 00 00 00 00 48 00 00 00 45 00 00 00 00 00 00 48 00 00 00 00 48 00 00 00 00 00 00 00 48 00 00 48 00 00 00 48 00 48 00 00 00 00 00 45 45 00 00 00 00 00 00 00 45 48 00 00 00 48 00 45 00 00 00 00 00 00 00 48 45 45 00 00 00 00 00 00 48 00 00 00 00 00 00 00 45 49 48 00 00 00 00 45 00 45 48 00 45 00 00 00 00 00 00 48 00 00 00 00 00 00 00 00 00 00 48 45 48 00 00 00 00 00 00 00 00 00 00 48 00 48 00 00 00 48 00 00 00 45 48 00 45 00 00 48 00 00 00 00 00 48 00 00 48 48 49 48 00 00 00 48 00 00 00 00 48 48 45 00 00 00 00 00 00 45 00 48 00 00 00 00 00 48 00 00 00 00 00 00 00 00 00 00 48 00 45 00 00 00 00 00 48 00 00 00 00 00 00 48 00 48 45 45 45 45 00 00 00 00 00 00 00 00 48 00 00 00 00 00 00 00 00 00 45 48 00 00 00 45 00 00 00 00 00 00 00 48 00 00 48 48 00 00 45 00 48 00 00 00 00 48 00 48 00 00 45 00 00 00 45 00 48 00 00 00 45 48 00 00 00 00 48 00 45 00 48 00 00 00 00 00 00 00 48 00 00 00 48 00 00 00 00 00 00 00 48 00 48 00 00 48 00 00 00 45 48 00 00 48 00 00 00 00 00 48 00 00 00 00 00 48 00 00 00 00 00 00 00 48 00 00 00 00 48 00 00 48 45 00 00 00 48 00 00 48 00 45 00 00 00 00 00 00 00 00 48 00 00 00 48 00 00 45 00 48 00 00 00 00 00 48 45 48 00 00 00 48 00 00 00 00 00 00 45 00 00 00 48 00 00 00 48 48 45 00 00 45 45 48 48 00 45 48 00 00 48 00 00 00 00 45 00 00 00 00 48 00 45 00 49 00 00 00 00 00 00 45 48 00 45 48 00 48 00 00 00 00 00 00 00 48 00 00 00 00 00 00 48 00 00 00 48 45 00 00 00 00 00 48 00 00 00 00 00 00 00 45 00 45 00 00 00 48 00 00 00 00 48 00 00 00 00 00 48 00 00 00 48 00 00 00 00 00 48 00 48 00 00 00 48 48 00 00 00 48 00 00 00 00 00 45 45 00 00 00 48 45 48 00 00 00 48 48 00 00 00 00 00 00 00 45 48 00 00 00 48 00 00 00 00 00 00 48 00 00 00 48 00 00 00 48 00 00 00 00 00 00 00 00 45 00 00 00 45 00 45 48 00 00 00 00 48 00 00 48 00 00 00 00 45 45 48 00 00 48 00 00 00 00 00 48 00 48 00 45 00 00 00 00 00 00 45 00 00 00 48 00 00 00 00 00 00 00 48 00 00 00 48 00 00 00 00 45 00 00 00 00 00 00 48 00 00 00 00 45 00 00 48 00 48 00 00 00 00 45 00 00 00 45 48
*/
|
#Input: tre valori interi, due indirizzi del segmento testo
#Output: nessuno
#$a0, $a1, $a2 <- 3 interi
#$s3 primo addr stack secondo addr
.data
.text
.globl branch3equal
branch3equal:
add $t0 $0 $0
add $v0 $0 $0
bne $a0 $a1 second
addi $t0 $t0 1
second: bne $a0 $a2 third
addi $t0 $t0 1
third: bne $a1 $a2 exit_2
addi $t0 $t0 1
bne $t0 3 end
move $v0 $a3
j end
exit_2: addi $sp $sp 4
lw $v0 0($sp)
end: jr $ra
|
.global s_prepare_buffers
s_prepare_buffers:
push %r12
push %r14
push %r15
push %r8
push %rbx
push %rcx
push %rdi
push %rsi
lea addresses_A_ht+0x6924, %rsi
clflush (%rsi)
nop
nop
nop
nop
nop
and %r15, %r15
mov $0x6162636465666768, %r14
movq %r14, %xmm1
movups %xmm1, (%rsi)
xor $28849, %rdi
lea addresses_D_ht+0x14e90, %rsi
lea addresses_UC_ht+0x199f6, %rdi
nop
sub $50662, %r8
mov $75, %rcx
rep movsb
nop
and $57634, %r8
lea addresses_WC_ht+0x60a4, %rdi
nop
nop
nop
nop
xor %r12, %r12
vmovups (%rdi), %ymm4
vextracti128 $1, %ymm4, %xmm4
vpextrq $0, %xmm4, %r15
nop
nop
nop
sub $62826, %r14
lea addresses_UC_ht+0x5a24, %rsi
nop
nop
sub $22825, %r12
movb $0x61, (%rsi)
nop
nop
nop
cmp $45511, %r12
lea addresses_UC_ht+0x1148, %rsi
lea addresses_UC_ht+0x1daa4, %rdi
nop
nop
nop
nop
nop
lfence
mov $117, %rcx
rep movsb
nop
nop
nop
and $18002, %rsi
lea addresses_normal_ht+0x82a4, %rdi
nop
nop
xor $53078, %r12
movl $0x61626364, (%rdi)
nop
nop
nop
and $45418, %r8
lea addresses_normal_ht+0x504, %r8
nop
nop
nop
nop
and $32711, %rcx
mov (%r8), %bx
nop
nop
dec %rbx
lea addresses_WT_ht+0x909c, %r15
sub %r14, %r14
mov $0x6162636465666768, %rsi
movq %rsi, (%r15)
nop
nop
nop
nop
nop
inc %rbx
lea addresses_UC_ht+0x7930, %rcx
nop
nop
nop
nop
add %r12, %r12
movl $0x61626364, (%rcx)
nop
nop
nop
nop
sub %r14, %r14
lea addresses_WT_ht+0x19aa4, %r14
clflush (%r14)
nop
xor %rdi, %rdi
mov (%r14), %r12w
nop
nop
nop
dec %r8
lea addresses_D_ht+0x6ea4, %rsi
dec %rbx
mov $0x6162636465666768, %r12
movq %r12, %xmm3
movups %xmm3, (%rsi)
nop
cmp %r12, %r12
pop %rsi
pop %rdi
pop %rcx
pop %rbx
pop %r8
pop %r15
pop %r14
pop %r12
ret
.global s_faulty_load
s_faulty_load:
push %r10
push %r11
push %r12
push %r8
push %rcx
push %rdi
// Store
lea addresses_RW+0x14ed4, %r10
nop
nop
nop
nop
nop
sub %rdi, %rdi
mov $0x5152535455565758, %r12
movq %r12, %xmm6
movups %xmm6, (%r10)
nop
inc %rcx
// Faulty Load
lea addresses_A+0x8aa4, %r8
nop
cmp %r11, %r11
movb (%r8), %r10b
lea oracles, %r11
and $0xff, %r10
shlq $12, %r10
mov (%r11,%r10,1), %r10
pop %rdi
pop %rcx
pop %r8
pop %r12
pop %r11
pop %r10
ret
/*
<gen_faulty_load>
[REF]
{'src': {'same': False, 'congruent': 0, 'NT': False, 'type': 'addresses_A', 'size': 4, 'AVXalign': False}, 'OP': 'LOAD'}
{'OP': 'STOR', 'dst': {'same': False, 'congruent': 2, 'NT': False, 'type': 'addresses_RW', 'size': 16, 'AVXalign': False}}
[Faulty Load]
{'src': {'same': True, 'congruent': 0, 'NT': False, 'type': 'addresses_A', 'size': 1, 'AVXalign': False}, 'OP': 'LOAD'}
<gen_prepare_buffer>
{'OP': 'STOR', 'dst': {'same': True, 'congruent': 7, 'NT': False, 'type': 'addresses_A_ht', 'size': 16, 'AVXalign': False}}
{'src': {'type': 'addresses_D_ht', 'congruent': 1, 'same': False}, 'OP': 'REPM', 'dst': {'type': 'addresses_UC_ht', 'congruent': 1, 'same': False}}
{'src': {'same': False, 'congruent': 8, 'NT': False, 'type': 'addresses_WC_ht', 'size': 32, 'AVXalign': False}, 'OP': 'LOAD'}
{'OP': 'STOR', 'dst': {'same': False, 'congruent': 7, 'NT': True, 'type': 'addresses_UC_ht', 'size': 1, 'AVXalign': False}}
{'src': {'type': 'addresses_UC_ht', 'congruent': 2, 'same': False}, 'OP': 'REPM', 'dst': {'type': 'addresses_UC_ht', 'congruent': 11, 'same': False}}
{'OP': 'STOR', 'dst': {'same': False, 'congruent': 10, 'NT': False, 'type': 'addresses_normal_ht', 'size': 4, 'AVXalign': False}}
{'src': {'same': False, 'congruent': 5, 'NT': True, 'type': 'addresses_normal_ht', 'size': 2, 'AVXalign': False}, 'OP': 'LOAD'}
{'OP': 'STOR', 'dst': {'same': False, 'congruent': 3, 'NT': False, 'type': 'addresses_WT_ht', 'size': 8, 'AVXalign': False}}
{'OP': 'STOR', 'dst': {'same': False, 'congruent': 1, 'NT': False, 'type': 'addresses_UC_ht', 'size': 4, 'AVXalign': False}}
{'src': {'same': False, 'congruent': 10, 'NT': False, 'type': 'addresses_WT_ht', 'size': 2, 'AVXalign': False}, 'OP': 'LOAD'}
{'OP': 'STOR', 'dst': {'same': False, 'congruent': 9, 'NT': False, 'type': 'addresses_D_ht', 'size': 16, 'AVXalign': False}}
{'00': 21829}
00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
*/
|
//===- Pass.cpp - Pass infrastructure implementation ----------------------===//
//
// 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
//
//===----------------------------------------------------------------------===//
//
// This file implements common pass infrastructure.
//
//===----------------------------------------------------------------------===//
#include "mlir/Pass/Pass.h"
#include "PassDetail.h"
#include "mlir/IR/Diagnostics.h"
#include "mlir/IR/Dialect.h"
#include "mlir/IR/Threading.h"
#include "mlir/IR/Verifier.h"
#include "mlir/Support/FileUtilities.h"
#include "llvm/ADT/STLExtras.h"
#include "llvm/ADT/ScopeExit.h"
#include "llvm/ADT/SetVector.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/Support/CrashRecoveryContext.h"
#include "llvm/Support/Mutex.h"
#include "llvm/Support/Signals.h"
#include "llvm/Support/Threading.h"
#include "llvm/Support/ToolOutputFile.h"
using namespace mlir;
using namespace mlir::detail;
//===----------------------------------------------------------------------===//
// Pass
//===----------------------------------------------------------------------===//
/// Out of line virtual method to ensure vtables and metadata are emitted to a
/// single .o file.
void Pass::anchor() {}
/// Attempt to initialize the options of this pass from the given string.
LogicalResult Pass::initializeOptions(StringRef options) {
return passOptions.parseFromString(options);
}
/// Copy the option values from 'other', which is another instance of this
/// pass.
void Pass::copyOptionValuesFrom(const Pass *other) {
passOptions.copyOptionValuesFrom(other->passOptions);
}
/// Prints out the pass in the textual representation of pipelines. If this is
/// an adaptor pass, print with the op_name(sub_pass,...) format.
void Pass::printAsTextualPipeline(raw_ostream &os) {
// Special case for adaptors to use the 'op_name(sub_passes)' format.
if (auto *adaptor = dyn_cast<OpToOpPassAdaptor>(this)) {
llvm::interleaveComma(adaptor->getPassManagers(), os,
[&](OpPassManager &pm) {
os << pm.getOpName() << "(";
pm.printAsTextualPipeline(os);
os << ")";
});
return;
}
// Otherwise, print the pass argument followed by its options. If the pass
// doesn't have an argument, print the name of the pass to give some indicator
// of what pass was run.
StringRef argument = getArgument();
if (!argument.empty())
os << argument;
else
os << "unknown<" << getName() << ">";
passOptions.print(os);
}
//===----------------------------------------------------------------------===//
// OpPassManagerImpl
//===----------------------------------------------------------------------===//
namespace mlir {
namespace detail {
struct OpPassManagerImpl {
OpPassManagerImpl(StringAttr identifier, OpPassManager::Nesting nesting)
: name(identifier.str()), identifier(identifier),
initializationGeneration(0), nesting(nesting) {}
OpPassManagerImpl(StringRef name, OpPassManager::Nesting nesting)
: name(name), initializationGeneration(0), nesting(nesting) {}
/// Merge the passes of this pass manager into the one provided.
void mergeInto(OpPassManagerImpl &rhs);
/// Nest a new operation pass manager for the given operation kind under this
/// pass manager.
OpPassManager &nest(StringAttr nestedName);
OpPassManager &nest(StringRef nestedName);
/// Add the given pass to this pass manager. If this pass has a concrete
/// operation type, it must be the same type as this pass manager.
void addPass(std::unique_ptr<Pass> pass);
/// Clear the list of passes in this pass manager, other options are
/// preserved.
void clear();
/// Coalesce adjacent AdaptorPasses into one large adaptor. This runs
/// recursively through the pipeline graph.
void coalesceAdjacentAdaptorPasses();
/// Return the operation name of this pass manager as an identifier.
StringAttr getOpName(MLIRContext &context) {
if (!identifier)
identifier = StringAttr::get(name, &context);
return *identifier;
}
/// The name of the operation that passes of this pass manager operate on.
std::string name;
/// The cached identifier (internalized in the context) for the name of the
/// operation that passes of this pass manager operate on.
Optional<StringAttr> identifier;
/// The set of passes to run as part of this pass manager.
std::vector<std::unique_ptr<Pass>> passes;
/// The current initialization generation of this pass manager. This is used
/// to indicate when a pass manager should be reinitialized.
unsigned initializationGeneration;
/// Control the implicit nesting of passes that mismatch the name set for this
/// OpPassManager.
OpPassManager::Nesting nesting;
};
} // namespace detail
} // namespace mlir
void OpPassManagerImpl::mergeInto(OpPassManagerImpl &rhs) {
assert(name == rhs.name && "merging unrelated pass managers");
for (auto &pass : passes)
rhs.passes.push_back(std::move(pass));
passes.clear();
}
OpPassManager &OpPassManagerImpl::nest(StringAttr nestedName) {
OpPassManager nested(nestedName, nesting);
auto *adaptor = new OpToOpPassAdaptor(std::move(nested));
addPass(std::unique_ptr<Pass>(adaptor));
return adaptor->getPassManagers().front();
}
OpPassManager &OpPassManagerImpl::nest(StringRef nestedName) {
OpPassManager nested(nestedName, nesting);
auto *adaptor = new OpToOpPassAdaptor(std::move(nested));
addPass(std::unique_ptr<Pass>(adaptor));
return adaptor->getPassManagers().front();
}
void OpPassManagerImpl::addPass(std::unique_ptr<Pass> pass) {
// If this pass runs on a different operation than this pass manager, then
// implicitly nest a pass manager for this operation if enabled.
auto passOpName = pass->getOpName();
if (passOpName && passOpName->str() != name) {
if (nesting == OpPassManager::Nesting::Implicit)
return nest(*passOpName).addPass(std::move(pass));
llvm::report_fatal_error(llvm::Twine("Can't add pass '") + pass->getName() +
"' restricted to '" + *passOpName +
"' on a PassManager intended to run on '" + name +
"', did you intend to nest?");
}
passes.emplace_back(std::move(pass));
}
void OpPassManagerImpl::clear() { passes.clear(); }
void OpPassManagerImpl::coalesceAdjacentAdaptorPasses() {
// Bail out early if there are no adaptor passes.
if (llvm::none_of(passes, [](std::unique_ptr<Pass> &pass) {
return isa<OpToOpPassAdaptor>(pass.get());
}))
return;
// Walk the pass list and merge adjacent adaptors.
OpToOpPassAdaptor *lastAdaptor = nullptr;
for (auto &passe : passes) {
// Check to see if this pass is an adaptor.
if (auto *currentAdaptor = dyn_cast<OpToOpPassAdaptor>(passe.get())) {
// If it is the first adaptor in a possible chain, remember it and
// continue.
if (!lastAdaptor) {
lastAdaptor = currentAdaptor;
continue;
}
// Otherwise, merge into the existing adaptor and delete the current one.
currentAdaptor->mergeInto(*lastAdaptor);
passe.reset();
} else if (lastAdaptor) {
// If this pass is not an adaptor, then coalesce and forget any existing
// adaptor.
for (auto &pm : lastAdaptor->getPassManagers())
pm.getImpl().coalesceAdjacentAdaptorPasses();
lastAdaptor = nullptr;
}
}
// If there was an adaptor at the end of the manager, coalesce it as well.
if (lastAdaptor) {
for (auto &pm : lastAdaptor->getPassManagers())
pm.getImpl().coalesceAdjacentAdaptorPasses();
}
// Now that the adaptors have been merged, erase the empty slot corresponding
// to the merged adaptors that were nulled-out in the loop above.
llvm::erase_if(passes, std::logical_not<std::unique_ptr<Pass>>());
}
//===----------------------------------------------------------------------===//
// OpPassManager
//===----------------------------------------------------------------------===//
OpPassManager::OpPassManager(StringAttr name, Nesting nesting)
: impl(new OpPassManagerImpl(name, nesting)) {}
OpPassManager::OpPassManager(StringRef name, Nesting nesting)
: impl(new OpPassManagerImpl(name, nesting)) {}
OpPassManager::OpPassManager(OpPassManager &&rhs) : impl(std::move(rhs.impl)) {}
OpPassManager::OpPassManager(const OpPassManager &rhs) { *this = rhs; }
OpPassManager &OpPassManager::operator=(const OpPassManager &rhs) {
impl = std::make_unique<OpPassManagerImpl>(rhs.impl->name, rhs.impl->nesting);
impl->initializationGeneration = rhs.impl->initializationGeneration;
for (auto &pass : rhs.impl->passes) {
auto newPass = pass->clone();
newPass->threadingSibling = pass.get();
impl->passes.push_back(std::move(newPass));
}
return *this;
}
OpPassManager::~OpPassManager() = default;
OpPassManager::pass_iterator OpPassManager::begin() {
return MutableArrayRef<std::unique_ptr<Pass>>{impl->passes}.begin();
}
OpPassManager::pass_iterator OpPassManager::end() {
return MutableArrayRef<std::unique_ptr<Pass>>{impl->passes}.end();
}
OpPassManager::const_pass_iterator OpPassManager::begin() const {
return ArrayRef<std::unique_ptr<Pass>>{impl->passes}.begin();
}
OpPassManager::const_pass_iterator OpPassManager::end() const {
return ArrayRef<std::unique_ptr<Pass>>{impl->passes}.end();
}
/// Nest a new operation pass manager for the given operation kind under this
/// pass manager.
OpPassManager &OpPassManager::nest(StringAttr nestedName) {
return impl->nest(nestedName);
}
OpPassManager &OpPassManager::nest(StringRef nestedName) {
return impl->nest(nestedName);
}
/// Add the given pass to this pass manager. If this pass has a concrete
/// operation type, it must be the same type as this pass manager.
void OpPassManager::addPass(std::unique_ptr<Pass> pass) {
impl->addPass(std::move(pass));
}
void OpPassManager::clear() { impl->clear(); }
/// Returns the number of passes held by this manager.
size_t OpPassManager::size() const { return impl->passes.size(); }
/// Returns the internal implementation instance.
OpPassManagerImpl &OpPassManager::getImpl() { return *impl; }
/// Return the operation name that this pass manager operates on.
StringRef OpPassManager::getOpName() const { return impl->name; }
/// Return the operation name that this pass manager operates on.
StringAttr OpPassManager::getOpName(MLIRContext &context) const {
return impl->getOpName(context);
}
/// Prints out the given passes as the textual representation of a pipeline.
static void printAsTextualPipeline(ArrayRef<std::unique_ptr<Pass>> passes,
raw_ostream &os) {
llvm::interleaveComma(passes, os, [&](const std::unique_ptr<Pass> &pass) {
pass->printAsTextualPipeline(os);
});
}
/// Prints out the passes of the pass manager as the textual representation
/// of pipelines.
void OpPassManager::printAsTextualPipeline(raw_ostream &os) {
::printAsTextualPipeline(impl->passes, os);
}
void OpPassManager::dump() {
llvm::errs() << "Pass Manager with " << impl->passes.size() << " passes: ";
::printAsTextualPipeline(impl->passes, llvm::errs());
llvm::errs() << "\n";
}
static void registerDialectsForPipeline(const OpPassManager &pm,
DialectRegistry &dialects) {
for (const Pass &pass : pm.getPasses())
pass.getDependentDialects(dialects);
}
void OpPassManager::getDependentDialects(DialectRegistry &dialects) const {
registerDialectsForPipeline(*this, dialects);
}
void OpPassManager::setNesting(Nesting nesting) { impl->nesting = nesting; }
OpPassManager::Nesting OpPassManager::getNesting() { return impl->nesting; }
LogicalResult OpPassManager::initialize(MLIRContext *context,
unsigned newInitGeneration) {
if (impl->initializationGeneration == newInitGeneration)
return success();
impl->initializationGeneration = newInitGeneration;
for (Pass &pass : getPasses()) {
// If this pass isn't an adaptor, directly initialize it.
auto *adaptor = dyn_cast<OpToOpPassAdaptor>(&pass);
if (!adaptor) {
if (failed(pass.initialize(context)))
return failure();
continue;
}
// Otherwise, initialize each of the adaptors pass managers.
for (OpPassManager &adaptorPM : adaptor->getPassManagers())
if (failed(adaptorPM.initialize(context, newInitGeneration)))
return failure();
}
return success();
}
//===----------------------------------------------------------------------===//
// OpToOpPassAdaptor
//===----------------------------------------------------------------------===//
LogicalResult OpToOpPassAdaptor::run(Pass *pass, Operation *op,
AnalysisManager am, bool verifyPasses,
unsigned parentInitGeneration) {
if (!op->isRegistered())
return op->emitOpError()
<< "trying to schedule a pass on an unregistered operation";
if (!op->hasTrait<OpTrait::IsIsolatedFromAbove>())
return op->emitOpError() << "trying to schedule a pass on an operation not "
"marked as 'IsolatedFromAbove'";
// Initialize the pass state with a callback for the pass to dynamically
// execute a pipeline on the currently visited operation.
PassInstrumentor *pi = am.getPassInstrumentor();
PassInstrumentation::PipelineParentInfo parentInfo = {llvm::get_threadid(),
pass};
auto dynamicPipelineCallback = [&](OpPassManager &pipeline,
Operation *root) -> LogicalResult {
if (!op->isAncestor(root))
return root->emitOpError()
<< "Trying to schedule a dynamic pipeline on an "
"operation that isn't "
"nested under the current operation the pass is processing";
assert(pipeline.getOpName() == root->getName().getStringRef());
// Before running, make sure to coalesce any adjacent pass adaptors in the
// pipeline.
pipeline.getImpl().coalesceAdjacentAdaptorPasses();
// Initialize the user provided pipeline and execute the pipeline.
if (failed(pipeline.initialize(root->getContext(), parentInitGeneration)))
return failure();
AnalysisManager nestedAm = root == op ? am : am.nest(root);
return OpToOpPassAdaptor::runPipeline(pipeline.getPasses(), root, nestedAm,
verifyPasses, parentInitGeneration,
pi, &parentInfo);
};
pass->passState.emplace(op, am, dynamicPipelineCallback);
// Instrument before the pass has run.
if (pi)
pi->runBeforePass(pass, op);
// Invoke the virtual runOnOperation method.
if (auto *adaptor = dyn_cast<OpToOpPassAdaptor>(pass))
adaptor->runOnOperation(verifyPasses);
else
pass->runOnOperation();
bool passFailed = pass->passState->irAndPassFailed.getInt();
// Invalidate any non preserved analyses.
am.invalidate(pass->passState->preservedAnalyses);
// When verifyPasses is specified, we run the verifier (unless the pass
// failed).
if (!passFailed && verifyPasses) {
bool runVerifierNow = true;
// Reduce compile time by avoiding running the verifier if the pass didn't
// change the IR since the last time the verifier was run:
//
// 1) If the pass said that it preserved all analyses then it can't have
// permuted the IR.
// 2) If we just ran an OpToOpPassAdaptor (e.g. to run function passes
// within a module) then each sub-unit will have been verified on the
// subunit (and those passes aren't allowed to modify the parent).
//
// We run these checks in EXPENSIVE_CHECKS mode out of caution.
#ifndef EXPENSIVE_CHECKS
runVerifierNow = !isa<OpToOpPassAdaptor>(pass) &&
!pass->passState->preservedAnalyses.isAll();
#endif
if (runVerifierNow)
passFailed = failed(verify(op));
}
// Instrument after the pass has run.
if (pi) {
if (passFailed)
pi->runAfterPassFailed(pass, op);
else
pi->runAfterPass(pass, op);
}
// Return if the pass signaled a failure.
return failure(passFailed);
}
/// Run the given operation and analysis manager on a provided op pass manager.
LogicalResult OpToOpPassAdaptor::runPipeline(
iterator_range<OpPassManager::pass_iterator> passes, Operation *op,
AnalysisManager am, bool verifyPasses, unsigned parentInitGeneration,
PassInstrumentor *instrumentor,
const PassInstrumentation::PipelineParentInfo *parentInfo) {
assert((!instrumentor || parentInfo) &&
"expected parent info if instrumentor is provided");
auto scopeExit = llvm::make_scope_exit([&] {
// Clear out any computed operation analyses. These analyses won't be used
// any more in this pipeline, and this helps reduce the current working set
// of memory. If preserving these analyses becomes important in the future
// we can re-evaluate this.
am.clear();
});
// Run the pipeline over the provided operation.
if (instrumentor)
instrumentor->runBeforePipeline(op->getName().getIdentifier(), *parentInfo);
for (Pass &pass : passes)
if (failed(run(&pass, op, am, verifyPasses, parentInitGeneration)))
return failure();
if (instrumentor)
instrumentor->runAfterPipeline(op->getName().getIdentifier(), *parentInfo);
return success();
}
/// Find an operation pass manager that can operate on an operation of the given
/// type, or nullptr if one does not exist.
static OpPassManager *findPassManagerFor(MutableArrayRef<OpPassManager> mgrs,
StringRef name) {
auto *it = llvm::find_if(
mgrs, [&](OpPassManager &mgr) { return mgr.getOpName() == name; });
return it == mgrs.end() ? nullptr : &*it;
}
/// Find an operation pass manager that can operate on an operation of the given
/// type, or nullptr if one does not exist.
static OpPassManager *findPassManagerFor(MutableArrayRef<OpPassManager> mgrs,
StringAttr name,
MLIRContext &context) {
auto *it = llvm::find_if(
mgrs, [&](OpPassManager &mgr) { return mgr.getOpName(context) == name; });
return it == mgrs.end() ? nullptr : &*it;
}
OpToOpPassAdaptor::OpToOpPassAdaptor(OpPassManager &&mgr) {
mgrs.emplace_back(std::move(mgr));
}
void OpToOpPassAdaptor::getDependentDialects(DialectRegistry &dialects) const {
for (auto &pm : mgrs)
pm.getDependentDialects(dialects);
}
/// Merge the current pass adaptor into given 'rhs'.
void OpToOpPassAdaptor::mergeInto(OpToOpPassAdaptor &rhs) {
for (auto &pm : mgrs) {
// If an existing pass manager exists, then merge the given pass manager
// into it.
if (auto *existingPM = findPassManagerFor(rhs.mgrs, pm.getOpName())) {
pm.getImpl().mergeInto(existingPM->getImpl());
} else {
// Otherwise, add the given pass manager to the list.
rhs.mgrs.emplace_back(std::move(pm));
}
}
mgrs.clear();
// After coalescing, sort the pass managers within rhs by name.
llvm::array_pod_sort(rhs.mgrs.begin(), rhs.mgrs.end(),
[](const OpPassManager *lhs, const OpPassManager *rhs) {
return lhs->getOpName().compare(rhs->getOpName());
});
}
/// Returns the adaptor pass name.
std::string OpToOpPassAdaptor::getAdaptorName() {
std::string name = "Pipeline Collection : [";
llvm::raw_string_ostream os(name);
llvm::interleaveComma(getPassManagers(), os, [&](OpPassManager &pm) {
os << '\'' << pm.getOpName() << '\'';
});
os << ']';
return os.str();
}
void OpToOpPassAdaptor::runOnOperation() {
llvm_unreachable(
"Unexpected call to Pass::runOnOperation() on OpToOpPassAdaptor");
}
/// Run the held pipeline over all nested operations.
void OpToOpPassAdaptor::runOnOperation(bool verifyPasses) {
if (getContext().isMultithreadingEnabled())
runOnOperationAsyncImpl(verifyPasses);
else
runOnOperationImpl(verifyPasses);
}
/// Run this pass adaptor synchronously.
void OpToOpPassAdaptor::runOnOperationImpl(bool verifyPasses) {
auto am = getAnalysisManager();
PassInstrumentation::PipelineParentInfo parentInfo = {llvm::get_threadid(),
this};
auto *instrumentor = am.getPassInstrumentor();
for (auto ®ion : getOperation()->getRegions()) {
for (auto &block : region) {
for (auto &op : block) {
auto *mgr = findPassManagerFor(mgrs, op.getName().getIdentifier(),
*op.getContext());
if (!mgr)
continue;
// Run the held pipeline over the current operation.
unsigned initGeneration = mgr->impl->initializationGeneration;
if (failed(runPipeline(mgr->getPasses(), &op, am.nest(&op),
verifyPasses, initGeneration, instrumentor,
&parentInfo)))
return signalPassFailure();
}
}
}
}
/// Utility functor that checks if the two ranges of pass managers have a size
/// mismatch.
static bool hasSizeMismatch(ArrayRef<OpPassManager> lhs,
ArrayRef<OpPassManager> rhs) {
return lhs.size() != rhs.size() ||
llvm::any_of(llvm::seq<size_t>(0, lhs.size()),
[&](size_t i) { return lhs[i].size() != rhs[i].size(); });
}
/// Run this pass adaptor synchronously.
void OpToOpPassAdaptor::runOnOperationAsyncImpl(bool verifyPasses) {
AnalysisManager am = getAnalysisManager();
MLIRContext *context = &getContext();
// Create the async executors if they haven't been created, or if the main
// pipeline has changed.
if (asyncExecutors.empty() || hasSizeMismatch(asyncExecutors.front(), mgrs))
asyncExecutors.assign(context->getThreadPool().getThreadCount(), mgrs);
// Run a prepass over the operation to collect the nested operations to
// execute over. This ensures that an analysis manager exists for each
// operation, as well as providing a queue of operations to execute over.
std::vector<std::pair<Operation *, AnalysisManager>> opAMPairs;
for (auto ®ion : getOperation()->getRegions()) {
for (auto &block : region) {
for (auto &op : block) {
// Add this operation iff the name matches any of the pass managers.
if (findPassManagerFor(mgrs, op.getName().getIdentifier(), *context))
opAMPairs.emplace_back(&op, am.nest(&op));
}
}
}
// Get the current thread for this adaptor.
PassInstrumentation::PipelineParentInfo parentInfo = {llvm::get_threadid(),
this};
auto *instrumentor = am.getPassInstrumentor();
// An atomic failure variable for the async executors.
std::vector<std::atomic<bool>> activePMs(asyncExecutors.size());
std::fill(activePMs.begin(), activePMs.end(), false);
auto processFn = [&](auto &opPMPair) {
// Find a pass manager for this operation.
auto it = llvm::find_if(activePMs, [](std::atomic<bool> &isActive) {
bool expectedInactive = false;
return isActive.compare_exchange_strong(expectedInactive, true);
});
unsigned pmIndex = it - activePMs.begin();
// Get the pass manager for this operation and execute it.
auto *pm =
findPassManagerFor(asyncExecutors[pmIndex],
opPMPair.first->getName().getIdentifier(), *context);
assert(pm && "expected valid pass manager for operation");
unsigned initGeneration = pm->impl->initializationGeneration;
LogicalResult pipelineResult =
runPipeline(pm->getPasses(), opPMPair.first, opPMPair.second,
verifyPasses, initGeneration, instrumentor, &parentInfo);
// Reset the active bit for this pass manager.
activePMs[pmIndex].store(false);
return pipelineResult;
};
// Signal a failure if any of the executors failed.
if (failed(failableParallelForEach(context, opAMPairs, processFn)))
signalPassFailure();
}
//===----------------------------------------------------------------------===//
// PassManager
//===----------------------------------------------------------------------===//
PassManager::PassManager(MLIRContext *ctx, Nesting nesting,
StringRef operationName)
: OpPassManager(StringAttr::get(ctx, operationName), nesting), context(ctx),
initializationKey(DenseMapInfo<llvm::hash_code>::getTombstoneKey()),
passTiming(false), verifyPasses(true) {}
PassManager::~PassManager() = default;
void PassManager::enableVerifier(bool enabled) { verifyPasses = enabled; }
/// Run the passes within this manager on the provided operation.
LogicalResult PassManager::run(Operation *op) {
MLIRContext *context = getContext();
assert(op->getName().getIdentifier() == getOpName(*context) &&
"operation has a different name than the PassManager or is from a "
"different context");
// Before running, make sure to coalesce any adjacent pass adaptors in the
// pipeline.
getImpl().coalesceAdjacentAdaptorPasses();
// Register all dialects for the current pipeline.
DialectRegistry dependentDialects;
getDependentDialects(dependentDialects);
context->appendDialectRegistry(dependentDialects);
for (StringRef name : dependentDialects.getDialectNames())
context->getOrLoadDialect(name);
// Initialize all of the passes within the pass manager with a new generation.
llvm::hash_code newInitKey = context->getRegistryHash();
if (newInitKey != initializationKey) {
if (failed(initialize(context, impl->initializationGeneration + 1)))
return failure();
initializationKey = newInitKey;
}
// Construct a top level analysis manager for the pipeline.
ModuleAnalysisManager am(op, instrumentor.get());
// Notify the context that we start running a pipeline for book keeping.
context->enterMultiThreadedExecution();
// If reproducer generation is enabled, run the pass manager with crash
// handling enabled.
LogicalResult result =
crashReproGenerator ? runWithCrashRecovery(op, am) : runPasses(op, am);
// Notify the context that the run is done.
context->exitMultiThreadedExecution();
// Dump all of the pass statistics if necessary.
if (passStatisticsMode)
dumpStatistics();
return result;
}
/// Add the provided instrumentation to the pass manager.
void PassManager::addInstrumentation(std::unique_ptr<PassInstrumentation> pi) {
if (!instrumentor)
instrumentor = std::make_unique<PassInstrumentor>();
instrumentor->addInstrumentation(std::move(pi));
}
LogicalResult PassManager::runPasses(Operation *op, AnalysisManager am) {
return OpToOpPassAdaptor::runPipeline(getPasses(), op, am, verifyPasses,
impl->initializationGeneration);
}
//===----------------------------------------------------------------------===//
// AnalysisManager
//===----------------------------------------------------------------------===//
/// Get an analysis manager for the given operation, which must be a proper
/// descendant of the current operation represented by this analysis manager.
AnalysisManager AnalysisManager::nest(Operation *op) {
Operation *currentOp = impl->getOperation();
assert(currentOp->isProperAncestor(op) &&
"expected valid descendant operation");
// Check for the base case where the provided operation is immediately nested.
if (currentOp == op->getParentOp())
return nestImmediate(op);
// Otherwise, we need to collect all ancestors up to the current operation.
SmallVector<Operation *, 4> opAncestors;
do {
opAncestors.push_back(op);
op = op->getParentOp();
} while (op != currentOp);
AnalysisManager result = *this;
for (Operation *op : llvm::reverse(opAncestors))
result = result.nestImmediate(op);
return result;
}
/// Get an analysis manager for the given immediately nested child operation.
AnalysisManager AnalysisManager::nestImmediate(Operation *op) {
assert(impl->getOperation() == op->getParentOp() &&
"expected immediate child operation");
auto it = impl->childAnalyses.find(op);
if (it == impl->childAnalyses.end())
it = impl->childAnalyses
.try_emplace(op, std::make_unique<NestedAnalysisMap>(op, impl))
.first;
return {it->second.get()};
}
/// Invalidate any non preserved analyses.
void detail::NestedAnalysisMap::invalidate(
const detail::PreservedAnalyses &pa) {
// If all analyses were preserved, then there is nothing to do here.
if (pa.isAll())
return;
// Invalidate the analyses for the current operation directly.
analyses.invalidate(pa);
// If no analyses were preserved, then just simply clear out the child
// analysis results.
if (pa.isNone()) {
childAnalyses.clear();
return;
}
// Otherwise, invalidate each child analysis map.
SmallVector<NestedAnalysisMap *, 8> mapsToInvalidate(1, this);
while (!mapsToInvalidate.empty()) {
auto *map = mapsToInvalidate.pop_back_val();
for (auto &analysisPair : map->childAnalyses) {
analysisPair.second->invalidate(pa);
if (!analysisPair.second->childAnalyses.empty())
mapsToInvalidate.push_back(analysisPair.second.get());
}
}
}
//===----------------------------------------------------------------------===//
// PassInstrumentation
//===----------------------------------------------------------------------===//
PassInstrumentation::~PassInstrumentation() = default;
//===----------------------------------------------------------------------===//
// PassInstrumentor
//===----------------------------------------------------------------------===//
namespace mlir {
namespace detail {
struct PassInstrumentorImpl {
/// Mutex to keep instrumentation access thread-safe.
llvm::sys::SmartMutex<true> mutex;
/// Set of registered instrumentations.
std::vector<std::unique_ptr<PassInstrumentation>> instrumentations;
};
} // namespace detail
} // namespace mlir
PassInstrumentor::PassInstrumentor() : impl(new PassInstrumentorImpl()) {}
PassInstrumentor::~PassInstrumentor() = default;
/// See PassInstrumentation::runBeforePipeline for details.
void PassInstrumentor::runBeforePipeline(
StringAttr name,
const PassInstrumentation::PipelineParentInfo &parentInfo) {
llvm::sys::SmartScopedLock<true> instrumentationLock(impl->mutex);
for (auto &instr : impl->instrumentations)
instr->runBeforePipeline(name, parentInfo);
}
/// See PassInstrumentation::runAfterPipeline for details.
void PassInstrumentor::runAfterPipeline(
StringAttr name,
const PassInstrumentation::PipelineParentInfo &parentInfo) {
llvm::sys::SmartScopedLock<true> instrumentationLock(impl->mutex);
for (auto &instr : llvm::reverse(impl->instrumentations))
instr->runAfterPipeline(name, parentInfo);
}
/// See PassInstrumentation::runBeforePass for details.
void PassInstrumentor::runBeforePass(Pass *pass, Operation *op) {
llvm::sys::SmartScopedLock<true> instrumentationLock(impl->mutex);
for (auto &instr : impl->instrumentations)
instr->runBeforePass(pass, op);
}
/// See PassInstrumentation::runAfterPass for details.
void PassInstrumentor::runAfterPass(Pass *pass, Operation *op) {
llvm::sys::SmartScopedLock<true> instrumentationLock(impl->mutex);
for (auto &instr : llvm::reverse(impl->instrumentations))
instr->runAfterPass(pass, op);
}
/// See PassInstrumentation::runAfterPassFailed for details.
void PassInstrumentor::runAfterPassFailed(Pass *pass, Operation *op) {
llvm::sys::SmartScopedLock<true> instrumentationLock(impl->mutex);
for (auto &instr : llvm::reverse(impl->instrumentations))
instr->runAfterPassFailed(pass, op);
}
/// See PassInstrumentation::runBeforeAnalysis for details.
void PassInstrumentor::runBeforeAnalysis(StringRef name, TypeID id,
Operation *op) {
llvm::sys::SmartScopedLock<true> instrumentationLock(impl->mutex);
for (auto &instr : impl->instrumentations)
instr->runBeforeAnalysis(name, id, op);
}
/// See PassInstrumentation::runAfterAnalysis for details.
void PassInstrumentor::runAfterAnalysis(StringRef name, TypeID id,
Operation *op) {
llvm::sys::SmartScopedLock<true> instrumentationLock(impl->mutex);
for (auto &instr : llvm::reverse(impl->instrumentations))
instr->runAfterAnalysis(name, id, op);
}
/// Add the given instrumentation to the collection.
void PassInstrumentor::addInstrumentation(
std::unique_ptr<PassInstrumentation> pi) {
llvm::sys::SmartScopedLock<true> instrumentationLock(impl->mutex);
impl->instrumentations.emplace_back(std::move(pi));
}
|
.thumb
.org 0x0
.equ ClassGrowthOption, Extra_Growth_Boosts+4
@r0=battle struct or char data ptr
ldr r1,[r0]
ldrb r1,[r1,#28] @hp growth
ldr r2,ClassGrowthOption
cmp r2,#0
beq GetExtraGrowthBoost
ldr r2,[r0,#4]
add r2,#27
ldrb r2,[r2]
add r1,r2
GetExtraGrowthBoost:
mov r2,#10 @index of hp boost
ldr r3,Extra_Growth_Boosts
bx r3
.align
Extra_Growth_Boosts:
@
|
/* TEMPLATE GENERATED TESTCASE FILE
Filename: CWE197_Numeric_Truncation_Error__int_listen_socket_to_short_74a.cpp
Label Definition File: CWE197_Numeric_Truncation_Error__int.label.xml
Template File: sources-sink-74a.tmpl.cpp
*/
/*
* @description
* CWE: 197 Numeric Truncation Error
* BadSource: listen_socket Read data using a listen socket (server side)
* GoodSource: Less than CHAR_MAX
* Sinks: to_short
* BadSink : Convert data to a short
* Flow Variant: 74 Data flow: data passed in a map from one function to another in different source files
*
* */
#include "std_testcase.h"
#include <map>
#ifdef _WIN32
#include <winsock2.h>
#include <windows.h>
#include <direct.h>
#pragma comment(lib, "ws2_32") /* include ws2_32.lib when linking */
#define CLOSE_SOCKET closesocket
#else
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
#define INVALID_SOCKET -1
#define SOCKET_ERROR -1
#define CLOSE_SOCKET close
#define SOCKET int
#endif
#define TCP_PORT 27015
#define LISTEN_BACKLOG 5
#define CHAR_ARRAY_SIZE (3 * sizeof(data) + 2)
using namespace std;
namespace CWE197_Numeric_Truncation_Error__int_listen_socket_to_short_74
{
#ifndef OMITBAD
/* bad function declaration */
void badSink(map<int, int> dataMap);
void bad()
{
int data;
map<int, int> dataMap;
/* Initialize data */
data = -1;
{
#ifdef _WIN32
WSADATA wsaData;
int wsaDataInit = 0;
#endif
int recvResult;
struct sockaddr_in service;
SOCKET listenSocket = INVALID_SOCKET;
SOCKET acceptSocket = INVALID_SOCKET;
char inputBuffer[CHAR_ARRAY_SIZE];
do
{
#ifdef _WIN32
if (WSAStartup(MAKEWORD(2,2), &wsaData) != NO_ERROR)
{
break;
}
wsaDataInit = 1;
#endif
/* POTENTIAL FLAW: Read data using a listen socket */
listenSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if (listenSocket == INVALID_SOCKET)
{
break;
}
memset(&service, 0, sizeof(service));
service.sin_family = AF_INET;
service.sin_addr.s_addr = INADDR_ANY;
service.sin_port = htons(TCP_PORT);
if (bind(listenSocket, (struct sockaddr*)&service, sizeof(service)) == SOCKET_ERROR)
{
break;
}
if (listen(listenSocket, LISTEN_BACKLOG) == SOCKET_ERROR)
{
break;
}
acceptSocket = accept(listenSocket, NULL, NULL);
if (acceptSocket == SOCKET_ERROR)
{
break;
}
/* Abort on error or the connection was closed */
recvResult = recv(acceptSocket, inputBuffer, CHAR_ARRAY_SIZE - 1, 0);
if (recvResult == SOCKET_ERROR || recvResult == 0)
{
break;
}
/* NUL-terminate the string */
inputBuffer[recvResult] = '\0';
/* Convert to int */
data = atoi(inputBuffer);
}
while (0);
if (listenSocket != INVALID_SOCKET)
{
CLOSE_SOCKET(listenSocket);
}
if (acceptSocket != INVALID_SOCKET)
{
CLOSE_SOCKET(acceptSocket);
}
#ifdef _WIN32
if (wsaDataInit)
{
WSACleanup();
}
#endif
}
/* Put data in a map */
dataMap[0] = data;
dataMap[1] = data;
dataMap[2] = data;
badSink(dataMap);
}
#endif /* OMITBAD */
#ifndef OMITGOOD
/* good function declarations */
/* goodG2B uses the GoodSource with the BadSink */
void goodG2BSink(map<int, int> dataMap);
static void goodG2B()
{
int data;
map<int, int> dataMap;
/* Initialize data */
data = -1;
/* FIX: Use a positive integer less than CHAR_MAX*/
data = CHAR_MAX-5;
/* Put data in a map */
dataMap[0] = data;
dataMap[1] = data;
dataMap[2] = data;
goodG2BSink(dataMap);
}
void good()
{
goodG2B();
}
#endif /* OMITGOOD */
} /* close namespace */
/* Below is the main(). It is only used when building this testcase on
* its own for testing or for building a binary to use in testing binary
* analysis tools. It is not used when compiling all the testcases as one
* application, which is how source code analysis tools are tested.
*/
#ifdef INCLUDEMAIN
using namespace CWE197_Numeric_Truncation_Error__int_listen_socket_to_short_74; /* so that we can use good and bad easily */
int main(int argc, char * argv[])
{
/* seed randomness */
srand( (unsigned)time(NULL) );
#ifndef OMITGOOD
printLine("Calling good()...");
good();
printLine("Finished good()");
#endif /* OMITGOOD */
#ifndef OMITBAD
printLine("Calling bad()...");
bad();
printLine("Finished bad()");
#endif /* OMITBAD */
return 0;
}
#endif
|
.program:
ji i4
noop
DATA_SECTION_OFFSET[0..32]
DATA_SECTION_OFFSET[32..64]
lw $ds $is 1
add $$ds $$ds $is
lw $r1 $fp i73 ; load input function selector
lw $r0 data_2 ; load fn selector for comparison
eq $r0 $r1 $r0 ; function selector comparison
jnzi $r0 i14 ; jump to selected function
lw $r0 data_3 ; load fn selector for comparison
eq $r0 $r1 $r0 ; function selector comparison
jnzi $r0 i17 ; jump to selected function
rvrt $zero ; revert if no selectors matched
lw $r1 $fp i74 ; Base register for method parameter
lw $r0 data_0 ; loading size for RETD
retd $r1 $r0
lw $r1 $fp i74 ; Base register for method parameter
lw $r0 data_1 ; loading size for RETD
retd $r1 $r0
noop ; word-alignment of data section
.data:
data_0 .u64 0x08
data_1 .u64 0x10
data_2 .u32 0x80da70e2
data_3 .u32 0x28c0f699
|
;-------------------
; test for push/pop
;-------------------
.equ spl = 0x3d
.equ sph = 0x3e
;-------------------
in r20,spl
in r21,sph
ldi r16,0x10
ldi r24,0x20
mov r7 ,r16
mov r8 ,r24
ldi r16,0x30
ldi r24,0x40
push r7
push r8
push r16
push r24
in r22,spl
in r23,sph
pop r6
pop r9
pop r17
pop r25
;-------------------
mov r5 ,r7
mov r10,r8
mov r18,r16
mov r26,r24
com r5
com r10
com r18
com r26
push r5
push r10
push r18
push r26
.def yl = r28
.def yh = r29
in yl ,spl
in yh ,sph
ldd r4 ,y+1
ldd r11,y+2
adiw yl ,2
out spl,yl
pop r19
pop r27
;-------------------
.def zl = r30
.def zh = r31
ldi zh,0x01
ldi zl,0x00
st z+,r7 ; (ldi) 0x10
st z+,r8 ; (ldi) 0x20
st z+,r16 ; (ldi) 0x30
st z+,r24 ; (ldi) 0x40
st z+,r6 ; (pop) 0x40
st z+,r9 ; (pop) 0x30
st z+,r17 ; (pop) 0x20
st z+,r25 ; (pop) 0x10
st z+,r5 ; (ldi) ~0x10
st z+,r10 ; (ldi) ~0x20
st z+,r18 ; (ldi) ~0x30
st z+,r26 ; (ldi) ~0x40
st z+,r4 ; (ldd) ~0x40
st z+,r11 ; (ldd) ~0x30
st z+,r19 ; (pop) ~0x20
st z+,r27 ; (pop) ~0x10
st z+,r20 ; (in) spl (reset value)
st z+,r21 ; (in) sph (reset value)
st z+,r22 ; (in) spl (after push)
st z+,r23 ; (in) sph (after push)
st z+,yl ; (in) spl (after adiw)
st z+,yh ; (in) sph (after adiw)
;-------------------
ldi r16,0xff
sts 0xffff,r16
halt:
rjmp halt
|
; A084672: G.f.: (1+x^2+2*x^4)/((1-x^3)*(1-x)^2).
; 1,2,4,7,12,18,25,34,44,55,68,82,97,114,132,151,172,194,217,242,268,295,324,354,385,418,452,487,524,562,601,642,684,727,772,818,865,914,964,1015,1068,1122,1177,1234,1292,1351,1412,1474,1537,1602,1668,1735,1804,1874
mul $0,2
pow $0,2
mov $1,$0
add $1,8
div $1,6
|
SECTION code_clib
PUBLIC heapalloc
PUBLIC _heapalloc
; fastcall
.heapalloc
._heapalloc
ex de, hl
jp 0xb881
|
TITLE Homework02 (HW02.ASM)
INCLUDE Irvine32.inc
.data
Val1 SBYTE 03h
Val2 SBYTE 02h
Val3 SBYTE 8fh
Rval SDWORD ?
.code
main EQU start@0
main PROC
movsx eax, Val1 ;eax = Val1
movsx ebx, Val2 ;ebx = Val2
movsx ecx, Val3 ;ecx = Val3
add eax, ebx ;eax = Val1 + Val2
mov ebx, eax ;ebx = Val1 + Val2
shl eax, 3 ;eax = 8*eax
shl ebx, 1 ;eax = 2*eax
add eax, ebx ;eax = eax + ebx = 10*(Val1 + Val2)
shl ebx, 1 ;eax = 2*eax
add eax, ebx ;eax = eax + ebx = 14*(Val1 + Val2)
sub ecx, eax ;ecx = ecx - eax = Val3 – 14 * (Val1 + Val2)
neg ecx ;ecx = -ecx = - (Val3 – 14 * (Val1 + Val2))
mov Rval, ecx ;Rval = ecx
exit
main ENDP
END main |
bootloader/bootloader.elf: file format elf32-littlearm
Disassembly of section .text:
00000000 <hang-0x80>:
0: 00002000 .word 0x00002000
4: 00000091 .word 0x00000091
...
1c: 00000080 .word 0x00000080
20: 00000080 .word 0x00000080
24: 00000080 .word 0x00000080
28: 00000080 .word 0x00000080
...
34: 00000080 .word 0x00000080
...
40: 00000241 .word 0x00000241
44: 0000024d .word 0x0000024d
48: 00000259 .word 0x00000259
4c: 00000265 .word 0x00000265
50: 00000271 .word 0x00000271
54: 0000027d .word 0x0000027d
58: 00000289 .word 0x00000289
5c: 00000295 .word 0x00000295
60: 000002a1 .word 0x000002a1
64: 000002b1 .word 0x000002b1
68: 000002c1 .word 0x000002c1
6c: 000002d1 .word 0x000002d1
70: 000002e1 .word 0x000002e1
74: 000002f1 .word 0x000002f1
78: 00000301 .word 0x00000301
7c: 00000000 .word 0x00000000
00000080 <hang>:
80: e7fe b.n 80 <hang>
...
00000090 <_start>:
90: f000 f964 bl 35c <main>
94: e7fc b.n 90 <_start>
Disassembly of section .text.FLSv1L_turnOnFlash:
00000096 <FLSv1L_turnOnFlash>:
96: b508 push {r3, lr}
98: 2111 movs r1, #17
9a: 2203 movs r2, #3
9c: f000 f8b4 bl 208 <mbus_remote_register_write>
a0: bd08 pop {r3, pc}
Disassembly of section .text.FLSv1L_turnOffFlash:
000000a2 <FLSv1L_turnOffFlash>:
a2: b508 push {r3, lr}
a4: 2111 movs r1, #17
a6: 2202 movs r2, #2
a8: f000 f8ae bl 208 <mbus_remote_register_write>
ac: bd08 pop {r3, pc}
Disassembly of section .text.FLSv1L_enableLargeCap:
000000ae <FLSv1L_enableLargeCap>:
ae: b508 push {r3, lr}
b0: 2109 movs r1, #9
b2: 223f movs r2, #63 ; 0x3f
b4: f000 f8a8 bl 208 <mbus_remote_register_write>
b8: bd08 pop {r3, pc}
Disassembly of section .text.FLSv1L_disableLargeCap:
000000ba <FLSv1L_disableLargeCap>:
ba: b508 push {r3, lr}
bc: 2109 movs r1, #9
be: 2200 movs r2, #0
c0: f000 f8a2 bl 208 <mbus_remote_register_write>
c4: bd08 pop {r3, pc}
Disassembly of section .text.FLSv1L_setIRQAddr:
000000c6 <FLSv1L_setIRQAddr>:
c6: b508 push {r3, lr}
c8: 0209 lsls r1, r1, #8
ca: 430a orrs r2, r1
cc: 210c movs r1, #12
ce: f000 f89b bl 208 <mbus_remote_register_write>
d2: bd08 pop {r3, pc}
Disassembly of section .text.FLSv1L_setOptTune:
000000d4 <FLSv1L_setOptTune>:
d4: b510 push {r4, lr}
d6: 2102 movs r1, #2
d8: 1c04 adds r4, r0, #0
da: 4a04 ldr r2, [pc, #16] ; (ec <FLSv1L_setOptTune+0x18>)
dc: f000 f894 bl 208 <mbus_remote_register_write>
e0: 1c20 adds r0, r4, #0
e2: 210a movs r1, #10
e4: 4a02 ldr r2, [pc, #8] ; (f0 <FLSv1L_setOptTune+0x1c>)
e6: f000 f88f bl 208 <mbus_remote_register_write>
ea: bd10 pop {r4, pc}
ec: 000500c0 .word 0x000500c0
f0: 0000023f .word 0x0000023f
Disassembly of section .text.FLSv1L_setSRAMStartAddr:
000000f4 <FLSv1L_setSRAMStartAddr>:
f4: b508 push {r3, lr}
f6: 1c0a adds r2, r1, #0
f8: 2106 movs r1, #6
fa: f000 f885 bl 208 <mbus_remote_register_write>
fe: bd08 pop {r3, pc}
Disassembly of section .text.FLSv1L_setFlashStartAddr:
00000100 <FLSv1L_setFlashStartAddr>:
100: b508 push {r3, lr}
102: 1c0a adds r2, r1, #0
104: 2107 movs r1, #7
106: f000 f87f bl 208 <mbus_remote_register_write>
10a: bd08 pop {r3, pc}
Disassembly of section .text.FLSv1L_doCopySRAM2Flash:
0000010c <FLSv1L_doCopySRAM2Flash>:
10c: b508 push {r3, lr}
10e: 4a03 ldr r2, [pc, #12] ; (11c <FLSv1L_doCopySRAM2Flash+0x10>)
110: 0109 lsls r1, r1, #4
112: 430a orrs r2, r1
114: 2105 movs r1, #5
116: f000 f877 bl 208 <mbus_remote_register_write>
11a: bd08 pop {r3, pc}
11c: 00008005 .word 0x00008005
Disassembly of section .text.FLSv1L_doEraseFlash:
00000120 <FLSv1L_doEraseFlash>:
120: b508 push {r3, lr}
122: 2105 movs r1, #5
124: 4a01 ldr r2, [pc, #4] ; (12c <FLSv1L_doEraseFlash+0xc>)
126: f000 f86f bl 208 <mbus_remote_register_write>
12a: bd08 pop {r3, pc}
12c: 00008009 .word 0x00008009
Disassembly of section .text.delay:
00000130 <delay>:
130: b500 push {lr}
132: 2300 movs r3, #0
134: e001 b.n 13a <delay+0xa>
136: 46c0 nop ; (mov r8, r8)
138: 3301 adds r3, #1
13a: 4283 cmp r3, r0
13c: d1fb bne.n 136 <delay+0x6>
13e: bd00 pop {pc}
Disassembly of section .text.write_regfile:
00000140 <write_regfile>:
140: 0880 lsrs r0, r0, #2
142: 0209 lsls r1, r1, #8
144: b508 push {r3, lr}
146: 0a09 lsrs r1, r1, #8
148: 4b05 ldr r3, [pc, #20] ; (160 <write_regfile+0x20>)
14a: 0600 lsls r0, r0, #24
14c: 4308 orrs r0, r1
14e: 6018 str r0, [r3, #0]
150: 4b04 ldr r3, [pc, #16] ; (164 <write_regfile+0x24>)
152: 2210 movs r2, #16
154: 601a str r2, [r3, #0]
156: 200a movs r0, #10
158: f7ff ffea bl 130 <delay>
15c: bd08 pop {r3, pc}
15e: 46c0 nop ; (mov r8, r8)
160: a0002000 .word 0xa0002000
164: a000200c .word 0xa000200c
Disassembly of section .text.set_halt_until_mbus_rx:
00000168 <set_halt_until_mbus_rx>:
168: 4805 ldr r0, [pc, #20] ; (180 <set_halt_until_mbus_rx+0x18>)
16a: b508 push {r3, lr}
16c: 6801 ldr r1, [r0, #0]
16e: 4b05 ldr r3, [pc, #20] ; (184 <set_halt_until_mbus_rx+0x1c>)
170: 4019 ands r1, r3
172: 2390 movs r3, #144 ; 0x90
174: 021b lsls r3, r3, #8
176: 4319 orrs r1, r3
178: f7ff ffe2 bl 140 <write_regfile>
17c: bd08 pop {r3, pc}
17e: 46c0 nop ; (mov r8, r8)
180: a0000028 .word 0xa0000028
184: ffff0fff .word 0xffff0fff
Disassembly of section .text.set_halt_until_mbus_tx:
00000188 <set_halt_until_mbus_tx>:
188: 4805 ldr r0, [pc, #20] ; (1a0 <set_halt_until_mbus_tx+0x18>)
18a: b508 push {r3, lr}
18c: 6801 ldr r1, [r0, #0]
18e: 4b05 ldr r3, [pc, #20] ; (1a4 <set_halt_until_mbus_tx+0x1c>)
190: 4019 ands r1, r3
192: 23a0 movs r3, #160 ; 0xa0
194: 021b lsls r3, r3, #8
196: 4319 orrs r1, r3
198: f7ff ffd2 bl 140 <write_regfile>
19c: bd08 pop {r3, pc}
19e: 46c0 nop ; (mov r8, r8)
1a0: a0000028 .word 0xa0000028
1a4: ffff0fff .word 0xffff0fff
Disassembly of section .text.mbus_write_message32:
000001a8 <mbus_write_message32>:
1a8: 4b02 ldr r3, [pc, #8] ; (1b4 <mbus_write_message32+0xc>)
1aa: 0100 lsls r0, r0, #4
1ac: 4318 orrs r0, r3
1ae: 6001 str r1, [r0, #0]
1b0: 2001 movs r0, #1
1b2: 4770 bx lr
1b4: a0003000 .word 0xa0003000
Disassembly of section .text.mbus_write_message:
000001b8 <mbus_write_message>:
1b8: 2300 movs r3, #0
1ba: b500 push {lr}
1bc: 429a cmp r2, r3
1be: d00a beq.n 1d6 <mbus_write_message+0x1e>
1c0: 4b06 ldr r3, [pc, #24] ; (1dc <mbus_write_message+0x24>)
1c2: 3a01 subs r2, #1
1c4: 0600 lsls r0, r0, #24
1c6: 4302 orrs r2, r0
1c8: 601a str r2, [r3, #0]
1ca: 4b05 ldr r3, [pc, #20] ; (1e0 <mbus_write_message+0x28>)
1cc: 2223 movs r2, #35 ; 0x23
1ce: 6019 str r1, [r3, #0]
1d0: 4b04 ldr r3, [pc, #16] ; (1e4 <mbus_write_message+0x2c>)
1d2: 601a str r2, [r3, #0]
1d4: 2301 movs r3, #1
1d6: 1c18 adds r0, r3, #0
1d8: bd00 pop {pc}
1da: 46c0 nop ; (mov r8, r8)
1dc: a0002000 .word 0xa0002000
1e0: a0002004 .word 0xa0002004
1e4: a000200c .word 0xa000200c
Disassembly of section .text.mbus_enumerate:
000001e8 <mbus_enumerate>:
1e8: 0603 lsls r3, r0, #24
1ea: 2080 movs r0, #128 ; 0x80
1ec: 0580 lsls r0, r0, #22
1ee: 4318 orrs r0, r3
1f0: 4b01 ldr r3, [pc, #4] ; (1f8 <mbus_enumerate+0x10>)
1f2: 6018 str r0, [r3, #0]
1f4: 4770 bx lr
1f6: 46c0 nop ; (mov r8, r8)
1f8: a0003000 .word 0xa0003000
Disassembly of section .text.mbus_sleep_all:
000001fc <mbus_sleep_all>:
1fc: 4b01 ldr r3, [pc, #4] ; (204 <mbus_sleep_all+0x8>)
1fe: 2200 movs r2, #0
200: 601a str r2, [r3, #0]
202: 4770 bx lr
204: a0003010 .word 0xa0003010
Disassembly of section .text.mbus_remote_register_write:
00000208 <mbus_remote_register_write>:
208: b507 push {r0, r1, r2, lr}
20a: 0212 lsls r2, r2, #8
20c: 0a12 lsrs r2, r2, #8
20e: 0609 lsls r1, r1, #24
210: 4311 orrs r1, r2
212: 0100 lsls r0, r0, #4
214: 9101 str r1, [sp, #4]
216: b2c0 uxtb r0, r0
218: a901 add r1, sp, #4
21a: 2201 movs r2, #1
21c: f7ff ffcc bl 1b8 <mbus_write_message>
220: bd07 pop {r0, r1, r2, pc}
Disassembly of section .text.init_interrupt:
00000224 <init_interrupt>:
224: 4a03 ldr r2, [pc, #12] ; (234 <init_interrupt+0x10>)
226: 4b04 ldr r3, [pc, #16] ; (238 <init_interrupt+0x14>)
228: 601a str r2, [r3, #0]
22a: 4b04 ldr r3, [pc, #16] ; (23c <init_interrupt+0x18>)
22c: 2200 movs r2, #0
22e: 601a str r2, [r3, #0]
230: 4770 bx lr
232: 46c0 nop ; (mov r8, r8)
234: 00007fff .word 0x00007fff
238: e000e280 .word 0xe000e280
23c: e000e100 .word 0xe000e100
Disassembly of section .text.handler_ext_int_0:
00000240 <handler_ext_int_0>:
240: 4b01 ldr r3, [pc, #4] ; (248 <handler_ext_int_0+0x8>)
242: 2201 movs r2, #1
244: 601a str r2, [r3, #0]
246: 4770 bx lr
248: e000e280 .word 0xe000e280
Disassembly of section .text.handler_ext_int_1:
0000024c <handler_ext_int_1>:
24c: 4b01 ldr r3, [pc, #4] ; (254 <handler_ext_int_1+0x8>)
24e: 2202 movs r2, #2
250: 601a str r2, [r3, #0]
252: 4770 bx lr
254: e000e280 .word 0xe000e280
Disassembly of section .text.handler_ext_int_2:
00000258 <handler_ext_int_2>:
258: 4b01 ldr r3, [pc, #4] ; (260 <handler_ext_int_2+0x8>)
25a: 2204 movs r2, #4
25c: 601a str r2, [r3, #0]
25e: 4770 bx lr
260: e000e280 .word 0xe000e280
Disassembly of section .text.handler_ext_int_3:
00000264 <handler_ext_int_3>:
264: 4b01 ldr r3, [pc, #4] ; (26c <handler_ext_int_3+0x8>)
266: 2208 movs r2, #8
268: 601a str r2, [r3, #0]
26a: 4770 bx lr
26c: e000e280 .word 0xe000e280
Disassembly of section .text.handler_ext_int_4:
00000270 <handler_ext_int_4>:
270: 4b01 ldr r3, [pc, #4] ; (278 <handler_ext_int_4+0x8>)
272: 2210 movs r2, #16
274: 601a str r2, [r3, #0]
276: 4770 bx lr
278: e000e280 .word 0xe000e280
Disassembly of section .text.handler_ext_int_5:
0000027c <handler_ext_int_5>:
27c: 4b01 ldr r3, [pc, #4] ; (284 <handler_ext_int_5+0x8>)
27e: 2220 movs r2, #32
280: 601a str r2, [r3, #0]
282: 4770 bx lr
284: e000e280 .word 0xe000e280
Disassembly of section .text.handler_ext_int_6:
00000288 <handler_ext_int_6>:
288: 4b01 ldr r3, [pc, #4] ; (290 <handler_ext_int_6+0x8>)
28a: 2240 movs r2, #64 ; 0x40
28c: 601a str r2, [r3, #0]
28e: 4770 bx lr
290: e000e280 .word 0xe000e280
Disassembly of section .text.handler_ext_int_7:
00000294 <handler_ext_int_7>:
294: 4b01 ldr r3, [pc, #4] ; (29c <handler_ext_int_7+0x8>)
296: 2280 movs r2, #128 ; 0x80
298: 601a str r2, [r3, #0]
29a: 4770 bx lr
29c: e000e280 .word 0xe000e280
Disassembly of section .text.handler_ext_int_8:
000002a0 <handler_ext_int_8>:
2a0: 4b02 ldr r3, [pc, #8] ; (2ac <handler_ext_int_8+0xc>)
2a2: 2280 movs r2, #128 ; 0x80
2a4: 0052 lsls r2, r2, #1
2a6: 601a str r2, [r3, #0]
2a8: 4770 bx lr
2aa: 46c0 nop ; (mov r8, r8)
2ac: e000e280 .word 0xe000e280
Disassembly of section .text.handler_ext_int_9:
000002b0 <handler_ext_int_9>:
2b0: 4b02 ldr r3, [pc, #8] ; (2bc <handler_ext_int_9+0xc>)
2b2: 2280 movs r2, #128 ; 0x80
2b4: 0092 lsls r2, r2, #2
2b6: 601a str r2, [r3, #0]
2b8: 4770 bx lr
2ba: 46c0 nop ; (mov r8, r8)
2bc: e000e280 .word 0xe000e280
Disassembly of section .text.handler_ext_int_10:
000002c0 <handler_ext_int_10>:
2c0: 4b02 ldr r3, [pc, #8] ; (2cc <handler_ext_int_10+0xc>)
2c2: 2280 movs r2, #128 ; 0x80
2c4: 00d2 lsls r2, r2, #3
2c6: 601a str r2, [r3, #0]
2c8: 4770 bx lr
2ca: 46c0 nop ; (mov r8, r8)
2cc: e000e280 .word 0xe000e280
Disassembly of section .text.handler_ext_int_11:
000002d0 <handler_ext_int_11>:
2d0: 4b02 ldr r3, [pc, #8] ; (2dc <handler_ext_int_11+0xc>)
2d2: 2280 movs r2, #128 ; 0x80
2d4: 0112 lsls r2, r2, #4
2d6: 601a str r2, [r3, #0]
2d8: 4770 bx lr
2da: 46c0 nop ; (mov r8, r8)
2dc: e000e280 .word 0xe000e280
Disassembly of section .text.handler_ext_int_12:
000002e0 <handler_ext_int_12>:
2e0: 4b02 ldr r3, [pc, #8] ; (2ec <handler_ext_int_12+0xc>)
2e2: 2280 movs r2, #128 ; 0x80
2e4: 0152 lsls r2, r2, #5
2e6: 601a str r2, [r3, #0]
2e8: 4770 bx lr
2ea: 46c0 nop ; (mov r8, r8)
2ec: e000e280 .word 0xe000e280
Disassembly of section .text.handler_ext_int_13:
000002f0 <handler_ext_int_13>:
2f0: 4b02 ldr r3, [pc, #8] ; (2fc <handler_ext_int_13+0xc>)
2f2: 2280 movs r2, #128 ; 0x80
2f4: 0192 lsls r2, r2, #6
2f6: 601a str r2, [r3, #0]
2f8: 4770 bx lr
2fa: 46c0 nop ; (mov r8, r8)
2fc: e000e280 .word 0xe000e280
Disassembly of section .text.handler_ext_int_14:
00000300 <handler_ext_int_14>:
300: 4b02 ldr r3, [pc, #8] ; (30c <handler_ext_int_14+0xc>)
302: 2280 movs r2, #128 ; 0x80
304: 01d2 lsls r2, r2, #7
306: 601a str r2, [r3, #0]
308: 4770 bx lr
30a: 46c0 nop ; (mov r8, r8)
30c: e000e280 .word 0xe000e280
Disassembly of section .text.initialization:
00000310 <initialization>:
310: b508 push {r3, lr}
312: 4a0d ldr r2, [pc, #52] ; (348 <initialization+0x38>)
314: 4b0d ldr r3, [pc, #52] ; (34c <initialization+0x3c>)
316: 480e ldr r0, [pc, #56] ; (350 <initialization+0x40>)
318: 490e ldr r1, [pc, #56] ; (354 <initialization+0x44>)
31a: 601a str r2, [r3, #0]
31c: f7ff ff10 bl 140 <write_regfile>
320: 490d ldr r1, [pc, #52] ; (358 <initialization+0x48>)
322: 20aa movs r0, #170 ; 0xaa
324: f7ff ff40 bl 1a8 <mbus_write_message32>
328: f7ff ff1e bl 168 <set_halt_until_mbus_rx>
32c: 2004 movs r0, #4
32e: f7ff ff5b bl 1e8 <mbus_enumerate>
332: f7ff ff29 bl 188 <set_halt_until_mbus_tx>
336: 2004 movs r0, #4
338: f7ff fecc bl d4 <FLSv1L_setOptTune>
33c: 2004 movs r0, #4
33e: 2110 movs r1, #16
340: 2200 movs r2, #0
342: f7ff fec0 bl c6 <FLSv1L_setIRQAddr>
346: bd08 pop {r3, pc}
348: deadbeef .word 0xdeadbeef
34c: 00000814 .word 0x00000814
350: a0000020 .word 0xa0000020
354: 0000dead .word 0x0000dead
358: aaaaaaaa .word 0xaaaaaaaa
Disassembly of section .text.startup.main:
0000035c <main>:
35c: b510 push {r4, lr}
35e: f7ff ff61 bl 224 <init_interrupt>
362: 4b42 ldr r3, [pc, #264] ; (46c <main+0x110>)
364: 681a ldr r2, [r3, #0]
366: 4b42 ldr r3, [pc, #264] ; (470 <main+0x114>)
368: 429a cmp r2, r3
36a: d001 beq.n 370 <main+0x14>
36c: f7ff ffd0 bl 310 <initialization>
370: 4940 ldr r1, [pc, #256] ; (474 <main+0x118>)
372: 22e5 movs r2, #229 ; 0xe5
374: 2044 movs r0, #68 ; 0x44
376: 24a0 movs r4, #160 ; 0xa0
378: f7ff ff1e bl 1b8 <mbus_write_message>
37c: 0624 lsls r4, r4, #24
37e: f7ff fef3 bl 168 <set_halt_until_mbus_rx>
382: 2004 movs r0, #4
384: f7ff fe87 bl 96 <FLSv1L_turnOnFlash>
388: 6823 ldr r3, [r4, #0]
38a: 2b03 cmp r3, #3
38c: d00c beq.n 3a8 <main+0x4c>
38e: f7ff fefb bl 188 <set_halt_until_mbus_tx>
392: 4937 ldr r1, [pc, #220] ; (470 <main+0x114>)
394: 20e0 movs r0, #224 ; 0xe0
396: f7ff ff07 bl 1a8 <mbus_write_message32>
39a: 6821 ldr r1, [r4, #0]
39c: 20e0 movs r0, #224 ; 0xe0
39e: f7ff ff03 bl 1a8 <mbus_write_message32>
3a2: f7ff ff2b bl 1fc <mbus_sleep_all>
3a6: e7fe b.n 3a6 <main+0x4a>
3a8: f7ff feee bl 188 <set_halt_until_mbus_tx>
3ac: 2004 movs r0, #4
3ae: f7ff fe7e bl ae <FLSv1L_enableLargeCap>
3b2: f7ff fee9 bl 188 <set_halt_until_mbus_tx>
3b6: 2004 movs r0, #4
3b8: 2100 movs r1, #0
3ba: f7ff fea1 bl 100 <FLSv1L_setFlashStartAddr>
3be: f7ff fed3 bl 168 <set_halt_until_mbus_rx>
3c2: 2004 movs r0, #4
3c4: f7ff feac bl 120 <FLSv1L_doEraseFlash>
3c8: 6823 ldr r3, [r4, #0]
3ca: 2b74 cmp r3, #116 ; 0x74
3cc: d00c beq.n 3e8 <main+0x8c>
3ce: f7ff fedb bl 188 <set_halt_until_mbus_tx>
3d2: 4927 ldr r1, [pc, #156] ; (470 <main+0x114>)
3d4: 20e1 movs r0, #225 ; 0xe1
3d6: f7ff fee7 bl 1a8 <mbus_write_message32>
3da: 6821 ldr r1, [r4, #0]
3dc: 20e1 movs r0, #225 ; 0xe1
3de: f7ff fee3 bl 1a8 <mbus_write_message32>
3e2: f7ff ff0b bl 1fc <mbus_sleep_all>
3e6: e7fe b.n 3e6 <main+0x8a>
3e8: f7ff fece bl 188 <set_halt_until_mbus_tx>
3ec: 2004 movs r0, #4
3ee: 2100 movs r1, #0
3f0: f7ff fe86 bl 100 <FLSv1L_setFlashStartAddr>
3f4: 2004 movs r0, #4
3f6: 2100 movs r1, #0
3f8: f7ff fe7c bl f4 <FLSv1L_setSRAMStartAddr>
3fc: f7ff feb4 bl 168 <set_halt_until_mbus_rx>
400: 2004 movs r0, #4
402: 491d ldr r1, [pc, #116] ; (478 <main+0x11c>)
404: f7ff fe82 bl 10c <FLSv1L_doCopySRAM2Flash>
408: 6823 ldr r3, [r4, #0]
40a: 2b5c cmp r3, #92 ; 0x5c
40c: d00c beq.n 428 <main+0xcc>
40e: f7ff febb bl 188 <set_halt_until_mbus_tx>
412: 4917 ldr r1, [pc, #92] ; (470 <main+0x114>)
414: 20e2 movs r0, #226 ; 0xe2
416: f7ff fec7 bl 1a8 <mbus_write_message32>
41a: 6821 ldr r1, [r4, #0]
41c: 20e2 movs r0, #226 ; 0xe2
41e: f7ff fec3 bl 1a8 <mbus_write_message32>
422: f7ff feeb bl 1fc <mbus_sleep_all>
426: e7fe b.n 426 <main+0xca>
428: f7ff fe9e bl 168 <set_halt_until_mbus_rx>
42c: 2004 movs r0, #4
42e: f7ff fe38 bl a2 <FLSv1L_turnOffFlash>
432: 6823 ldr r3, [r4, #0]
434: 2b06 cmp r3, #6
436: d00c beq.n 452 <main+0xf6>
438: f7ff fea6 bl 188 <set_halt_until_mbus_tx>
43c: 490c ldr r1, [pc, #48] ; (470 <main+0x114>)
43e: 20e3 movs r0, #227 ; 0xe3
440: f7ff feb2 bl 1a8 <mbus_write_message32>
444: 6821 ldr r1, [r4, #0]
446: 20e3 movs r0, #227 ; 0xe3
448: f7ff feae bl 1a8 <mbus_write_message32>
44c: f7ff fed6 bl 1fc <mbus_sleep_all>
450: e7fe b.n 450 <main+0xf4>
452: f7ff fe99 bl 188 <set_halt_until_mbus_tx>
456: 2004 movs r0, #4
458: f7ff fe2f bl ba <FLSv1L_disableLargeCap>
45c: 4907 ldr r1, [pc, #28] ; (47c <main+0x120>)
45e: 20dd movs r0, #221 ; 0xdd
460: f7ff fea2 bl 1a8 <mbus_write_message32>
464: f7ff feca bl 1fc <mbus_sleep_all>
468: e7fe b.n 468 <main+0x10c>
46a: 46c0 nop ; (mov r8, r8)
46c: 00000814 .word 0x00000814
470: deadbeef .word 0xdeadbeef
474: 00000480 .word 0x00000480
478: 000007fe .word 0x000007fe
47c: 0ea7f00d .word 0x0ea7f00d
|
COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
Copyright (c) GeoWorks 1992 -- All Rights Reserved
PROJECT: PC GEOS
MODULE: GeoCalc/Document
FILE: documentMouse.asm
AUTHOR: Gene Anderson, Oct 12, 1992
ROUTINES:
Name Description
---- -----------
REVISION HISTORY:
Name Date Description
---- ---- -----------
Gene 10/12/92 Initial revision
DESCRIPTION:
Mouse messages for the GeoCalc document
$Id: documentMouse.asm,v 1.1 97/04/04 15:48:09 newdeal Exp $
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@
Document segment resource
if _CHARTS
COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
CheckGrObjMouse
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
SYNOPSIS: See if a mouse event is destined for the grobj
CALLED BY: GeoCalcDocumentPtr
PASS: *ds:si - GeoCalc document object
ss:bp - ptr to LargeMouseData
RETURN: z flag - clear (jnz) if destined for grobj
^lcx:dx - new pointer image
ax - MouseReturnFlags
^lbx:si - OD of grobj
DESTROYED: ax - if not destined for grobj
PSEUDO CODE/STRATEGY:
KNOWN BUGS/SIDE EFFECTS/IDEAS:
REVISION HISTORY:
Name Date Description
---- ---- -----------
gene 10/12/92 Initial version
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@
CheckGrObjMouse proc near
uses di
.enter
call GetGrObjBodyOD ;^lbx:si <- OD of grobj
CheckHack <(offset LMD_location) eq 0>
mov ax, MSG_GB_EVALUATE_MOUSE_POSITION
mov di, mask MF_CALL or mask MF_FIXUP_DS
call ObjMessage
cmp al, GOMRF_NOTHING ;set Z flag for not grobj
mov al, 0 ;ax <- MouseReturnFlags
.leave
ret
CheckGrObjMouse endp
endif
COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
GeoCalcDocumentPtr
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
SYNOPSIS: Handle pointer events for GeoCalc document
CALLED BY: MSG_META_LARGE_PTR
PASS: *ds:si - instance data
ds:di - *ds:si
es - seg addr of GeoCalcDocumentClass
ax - the message
ss:bp - ptr to LargeMouseData
RETURN: ax - MouseReturnFlags
DESTROYED: bx, si, di, ds, es (method handler)
PSEUDO CODE/STRATEGY:
KNOWN BUGS/SIDE EFFECTS/IDEAS:
REVISION HISTORY:
Name Date Description
---- ---- -----------
gene 10/12/92 Initial version
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@
GeoCalcDocumentPtr method dynamic GeoCalcDocumentClass,
MSG_META_LARGE_PTR
;
; See if the edit bar has the focus. If we're doing cell references
; in the edit bar, just pass the ptr event off so it goes to the
; spreadsheet.
;
call CheckEditBarFocus
jc notPtrTool ;branch if edit bar has focus
;
; Get the current tool -- if it isn't the pointer, just pass it on
;
CHART< call IsPtrTool >
CHART< jnz notPtrTool ;branch if not pointer tool >
;
; Ask the GrObj if it can deal with the pointer
;
if _CHARTS
push si
call CheckGrObjMouse
pop si ;*ds:si <- document object
jnz isGrObj ;branch if for grobj
endif
;
; If not, send to the spreadsheet
;
call GetDocSpreadsheet ;^
mov ax, MSG_META_LARGE_PTR
mov di, mask MF_FIXUP_DS or mask MF_CALL
call ObjMessage
isGrObj::
ornf ax, mask MRF_PROCESSED ;ax <- MouseReturnFlags
ret
notPtrTool:
mov di, offset GeoCalcDocumentClass
GOTO ObjCallSuperNoLock
GeoCalcDocumentPtr endm
COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
GeoCalcDocumentStartSelect
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
SYNOPSIS: Handle start select events for GeoCalc document
CALLED BY: MSG_META_LARGE_START_SELECT
PASS: *ds:si - instance data
ds:di - *ds:si
es - seg addr of GeoCalcDocumentClass
ax - the message
ss:bp - ptr to LargeMouseData
RETURN: ax - MouseReturnFlags
DESTROYED: bx, si, di, ds, es (method handler)
PSEUDO CODE/STRATEGY:
KNOWN BUGS/SIDE EFFECTS/IDEAS:
REVISION HISTORY:
Name Date Description
---- ---- -----------
gene 10/12/92 Initial version
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@
GeoCalcDocumentStartSelect method dynamic GeoCalcDocumentClass,
MSG_META_LARGE_START_SELECT
mov di, si ;*ds:di <- document object
;
; See if the edit bar has the focus. If we're doing cell references
; in the edit bar, just pass the ptr event off so it goes to the
; spreadsheet.
;
call CheckEditBarFocus
jc notPtrTool ;branch if edit bar has focus
;
; Get the current tool -- if it isn't the pointer, just pass it on
;
if _CHARTS
call IsPtrTool
jnz notPtrTool ;branch if not pointer tool
;
; Ask the GrObj if it can deal with the pointer
;
call CheckGrObjMouse
mov cl, GCTL_GROBJ
jnz changeTarget ;branch if for grobj
endif
;
; If not, send to the spreadsheet
;
mov si, di ;*ds:si <- document object
call GetDocSpreadsheet ;^lbx:si <- OD of spreadsheet
mov cl, GCTL_SPREADSHEET
;
; Tell either the spreadsheet or the grobj to grab the focus and
; target...
;
changeTarget::
call SetTargetLayerOpt
;
; ...and then pass it the start select.
;
mov ax, MSG_META_LARGE_START_SELECT
mov di, mask MF_FIXUP_DS or mask MF_CALL
call ObjMessage
ret
notPtrTool:
mov di, offset GeoCalcDocumentClass
GOTO ObjCallSuperNoLock
GeoCalcDocumentStartSelect endm
COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
SetTargetLayer
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
SYNOPSIS: Set the target layer
CALLED BY: GeoCalcDocumentStartSelect()
PASS: ^lbx:si - OD of grobj or spreadsheet
cl - GeoCalcTargetLayer
ds - fixupable segment owned by GeoCalc
carry - clear to check if target layer changing
RETURN: none
DESTROYED: none
PSEUDO CODE/STRATEGY:
KNOWN BUGS/SIDE EFFECTS/IDEAS:
REVISION HISTORY:
Name Date Description
---- ---- -----------
gene 10/13/92 Initial version
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@
SetTargetLayerOpt proc near
clc ;carry <- optimization OK
FALL_THRU SetTargetLayer
SetTargetLayerOpt endp
SetTargetLayer proc near
uses ax, bx, cx, dx, bp, di, si
.enter
;
; See if we're allowed to optimize and check our current
; notion of the target.
;
jc doChange ;branch if no optimization
;
; See if the layer has actually changed -- if not, quit
;
push cx
mov ax, MSG_GEOCALC_APPLICATION_GET_TARGET_LAYER
call UserCallApplication
mov dl, cl ;dl <- current layer
pop cx
cmp cl, dl ;layer changed?
je quit ;branch if not changed
;
; Notify the app obj of the target change
;
doChange:
push cx
mov ax, MSG_GEOCALC_APPLICATION_SET_TARGET_LAYER
call UserCallApplication
pop cx
if _CHARTS
;
; If the new layer is the spreadsheet layer, unselect all grobjs
;
cmp cl, GCTL_SPREADSHEET
jne noDeselect
push bx, si ; save spreadsheet obj
mov ax, MSG_VIS_FIND_PARENT
call callObjMessage ; ^lcx:dx = document obj
jcxz oops
movdw bxsi, cxdx ; ^lbx:si = document obj
mov cx, 1 ; first child is grobj body
mov ax, MSG_VIS_FIND_CHILD_AT_POSITION
call callObjMessage ; ^lcx:dx = grobj body
jcxz oops
movdw bxsi, cxdx
mov ax, MSG_GB_REMOVE_ALL_GROBJS_FROM_SELECTION_LIST
call callObjMessage
oops:
pop bx, si ; restore ss obj
noDeselect:
endif
;
; Set the focus and target to the specified OD
;
mov ax, MSG_META_GRAB_FOCUS_EXCL
call callObjMessage
mov ax, MSG_META_GRAB_TARGET_EXCL
call callObjMessage
quit:
.leave
ret
callObjMessage:
mov di, mask MF_FIXUP_DS or mask MF_CALL
call ObjMessage
retn
SetTargetLayer endp
COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
GeoCalcDocumentSetTarget
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
SYNOPSIS: Set the target layer
CALLED BY: MSG_GEOCALC_DOCUMENT_SET_TARGET
PASS: *ds:si - instance data
ds:di - *ds:si
es - seg addr of GeoCalcDocumentClass
ax - the message
cl - GeoCalcTargetLayer
RETURN: none
DESTROYED: bx, si, di, ds, es (method handler)
PSEUDO CODE/STRATEGY:
KNOWN BUGS/SIDE EFFECTS/IDEAS:
REVISION HISTORY:
Name Date Description
---- ---- -----------
gene 12/28/92 Initial version
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@
GeoCalcDocumentSetTarget method dynamic GeoCalcDocumentClass,
MSG_GEOCALC_DOCUMENT_SET_TARGET
cmp cl, GCTL_SPREADSHEET
je isSpreadsheet
if _CHARTS
call GetGrObjBodyOD ;^lbx:si <- OD of GrObj
jmp setLayer
else
EC< ERROR -1 >
endif
isSpreadsheet:
call GetDocSpreadsheet ;^lbx:si <- OD of spreadsheet
setLayer::
call SetTargetLayerOpt
ret
GeoCalcDocumentSetTarget endm
COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
GeoCalcDocumentGainedFocus
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
SYNOPSIS: Handle gaining the focus
CALLED BY: MSG_META_GAINED_FOCUS_EXCL
PASS: *ds:si - instance data
ds:di - *ds:si
es - seg addr of GeoCalcDocumentClass
ax - the message
RETURN: none
DESTROYED: bx, si, di, ds, es (method handler)
PSEUDO CODE/STRATEGY:
KNOWN BUGS/SIDE EFFECTS/IDEAS:
REVISION HISTORY:
Name Date Description
---- ---- -----------
gene 2/ 2/93 Initial version
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@
GeoCalcDocumentGainedFocus method dynamic GeoCalcDocumentClass,
MSG_META_GAINED_FOCUS_EXCL
ornf ds:[di].GCDI_flags, mask GCDF_IS_FOCUS
mov di, offset GeoCalcDocumentClass
GOTO ObjCallSuperNoLock
GeoCalcDocumentGainedFocus endm
COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
GeoCalcDocumentLostFocus
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
SYNOPSIS: Handle losing the focus
CALLED BY: MSG_META_LOST_FOCUS_EXCL
PASS: *ds:si - instance data
ds:di - *ds:si
es - seg addr of GeoCalcDocumentClass
ax - the message
RETURN: none
DESTROYED: bx, si, di, ds, es (method handler)
PSEUDO CODE/STRATEGY:
KNOWN BUGS/SIDE EFFECTS/IDEAS:
REVISION HISTORY:
Name Date Description
---- ---- -----------
gene 2/ 2/93 Initial version
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@
GeoCalcDocumentLostFocus method dynamic GeoCalcDocumentClass,
MSG_META_LOST_FOCUS_EXCL
andnf ds:[di].GCDI_flags, not (mask GCDF_IS_FOCUS)
mov di, offset GeoCalcDocumentClass
GOTO ObjCallSuperNoLock
GeoCalcDocumentLostFocus endm
COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
CheckEditBarFocus
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
SYNOPSIS: See if the edit bar has the focus
CALLED BY: UTILITY
PASS: *ds:si - geocalc document object
RETURN: carry - clear if edit bar doesn't have focus
DESTROYED: none
PSEUDO CODE/STRATEGY:
KNOWN BUGS/SIDE EFFECTS/IDEAS:
REVISION HISTORY:
Name Date Description
---- ---- -----------
gene 2/ 2/93 Initial version
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@
CheckEditBarFocus proc near
uses si
class GeoCalcDocumentClass
.enter
EC < call ECGeoCalcDocument ;>
;
; Do the quick check to see if we have the focus
; (ie. that the edit bar doesn't). This is the common case.
;
mov si, ds:[si]
add si, ds:[si].GeoCalcDocument_offset
test ds:[si].GCDI_flags, mask GCDF_IS_FOCUS
jnz noEditBarFocus ;branch (carry clear)
;
; We don't have the focus -- see if the edit bar does
;
push ax, cx, di
mov ax, MSG_SSEBC_GET_FLAGS
GetResourceHandleNS GCEditBarControl, bx
mov si, offset GCEditBarControl ;^lbx:si <- OD of display ctrl
mov di, mask MF_CALL or mask MF_FIXUP_DS
call ObjMessage
test cl, mask SSEBCF_IS_FOCUS ;is edit bar focus?
pop ax, cx, di
jz noEditBarFocus ;exit if not
stc ;carry <- edit bar has focus
noEditBarFocus:
.leave
ret
CheckEditBarFocus endp
COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
GeoCalcDocumentGetFlags
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
SYNOPSIS: Get flags for a GeoCalc document
CALLED BY: MSG_GEOCALC_DOCUMENT_GET_FLAGS
PASS: *ds:si - instance data
ds:di - *ds:si
es - seg addr of GeoCalcDocumentClass
ax - the message
RETURN: cl - GeoCalcDocumentFlags
DESTROYED: bx, si, di, ds, es (method handler)
PSEUDO CODE/STRATEGY:
KNOWN BUGS/SIDE EFFECTS/IDEAS:
REVISION HISTORY:
Name Date Description
---- ---- -----------
gene 2/ 3/93 Initial version
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@
GeoCalcDocumentGetFlags method dynamic GeoCalcDocumentClass,
MSG_GEOCALC_DOCUMENT_GET_FLAGS
mov cl, ds:[di].GCDI_flags ;cl <- GeoCalcDocumentFlags
ret
GeoCalcDocumentGetFlags endm
Document ends
|
.global s_prepare_buffers
s_prepare_buffers:
push %r10
push %r11
push %r15
push %rbx
push %rcx
push %rdi
push %rdx
push %rsi
lea addresses_WT_ht+0x1ab87, %r11
nop
nop
cmp $44662, %r10
movw $0x6162, (%r11)
add %r10, %r10
lea addresses_normal_ht+0xf787, %rsi
lea addresses_D_ht+0x20f7, %rdi
clflush (%rdi)
nop
nop
nop
nop
nop
inc %rdx
mov $46, %rcx
rep movsq
nop
nop
nop
cmp $53069, %rcx
lea addresses_UC_ht+0x8607, %rsi
nop
nop
nop
sub %r15, %r15
movb (%rsi), %cl
nop
nop
nop
nop
nop
add %rdi, %rdi
lea addresses_WT_ht+0x4af, %rdx
nop
nop
nop
nop
add $61253, %r11
mov (%rdx), %r15w
nop
nop
sub $47940, %rdi
lea addresses_WT_ht+0x12287, %rsi
lea addresses_WT_ht+0x6b07, %rdi
clflush (%rdi)
dec %rbx
mov $76, %rcx
rep movsb
nop
dec %rbx
lea addresses_normal_ht+0xfe07, %rsi
clflush (%rsi)
nop
nop
nop
nop
cmp %r10, %r10
movl $0x61626364, (%rsi)
nop
nop
nop
nop
add %rdx, %rdx
lea addresses_A_ht+0x15d2b, %rbx
nop
nop
and %r15, %r15
mov $0x6162636465666768, %rdi
movq %rdi, %xmm5
movups %xmm5, (%rbx)
nop
nop
nop
nop
sub %rcx, %rcx
pop %rsi
pop %rdx
pop %rdi
pop %rcx
pop %rbx
pop %r15
pop %r11
pop %r10
ret
.global s_faulty_load
s_faulty_load:
push %r10
push %r11
push %r12
push %r13
push %rax
push %rdx
push %rsi
// Store
lea addresses_UC+0x11704, %rdx
nop
xor %r13, %r13
mov $0x5152535455565758, %rsi
movq %rsi, %xmm5
movups %xmm5, (%rdx)
nop
nop
nop
nop
nop
and $19414, %r11
// Store
mov $0xa07, %r11
nop
add %rsi, %rsi
movb $0x51, (%r11)
sub $33722, %r13
// Store
lea addresses_PSE+0xfe03, %rdx
nop
nop
nop
nop
sub %r10, %r10
movb $0x51, (%rdx)
nop
nop
and %rdx, %rdx
// Store
lea addresses_A+0x18887, %r11
clflush (%r11)
nop
nop
sub %r13, %r13
movl $0x51525354, (%r11)
nop
nop
nop
nop
sub $50952, %r12
// Store
lea addresses_WT+0x17507, %r11
nop
nop
nop
nop
add $45862, %r12
movl $0x51525354, (%r11)
nop
nop
nop
sub $4669, %r12
// Store
lea addresses_D+0x1fa07, %r11
nop
and $9660, %rdx
mov $0x5152535455565758, %rsi
movq %rsi, (%r11)
nop
nop
dec %r12
// Faulty Load
lea addresses_WT+0x18e07, %r10
nop
nop
nop
nop
nop
and %rax, %rax
vmovaps (%r10), %ymm1
vextracti128 $0, %ymm1, %xmm1
vpextrq $1, %xmm1, %r12
lea oracles, %r11
and $0xff, %r12
shlq $12, %r12
mov (%r11,%r12,1), %r12
pop %rsi
pop %rdx
pop %rax
pop %r13
pop %r12
pop %r11
pop %r10
ret
/*
<gen_faulty_load>
[REF]
{'OP': 'LOAD', 'src': {'type': 'addresses_WT', 'size': 2, 'AVXalign': False, 'NT': False, 'congruent': 0, 'same': False}}
{'OP': 'STOR', 'dst': {'type': 'addresses_UC', 'size': 16, 'AVXalign': False, 'NT': False, 'congruent': 0, 'same': False}}
{'OP': 'STOR', 'dst': {'type': 'addresses_P', 'size': 1, 'AVXalign': False, 'NT': False, 'congruent': 10, 'same': False}}
{'OP': 'STOR', 'dst': {'type': 'addresses_PSE', 'size': 1, 'AVXalign': False, 'NT': False, 'congruent': 1, 'same': False}}
{'OP': 'STOR', 'dst': {'type': 'addresses_A', 'size': 4, 'AVXalign': False, 'NT': False, 'congruent': 7, 'same': False}}
{'OP': 'STOR', 'dst': {'type': 'addresses_WT', 'size': 4, 'AVXalign': False, 'NT': True, 'congruent': 7, 'same': False}}
{'OP': 'STOR', 'dst': {'type': 'addresses_D', 'size': 8, 'AVXalign': False, 'NT': False, 'congruent': 9, 'same': False}}
[Faulty Load]
{'OP': 'LOAD', 'src': {'type': 'addresses_WT', 'size': 32, 'AVXalign': True, 'NT': False, 'congruent': 0, 'same': True}}
<gen_prepare_buffer>
{'OP': 'STOR', 'dst': {'type': 'addresses_WT_ht', 'size': 2, 'AVXalign': False, 'NT': False, 'congruent': 5, 'same': False}}
{'OP': 'REPM', 'src': {'type': 'addresses_normal_ht', 'congruent': 7, 'same': False}, 'dst': {'type': 'addresses_D_ht', 'congruent': 4, 'same': False}}
{'OP': 'LOAD', 'src': {'type': 'addresses_UC_ht', 'size': 1, 'AVXalign': False, 'NT': False, 'congruent': 11, 'same': False}}
{'OP': 'LOAD', 'src': {'type': 'addresses_WT_ht', 'size': 2, 'AVXalign': False, 'NT': False, 'congruent': 2, 'same': False}}
{'OP': 'REPM', 'src': {'type': 'addresses_WT_ht', 'congruent': 5, 'same': False}, 'dst': {'type': 'addresses_WT_ht', 'congruent': 7, 'same': False}}
{'OP': 'STOR', 'dst': {'type': 'addresses_normal_ht', 'size': 4, 'AVXalign': False, 'NT': False, 'congruent': 10, 'same': False}}
{'OP': 'STOR', 'dst': {'type': 'addresses_A_ht', 'size': 16, 'AVXalign': False, 'NT': False, 'congruent': 0, 'same': False}}
{'00': 1, '44': 166, '49': 33}
00 44 44 44 49 44 44 44 44 44 44 44 44 44 49 44 49 44 44 44 44 44 44 49 44 44 44 44 44 44 44 44 44 44 49 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 49 44 44 44 44 44 44 44 44 44 44 44 49 44 44 49 49 49 44 44 44 44 44 49 44 44 44 44 44 44 49 44 44 44 44 44 44 44 49 44 44 44 49 44 49 44 44 49 49 44 44 44 44 44 49 44 49 44 44 44 49 44 44 44 44 44 44 44 44 44 44 44 49 49 44 44 44 49 44 44 44 44 49 44 49 44 44 49 44 44 44 49 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 49 49 44 49 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 49 49 49 44 44 44 44 44 44 44 44
*/
|
;/* inffas32.asm is a hand tuned assembler version of inffast.c -- fast decoding
; *
; * inffas32.asm is derivated from inffas86.c, with translation of assembly code
; *
; * Copyright (C) 1995-2003 Mark Adler
; * For conditions of distribution and use, see copyright notice in zlib.h
; *
; * Copyright (C) 2003 Chris Anderson <christop@charm.net>
; * Please use the copyright conditions above.
; *
; * Mar-13-2003 -- Most of this is derived from inffast.S which is derived from
; * the gcc -S output of zlib-1.2.0/inffast.c. Zlib-1.2.0 is in beta release at
; * the moment. I have successfully compiled and tested this code with gcc2.96,
; * gcc3.2, icc5.0, msvc6.0. It is very close to the speed of inffast.S
; * compiled with gcc -DNO_MMX, but inffast.S is still faster on the P3 with MMX
; * enabled. I will attempt to merge the MMX code into this version. Newer
; * versions of this and inffast.S can be found at
; * http://www.eetbeetee.com/zlib/ and http://www.charm.net/~christop/zlib/
; *
; * 2005 : modification by Gilles Vollant
; */
; For Visual C++ 4.x and higher and ML 6.x and higher
; ml.exe is in directory \MASM611C of Win95 DDK
; ml.exe is also distributed in http://www.masm32.com/masmdl.htm
; and in VC++2003 toolkit at http://msdn.microsoft.com/visualc/vctoolkit2003/
;
;
; compile with command line option
; ml /coff /Zi /c /Flinffas32.lst inffas32.asm
; if you define NO_GZIP (see inflate.h), compile with
; ml /coff /Zi /c /Flinffas32.lst /DNO_GUNZIP inffas32.asm
; zlib122sup is 0 fort zlib 1.2.2.1 and lower
; zlib122sup is 8 fort zlib 1.2.2.2 and more (with addition of dmax and head
; in inflate_state in inflate.h)
zlib1222sup equ 8
IFDEF GUNZIP
INFLATE_MODE_TYPE equ 11
INFLATE_MODE_BAD equ 26
ELSE
IFNDEF NO_GUNZIP
INFLATE_MODE_TYPE equ 11
INFLATE_MODE_BAD equ 26
ELSE
INFLATE_MODE_TYPE equ 3
INFLATE_MODE_BAD equ 17
ENDIF
ENDIF
; 75 "inffast.S"
;FILE "inffast.S"
;;;GLOBAL _inflate_fast
;;;SECTION .text
.586p
.mmx
name inflate_fast_x86
.MODEL FLAT
_DATA segment
inflate_fast_use_mmx:
dd 1
_TEXT segment
ALIGN 4
db 'Fast decoding Code from Chris Anderson'
db 0
ALIGN 4
invalid_literal_length_code_msg:
db 'invalid literal/length code'
db 0
ALIGN 4
invalid_distance_code_msg:
db 'invalid distance code'
db 0
ALIGN 4
invalid_distance_too_far_msg:
db 'invalid distance too far back'
db 0
ALIGN 4
inflate_fast_mask:
dd 0
dd 1
dd 3
dd 7
dd 15
dd 31
dd 63
dd 127
dd 255
dd 511
dd 1023
dd 2047
dd 4095
dd 8191
dd 16383
dd 32767
dd 65535
dd 131071
dd 262143
dd 524287
dd 1048575
dd 2097151
dd 4194303
dd 8388607
dd 16777215
dd 33554431
dd 67108863
dd 134217727
dd 268435455
dd 536870911
dd 1073741823
dd 2147483647
dd 4294967295
mode_state equ 0 ;/* state->mode */
wsize_state equ (32+zlib1222sup) ;/* state->wsize */
write_state equ (36+4+zlib1222sup) ;/* state->write */
window_state equ (40+4+zlib1222sup) ;/* state->window */
hold_state equ (44+4+zlib1222sup) ;/* state->hold */
bits_state equ (48+4+zlib1222sup) ;/* state->bits */
lencode_state equ (64+4+zlib1222sup) ;/* state->lencode */
distcode_state equ (68+4+zlib1222sup) ;/* state->distcode */
lenbits_state equ (72+4+zlib1222sup) ;/* state->lenbits */
distbits_state equ (76+4+zlib1222sup) ;/* state->distbits */
;;SECTION .text
; 205 "inffast.S"
;GLOBAL inflate_fast_use_mmx
;SECTION .data
; GLOBAL inflate_fast_use_mmx:object
;.mem_usage inflate_fast_use_mmx, 4
; 226 "inffast.S"
;SECTION .text
ALIGN 4
_inflate_fast proc near
.FPO (16, 4, 0, 0, 1, 0)
push edi
push esi
push ebp
push ebx
pushfd
sub esp,64
cld
mov esi, [esp+88]
mov edi, [esi+28]
mov edx, [esi+4]
mov eax, [esi+0]
add edx,eax
sub edx,11
mov [esp+44],eax
mov [esp+20],edx
mov ebp, [esp+92]
mov ecx, [esi+16]
mov ebx, [esi+12]
sub ebp,ecx
neg ebp
add ebp,ebx
sub ecx,257
add ecx,ebx
mov [esp+60],ebx
mov [esp+40],ebp
mov [esp+16],ecx
; 285 "inffast.S"
mov eax, [edi+lencode_state]
mov ecx, [edi+distcode_state]
mov [esp+8],eax
mov [esp+12],ecx
mov eax,1
mov ecx, [edi+lenbits_state]
shl eax,cl
dec eax
mov [esp+0],eax
mov eax,1
mov ecx, [edi+distbits_state]
shl eax,cl
dec eax
mov [esp+4],eax
mov eax, [edi+wsize_state]
mov ecx, [edi+write_state]
mov edx, [edi+window_state]
mov [esp+52],eax
mov [esp+48],ecx
mov [esp+56],edx
mov ebp, [edi+hold_state]
mov ebx, [edi+bits_state]
; 321 "inffast.S"
mov esi, [esp+44]
mov ecx, [esp+20]
cmp ecx,esi
ja L_align_long
add ecx,11
sub ecx,esi
mov eax,12
sub eax,ecx
lea edi, [esp+28]
rep movsb
mov ecx,eax
xor eax,eax
rep stosb
lea esi, [esp+28]
mov [esp+20],esi
jmp L_is_aligned
L_align_long:
test esi,3
jz L_is_aligned
xor eax,eax
mov al, [esi]
inc esi
mov ecx,ebx
add ebx,8
shl eax,cl
or ebp,eax
jmp L_align_long
L_is_aligned:
mov edi, [esp+60]
; 366 "inffast.S"
L_check_mmx:
cmp dword ptr [inflate_fast_use_mmx],2
je L_init_mmx
ja L_do_loop
push eax
push ebx
push ecx
push edx
pushfd
mov eax, [esp]
xor dword ptr [esp],0200000h
popfd
pushfd
pop edx
xor edx,eax
jz L_dont_use_mmx
xor eax,eax
cpuid
cmp ebx,0756e6547h
jne L_dont_use_mmx
cmp ecx,06c65746eh
jne L_dont_use_mmx
cmp edx,049656e69h
jne L_dont_use_mmx
mov eax,1
cpuid
shr eax,8
and eax,15
cmp eax,6
jne L_dont_use_mmx
test edx,0800000h
jnz L_use_mmx
jmp L_dont_use_mmx
L_use_mmx:
mov dword ptr [inflate_fast_use_mmx],2
jmp L_check_mmx_pop
L_dont_use_mmx:
mov dword ptr [inflate_fast_use_mmx],3
L_check_mmx_pop:
pop edx
pop ecx
pop ebx
pop eax
jmp L_check_mmx
; 426 "inffast.S"
ALIGN 4
L_do_loop:
; 437 "inffast.S"
cmp bl,15
ja L_get_length_code
xor eax,eax
lodsw
mov cl,bl
add bl,16
shl eax,cl
or ebp,eax
L_get_length_code:
mov edx, [esp+0]
mov ecx, [esp+8]
and edx,ebp
mov eax, [ecx+edx*4]
L_dolen:
mov cl,ah
sub bl,ah
shr ebp,cl
test al,al
jnz L_test_for_length_base
shr eax,16
stosb
L_while_test:
cmp [esp+16],edi
jbe L_break_loop
cmp [esp+20],esi
ja L_do_loop
jmp L_break_loop
L_test_for_length_base:
; 502 "inffast.S"
mov edx,eax
shr edx,16
mov cl,al
test al,16
jz L_test_for_second_level_length
and cl,15
jz L_save_len
cmp bl,cl
jae L_add_bits_to_len
mov ch,cl
xor eax,eax
lodsw
mov cl,bl
add bl,16
shl eax,cl
or ebp,eax
mov cl,ch
L_add_bits_to_len:
mov eax,1
shl eax,cl
dec eax
sub bl,cl
and eax,ebp
shr ebp,cl
add edx,eax
L_save_len:
mov [esp+24],edx
L_decode_distance:
; 549 "inffast.S"
cmp bl,15
ja L_get_distance_code
xor eax,eax
lodsw
mov cl,bl
add bl,16
shl eax,cl
or ebp,eax
L_get_distance_code:
mov edx, [esp+4]
mov ecx, [esp+12]
and edx,ebp
mov eax, [ecx+edx*4]
L_dodist:
mov edx,eax
shr edx,16
mov cl,ah
sub bl,ah
shr ebp,cl
; 584 "inffast.S"
mov cl,al
test al,16
jz L_test_for_second_level_dist
and cl,15
jz L_check_dist_one
cmp bl,cl
jae L_add_bits_to_dist
mov ch,cl
xor eax,eax
lodsw
mov cl,bl
add bl,16
shl eax,cl
or ebp,eax
mov cl,ch
L_add_bits_to_dist:
mov eax,1
shl eax,cl
dec eax
sub bl,cl
and eax,ebp
shr ebp,cl
add edx,eax
jmp L_check_window
L_check_window:
; 625 "inffast.S"
mov [esp+44],esi
mov eax,edi
sub eax, [esp+40]
cmp eax,edx
jb L_clip_window
mov ecx, [esp+24]
mov esi,edi
sub esi,edx
sub ecx,3
mov al, [esi]
mov [edi],al
mov al, [esi+1]
mov dl, [esi+2]
add esi,3
mov [edi+1],al
mov [edi+2],dl
add edi,3
rep movsb
mov esi, [esp+44]
jmp L_while_test
ALIGN 4
L_check_dist_one:
cmp edx,1
jne L_check_window
cmp [esp+40],edi
je L_check_window
dec edi
mov ecx, [esp+24]
mov al, [edi]
sub ecx,3
mov [edi+1],al
mov [edi+2],al
mov [edi+3],al
add edi,4
rep stosb
jmp L_while_test
ALIGN 4
L_test_for_second_level_length:
test al,64
jnz L_test_for_end_of_block
mov eax,1
shl eax,cl
dec eax
and eax,ebp
add eax,edx
mov edx, [esp+8]
mov eax, [edx+eax*4]
jmp L_dolen
ALIGN 4
L_test_for_second_level_dist:
test al,64
jnz L_invalid_distance_code
mov eax,1
shl eax,cl
dec eax
and eax,ebp
add eax,edx
mov edx, [esp+12]
mov eax, [edx+eax*4]
jmp L_dodist
ALIGN 4
L_clip_window:
; 721 "inffast.S"
mov ecx,eax
mov eax, [esp+52]
neg ecx
mov esi, [esp+56]
cmp eax,edx
jb L_invalid_distance_too_far
add ecx,edx
cmp dword ptr [esp+48],0
jne L_wrap_around_window
sub eax,ecx
add esi,eax
; 749 "inffast.S"
mov eax, [esp+24]
cmp eax,ecx
jbe L_do_copy1
sub eax,ecx
rep movsb
mov esi,edi
sub esi,edx
jmp L_do_copy1
cmp eax,ecx
jbe L_do_copy1
sub eax,ecx
rep movsb
mov esi,edi
sub esi,edx
jmp L_do_copy1
L_wrap_around_window:
; 793 "inffast.S"
mov eax, [esp+48]
cmp ecx,eax
jbe L_contiguous_in_window
add esi, [esp+52]
add esi,eax
sub esi,ecx
sub ecx,eax
mov eax, [esp+24]
cmp eax,ecx
jbe L_do_copy1
sub eax,ecx
rep movsb
mov esi, [esp+56]
mov ecx, [esp+48]
cmp eax,ecx
jbe L_do_copy1
sub eax,ecx
rep movsb
mov esi,edi
sub esi,edx
jmp L_do_copy1
L_contiguous_in_window:
; 836 "inffast.S"
add esi,eax
sub esi,ecx
mov eax, [esp+24]
cmp eax,ecx
jbe L_do_copy1
sub eax,ecx
rep movsb
mov esi,edi
sub esi,edx
L_do_copy1:
; 862 "inffast.S"
mov ecx,eax
rep movsb
mov esi, [esp+44]
jmp L_while_test
; 878 "inffast.S"
ALIGN 4
L_init_mmx:
emms
movd mm0,ebp
mov ebp,ebx
; 896 "inffast.S"
movd mm4,dword ptr [esp+0]
movq mm3,mm4
movd mm5,dword ptr [esp+4]
movq mm2,mm5
pxor mm1,mm1
mov ebx, [esp+8]
jmp L_do_loop_mmx
ALIGN 4
L_do_loop_mmx:
psrlq mm0,mm1
cmp ebp,32
ja L_get_length_code_mmx
movd mm6,ebp
movd mm7,dword ptr [esi]
add esi,4
psllq mm7,mm6
add ebp,32
por mm0,mm7
L_get_length_code_mmx:
pand mm4,mm0
movd eax,mm4
movq mm4,mm3
mov eax, [ebx+eax*4]
L_dolen_mmx:
movzx ecx,ah
movd mm1,ecx
sub ebp,ecx
test al,al
jnz L_test_for_length_base_mmx
shr eax,16
stosb
L_while_test_mmx:
cmp [esp+16],edi
jbe L_break_loop
cmp [esp+20],esi
ja L_do_loop_mmx
jmp L_break_loop
L_test_for_length_base_mmx:
mov edx,eax
shr edx,16
test al,16
jz L_test_for_second_level_length_mmx
and eax,15
jz L_decode_distance_mmx
psrlq mm0,mm1
movd mm1,eax
movd ecx,mm0
sub ebp,eax
and ecx, [inflate_fast_mask+eax*4]
add edx,ecx
L_decode_distance_mmx:
psrlq mm0,mm1
cmp ebp,32
ja L_get_dist_code_mmx
movd mm6,ebp
movd mm7,dword ptr [esi]
add esi,4
psllq mm7,mm6
add ebp,32
por mm0,mm7
L_get_dist_code_mmx:
mov ebx, [esp+12]
pand mm5,mm0
movd eax,mm5
movq mm5,mm2
mov eax, [ebx+eax*4]
L_dodist_mmx:
movzx ecx,ah
mov ebx,eax
shr ebx,16
sub ebp,ecx
movd mm1,ecx
test al,16
jz L_test_for_second_level_dist_mmx
and eax,15
jz L_check_dist_one_mmx
L_add_bits_to_dist_mmx:
psrlq mm0,mm1
movd mm1,eax
movd ecx,mm0
sub ebp,eax
and ecx, [inflate_fast_mask+eax*4]
add ebx,ecx
L_check_window_mmx:
mov [esp+44],esi
mov eax,edi
sub eax, [esp+40]
cmp eax,ebx
jb L_clip_window_mmx
mov ecx,edx
mov esi,edi
sub esi,ebx
sub ecx,3
mov al, [esi]
mov [edi],al
mov al, [esi+1]
mov dl, [esi+2]
add esi,3
mov [edi+1],al
mov [edi+2],dl
add edi,3
rep movsb
mov esi, [esp+44]
mov ebx, [esp+8]
jmp L_while_test_mmx
ALIGN 4
L_check_dist_one_mmx:
cmp ebx,1
jne L_check_window_mmx
cmp [esp+40],edi
je L_check_window_mmx
dec edi
mov ecx,edx
mov al, [edi]
sub ecx,3
mov [edi+1],al
mov [edi+2],al
mov [edi+3],al
add edi,4
rep stosb
mov ebx, [esp+8]
jmp L_while_test_mmx
ALIGN 4
L_test_for_second_level_length_mmx:
test al,64
jnz L_test_for_end_of_block
and eax,15
psrlq mm0,mm1
movd ecx,mm0
and ecx, [inflate_fast_mask+eax*4]
add ecx,edx
mov eax, [ebx+ecx*4]
jmp L_dolen_mmx
ALIGN 4
L_test_for_second_level_dist_mmx:
test al,64
jnz L_invalid_distance_code
and eax,15
psrlq mm0,mm1
movd ecx,mm0
and ecx, [inflate_fast_mask+eax*4]
mov eax, [esp+12]
add ecx,ebx
mov eax, [eax+ecx*4]
jmp L_dodist_mmx
ALIGN 4
L_clip_window_mmx:
mov ecx,eax
mov eax, [esp+52]
neg ecx
mov esi, [esp+56]
cmp eax,ebx
jb L_invalid_distance_too_far
add ecx,ebx
cmp dword ptr [esp+48],0
jne L_wrap_around_window_mmx
sub eax,ecx
add esi,eax
cmp edx,ecx
jbe L_do_copy1_mmx
sub edx,ecx
rep movsb
mov esi,edi
sub esi,ebx
jmp L_do_copy1_mmx
cmp edx,ecx
jbe L_do_copy1_mmx
sub edx,ecx
rep movsb
mov esi,edi
sub esi,ebx
jmp L_do_copy1_mmx
L_wrap_around_window_mmx:
mov eax, [esp+48]
cmp ecx,eax
jbe L_contiguous_in_window_mmx
add esi, [esp+52]
add esi,eax
sub esi,ecx
sub ecx,eax
cmp edx,ecx
jbe L_do_copy1_mmx
sub edx,ecx
rep movsb
mov esi, [esp+56]
mov ecx, [esp+48]
cmp edx,ecx
jbe L_do_copy1_mmx
sub edx,ecx
rep movsb
mov esi,edi
sub esi,ebx
jmp L_do_copy1_mmx
L_contiguous_in_window_mmx:
add esi,eax
sub esi,ecx
cmp edx,ecx
jbe L_do_copy1_mmx
sub edx,ecx
rep movsb
mov esi,edi
sub esi,ebx
L_do_copy1_mmx:
mov ecx,edx
rep movsb
mov esi, [esp+44]
mov ebx, [esp+8]
jmp L_while_test_mmx
; 1174 "inffast.S"
L_invalid_distance_code:
mov ecx, invalid_distance_code_msg
mov edx,INFLATE_MODE_BAD
jmp L_update_stream_state
L_test_for_end_of_block:
test al,32
jz L_invalid_literal_length_code
mov ecx,0
mov edx,INFLATE_MODE_TYPE
jmp L_update_stream_state
L_invalid_literal_length_code:
mov ecx, invalid_literal_length_code_msg
mov edx,INFLATE_MODE_BAD
jmp L_update_stream_state
L_invalid_distance_too_far:
mov esi, [esp+44]
mov ecx, invalid_distance_too_far_msg
mov edx,INFLATE_MODE_BAD
jmp L_update_stream_state
L_update_stream_state:
mov eax, [esp+88]
test ecx,ecx
jz L_skip_msg
mov [eax+24],ecx
L_skip_msg:
mov eax, [eax+28]
mov [eax+mode_state],edx
jmp L_break_loop
ALIGN 4
L_break_loop:
; 1243 "inffast.S"
cmp dword ptr [inflate_fast_use_mmx],2
jne L_update_next_in
mov ebx,ebp
L_update_next_in:
; 1266 "inffast.S"
mov eax, [esp+88]
mov ecx,ebx
mov edx, [eax+28]
shr ecx,3
sub esi,ecx
shl ecx,3
sub ebx,ecx
mov [eax+12],edi
mov [edx+bits_state],ebx
mov ecx,ebx
lea ebx, [esp+28]
cmp [esp+20],ebx
jne L_buf_not_used
sub esi,ebx
mov ebx, [eax+0]
mov [esp+20],ebx
add esi,ebx
mov ebx, [eax+4]
sub ebx,11
add [esp+20],ebx
L_buf_not_used:
mov [eax+0],esi
mov ebx,1
shl ebx,cl
dec ebx
cmp dword ptr [inflate_fast_use_mmx],2
jne L_update_hold
psrlq mm0,mm1
movd ebp,mm0
emms
L_update_hold:
and ebp,ebx
mov [edx+hold_state],ebp
mov ebx, [esp+20]
cmp ebx,esi
jbe L_last_is_smaller
sub ebx,esi
add ebx,11
mov [eax+4],ebx
jmp L_fixup_out
L_last_is_smaller:
sub esi,ebx
neg esi
add esi,11
mov [eax+4],esi
L_fixup_out:
mov ebx, [esp+16]
cmp ebx,edi
jbe L_end_is_smaller
sub ebx,edi
add ebx,257
mov [eax+16],ebx
jmp L_done
L_end_is_smaller:
sub edi,ebx
neg edi
add edi,257
mov [eax+16],edi
L_done:
add esp,64
popfd
pop ebx
pop ebp
pop esi
pop edi
ret
_inflate_fast endp
_TEXT ends
end
|
; A204565: Number of (n+1) X 2 0..3 arrays with every 2 X 2 subblock having equal diagonal elements or equal antidiagonal elements, and new values 0..3 introduced in row major order.
; Submitted by Jamie Morken(s1)
; 8,42,256,1682,11448,79162,551216,3849762,26922088,188375882,1318394976,9228056242,64594267928,452153498202,3165055355536,22155330093122,155087138464968,1085609452694122,7599264619176896,53194847685192402,372363919849209208,2606547397103051642,18245831654197123056,127720821202807146082,894045747289931876648,6258320227640368698762,43808241583315117578016,306657691052703433106162,2146603837277416861923288,15026226860667396524003482,105183588023848211139645776,736285116164466784392384642
add $0,1
mov $1,3
pow $1,$0
mov $2,7
pow $2,$0
add $2,$1
add $1,$2
add $2,$1
mov $0,$2
sub $0,23
div $0,3
add $0,8
|
.data
input_first: .asciiz "Moltiplicando?"
.align 2
input_second: .asciiz "Moltiplicatore?"
output: .asciiz "Il prodotto è: "
.text
.globl main
main:
li $v0, 51
la $a0, input_first
syscall
move $s0, $a0
li $v0, 51
la $a0, input_second
syscall
move $a1, $a0
move $a0, $s0
jal prodotto_s
move $a1, $v0
li $v0, 56
la $a0, output
syscall
li $v0, 10
syscall |
; int putc_callee(int c, FILE *stream)
INCLUDE "clib_cfg.asm"
SECTION code_stdio
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
IF __CLIB_OPT_MULTITHREAD & $02
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
PUBLIC _putc_callee
EXTERN _fputc_callee
defc _putc_callee = _fputc_callee
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
ELSE
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
PUBLIC _putc_callee
EXTERN _putc_unlocked_callee
defc _putc_callee = _putc_unlocked_callee
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
ENDIF
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
|
#include<catch.h>
#include"../src/core/utils.h"
TEST_CASE("range small")
{
bird::Range range(.03,.04);
CHECK( range.min == .03 );
CHECK( range.max == .04 );
}
TEST_CASE("range big")
{
bird::Range range(1,1000000);
CHECK( range.min == 1 );
CHECK( range.max == 1000000 );
}
TEST_CASE("range negative")
{
bird::Range range(-1000000,1000000);
CHECK( range.min == -1000000 );
CHECK( range.max == 1000000 );
}
TEST_CASE("range between true")
{
bird::Range range(.03,.04);
CHECK( range.between(.03) );
CHECK( range.between(.031) );
CHECK( range.between(.039) );
CHECK( range.between(.04) );
}
TEST_CASE("range between false")
{
bird::Range range(.03,.04);
CHECK( !range.between(.029) );
CHECK( !range.between(.041) );
}
TEST_CASE("range cap")
{
bird::Range range(5,10);
CHECK( range.cap(1) == 5 );
CHECK( range.cap(100) == 10 );
}
TEST_CASE("range size")
{
bird::Range range(-10,10);
CHECK( range.size() == 20 );
}
TEST_CASE("range adjust")
{
bird::Range range1(-10,10);
bird::Range range2(0,100);
CHECK(range1.adjust(75,range2) == 5);
CHECK(range1.adjust(50,range2) == 0);
CHECK(range2.adjust(-5,range1) == 25);
CHECK(range2.adjust(0,range1) == 50);
CHECK(range2.adjust(10,range2) == 10);
}
TEST_CASE("timer fixed")
{
bird::Timer timer(.5);
CHECK(timer.restart() == .5);
CHECK(timer.elapsed() == .5);
}
TEST_CASE("timer dynamic")
{
bird::Timer timer;
while(timer.elapsed() <.01);
CHECK(timer.restart() > 0);
while(timer.elapsed() <.01);
CHECK(timer.restart() < .1);
}
TEST_CASE("timer time_out")
{
bird::Timer timer;
CHECK(!timer.time_out(.01));
while(timer.elapsed() <.01);
CHECK(timer.time_out(.01));
}
TEST_CASE("composite filter")
{
bird::Complementary_Filter cf1 = bird::Complementary_Filter({-1,1},.5);
cf1.update(-1,1);
CHECK(cf1.value == 0);
bird::Complementary_Filter cf2 = bird::Complementary_Filter({-1,1},.25);
cf2.update(-1,1);
CHECK(cf2.value == 0.5);
bird::Complementary_Filter cf3 = bird::Complementary_Filter({-1,1},.9);
cf3.update(-1,1);
CHECK(cf3.value == -0.8);
}
TEST_CASE("low pass filter")
{
bird::Low_Pass_Filter lpf1 = bird::Low_Pass_Filter({-1,1},.5);
lpf1=.5;
CHECK(lpf1.value == .5);
lpf1+=.5;
CHECK(lpf1.value == .5);
lpf1+=1;
CHECK(lpf1.value == .75);
lpf1+=-.75;
CHECK(lpf1.value == 0);
} |
//WiFi 802.11b (1 AP, 12 STA Nodes)
//Varying cbr
//Author: John, Kaushik, Umesh
#include "ns3/core-module.h"
#include "ns3/propagation-module.h"
#include "ns3/network-module.h"
#include "ns3/applications-module.h"
#include "ns3/mobility-module.h"
#include "ns3/internet-module.h"
#include "ns3/flow-monitor-module.h"
#include "ns3/wifi-module.h"
using namespace ns3;
void experiment (bool enableCtsRts)
{
// Enable or disable CTS/RTS
UintegerValue ctsThr = (enableCtsRts ? UintegerValue (100) : UintegerValue (2200));
Config::SetDefault ("ns3::WifiRemoteStationManager::RtsCtsThreshold", ctsThr);
// Create 1 AP and 12 STA Nodes
NodeContainer wifiStaNodes;
wifiStaNodes.Create (12);
NodeContainer wifiApNode;
wifiApNode.Create (1);
// Install wireless devices
WifiHelper wifi;
wifi.SetStandard (WIFI_PHY_STANDARD_80211b);
std::string phyMode ("DsssRate5_5Mbps");
wifi.SetRemoteStationManager ("ns3::ConstantRateWifiManager",
"DataMode",StringValue (phyMode),
"ControlMode",StringValue (phyMode));
YansWifiChannelHelper wifiChannel = YansWifiChannelHelper::Default ();
YansWifiPhyHelper wifiPhy = YansWifiPhyHelper::Default ();
wifiPhy.SetChannel (wifiChannel.Create ());
NqosWifiMacHelper wifiMac = NqosWifiMacHelper::Default ();
Ssid ssid = Ssid ("ns-3-ssid");
wifiMac.SetType ("ns3::StaWifiMac",
"Ssid", SsidValue (ssid),
"ActiveProbing", BooleanValue (false));
NetDeviceContainer staDevices;
staDevices = wifi.Install (wifiPhy, wifiMac, wifiStaNodes);
wifiMac.SetType ("ns3::ApWifiMac",
"Ssid", SsidValue (ssid));
NetDeviceContainer apDevices;
apDevices = wifi.Install (wifiPhy, wifiMac, wifiApNode);
// uncomment the following to have pcap output
// wifiPhy.EnablePcap (enableCtsRts ? "rtscts-pcap-node" : "basic-pcap-node" , nodes);
// Add Mobility
MobilityHelper mobility;
mobility.SetMobilityModel ("ns3::ConstantPositionMobilityModel");
mobility.Install (wifiStaNodes);
mobility.Install (wifiApNode);
Ptr<ConstantPositionMobilityModel> ApNode = wifiApNode.Get (0)->GetObject<ConstantPositionMobilityModel> ();
Ptr<ConstantPositionMobilityModel> Node1 = wifiStaNodes.Get (0)->GetObject<ConstantPositionMobilityModel> ();
Ptr<ConstantPositionMobilityModel> Node2 = wifiStaNodes.Get (1)->GetObject<ConstantPositionMobilityModel> ();
Ptr<ConstantPositionMobilityModel> Node3 = wifiStaNodes.Get (2)->GetObject<ConstantPositionMobilityModel> ();
Ptr<ConstantPositionMobilityModel> Node4 = wifiStaNodes.Get (3)->GetObject<ConstantPositionMobilityModel> ();
Ptr<ConstantPositionMobilityModel> Node5 = wifiStaNodes.Get (4)->GetObject<ConstantPositionMobilityModel> ();
Ptr<ConstantPositionMobilityModel> Node6 = wifiStaNodes.Get (5)->GetObject<ConstantPositionMobilityModel> ();
Ptr<ConstantPositionMobilityModel> Node7 = wifiStaNodes.Get (6)->GetObject<ConstantPositionMobilityModel> ();
Ptr<ConstantPositionMobilityModel> Node8 = wifiStaNodes.Get (7)->GetObject<ConstantPositionMobilityModel> ();
Ptr<ConstantPositionMobilityModel> Node9 = wifiStaNodes.Get (8)->GetObject<ConstantPositionMobilityModel> ();
Ptr<ConstantPositionMobilityModel> Node10 = wifiStaNodes.Get (9)->GetObject<ConstantPositionMobilityModel> ();
Ptr<ConstantPositionMobilityModel> Node11 = wifiStaNodes.Get (10)->GetObject<ConstantPositionMobilityModel> ();
Ptr<ConstantPositionMobilityModel> Node12 = wifiStaNodes.Get (11)->GetObject<ConstantPositionMobilityModel> ();
ApNode->SetPosition (Vector (0, 0, 0));
Node1->SetPosition (Vector (0, 50, 0));
Node2->SetPosition (Vector (30, 40, 0));
Node3->SetPosition (Vector (40, 30, 0));
Node4->SetPosition (Vector (50, 0, 0));
Node5->SetPosition (Vector (40, -30, 0));
Node6->SetPosition (Vector (30, -40, 0));
Node7->SetPosition (Vector (0, -50, 0));
Node8->SetPosition (Vector (-30, -40, 0));
Node9->SetPosition (Vector (-40, -30, 0));
Node10->SetPosition (Vector (-50, 0, 0));
Node11->SetPosition (Vector (-40, 30, 0));
Node12->SetPosition (Vector (-30, 40, 0));
// Install TCP/IP stack & assign IP addresses
InternetStackHelper internet;
internet.Install (wifiApNode);
internet.Install (wifiStaNodes);
Ipv4AddressHelper ipv4;
ipv4.SetBase ("10.0.0.0", "255.0.0.0");
ipv4.Assign (apDevices);
ipv4.Assign (staDevices);
// Install applications: two CBR streams each saturating the channel
ApplicationContainer cbrApps;
uint16_t cbrPort = 12345;
OnOffHelper onOffHelper ("ns3::UdpSocketFactory", InetSocketAddress (Ipv4Address ("10.0.0.1"), cbrPort));
onOffHelper.SetAttribute ("PacketSize", UintegerValue (1400));
onOffHelper.SetAttribute ("OnTime", StringValue ("ns3::ConstantRandomVariable[Constant=1]"));
onOffHelper.SetAttribute ("OffTime", StringValue ("ns3::ConstantRandomVariable[Constant=0]"));
// flow 1: node 1 -> AP
onOffHelper.SetAttribute ("DataRate", StringValue ("6000000bps"));
onOffHelper.SetAttribute ("StartTime", TimeValue (Seconds (1.000000)));
cbrApps.Add (onOffHelper.Install (wifiStaNodes.Get (0)));
// flow 2: node 3 -> AP
onOffHelper.SetAttribute ("DataRate", StringValue ("6000100bps"));
onOffHelper.SetAttribute ("StartTime", TimeValue (Seconds (1.001)));
cbrApps.Add (onOffHelper.Install (wifiStaNodes.Get (2)));
// flow 3: node 5 -> AP
onOffHelper.SetAttribute ("DataRate", StringValue ("6000200bps"));
onOffHelper.SetAttribute ("StartTime", TimeValue (Seconds (1.002)));
cbrApps.Add (onOffHelper.Install (wifiStaNodes.Get (4)));
// flow 4: node 7 -> AP
onOffHelper.SetAttribute ("DataRate", StringValue ("6000300bps"));
onOffHelper.SetAttribute ("StartTime", TimeValue (Seconds (1.003)));
cbrApps.Add (onOffHelper.Install (wifiStaNodes.Get (6)));
// flow 5: node 9 -> AP
onOffHelper.SetAttribute ("DataRate", StringValue ("6000400bps"));
onOffHelper.SetAttribute ("StartTime", TimeValue (Seconds (1.004)));
cbrApps.Add (onOffHelper.Install (wifiStaNodes.Get (8)));
// flow 6: node 11 -> AP
onOffHelper.SetAttribute ("DataRate", StringValue ("6000500bps"));
onOffHelper.SetAttribute ("StartTime", TimeValue (Seconds (1.005)));
cbrApps.Add (onOffHelper.Install (wifiStaNodes.Get (10)));
// flow 7: node 12 -> AP
//onOffHelper.SetAttribute ("DataRate", StringValue ("3000600bps"));
//onOffHelper.SetAttribute ("StartTime", TimeValue (Seconds (1.006)));
//cbrApps.Add (onOffHelper.Install (wifiStaNodes.Get (11)));
// flow 8: node 10 -> AP
//onOffHelper.SetAttribute ("DataRate", StringValue ("3000700bps"));
//onOffHelper.SetAttribute ("StartTime", TimeValue (Seconds (1.007)));
//cbrApps.Add (onOffHelper.Install (wifiStaNodes.Get (9)));
// flow 9: node 8 -> AP
//onOffHelper.SetAttribute ("DataRate", StringValue ("3000800bps"));
//onOffHelper.SetAttribute ("StartTime", TimeValue (Seconds (1.008)));
//cbrApps.Add (onOffHelper.Install (wifiStaNodes.Get (7)));
// flow 10: node 6 -> AP
//onOffHelper.SetAttribute ("DataRate", StringValue ("3000900bps"));
//onOffHelper.SetAttribute ("StartTime", TimeValue (Seconds (1.009)));
//cbrApps.Add (onOffHelper.Install (wifiStaNodes.Get (5)));
// flow 11: node 4 -> AP
//onOffHelper.SetAttribute ("DataRate", StringValue ("3001000bps"));
//onOffHelper.SetAttribute ("StartTime", TimeValue (Seconds (1.010)));
//cbrApps.Add (onOffHelper.Install (wifiStaNodes.Get (3)));
// flow 12: node 2 -> AP
//onOffHelper.SetAttribute ("DataRate", StringValue ("3001100bps"));
//onOffHelper.SetAttribute ("StartTime", TimeValue (Seconds (1.011)));
//cbrApps.Add (onOffHelper.Install (wifiStaNodes.Get (1)));
uint16_t echoPort = 9;
UdpEchoClientHelper echoClientHelper (Ipv4Address ("10.0.0.1"), echoPort);
echoClientHelper.SetAttribute ("MaxPackets", UintegerValue (1));
echoClientHelper.SetAttribute ("Interval", TimeValue (Seconds (0.1)));
echoClientHelper.SetAttribute ("PacketSize", UintegerValue (10));
ApplicationContainer pingApps;
// again using different start times to workaround Bug 388 and Bug 912
echoClientHelper.SetAttribute ("StartTime", TimeValue (Seconds (0.001)));
pingApps.Add (echoClientHelper.Install (wifiStaNodes.Get (0)));
echoClientHelper.SetAttribute ("StartTime", TimeValue (Seconds (0.006)));
pingApps.Add (echoClientHelper.Install (wifiStaNodes.Get (2)));
echoClientHelper.SetAttribute ("StartTime", TimeValue (Seconds (0.011)));
pingApps.Add (echoClientHelper.Install (wifiStaNodes.Get (4)));
echoClientHelper.SetAttribute ("StartTime", TimeValue (Seconds (0.016)));
pingApps.Add (echoClientHelper.Install (wifiStaNodes.Get (6)));
echoClientHelper.SetAttribute ("StartTime", TimeValue (Seconds (0.021)));
pingApps.Add (echoClientHelper.Install (wifiStaNodes.Get (8)));
echoClientHelper.SetAttribute ("StartTime", TimeValue (Seconds (0.026)));
pingApps.Add (echoClientHelper.Install (wifiStaNodes.Get (10)));
//echoClientHelper.SetAttribute ("StartTime", TimeValue (Seconds (0.031)));
//pingApps.Add (echoClientHelper.Install (wifiStaNodes.Get (11)));
//echoClientHelper.SetAttribute ("StartTime", TimeValue (Seconds (0.036)));
//pingApps.Add (echoClientHelper.Install (wifiStaNodes.Get (9)));
//echoClientHelper.SetAttribute ("StartTime", TimeValue (Seconds (0.041)));
//pingApps.Add (echoClientHelper.Install (wifiStaNodes.Get (7)));
//echoClientHelper.SetAttribute ("StartTime", TimeValue (Seconds (0.046)));
//pingApps.Add (echoClientHelper.Install (wifiStaNodes.Get (5)));
//echoClientHelper.SetAttribute ("StartTime", TimeValue (Seconds (0.051)));
//pingApps.Add (echoClientHelper.Install (wifiStaNodes.Get (3)));
//echoClientHelper.SetAttribute ("StartTime", TimeValue (Seconds (0.056)));
//pingApps.Add (echoClientHelper.Install (wifiStaNodes.Get (1)));
// Install FlowMonitor on all nodes
FlowMonitorHelper flowmon;
Ptr<FlowMonitor> monitor = flowmon.InstallAll ();
// Run simulation for 10 seconds
Simulator::Stop (Seconds (10));
Simulator::Run ();
// Print per flow statistics
monitor->CheckForLostPackets ();
Ptr<Ipv4FlowClassifier> classifier = DynamicCast<Ipv4FlowClassifier> (flowmon.GetClassifier ());
FlowMonitor::FlowStatsContainer stats = monitor->GetFlowStats ();
for (std::map<FlowId, FlowMonitor::FlowStats>::const_iterator i = stats.begin (); i != stats.end (); ++i)
{
// first 2 FlowIds are for ECHO apps, we don't want to display them
//
// Duration for throughput measurement is 9.0 seconds, since
// StartTime of the OnOffApplication is at about "second 1"
// and
// Simulator::Stops at "second 10".
if (i->first > 6)
{
Ipv4FlowClassifier::FiveTuple t = classifier->FindFlow (i->first);
std::cout << "Flow " << i->first - 6 << " (" << t.sourceAddress << " -> " << t.destinationAddress << ")\n";
std::cout << " Tx Packets: " << i->second.txPackets << "\n";
std::cout << " Tx Bytes: " << i->second.txBytes << "\n";
std::cout << " TxOffered: " << i->second.txBytes * 8.0 / 9.0 / 1000 / 1000 << " Mbps\n";
std::cout << " Rx Packets: " << i->second.rxPackets << "\n";
std::cout << " Rx Bytes: " << i->second.rxBytes << "\n";
std::cout << " Throughput: " << i->second.rxBytes * 8.0 / 9.0 / 1000 / 1000 << " Mbps\n";
}
}
// Cleanup
Simulator::Destroy ();
}
int main (int argc, char **argv)
{
CommandLine cmd;
cmd.Parse (argc, argv);
std::cout << "Hidden station experiment with RTS/CTS disabled:\n" << std::flush;
experiment (false);
std::cout << "------------------------------------------------\n";
std::cout << "Hidden station experiment with RTS/CTS enabled:\n";
experiment (true);
return 0;
}
|
CGROUP group code
code segment dword 'CODE'
assume cs:CGROUP,ds:CGROUP
public pj_fcompare
;pj_fcompare(USHORT *s1, USHORT *s2, unsigned count)
pj_fcompare PROC near
push esi
push edi
push ecx
mov esi,[esp+16]
mov edi,[esp+20]
mov ecx,[esp+24]
inc ecx
repe cmpsw
mov eax,[esp+24]
sub eax,ecx
pop ecx
pop edi
pop esi
ret
pj_fcompare ENDP
code ends
end
|
.size 8000
.text@48
inc a
ldff(45), a
jp lstatint
.text@100
jp lbegin
.data@143
c0
.text@150
lbegin:
ld a, 00
ldff(ff), a
ld a, 30
ldff(00), a
ld a, 01
ldff(4d), a
stop, 00
ld a, ff
ldff(45), a
ld b, 03
call lwaitly_b
ld c, 41
lbegin_waitm0:
ldff a, (c)
and a, b
jrnz lbegin_waitm0
ld a, 80
ldff(68), a
ld a, ff
ld c, 69
ldff(c), a
ldff(c), a
ldff(c), a
ldff(c), a
ldff(c), a
ldff(c), a
xor a, a
ldff(c), a
ldff(c), a
ld a, 40
ldff(41), a
ld a, 02
ldff(ff), a
ei
ld a, b
inc a
inc a
ldff(45), a
ld c, 0f
.text@1000
lstatint:
xor a, a
ldff(41), a
.text@10cb
xor a, a
ldff(c), a
ld a, 40
ldff(41), a
nop
nop
nop
nop
nop
nop
nop
nop
nop
nop
nop
ldff a, (c)
and a, b
jp lprint_a
.text@7000
lprint_a:
push af
ld b, 91
call lwaitly_b
xor a, a
ldff(40), a
pop af
ld(9800), a
ld bc, 7a00
ld hl, 8000
ld d, a0
lprint_copytiles:
ld a, (bc)
inc bc
ld(hl++), a
dec d
jrnz lprint_copytiles
ld a, c0
ldff(47), a
ld a, 80
ldff(68), a
ld a, ff
ldff(69), a
ldff(69), a
ldff(69), a
ldff(69), a
ldff(69), a
ldff(69), a
xor a, a
ldff(69), a
ldff(69), a
ldff(43), a
ld a, 91
ldff(40), a
lprint_limbo:
jr lprint_limbo
.text@7400
lwaitly_b:
ld c, 44
lwaitly_b_loop:
ldff a, (c)
cmp a, b
jrnz lwaitly_b_loop
ret
.data@7a00
00 00 7f 7f 41 41 41 41
41 41 41 41 41 41 7f 7f
00 00 08 08 08 08 08 08
08 08 08 08 08 08 08 08
00 00 7f 7f 01 01 01 01
7f 7f 40 40 40 40 7f 7f
00 00 7f 7f 01 01 01 01
3f 3f 01 01 01 01 7f 7f
00 00 41 41 41 41 41 41
7f 7f 01 01 01 01 01 01
00 00 7f 7f 40 40 40 40
7e 7e 01 01 01 01 7e 7e
00 00 7f 7f 40 40 40 40
7f 7f 41 41 41 41 7f 7f
00 00 7f 7f 01 01 02 02
04 04 08 08 10 10 10 10
00 00 3e 3e 41 41 41 41
3e 3e 41 41 41 41 3e 3e
00 00 7f 7f 41 41 41 41
7f 7f 01 01 01 01 7f 7f
|
music_addr=$7000
sid_init = $7000
sid_play = $7003
*=music_addr
!bin "source/fallen_down.sid",,$7e
ctr=$4000
clr=$4004
sprite_location=$2000
*=sprite_location
!source "graphics/sprite1.gpx"
!source "graphics/sprites2.asm"
code_addr=$c000
*=code_addr
!source "source/main.asm"
!source "source/rand.asm"
!source "source/sprites.asm"
|
; BR 2039212
bits 64
call qword far [rax]
jmp qword far [rax]
call dword far [rax]
jmp dword far [rax]
call far [rax]
jmp far [rax]
|
namespace srrg2_core {
template <typename CellType_, typename AllocatorType_, typename CellTraits_>
Matrix_<CellType_, AllocatorType_, CellTraits_>::Matrix_() {
clear();
}
template <typename CellType_, typename AllocatorType_, typename CellTraits_>
Matrix_<CellType_, AllocatorType_, CellTraits_>::Matrix_(std::size_t rows_, std::size_t cols_) {
_cols = 0;
resize(rows_, cols_);
}
template <typename CellType_, typename AllocatorType_, typename CellTraits_>
Matrix_<CellType_, AllocatorType_, CellTraits_>::Matrix_(const Matrix_& other) {
assign(other);
}
template <typename CellType_, typename AllocatorType_, typename CellTraits_>
Matrix_<CellType_, AllocatorType_, CellTraits_>& Matrix_<CellType_, AllocatorType_, CellTraits_>::
operator=(const Matrix_& other) {
assign(other);
return *this;
}
template <typename CellType_, typename AllocatorType_, typename CellTraits_>
void Matrix_<CellType_, AllocatorType_, CellTraits_>::fill(const CellType_& value) {
std::fill(_data.begin(), _data.end(), value);
}
template <typename CellType_, typename AllocatorType_, typename CellTraits_>
void Matrix_<CellType_, AllocatorType_, CellTraits_>::updateEightNeighborOffsets() {
if (rows() < 2 || cols() < 2) {
// TODO: che cazz? (cit. dom)
memset(_eight_neighbors_offsets, 0, 8 * sizeof(int));
return;
}
int k = 0;
for (int r = -1; r <= 1; ++r) {
for (int c = -1; c <= 1; ++c) {
if (!r && !c) {
continue;
}
_eight_neighbors_offsets[k] = _cols * r + c;
++k;
}
}
}
template <typename CellType_, typename AllocatorType_, typename CellTraits_>
void Matrix_<CellType_, AllocatorType_, CellTraits_>::resize(std::size_t rows_,
std::size_t cols_) {
// if size is ok, do nothing
if (rows_ == _row_ptrs.size() && _cols == cols_) {
return;
}
std::size_t num_elements = rows_ * cols_;
if (!num_elements) {
clear();
}
_cols = cols_;
_row_ptrs.resize(rows_);
_data.resize(num_elements);
reindex();
}
template <typename CellType_, typename AllocatorType_, typename CellTraits_>
void Matrix_<CellType_, AllocatorType_, CellTraits_>::clear() {
_cols = 0;
_row_ptrs.clear();
_data.clear();
}
template <typename CellType_, typename AllocatorType_, typename CellTraits_>
void Matrix_<CellType_, AllocatorType_, CellTraits_>::reindex() {
CellType* row_ptr = &_data[0];
for (std::size_t r = 0; r < rows(); r++) {
_row_ptrs[r] = row_ptr;
row_ptr += _cols;
}
updateEightNeighborOffsets();
}
template <typename CellType_, typename AllocatorType_, typename CellTraits_>
void Matrix_<CellType_, AllocatorType_, CellTraits_>::assign(const Matrix_& other) {
if (!other._data.size()) {
clear();
return;
}
_cols = other._cols;
_data = other._data;
_row_ptrs.resize(other._row_ptrs.size());
reindex();
}
// mc bilinear interpolation
template <typename CellType_, typename AllocatorType_, typename CellTraits_>
bool Matrix_<CellType_, AllocatorType_, CellTraits_>::getSubPixel(
CellType_& interpolated_value_,
const Vector2f& interpolation_point_) const {
using namespace std;
if (!inside(interpolation_point_.x(), interpolation_point_.y())) {
return false;
}
int x0 = interpolation_point_.x(); // rows
int y0 = interpolation_point_.y(); // cols
int x1 = x0 + 1;
int y1 = y0 + 1;
if (!inside(x1, y1)) {
return false;
}
const float dx = interpolation_point_.x() - (float) x0;
const float dy = interpolation_point_.y() - (float) y0;
const float dx1 = 1.f - dx;
const float dy1 = 1.f - dy;
Traits::setZero(interpolated_value_);
Traits::sumAndScale(interpolated_value_, (*this)(x0, y0), dy1 * dx1);
Traits::sumAndScale(interpolated_value_, (*this)(x0, y1), dy1 * dx);
Traits::sumAndScale(interpolated_value_, (*this)(x1, y0), dy * dx1);
Traits::sumAndScale(interpolated_value_, (*this)(x1, y1), dy * dx);
Traits::postInterpolate(interpolated_value_);
return true;
}
} // namespace srrg2_core
|
//==---------- pi_arguments_handler.hpp - PI call arguments handler --------==//
// i
//
// 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
//
//===----------------------------------------------------------------------===//
#pragma once
#include <CL/sycl/detail/pi.hpp>
#include <CL/sycl/detail/type_traits.hpp>
#include <functional>
#include <optional>
#include <tuple>
__SYCL_INLINE_NAMESPACE(cl) {
namespace sycl {
namespace xpti_helpers {
template <typename TupleT, size_t... Is>
inline auto get(char *Data, const std::index_sequence<Is...> &) {
// Our type should be last in Is sequence
using TargetType =
typename std::tuple_element<sizeof...(Is) - 1, TupleT>::type;
// Calculate sizeof all elements before target + target element then substract
// sizeof target element
const size_t Offset =
(sizeof(typename std::tuple_element<Is, TupleT>::type) + ...) -
sizeof(TargetType);
return *(typename std::decay<TargetType>::type *)(Data + Offset);
}
template <typename TupleT, size_t... Is>
inline TupleT unpack(char *Data,
const std::index_sequence<Is...> & /*1..TupleSize*/) {
return {get<TupleT>(Data, std::make_index_sequence<Is + 1>{})...};
}
template <typename T> struct to_function {};
template <typename... Args> struct to_function<std::tuple<Args...>> {
using type =
std::function<void(const pi_plugin &, std::optional<pi_result>, Args...)>;
};
/// PiArgumentsHandler is a helper class to process incoming XPTI function call
/// events and unpack contained arguments.
///
/// Usage:
///
/// PiArgumentsHandler provides set_<API name> member functions, that accept a
/// lambda with the same arguments as target PI API. Use it to set up handling
/// for particular API. By default an empty lambda is used.
///
/// When an event is signaled, use PiArgumentsHandler::handle() member function
/// to process the incoming event and call necessary handler.
///
/// See sycl/tools/pi-trace/ for an example.
class PiArgumentsHandler {
public:
void handle(uint32_t ID, const pi_plugin &Plugin,
std::optional<pi_result> Result, void *ArgsData) {
#define _PI_API(api) \
if (ID == static_cast<uint32_t>(detail::PiApiKind::api)) { \
MHandler##_##api(Plugin, Result, ArgsData); \
return; \
}
#include <CL/sycl/detail/pi.def>
#undef _PI_API
}
#define _PI_API(api) \
void set##_##api( \
const typename to_function<typename detail::function_traits<decltype( \
api)>::args_type>::type &Handler) { \
MHandler##_##api = [Handler](const pi_plugin &Plugin, \
std::optional<pi_result> Res, void *Data) { \
using TupleT = \
typename detail::function_traits<decltype(api)>::args_type; \
TupleT Tuple = unpack<TupleT>( \
(char *)Data, \
std::make_index_sequence<std::tuple_size<TupleT>::value>{}); \
const auto Wrapper = [&Plugin, Res, Handler](auto &... Args) { \
Handler(Plugin, Res, Args...); \
}; \
std::apply(Wrapper, Tuple); \
}; \
}
#include <CL/sycl/detail/pi.def>
#undef _PI_API
private:
#define _PI_API(api) \
std::function<void(const pi_plugin &, std::optional<pi_result>, void *)> \
MHandler##_##api = \
[](const pi_plugin &, std::optional<pi_result>, void *) {};
#include <CL/sycl/detail/pi.def>
#undef _PI_API
};
} // namespace xpti_helpers
} // namespace sycl
} // __SYCL_INLINE_NAMESPACE(cl)
|
; A188172: Number of divisors d of n of the form d == 7 (mod 8).
; 0,0,0,0,0,0,1,0,0,0,0,0,0,1,1,0,0,0,0,0,1,0,1,0,0,0,0,1,0,1,1,0,0,0,1,0,0,0,1,0,0,1,0,0,1,1,1,0,1,0,0,0,0,0,1,1,0,0,0,1,0,1,2,0,0,0,0,0,1,1,1,0,0,0,1,0,1,1,1,0,0,0,0,1,0,0,1,0,0,1,1,1,1,1,1,0,0,1,0,0
add $0,1
mov $2,$0
lpb $0
mov $3,$2
dif $3,$0
cmp $3,$2
cmp $3,0
mul $3,$0
sub $0,1
add $4,1
lpb $4
add $1,1
add $4,$3
mod $4,8
lpe
trn $4,3
lpe
mov $0,$1
|
HallOfFamePC:
callab FallingStarEnd
call ClearScreen
ld c, 100
call DelayFrames
call DisableLCD
ld a, $a7
ld [rWX], a
xor a
ld [rSCX], a
ld [rSCY], a
ld [hSCX], a
ld [hSCY], a
ld [hWY], a
ld [rWY], a
call CreditsLoadFont
coord hl, 0, 0
call FillFourRowsWithBlack
coord hl, 0, 14
call FillFourRowsWithBlack
ld a, %11000000
ld [rBGP], a
call UpdateGBCPal_BGP
call EnableLCD
call StopAllMusic
ld hl, vBGMap1
call CreditsCopyTileMapToVRAM
ld hl, vBGMap0
call CreditsCopyTileMapToVRAM
ld c, BANK(Music_Credits)
ld a, MUSIC_CREDITS
call PlayMusic
ld c, 128
call DelayFrames
xor a
ld [wHoFMonSpecies], a
ld [wNumCreditsMonsDisplayed], a
jp Credits
FadeInCreditsText:
ld a, 1
ld [H_AUTOBGTRANSFERENABLED], a
ld hl, HoFGBPalettes
ld b, 4
.loop
ld a, [hli]
ld [rBGP], a
call UpdateGBCPal_BGP
ld c, 5
call DelayFrames
dec b
jr nz, .loop
ret
HoFGBPalettes:
db %11000000
db %11010000
db %11100000
db %11110000
DisplayCreditsMon:
ld hl, vBGMap1
call CreditsCopyTileMapToVRAM
xor a
ld [H_AUTOBGTRANSFERENABLED], a
ld hl, rLCDC
set 3, [hl]
call SaveScreenTilesToBuffer2
call FillMiddleOfScreenWithWhite
call GetNextCreditsMon
ld hl, vBGMap0 + 12
call CreditsCopyTileMapToVRAM
xor a
ld [H_AUTOBGTRANSFERENABLED], a
call LoadScreenTilesFromBuffer2DisableBGTransfer
ld hl, vBGMap0
call CreditsCopyTileMapToVRAM
ld a, %11111100 ; make the mon a black silhouette
ld [rBGP], a
call UpdateGBCPal_BGP
ld hl, rLCDC
res 3, [hl]
ld a, 1
ld [H_AUTOBGTRANSFERENABLED], a
ld b, 0
ld c, 10
call ScrollCreditsMonLeft
call FillLeftHalfOfScreenWithWhite
ld c, 10
call ScrollCreditsMonLeft
call FillRightHalfOfScreenWithWhite
ld c, 8
call ScrollCreditsMonLeft
ld a, %11000000
ld [rBGP], a
call UpdateGBCPal_BGP
xor a
ld [hSCX], a
ret
ScrollCreditsMonLeft:
ld a, b
ld [hSCX], a
add 8
ld b, a
call DelayFrame
dec c
jr nz, ScrollCreditsMonLeft
ret
GetNextCreditsMon:
ld hl, wNumCreditsMonsDisplayed
ld c, [hl]
inc [hl]
ld b, 0
ld hl, CreditsMons
add hl, bc
ld a, [hl]
ld [wcf91], a
ld [wd0b5], a
coord hl, 8, 6
call GetMonHeader
call LoadFrontSpriteByMonIndex
ret
INCLUDE "data/credit_mons.asm"
CreditsCopyTileMapToVRAM:
ld a, l
ld [H_AUTOBGTRANSFERDEST], a
ld a, h
ld [H_AUTOBGTRANSFERDEST + 1], a
ld a, 1
ld [H_AUTOBGTRANSFERENABLED], a
jp Delay3
CreditsLoadFont:
call LoadFontTilePatterns
ld hl, vChars1
ld bc, $40 * $10
call ZeroMemory
call LoadTextBoxTilePatterns
ld hl, vChars2 + $60 * $10
ld bc, $10 * $10
call ZeroMemory
ld hl, vChars2 + $7e * $10
ld bc, $1 * $10
ld a, $ff
call FillMemory
ret
ZeroMemory:
; zero bc bytes at hl
ld [hl], 0
inc hl
inc hl
dec bc
ld a, b
or c
jr nz, ZeroMemory
ret
FillFourRowsWithBlack:
ld bc, SCREEN_WIDTH * 4
ld a, $7e
jp FillMemory
FillMiddleOfScreenWithWhite:
coord hl, 0, 4
ld bc, SCREEN_WIDTH * 10
ld a, " "
jp FillMemory
FillLeftHalfOfScreenWithWhite:
coord hl, 0, 4
push bc
call FillHalfOfScreenWithWhite
pop bc
ret
FillRightHalfOfScreenWithWhite:
coord hl, 10, 4
push bc
call FillHalfOfScreenWithWhite
pop bc
ret
FillHalfOfScreenWithWhite:
ld b, 10
ld c, 10
ld a, " "
.loop
push bc
push hl
.innerLoop
ld [hli], a
dec c
jr nz, .innerLoop
pop hl
ld bc, SCREEN_WIDTH
add hl, bc
pop bc
dec b
jr nz, .loop
ret
Credits: ; Roll credits
ld de, CreditsOrder
push de
.nextCreditsScreen
pop de
coord hl, 9, 6
push hl
call FillMiddleOfScreenWithWhite
pop hl
.nextCreditsCommand
ld a, [de]
inc de
push de
cp $ff
jr z, .fadeInTextAndShowMon
cp $fe
jr z, .showTextAndShowMon
cp $fd
jr z, .fadeInText
cp $fc
jr z, .showText
cp $fb
jr z, .showCopyrightText
cp $fa
jr z, .showTheEnd
call PlaceCreditsText
pop de
jr .nextCreditsCommand
.showCopyrightText
callba LoadCopyrightTiles
pop de
jr .nextCreditsCommand
.fadeInTextAndShowMon
call FadeInCreditsText
ld c, 102
jr .next1
.showTextAndShowMon
ld c, 122
.next1
call DelayFrames
call DisplayCreditsMon
jr .nextCreditsScreen
.fadeInText
call FadeInCreditsText
ld c, 132
jr .next2
.showText
ld c, 152
.next2
call DelayFrames
jr .nextCreditsScreen
.showTheEnd
call ShowTheEndGFX
pop de
ret
ShowTheEndGFX:
ld c, 24
call DelayFrames
call FillMiddleOfScreenWithWhite
ld de, TheEndGfx
ld hl, vChars2 + $600
lb bc, BANK(TheEndGfx), (TheEndGfxEnd - TheEndGfx) / $10
call CopyVideoData
coord hl, 4, 8
ld de, TheEndTextString
call PlaceString
coord hl, 4, 9
inc de
call PlaceString
jp FadeInCreditsText
TheEndTextString:
; "T H E E N D"
db $60, " ", $62, " ", $64, " ", $64, " ", $66, " ", $68, "@"
db $61, " ", $63, " ", $65, " ", $65, " ", $67, " ", $69, "@"
PlaceCreditsText:
push hl
push hl
ld hl, CreditsTextPointers
ld c, a
ld b, 0
add hl, bc
add hl, bc
ld e, [hl]
inc hl
ld d, [hl]
pop hl
ld a, [de]
inc de
ld c, a
ld b, $ff
add hl, bc
call PlaceString
pop hl
ld bc, SCREEN_WIDTH * 2
add hl, bc
ret
INCLUDE "data/credits_order.asm"
INCLUDE "text/credits_text.asm"
TheEndGfx: ; 7473e (1d:473e) (7473f on blue)
INCBIN "gfx/theend.interleave.2bpp"
TheEndGfxEnd:
|
; A021940: Decimal expansion of 1/936.
; 0,0,1,0,6,8,3,7,6,0,6,8,3,7,6,0,6,8,3,7,6,0,6,8,3,7,6,0,6,8,3,7,6,0,6,8,3,7,6,0,6,8,3,7,6,0,6,8,3,7,6,0,6,8,3,7,6,0,6,8,3,7,6,0,6,8,3,7,6,0,6,8,3,7,6,0,6,8,3,7,6,0,6,8,3,7,6,0,6,8,3,7,6,0,6,8,3,7,6
add $0,1
mov $1,10
pow $1,$0
mul $1,2
div $1,1872
mod $1,10
mov $0,$1
|
////
//// Created by heisenberg on 4/11/20.
////
//
//#include <bits/stdc++.h>
//
//#define fi freopen("in.txt", "r", stdin)
//#define fo freopen("out.txt", "w", stdout)
//
//using namespace std;
//#define ll long long
//#define VISITED 1
//#define UNVISITED -1
//vector<vector<pair<ll, ll>>> pascalTriangle;
//
//ll N;
//
//
//void makePascal() {
// ll level = 67;
//
// // 0
// pascalTriangle.emplace_back();
// pascalTriangle[0].emplace_back(make_pair(1, -1));
//
// // 1
// pascalTriangle.emplace_back();
// pascalTriangle[1].emplace_back(make_pair(1, -1));
// pascalTriangle[1].emplace_back(make_pair(1, -1));
//
// for (ll i = 2; i < level; i++) {
// pascalTriangle.emplace_back();
// for (ll j = 0; j <= i; j++) {
// if (j == 0 || j == i) {
// pascalTriangle[i].emplace_back(make_pair(1, -1));
// } else {
// ll a = pascalTriangle[i - 1][j - 1].first + pascalTriangle[i - 1][j].first;
//
// pascalTriangle[i].emplace_back(
// make_pair(a, -1));
// }
// }
// }
//
//// cout << "fhkjd --> " << pascalTriangle[2][1].first << endl;
//}
//
//bool dp(vector<pair<ll, ll>> &path, ll i, ll j, ll left) {
// if (i < 0 || j < 0 || i >= pascalTriangle.size() || j >= pascalTriangle[i].size()) {
// return;
// }
// if (pascalTriangle[i][j].second != -1) {
// return;
// }
// if (pascalTriangle[i][j].first > left){
// return;
// }
//
// if(left == 0){
// // do sth
// return;
// }
//
// dp(path, i, j , left - pascalTriangle[i][j].first);
// dp(path, i, j , left - pascalTriangle[i][j].first);
// dp(path, i, j , left - pascalTriangle[i][j].first);
// dp(path, i, j , left - pascalTriangle[i][j].first);
// dp(path, i, j , left - pascalTriangle[i][j].first);
// dp(path, i, j , left - pascalTriangle[i][j].first);
//
//}
//
//int main() {
//// fi;
// ios_base::sync_with_stdio(false);
// cin.tie(NULL);
// int t = 0, T;
// makePascal();
//
// cin >> T;
// while (T--) {
// t++;
// cout << "Case #" << t << ": ";
// cin >> N;
//
// vector<pair<ll, ll>> path;
//
// dp(path, 0, 0, N);
//
// }
//
//// for(int i = 0 ; i < pascalTriangle.size(); i++){
//// for(int j = 0 ; j < pascalTriangle[i].size(); j++){
//// cout << pascalTriangle[i][j].first << " " ;
//// }
//// cout << endl;
//// }
//
//// ll a = 1e09;
//// cout << a << endl;
//
// return 0;
//} |
; A002419: 4-dimensional figurate numbers: (6*n-2)*binomial(n+2,3)/4.
; 1,10,40,110,245,476,840,1380,2145,3190,4576,6370,8645,11480,14960,19176,24225,30210,37240,45430,54901,65780,78200,92300,108225,126126,146160,168490,193285,220720,250976,284240,320705,360570,404040,451326,502645,558220,618280,683060,752801,827750,908160,994290,1086405,1184776,1289680,1401400,1520225,1646450,1780376,1922310,2072565,2231460,2399320,2576476,2763265,2960030,3167120,3384890,3613701,3853920,4105920,4370080,4646785,4936426,5239400,5556110,5886965,6232380,6592776,6968580,7360225,7768150,8192800,8634626,9094085,9571640,10067760,10582920,11117601,11672290,12247480,12843670,13461365,14101076,14763320,15448620,16157505,16890510,17648176,18431050,19239685,20074640,20936480,21825776,22743105,23689050,24664200,25669150
add $0,1
mov $2,1
lpb $0
sub $0,1
add $3,$2
add $4,$3
add $1,$4
add $2,6
lpe
mov $0,$1
|
_rm: file format elf32-i386
Disassembly of section .text:
00000000 <main>:
#include "stat.h"
#include "user.h"
int
main(int argc, char *argv[])
{
0: 55 push %ebp
1: 89 e5 mov %esp,%ebp
3: 57 push %edi
4: 56 push %esi
5: 53 push %ebx
6: 83 e4 f0 and $0xfffffff0,%esp
9: 83 ec 10 sub $0x10,%esp
c: 8b 7d 08 mov 0x8(%ebp),%edi
int i;
if(argc < 2){
f: 83 ff 01 cmp $0x1,%edi
12: 7e 4a jle 5e <main+0x5e>
14: 8b 45 0c mov 0xc(%ebp),%eax
printf(2, "Usage: rm files...\n");
exit(0);
}
for(i = 1; i < argc; i++){
17: be 01 00 00 00 mov $0x1,%esi
1c: 8d 58 04 lea 0x4(%eax),%ebx
1f: 90 nop
if(unlink(argv[i]) < 0){
20: 8b 03 mov (%ebx),%eax
22: 89 04 24 mov %eax,(%esp)
25: e8 ce 02 00 00 call 2f8 <unlink>
2a: 85 c0 test %eax,%eax
2c: 78 14 js 42 <main+0x42>
for(i = 1; i < argc; i++){
2e: 46 inc %esi
2f: 83 c3 04 add $0x4,%ebx
32: 39 f7 cmp %esi,%edi
34: 75 ea jne 20 <main+0x20>
printf(2, "rm: %s failed to delete\n", argv[i]);
break;
}
}
exit(0);
36: c7 04 24 00 00 00 00 movl $0x0,(%esp)
3d: e8 66 02 00 00 call 2a8 <exit>
printf(2, "rm: %s failed to delete\n", argv[i]);
42: 8b 03 mov (%ebx),%eax
44: c7 44 24 04 8c 07 00 movl $0x78c,0x4(%esp)
4b: 00
4c: c7 04 24 02 00 00 00 movl $0x2,(%esp)
53: 89 44 24 08 mov %eax,0x8(%esp)
57: e8 a4 03 00 00 call 400 <printf>
break;
5c: eb d8 jmp 36 <main+0x36>
printf(2, "Usage: rm files...\n");
5e: c7 44 24 04 78 07 00 movl $0x778,0x4(%esp)
65: 00
66: c7 04 24 02 00 00 00 movl $0x2,(%esp)
6d: e8 8e 03 00 00 call 400 <printf>
exit(0);
72: c7 04 24 00 00 00 00 movl $0x0,(%esp)
79: e8 2a 02 00 00 call 2a8 <exit>
7e: 66 90 xchg %ax,%ax
00000080 <strcpy>:
#include "user.h"
#include "x86.h"
char*
strcpy(char *s, const char *t)
{
80: 55 push %ebp
81: 89 e5 mov %esp,%ebp
83: 8b 45 08 mov 0x8(%ebp),%eax
86: 8b 4d 0c mov 0xc(%ebp),%ecx
89: 53 push %ebx
char *os;
os = s;
while((*s++ = *t++) != 0)
8a: 89 c2 mov %eax,%edx
8c: 8d 74 26 00 lea 0x0(%esi,%eiz,1),%esi
90: 41 inc %ecx
91: 0f b6 59 ff movzbl -0x1(%ecx),%ebx
95: 42 inc %edx
96: 84 db test %bl,%bl
98: 88 5a ff mov %bl,-0x1(%edx)
9b: 75 f3 jne 90 <strcpy+0x10>
;
return os;
}
9d: 5b pop %ebx
9e: 5d pop %ebp
9f: c3 ret
000000a0 <strcmp>:
int
strcmp(const char *p, const char *q)
{
a0: 55 push %ebp
a1: 89 e5 mov %esp,%ebp
a3: 8b 4d 08 mov 0x8(%ebp),%ecx
a6: 53 push %ebx
a7: 8b 5d 0c mov 0xc(%ebp),%ebx
while(*p && *p == *q)
aa: 0f b6 01 movzbl (%ecx),%eax
ad: 0f b6 13 movzbl (%ebx),%edx
b0: 84 c0 test %al,%al
b2: 75 18 jne cc <strcmp+0x2c>
b4: eb 22 jmp d8 <strcmp+0x38>
b6: 8d 76 00 lea 0x0(%esi),%esi
b9: 8d bc 27 00 00 00 00 lea 0x0(%edi,%eiz,1),%edi
p++, q++;
c0: 41 inc %ecx
while(*p && *p == *q)
c1: 0f b6 01 movzbl (%ecx),%eax
p++, q++;
c4: 43 inc %ebx
c5: 0f b6 13 movzbl (%ebx),%edx
while(*p && *p == *q)
c8: 84 c0 test %al,%al
ca: 74 0c je d8 <strcmp+0x38>
cc: 38 d0 cmp %dl,%al
ce: 74 f0 je c0 <strcmp+0x20>
return (uchar)*p - (uchar)*q;
}
d0: 5b pop %ebx
return (uchar)*p - (uchar)*q;
d1: 29 d0 sub %edx,%eax
}
d3: 5d pop %ebp
d4: c3 ret
d5: 8d 76 00 lea 0x0(%esi),%esi
d8: 5b pop %ebx
d9: 31 c0 xor %eax,%eax
return (uchar)*p - (uchar)*q;
db: 29 d0 sub %edx,%eax
}
dd: 5d pop %ebp
de: c3 ret
df: 90 nop
000000e0 <strlen>:
uint
strlen(const char *s)
{
e0: 55 push %ebp
e1: 89 e5 mov %esp,%ebp
e3: 8b 4d 08 mov 0x8(%ebp),%ecx
int n;
for(n = 0; s[n]; n++)
e6: 80 39 00 cmpb $0x0,(%ecx)
e9: 74 15 je 100 <strlen+0x20>
eb: 31 d2 xor %edx,%edx
ed: 8d 76 00 lea 0x0(%esi),%esi
f0: 42 inc %edx
f1: 80 3c 11 00 cmpb $0x0,(%ecx,%edx,1)
f5: 89 d0 mov %edx,%eax
f7: 75 f7 jne f0 <strlen+0x10>
;
return n;
}
f9: 5d pop %ebp
fa: c3 ret
fb: 90 nop
fc: 8d 74 26 00 lea 0x0(%esi,%eiz,1),%esi
for(n = 0; s[n]; n++)
100: 31 c0 xor %eax,%eax
}
102: 5d pop %ebp
103: c3 ret
104: 8d b6 00 00 00 00 lea 0x0(%esi),%esi
10a: 8d bf 00 00 00 00 lea 0x0(%edi),%edi
00000110 <memset>:
void*
memset(void *dst, int c, uint n)
{
110: 55 push %ebp
111: 89 e5 mov %esp,%ebp
113: 8b 55 08 mov 0x8(%ebp),%edx
116: 57 push %edi
}
static inline void
stosb(void *addr, int data, int cnt)
{
asm volatile("cld; rep stosb" :
117: 8b 4d 10 mov 0x10(%ebp),%ecx
11a: 8b 45 0c mov 0xc(%ebp),%eax
11d: 89 d7 mov %edx,%edi
11f: fc cld
120: f3 aa rep stos %al,%es:(%edi)
stosb(dst, c, n);
return dst;
}
122: 5f pop %edi
123: 89 d0 mov %edx,%eax
125: 5d pop %ebp
126: c3 ret
127: 89 f6 mov %esi,%esi
129: 8d bc 27 00 00 00 00 lea 0x0(%edi,%eiz,1),%edi
00000130 <strchr>:
char*
strchr(const char *s, char c)
{
130: 55 push %ebp
131: 89 e5 mov %esp,%ebp
133: 8b 45 08 mov 0x8(%ebp),%eax
136: 0f b6 4d 0c movzbl 0xc(%ebp),%ecx
for(; *s; s++)
13a: 0f b6 10 movzbl (%eax),%edx
13d: 84 d2 test %dl,%dl
13f: 74 1b je 15c <strchr+0x2c>
if(*s == c)
141: 38 d1 cmp %dl,%cl
143: 75 0f jne 154 <strchr+0x24>
145: eb 17 jmp 15e <strchr+0x2e>
147: 89 f6 mov %esi,%esi
149: 8d bc 27 00 00 00 00 lea 0x0(%edi,%eiz,1),%edi
150: 38 ca cmp %cl,%dl
152: 74 0a je 15e <strchr+0x2e>
for(; *s; s++)
154: 40 inc %eax
155: 0f b6 10 movzbl (%eax),%edx
158: 84 d2 test %dl,%dl
15a: 75 f4 jne 150 <strchr+0x20>
return (char*)s;
return 0;
15c: 31 c0 xor %eax,%eax
}
15e: 5d pop %ebp
15f: c3 ret
00000160 <gets>:
char*
gets(char *buf, int max)
{
160: 55 push %ebp
161: 89 e5 mov %esp,%ebp
163: 57 push %edi
164: 56 push %esi
int i, cc;
char c;
for(i=0; i+1 < max; ){
165: 31 f6 xor %esi,%esi
{
167: 53 push %ebx
168: 83 ec 3c sub $0x3c,%esp
16b: 8b 5d 08 mov 0x8(%ebp),%ebx
cc = read(0, &c, 1);
16e: 8d 7d e7 lea -0x19(%ebp),%edi
for(i=0; i+1 < max; ){
171: eb 32 jmp 1a5 <gets+0x45>
173: 90 nop
174: 8d 74 26 00 lea 0x0(%esi,%eiz,1),%esi
cc = read(0, &c, 1);
178: ba 01 00 00 00 mov $0x1,%edx
17d: 89 54 24 08 mov %edx,0x8(%esp)
181: 89 7c 24 04 mov %edi,0x4(%esp)
185: c7 04 24 00 00 00 00 movl $0x0,(%esp)
18c: e8 2f 01 00 00 call 2c0 <read>
if(cc < 1)
191: 85 c0 test %eax,%eax
193: 7e 19 jle 1ae <gets+0x4e>
break;
buf[i++] = c;
195: 0f b6 45 e7 movzbl -0x19(%ebp),%eax
199: 43 inc %ebx
19a: 88 43 ff mov %al,-0x1(%ebx)
if(c == '\n' || c == '\r')
19d: 3c 0a cmp $0xa,%al
19f: 74 1f je 1c0 <gets+0x60>
1a1: 3c 0d cmp $0xd,%al
1a3: 74 1b je 1c0 <gets+0x60>
for(i=0; i+1 < max; ){
1a5: 46 inc %esi
1a6: 3b 75 0c cmp 0xc(%ebp),%esi
1a9: 89 5d d4 mov %ebx,-0x2c(%ebp)
1ac: 7c ca jl 178 <gets+0x18>
break;
}
buf[i] = '\0';
1ae: 8b 45 d4 mov -0x2c(%ebp),%eax
1b1: c6 00 00 movb $0x0,(%eax)
return buf;
}
1b4: 8b 45 08 mov 0x8(%ebp),%eax
1b7: 83 c4 3c add $0x3c,%esp
1ba: 5b pop %ebx
1bb: 5e pop %esi
1bc: 5f pop %edi
1bd: 5d pop %ebp
1be: c3 ret
1bf: 90 nop
1c0: 8b 45 08 mov 0x8(%ebp),%eax
1c3: 01 c6 add %eax,%esi
1c5: 89 75 d4 mov %esi,-0x2c(%ebp)
1c8: eb e4 jmp 1ae <gets+0x4e>
1ca: 8d b6 00 00 00 00 lea 0x0(%esi),%esi
000001d0 <stat>:
int
stat(const char *n, struct stat *st)
{
1d0: 55 push %ebp
int fd;
int r;
fd = open(n, O_RDONLY);
1d1: 31 c0 xor %eax,%eax
{
1d3: 89 e5 mov %esp,%ebp
1d5: 83 ec 18 sub $0x18,%esp
fd = open(n, O_RDONLY);
1d8: 89 44 24 04 mov %eax,0x4(%esp)
1dc: 8b 45 08 mov 0x8(%ebp),%eax
{
1df: 89 5d f8 mov %ebx,-0x8(%ebp)
1e2: 89 75 fc mov %esi,-0x4(%ebp)
fd = open(n, O_RDONLY);
1e5: 89 04 24 mov %eax,(%esp)
1e8: e8 fb 00 00 00 call 2e8 <open>
if(fd < 0)
1ed: 85 c0 test %eax,%eax
1ef: 78 2f js 220 <stat+0x50>
1f1: 89 c3 mov %eax,%ebx
return -1;
r = fstat(fd, st);
1f3: 8b 45 0c mov 0xc(%ebp),%eax
1f6: 89 1c 24 mov %ebx,(%esp)
1f9: 89 44 24 04 mov %eax,0x4(%esp)
1fd: e8 fe 00 00 00 call 300 <fstat>
close(fd);
202: 89 1c 24 mov %ebx,(%esp)
r = fstat(fd, st);
205: 89 c6 mov %eax,%esi
close(fd);
207: e8 c4 00 00 00 call 2d0 <close>
return r;
}
20c: 89 f0 mov %esi,%eax
20e: 8b 5d f8 mov -0x8(%ebp),%ebx
211: 8b 75 fc mov -0x4(%ebp),%esi
214: 89 ec mov %ebp,%esp
216: 5d pop %ebp
217: c3 ret
218: 90 nop
219: 8d b4 26 00 00 00 00 lea 0x0(%esi,%eiz,1),%esi
return -1;
220: be ff ff ff ff mov $0xffffffff,%esi
225: eb e5 jmp 20c <stat+0x3c>
227: 89 f6 mov %esi,%esi
229: 8d bc 27 00 00 00 00 lea 0x0(%edi,%eiz,1),%edi
00000230 <atoi>:
int
atoi(const char *s)
{
230: 55 push %ebp
231: 89 e5 mov %esp,%ebp
233: 8b 4d 08 mov 0x8(%ebp),%ecx
236: 53 push %ebx
int n;
n = 0;
while('0' <= *s && *s <= '9')
237: 0f be 11 movsbl (%ecx),%edx
23a: 88 d0 mov %dl,%al
23c: 2c 30 sub $0x30,%al
23e: 3c 09 cmp $0x9,%al
n = 0;
240: b8 00 00 00 00 mov $0x0,%eax
while('0' <= *s && *s <= '9')
245: 77 1e ja 265 <atoi+0x35>
247: 89 f6 mov %esi,%esi
249: 8d bc 27 00 00 00 00 lea 0x0(%edi,%eiz,1),%edi
n = n*10 + *s++ - '0';
250: 41 inc %ecx
251: 8d 04 80 lea (%eax,%eax,4),%eax
254: 8d 44 42 d0 lea -0x30(%edx,%eax,2),%eax
while('0' <= *s && *s <= '9')
258: 0f be 11 movsbl (%ecx),%edx
25b: 88 d3 mov %dl,%bl
25d: 80 eb 30 sub $0x30,%bl
260: 80 fb 09 cmp $0x9,%bl
263: 76 eb jbe 250 <atoi+0x20>
return n;
}
265: 5b pop %ebx
266: 5d pop %ebp
267: c3 ret
268: 90 nop
269: 8d b4 26 00 00 00 00 lea 0x0(%esi,%eiz,1),%esi
00000270 <memmove>:
void*
memmove(void *vdst, const void *vsrc, int n)
{
270: 55 push %ebp
271: 89 e5 mov %esp,%ebp
273: 56 push %esi
274: 8b 45 08 mov 0x8(%ebp),%eax
277: 53 push %ebx
278: 8b 5d 10 mov 0x10(%ebp),%ebx
27b: 8b 75 0c mov 0xc(%ebp),%esi
char *dst;
const char *src;
dst = vdst;
src = vsrc;
while(n-- > 0)
27e: 85 db test %ebx,%ebx
280: 7e 1a jle 29c <memmove+0x2c>
282: 31 d2 xor %edx,%edx
284: 8d b6 00 00 00 00 lea 0x0(%esi),%esi
28a: 8d bf 00 00 00 00 lea 0x0(%edi),%edi
*dst++ = *src++;
290: 0f b6 0c 16 movzbl (%esi,%edx,1),%ecx
294: 88 0c 10 mov %cl,(%eax,%edx,1)
297: 42 inc %edx
while(n-- > 0)
298: 39 d3 cmp %edx,%ebx
29a: 75 f4 jne 290 <memmove+0x20>
return vdst;
}
29c: 5b pop %ebx
29d: 5e pop %esi
29e: 5d pop %ebp
29f: c3 ret
000002a0 <fork>:
name: \
movl $SYS_ ## name, %eax; \
int $T_SYSCALL; \
ret
SYSCALL(fork)
2a0: b8 01 00 00 00 mov $0x1,%eax
2a5: cd 40 int $0x40
2a7: c3 ret
000002a8 <exit>:
SYSCALL(exit)
2a8: b8 02 00 00 00 mov $0x2,%eax
2ad: cd 40 int $0x40
2af: c3 ret
000002b0 <wait>:
SYSCALL(wait)
2b0: b8 03 00 00 00 mov $0x3,%eax
2b5: cd 40 int $0x40
2b7: c3 ret
000002b8 <pipe>:
SYSCALL(pipe)
2b8: b8 04 00 00 00 mov $0x4,%eax
2bd: cd 40 int $0x40
2bf: c3 ret
000002c0 <read>:
SYSCALL(read)
2c0: b8 05 00 00 00 mov $0x5,%eax
2c5: cd 40 int $0x40
2c7: c3 ret
000002c8 <write>:
SYSCALL(write)
2c8: b8 10 00 00 00 mov $0x10,%eax
2cd: cd 40 int $0x40
2cf: c3 ret
000002d0 <close>:
SYSCALL(close)
2d0: b8 15 00 00 00 mov $0x15,%eax
2d5: cd 40 int $0x40
2d7: c3 ret
000002d8 <kill>:
SYSCALL(kill)
2d8: b8 06 00 00 00 mov $0x6,%eax
2dd: cd 40 int $0x40
2df: c3 ret
000002e0 <exec>:
SYSCALL(exec)
2e0: b8 07 00 00 00 mov $0x7,%eax
2e5: cd 40 int $0x40
2e7: c3 ret
000002e8 <open>:
SYSCALL(open)
2e8: b8 0f 00 00 00 mov $0xf,%eax
2ed: cd 40 int $0x40
2ef: c3 ret
000002f0 <mknod>:
SYSCALL(mknod)
2f0: b8 11 00 00 00 mov $0x11,%eax
2f5: cd 40 int $0x40
2f7: c3 ret
000002f8 <unlink>:
SYSCALL(unlink)
2f8: b8 12 00 00 00 mov $0x12,%eax
2fd: cd 40 int $0x40
2ff: c3 ret
00000300 <fstat>:
SYSCALL(fstat)
300: b8 08 00 00 00 mov $0x8,%eax
305: cd 40 int $0x40
307: c3 ret
00000308 <link>:
SYSCALL(link)
308: b8 13 00 00 00 mov $0x13,%eax
30d: cd 40 int $0x40
30f: c3 ret
00000310 <mkdir>:
SYSCALL(mkdir)
310: b8 14 00 00 00 mov $0x14,%eax
315: cd 40 int $0x40
317: c3 ret
00000318 <chdir>:
SYSCALL(chdir)
318: b8 09 00 00 00 mov $0x9,%eax
31d: cd 40 int $0x40
31f: c3 ret
00000320 <dup>:
SYSCALL(dup)
320: b8 0a 00 00 00 mov $0xa,%eax
325: cd 40 int $0x40
327: c3 ret
00000328 <getpid>:
SYSCALL(getpid)
328: b8 0b 00 00 00 mov $0xb,%eax
32d: cd 40 int $0x40
32f: c3 ret
00000330 <sbrk>:
SYSCALL(sbrk)
330: b8 0c 00 00 00 mov $0xc,%eax
335: cd 40 int $0x40
337: c3 ret
00000338 <sleep>:
SYSCALL(sleep)
338: b8 0d 00 00 00 mov $0xd,%eax
33d: cd 40 int $0x40
33f: c3 ret
00000340 <uptime>:
SYSCALL(uptime)
340: b8 0e 00 00 00 mov $0xe,%eax
345: cd 40 int $0x40
347: c3 ret
00000348 <detach>:
SYSCALL(detach)
348: b8 16 00 00 00 mov $0x16,%eax
34d: cd 40 int $0x40
34f: c3 ret
00000350 <priority>:
SYSCALL(priority)
350: b8 17 00 00 00 mov $0x17,%eax
355: cd 40 int $0x40
357: c3 ret
358: 66 90 xchg %ax,%ax
35a: 66 90 xchg %ax,%ax
35c: 66 90 xchg %ax,%ax
35e: 66 90 xchg %ax,%ax
00000360 <printint>:
write(fd, &c, 1);
}
static void
printint(int fd, int xx, int base, int sgn)
{
360: 55 push %ebp
361: 89 e5 mov %esp,%ebp
363: 57 push %edi
364: 56 push %esi
365: 53 push %ebx
char buf[16];
int i, neg;
uint x;
neg = 0;
if(sgn && xx < 0){
366: 89 d3 mov %edx,%ebx
368: c1 eb 1f shr $0x1f,%ebx
{
36b: 83 ec 4c sub $0x4c,%esp
if(sgn && xx < 0){
36e: 84 db test %bl,%bl
{
370: 89 45 c0 mov %eax,-0x40(%ebp)
373: 89 d0 mov %edx,%eax
if(sgn && xx < 0){
375: 74 79 je 3f0 <printint+0x90>
377: f6 45 08 01 testb $0x1,0x8(%ebp)
37b: 74 73 je 3f0 <printint+0x90>
neg = 1;
x = -xx;
37d: f7 d8 neg %eax
neg = 1;
37f: c7 45 c4 01 00 00 00 movl $0x1,-0x3c(%ebp)
} else {
x = xx;
}
i = 0;
386: 31 f6 xor %esi,%esi
388: 8d 5d d7 lea -0x29(%ebp),%ebx
38b: eb 05 jmp 392 <printint+0x32>
38d: 8d 76 00 lea 0x0(%esi),%esi
do{
buf[i++] = digits[x % base];
390: 89 fe mov %edi,%esi
392: 31 d2 xor %edx,%edx
394: f7 f1 div %ecx
396: 8d 7e 01 lea 0x1(%esi),%edi
399: 0f b6 92 ac 07 00 00 movzbl 0x7ac(%edx),%edx
}while((x /= base) != 0);
3a0: 85 c0 test %eax,%eax
buf[i++] = digits[x % base];
3a2: 88 14 3b mov %dl,(%ebx,%edi,1)
}while((x /= base) != 0);
3a5: 75 e9 jne 390 <printint+0x30>
if(neg)
3a7: 8b 55 c4 mov -0x3c(%ebp),%edx
3aa: 85 d2 test %edx,%edx
3ac: 74 08 je 3b6 <printint+0x56>
buf[i++] = '-';
3ae: c6 44 3d d8 2d movb $0x2d,-0x28(%ebp,%edi,1)
3b3: 8d 7e 02 lea 0x2(%esi),%edi
3b6: 8d 74 3d d7 lea -0x29(%ebp,%edi,1),%esi
3ba: 8b 7d c0 mov -0x40(%ebp),%edi
3bd: 8d 76 00 lea 0x0(%esi),%esi
3c0: 0f b6 06 movzbl (%esi),%eax
3c3: 4e dec %esi
write(fd, &c, 1);
3c4: 89 5c 24 04 mov %ebx,0x4(%esp)
3c8: 89 3c 24 mov %edi,(%esp)
3cb: 88 45 d7 mov %al,-0x29(%ebp)
3ce: b8 01 00 00 00 mov $0x1,%eax
3d3: 89 44 24 08 mov %eax,0x8(%esp)
3d7: e8 ec fe ff ff call 2c8 <write>
while(--i >= 0)
3dc: 39 de cmp %ebx,%esi
3de: 75 e0 jne 3c0 <printint+0x60>
putc(fd, buf[i]);
}
3e0: 83 c4 4c add $0x4c,%esp
3e3: 5b pop %ebx
3e4: 5e pop %esi
3e5: 5f pop %edi
3e6: 5d pop %ebp
3e7: c3 ret
3e8: 90 nop
3e9: 8d b4 26 00 00 00 00 lea 0x0(%esi,%eiz,1),%esi
neg = 0;
3f0: c7 45 c4 00 00 00 00 movl $0x0,-0x3c(%ebp)
3f7: eb 8d jmp 386 <printint+0x26>
3f9: 8d b4 26 00 00 00 00 lea 0x0(%esi,%eiz,1),%esi
00000400 <printf>:
// Print to the given fd. Only understands %d, %x, %p, %s.
void
printf(int fd, const char *fmt, ...)
{
400: 55 push %ebp
401: 89 e5 mov %esp,%ebp
403: 57 push %edi
404: 56 push %esi
405: 53 push %ebx
406: 83 ec 3c sub $0x3c,%esp
int c, i, state;
uint *ap;
state = 0;
ap = (uint*)(void*)&fmt + 1;
for(i = 0; fmt[i]; i++){
409: 8b 75 0c mov 0xc(%ebp),%esi
40c: 0f b6 1e movzbl (%esi),%ebx
40f: 84 db test %bl,%bl
411: 0f 84 d1 00 00 00 je 4e8 <printf+0xe8>
state = 0;
417: 31 ff xor %edi,%edi
419: 46 inc %esi
ap = (uint*)(void*)&fmt + 1;
41a: 8d 45 10 lea 0x10(%ebp),%eax
write(fd, &c, 1);
41d: 89 fa mov %edi,%edx
41f: 8b 7d 08 mov 0x8(%ebp),%edi
ap = (uint*)(void*)&fmt + 1;
422: 89 45 d0 mov %eax,-0x30(%ebp)
425: eb 41 jmp 468 <printf+0x68>
427: 89 f6 mov %esi,%esi
429: 8d bc 27 00 00 00 00 lea 0x0(%edi,%eiz,1),%edi
c = fmt[i] & 0xff;
if(state == 0){
if(c == '%'){
430: 83 f8 25 cmp $0x25,%eax
433: 89 55 d4 mov %edx,-0x2c(%ebp)
state = '%';
436: ba 25 00 00 00 mov $0x25,%edx
if(c == '%'){
43b: 74 1e je 45b <printf+0x5b>
write(fd, &c, 1);
43d: b8 01 00 00 00 mov $0x1,%eax
442: 89 44 24 08 mov %eax,0x8(%esp)
446: 8d 45 e2 lea -0x1e(%ebp),%eax
449: 89 44 24 04 mov %eax,0x4(%esp)
44d: 89 3c 24 mov %edi,(%esp)
450: 88 5d e2 mov %bl,-0x1e(%ebp)
453: e8 70 fe ff ff call 2c8 <write>
458: 8b 55 d4 mov -0x2c(%ebp),%edx
45b: 46 inc %esi
for(i = 0; fmt[i]; i++){
45c: 0f b6 5e ff movzbl -0x1(%esi),%ebx
460: 84 db test %bl,%bl
462: 0f 84 80 00 00 00 je 4e8 <printf+0xe8>
if(state == 0){
468: 85 d2 test %edx,%edx
c = fmt[i] & 0xff;
46a: 0f be cb movsbl %bl,%ecx
46d: 0f b6 c3 movzbl %bl,%eax
if(state == 0){
470: 74 be je 430 <printf+0x30>
} else {
putc(fd, c);
}
} else if(state == '%'){
472: 83 fa 25 cmp $0x25,%edx
475: 75 e4 jne 45b <printf+0x5b>
if(c == 'd'){
477: 83 f8 64 cmp $0x64,%eax
47a: 0f 84 f0 00 00 00 je 570 <printf+0x170>
printint(fd, *ap, 10, 1);
ap++;
} else if(c == 'x' || c == 'p'){
480: 81 e1 f7 00 00 00 and $0xf7,%ecx
486: 83 f9 70 cmp $0x70,%ecx
489: 74 65 je 4f0 <printf+0xf0>
printint(fd, *ap, 16, 0);
ap++;
} else if(c == 's'){
48b: 83 f8 73 cmp $0x73,%eax
48e: 0f 84 8c 00 00 00 je 520 <printf+0x120>
s = "(null)";
while(*s != 0){
putc(fd, *s);
s++;
}
} else if(c == 'c'){
494: 83 f8 63 cmp $0x63,%eax
497: 0f 84 13 01 00 00 je 5b0 <printf+0x1b0>
putc(fd, *ap);
ap++;
} else if(c == '%'){
49d: 83 f8 25 cmp $0x25,%eax
4a0: 0f 84 e2 00 00 00 je 588 <printf+0x188>
write(fd, &c, 1);
4a6: b8 01 00 00 00 mov $0x1,%eax
4ab: 46 inc %esi
4ac: 89 44 24 08 mov %eax,0x8(%esp)
4b0: 8d 45 e7 lea -0x19(%ebp),%eax
4b3: 89 44 24 04 mov %eax,0x4(%esp)
4b7: 89 3c 24 mov %edi,(%esp)
4ba: c6 45 e7 25 movb $0x25,-0x19(%ebp)
4be: e8 05 fe ff ff call 2c8 <write>
4c3: ba 01 00 00 00 mov $0x1,%edx
4c8: 8d 45 e6 lea -0x1a(%ebp),%eax
4cb: 89 54 24 08 mov %edx,0x8(%esp)
4cf: 89 44 24 04 mov %eax,0x4(%esp)
4d3: 89 3c 24 mov %edi,(%esp)
4d6: 88 5d e6 mov %bl,-0x1a(%ebp)
4d9: e8 ea fd ff ff call 2c8 <write>
for(i = 0; fmt[i]; i++){
4de: 0f b6 5e ff movzbl -0x1(%esi),%ebx
} else {
// Unknown % sequence. Print it to draw attention.
putc(fd, '%');
putc(fd, c);
}
state = 0;
4e2: 31 d2 xor %edx,%edx
for(i = 0; fmt[i]; i++){
4e4: 84 db test %bl,%bl
4e6: 75 80 jne 468 <printf+0x68>
}
}
}
4e8: 83 c4 3c add $0x3c,%esp
4eb: 5b pop %ebx
4ec: 5e pop %esi
4ed: 5f pop %edi
4ee: 5d pop %ebp
4ef: c3 ret
printint(fd, *ap, 16, 0);
4f0: c7 04 24 00 00 00 00 movl $0x0,(%esp)
4f7: b9 10 00 00 00 mov $0x10,%ecx
4fc: 8b 5d d0 mov -0x30(%ebp),%ebx
4ff: 89 f8 mov %edi,%eax
501: 8b 13 mov (%ebx),%edx
503: e8 58 fe ff ff call 360 <printint>
ap++;
508: 89 d8 mov %ebx,%eax
state = 0;
50a: 31 d2 xor %edx,%edx
ap++;
50c: 83 c0 04 add $0x4,%eax
50f: 89 45 d0 mov %eax,-0x30(%ebp)
512: e9 44 ff ff ff jmp 45b <printf+0x5b>
517: 89 f6 mov %esi,%esi
519: 8d bc 27 00 00 00 00 lea 0x0(%edi,%eiz,1),%edi
s = (char*)*ap;
520: 8b 45 d0 mov -0x30(%ebp),%eax
523: 8b 10 mov (%eax),%edx
ap++;
525: 83 c0 04 add $0x4,%eax
528: 89 45 d0 mov %eax,-0x30(%ebp)
if(s == 0)
52b: 85 d2 test %edx,%edx
52d: 0f 84 aa 00 00 00 je 5dd <printf+0x1dd>
while(*s != 0){
533: 0f b6 02 movzbl (%edx),%eax
s = (char*)*ap;
536: 89 d3 mov %edx,%ebx
while(*s != 0){
538: 84 c0 test %al,%al
53a: 74 27 je 563 <printf+0x163>
53c: 8d 74 26 00 lea 0x0(%esi,%eiz,1),%esi
540: 88 45 e3 mov %al,-0x1d(%ebp)
write(fd, &c, 1);
543: b8 01 00 00 00 mov $0x1,%eax
s++;
548: 43 inc %ebx
write(fd, &c, 1);
549: 89 44 24 08 mov %eax,0x8(%esp)
54d: 8d 45 e3 lea -0x1d(%ebp),%eax
550: 89 44 24 04 mov %eax,0x4(%esp)
554: 89 3c 24 mov %edi,(%esp)
557: e8 6c fd ff ff call 2c8 <write>
while(*s != 0){
55c: 0f b6 03 movzbl (%ebx),%eax
55f: 84 c0 test %al,%al
561: 75 dd jne 540 <printf+0x140>
state = 0;
563: 31 d2 xor %edx,%edx
565: e9 f1 fe ff ff jmp 45b <printf+0x5b>
56a: 8d b6 00 00 00 00 lea 0x0(%esi),%esi
printint(fd, *ap, 10, 1);
570: c7 04 24 01 00 00 00 movl $0x1,(%esp)
577: b9 0a 00 00 00 mov $0xa,%ecx
57c: e9 7b ff ff ff jmp 4fc <printf+0xfc>
581: 8d b4 26 00 00 00 00 lea 0x0(%esi,%eiz,1),%esi
write(fd, &c, 1);
588: b9 01 00 00 00 mov $0x1,%ecx
58d: 8d 45 e5 lea -0x1b(%ebp),%eax
590: 89 4c 24 08 mov %ecx,0x8(%esp)
594: 89 44 24 04 mov %eax,0x4(%esp)
598: 89 3c 24 mov %edi,(%esp)
59b: 88 5d e5 mov %bl,-0x1b(%ebp)
59e: e8 25 fd ff ff call 2c8 <write>
state = 0;
5a3: 31 d2 xor %edx,%edx
5a5: e9 b1 fe ff ff jmp 45b <printf+0x5b>
5aa: 8d b6 00 00 00 00 lea 0x0(%esi),%esi
putc(fd, *ap);
5b0: 8b 5d d0 mov -0x30(%ebp),%ebx
5b3: 8b 03 mov (%ebx),%eax
ap++;
5b5: 83 c3 04 add $0x4,%ebx
write(fd, &c, 1);
5b8: 89 3c 24 mov %edi,(%esp)
putc(fd, *ap);
5bb: 88 45 e4 mov %al,-0x1c(%ebp)
write(fd, &c, 1);
5be: b8 01 00 00 00 mov $0x1,%eax
5c3: 89 44 24 08 mov %eax,0x8(%esp)
5c7: 8d 45 e4 lea -0x1c(%ebp),%eax
5ca: 89 44 24 04 mov %eax,0x4(%esp)
5ce: e8 f5 fc ff ff call 2c8 <write>
state = 0;
5d3: 31 d2 xor %edx,%edx
ap++;
5d5: 89 5d d0 mov %ebx,-0x30(%ebp)
5d8: e9 7e fe ff ff jmp 45b <printf+0x5b>
s = "(null)";
5dd: bb a5 07 00 00 mov $0x7a5,%ebx
while(*s != 0){
5e2: b0 28 mov $0x28,%al
5e4: e9 57 ff ff ff jmp 540 <printf+0x140>
5e9: 66 90 xchg %ax,%ax
5eb: 66 90 xchg %ax,%ax
5ed: 66 90 xchg %ax,%ax
5ef: 90 nop
000005f0 <free>:
static Header base;
static Header *freep;
void
free(void *ap)
{
5f0: 55 push %ebp
Header *bp, *p;
bp = (Header*)ap - 1;
for(p = freep; !(bp > p && bp < p->s.ptr); p = p->s.ptr)
5f1: a1 3c 0a 00 00 mov 0xa3c,%eax
{
5f6: 89 e5 mov %esp,%ebp
5f8: 57 push %edi
5f9: 56 push %esi
5fa: 53 push %ebx
5fb: 8b 5d 08 mov 0x8(%ebp),%ebx
bp = (Header*)ap - 1;
5fe: 8d 4b f8 lea -0x8(%ebx),%ecx
601: eb 0d jmp 610 <free+0x20>
603: 90 nop
604: 90 nop
605: 90 nop
606: 90 nop
607: 90 nop
608: 90 nop
609: 90 nop
60a: 90 nop
60b: 90 nop
60c: 90 nop
60d: 90 nop
60e: 90 nop
60f: 90 nop
for(p = freep; !(bp > p && bp < p->s.ptr); p = p->s.ptr)
610: 39 c8 cmp %ecx,%eax
612: 8b 10 mov (%eax),%edx
614: 73 32 jae 648 <free+0x58>
616: 39 d1 cmp %edx,%ecx
618: 72 04 jb 61e <free+0x2e>
if(p >= p->s.ptr && (bp > p || bp < p->s.ptr))
61a: 39 d0 cmp %edx,%eax
61c: 72 32 jb 650 <free+0x60>
break;
if(bp + bp->s.size == p->s.ptr){
61e: 8b 73 fc mov -0x4(%ebx),%esi
621: 8d 3c f1 lea (%ecx,%esi,8),%edi
624: 39 fa cmp %edi,%edx
626: 74 30 je 658 <free+0x68>
bp->s.size += p->s.ptr->s.size;
bp->s.ptr = p->s.ptr->s.ptr;
} else
bp->s.ptr = p->s.ptr;
628: 89 53 f8 mov %edx,-0x8(%ebx)
if(p + p->s.size == bp){
62b: 8b 50 04 mov 0x4(%eax),%edx
62e: 8d 34 d0 lea (%eax,%edx,8),%esi
631: 39 f1 cmp %esi,%ecx
633: 74 3c je 671 <free+0x81>
p->s.size += bp->s.size;
p->s.ptr = bp->s.ptr;
} else
p->s.ptr = bp;
635: 89 08 mov %ecx,(%eax)
freep = p;
}
637: 5b pop %ebx
freep = p;
638: a3 3c 0a 00 00 mov %eax,0xa3c
}
63d: 5e pop %esi
63e: 5f pop %edi
63f: 5d pop %ebp
640: c3 ret
641: 8d b4 26 00 00 00 00 lea 0x0(%esi,%eiz,1),%esi
if(p >= p->s.ptr && (bp > p || bp < p->s.ptr))
648: 39 d0 cmp %edx,%eax
64a: 72 04 jb 650 <free+0x60>
64c: 39 d1 cmp %edx,%ecx
64e: 72 ce jb 61e <free+0x2e>
{
650: 89 d0 mov %edx,%eax
652: eb bc jmp 610 <free+0x20>
654: 8d 74 26 00 lea 0x0(%esi,%eiz,1),%esi
bp->s.size += p->s.ptr->s.size;
658: 8b 7a 04 mov 0x4(%edx),%edi
65b: 01 fe add %edi,%esi
65d: 89 73 fc mov %esi,-0x4(%ebx)
bp->s.ptr = p->s.ptr->s.ptr;
660: 8b 10 mov (%eax),%edx
662: 8b 12 mov (%edx),%edx
664: 89 53 f8 mov %edx,-0x8(%ebx)
if(p + p->s.size == bp){
667: 8b 50 04 mov 0x4(%eax),%edx
66a: 8d 34 d0 lea (%eax,%edx,8),%esi
66d: 39 f1 cmp %esi,%ecx
66f: 75 c4 jne 635 <free+0x45>
p->s.size += bp->s.size;
671: 8b 4b fc mov -0x4(%ebx),%ecx
freep = p;
674: a3 3c 0a 00 00 mov %eax,0xa3c
p->s.size += bp->s.size;
679: 01 ca add %ecx,%edx
67b: 89 50 04 mov %edx,0x4(%eax)
p->s.ptr = bp->s.ptr;
67e: 8b 53 f8 mov -0x8(%ebx),%edx
681: 89 10 mov %edx,(%eax)
}
683: 5b pop %ebx
684: 5e pop %esi
685: 5f pop %edi
686: 5d pop %ebp
687: c3 ret
688: 90 nop
689: 8d b4 26 00 00 00 00 lea 0x0(%esi,%eiz,1),%esi
00000690 <malloc>:
return freep;
}
void*
malloc(uint nbytes)
{
690: 55 push %ebp
691: 89 e5 mov %esp,%ebp
693: 57 push %edi
694: 56 push %esi
695: 53 push %ebx
696: 83 ec 1c sub $0x1c,%esp
Header *p, *prevp;
uint nunits;
nunits = (nbytes + sizeof(Header) - 1)/sizeof(Header) + 1;
699: 8b 45 08 mov 0x8(%ebp),%eax
if((prevp = freep) == 0){
69c: 8b 15 3c 0a 00 00 mov 0xa3c,%edx
nunits = (nbytes + sizeof(Header) - 1)/sizeof(Header) + 1;
6a2: 8d 78 07 lea 0x7(%eax),%edi
6a5: c1 ef 03 shr $0x3,%edi
6a8: 47 inc %edi
if((prevp = freep) == 0){
6a9: 85 d2 test %edx,%edx
6ab: 0f 84 8f 00 00 00 je 740 <malloc+0xb0>
6b1: 8b 02 mov (%edx),%eax
6b3: 8b 48 04 mov 0x4(%eax),%ecx
base.s.ptr = freep = prevp = &base;
base.s.size = 0;
}
for(p = prevp->s.ptr; ; prevp = p, p = p->s.ptr){
if(p->s.size >= nunits){
6b6: 39 cf cmp %ecx,%edi
6b8: 76 66 jbe 720 <malloc+0x90>
6ba: 81 ff 00 10 00 00 cmp $0x1000,%edi
6c0: bb 00 10 00 00 mov $0x1000,%ebx
6c5: 0f 43 df cmovae %edi,%ebx
p = sbrk(nu * sizeof(Header));
6c8: 8d 34 dd 00 00 00 00 lea 0x0(,%ebx,8),%esi
6cf: eb 10 jmp 6e1 <malloc+0x51>
6d1: 8d b4 26 00 00 00 00 lea 0x0(%esi,%eiz,1),%esi
for(p = prevp->s.ptr; ; prevp = p, p = p->s.ptr){
6d8: 8b 02 mov (%edx),%eax
if(p->s.size >= nunits){
6da: 8b 48 04 mov 0x4(%eax),%ecx
6dd: 39 f9 cmp %edi,%ecx
6df: 73 3f jae 720 <malloc+0x90>
p->s.size = nunits;
}
freep = prevp;
return (void*)(p + 1);
}
if(p == freep)
6e1: 39 05 3c 0a 00 00 cmp %eax,0xa3c
6e7: 89 c2 mov %eax,%edx
6e9: 75 ed jne 6d8 <malloc+0x48>
p = sbrk(nu * sizeof(Header));
6eb: 89 34 24 mov %esi,(%esp)
6ee: e8 3d fc ff ff call 330 <sbrk>
if(p == (char*)-1)
6f3: 83 f8 ff cmp $0xffffffff,%eax
6f6: 74 18 je 710 <malloc+0x80>
hp->s.size = nu;
6f8: 89 58 04 mov %ebx,0x4(%eax)
free((void*)(hp + 1));
6fb: 83 c0 08 add $0x8,%eax
6fe: 89 04 24 mov %eax,(%esp)
701: e8 ea fe ff ff call 5f0 <free>
return freep;
706: 8b 15 3c 0a 00 00 mov 0xa3c,%edx
if((p = morecore(nunits)) == 0)
70c: 85 d2 test %edx,%edx
70e: 75 c8 jne 6d8 <malloc+0x48>
return 0;
}
}
710: 83 c4 1c add $0x1c,%esp
return 0;
713: 31 c0 xor %eax,%eax
}
715: 5b pop %ebx
716: 5e pop %esi
717: 5f pop %edi
718: 5d pop %ebp
719: c3 ret
71a: 8d b6 00 00 00 00 lea 0x0(%esi),%esi
if(p->s.size == nunits)
720: 39 cf cmp %ecx,%edi
722: 74 4c je 770 <malloc+0xe0>
p->s.size -= nunits;
724: 29 f9 sub %edi,%ecx
726: 89 48 04 mov %ecx,0x4(%eax)
p += p->s.size;
729: 8d 04 c8 lea (%eax,%ecx,8),%eax
p->s.size = nunits;
72c: 89 78 04 mov %edi,0x4(%eax)
freep = prevp;
72f: 89 15 3c 0a 00 00 mov %edx,0xa3c
}
735: 83 c4 1c add $0x1c,%esp
return (void*)(p + 1);
738: 83 c0 08 add $0x8,%eax
}
73b: 5b pop %ebx
73c: 5e pop %esi
73d: 5f pop %edi
73e: 5d pop %ebp
73f: c3 ret
base.s.ptr = freep = prevp = &base;
740: b8 40 0a 00 00 mov $0xa40,%eax
745: ba 40 0a 00 00 mov $0xa40,%edx
base.s.size = 0;
74a: 31 c9 xor %ecx,%ecx
base.s.ptr = freep = prevp = &base;
74c: a3 3c 0a 00 00 mov %eax,0xa3c
base.s.size = 0;
751: b8 40 0a 00 00 mov $0xa40,%eax
base.s.ptr = freep = prevp = &base;
756: 89 15 40 0a 00 00 mov %edx,0xa40
base.s.size = 0;
75c: 89 0d 44 0a 00 00 mov %ecx,0xa44
762: e9 53 ff ff ff jmp 6ba <malloc+0x2a>
767: 89 f6 mov %esi,%esi
769: 8d bc 27 00 00 00 00 lea 0x0(%edi,%eiz,1),%edi
prevp->s.ptr = p->s.ptr;
770: 8b 08 mov (%eax),%ecx
772: 89 0a mov %ecx,(%edx)
774: eb b9 jmp 72f <malloc+0x9f>
|
; A154957: A symmetric (0,1)-triangle.
; 1,1,1,1,0,1,1,0,0,1,1,0,1,0,1,1,0,1,1,0,1,1,0,1,0,1,0,1,1,0,1,0,0,1,0,1,1,0,1,0,1,0,1,0,1,1,0,1,0,1,1,0,1,0,1,1,0,1,0,1,0,1,0,1,0,1,1,0,1,0,1,0,0,1,0,1,0,1,1,0,1,0,1,0,1,0,1,0,1,0,1,1,0,1,0,1,0,1,1,0
seq $0,204028 ; Symmetric matrix based on f(i,j)=min(3i-2,3j-2), by antidiagonals.
mod $0,2
|
$NOMOD51
$INCLUDE(hwconf.inc)
;------------------------------------------------------------------------------
; This file is part of the C51 Compiler package
; Copyright (c) 1988-2002 Keil Elektronik GmbH and Keil Software, Inc.
;------------------------------------------------------------------------------
; STARTUP.A51: This code is executed after processor reset.
;
; To translate this file use A51 with the following invocation:
;
; A51 STARTUP.A51
;
; To link the modified STARTUP.OBJ file to your application use the following
; BL51 invocation:
;
; BL51 <your object file list>, STARTUP.OBJ <controls>
;
;------------------------------------------------------------------------------
;
; User-defined Power-On Initialization of Memory
;
; With the following EQU statements the initialization of memory
; at processor reset can be defined:
;
; ; the absolute start-address of IDATA memory is always 0
IDATALEN EQU 0FFH ; the length of IDATA memory in bytes.
;
; See hwconf.inc for XDATASTART
; See hwconf.inc for XDATALEN
;
PDATASTART EQU 0H ; the absolute start-address of PDATA memory
PDATALEN EQU 0H ; the length of PDATA memory in bytes.
;
; Notes: The IDATA space overlaps physically the DATA and BIT areas of the
; 8051 CPU. At minimum the memory space occupied from the C51
; run-time routines must be set to zero.
;------------------------------------------------------------------------------
;
; Reentrant Stack Initilization
;
; The following EQU statements define the stack pointer for reentrant
; functions and initialized it:
;
; Stack Space for reentrant functions in the SMALL model.
IBPSTACK EQU 0 ; set to 1 if small reentrant is used.
IBPSTACKTOP EQU 0FFH+1 ; set top of stack to highest location+1.
;
; Stack Space for reentrant functions in the LARGE model.
XBPSTACK EQU 0 ; set to 1 if large reentrant is used.
XBPSTACKTOP EQU 0FFFFH+1; set top of stack to highest location+1.
;
; Stack Space for reentrant functions in the COMPACT model.
PBPSTACK EQU 0 ; set to 1 if compact reentrant is used.
PBPSTACKTOP EQU 0FFFFH+1; set top of stack to highest location+1.
;
;------------------------------------------------------------------------------
;
; Page Definition for Using the Compact Model with 64 KByte xdata RAM
;
; The following EQU statements define the xdata page used for pdata
; variables. The EQU PPAGE must conform with the PPAGE control used
; in the linker invocation.
;
PPAGEENABLE EQU 0 ; set to 1 if pdata object are used.
;
PPAGE EQU 0 ; define PPAGE number.
;
PPAGE_SFR DATA 0A0H ; SFR that supplies uppermost address byte
; (most 8051 variants use P2 as uppermost address byte)
;
;------------------------------------------------------------------------------
; Standard SFR Symbols
ACC DATA 0E0H
B DATA 0F0H
SP DATA 81H
DPL DATA 82H
DPH DATA 83H
AUXR DATA 8EH
;------------------------------------------------------------------------------
NAME ?C_STARTUP
?C_C51STARTUP SEGMENT CODE
?STACK SEGMENT IDATA
RSEG ?STACK
DS 1
EXTRN CODE (?C_START)
PUBLIC ?C_STARTUP
CSEG AT 0
?C_STARTUP: LJMP STARTUP1
RSEG ?C_C51STARTUP
STARTUP1:
; Mapping before memory and stack inialization
MOV SP, #?STACK-1
; Use GPR to determin if boot code is there
MOV A, GPR
CJNE A, #1BH, RUNONROM
LJMP RUNONRAM
RUNONROM: CALL hw_init
RUNONRAM: NOP
IF IDATALEN <> 0
MOV R0, #IDATALEN - 1
CLR A
IDATALOOP: MOV @R0, A
DJNZ R0, IDATALOOP
ENDIF
IF XDATALEN <> 0
STARTUP_XMEM
MOV DPTR, #XDATASTART
MOV R7, #LOW (XDATALEN)
IF (LOW (XDATALEN)) <> 0
MOV R6, #(HIGH (XDATALEN)) + 1
ELSE
MOV R6, #HIGH (XDATALEN)
ENDIF
CLR A
XDATALOOP: MOVX @DPTR, A
INC DPTR
DJNZ R7, XDATALOOP
DJNZ R6, XDATALOOP
ENDIF
IF PPAGEENABLE <> 0
MOV PPAGE_SFR, #PPAGE
ENDIF
IF PDATALEN <> 0
MOV R0, #LOW (PDATASTART)
MOV R7, #LOW (PDATALEN)
CLR A
PDATALOOP: MOVX @R0, A
INC R0
DJNZ R7, PDATALOOP
ENDIF
IF IBPSTACK <> 0
EXTRN DATA (?C_IBP)
MOV ?C_IBP, #LOW (IBPSTACKTOP)
ENDIF
IF XBPSTACK <> 0
EXTRN DATA (?C_XBP)
MOV ?C_XBP, #HIGH (XBPSTACKTOP)
MOV ?C_XBP + 1, #LOW (XBPSTACKTOP)
ENDIF
IF PBPSTACK <> 0
EXTRN DATA (?C_PBP)
MOV ?C_PBP, #LOW (PBPSTACKTOP)
ENDIF
MOV SP, #?STACK-1
; This code is required if you use L51_BANK.A51 with Banking Mode 4
; EXTRN CODE (?B_SWITCH0)
; CALL ?B_SWITCH0 ; init bank mechanism to code bank 0
LJMP ?C_START
hw_init:
; Speed up the SI interface by writing to IPU_CFG:SPI_MST_CFG.
MOV RA_DA3, #0
MOV RA_DA2, #0
MOV RA_DA1, #007H
MOV RA_DA0, #0E5H
MOV RA_AD3, #070H
MOV RA_AD2, #0
MOV RA_AD1, #0
MOV RA_AD0_WR, #050H ; this write start the AHB write!
$IF (BOOT_VIA_SPI = 1)
; Configure registers for loading the internal memory from FLASH. ICPU_CFG:MEMACC
MOV RA_DA3, #HIGH (IMAGE_SIZE)
MOV RA_DA2, #LOW (IMAGE_SIZE)
MOV RA_DA1, #0
MOV RA_DA0, #0
; MOV RA_AD3, #070H
; MOV RA_AD2, #0
; MOV RA_AD1, #0
MOV RA_AD0_WR, #078H ; this write start the AHB write!
; Start the actual load, the 8051 will be gated while the load is going on,
; so we can just continue as if nothing had happend (8051 will be released
; once the onchip memory contains the progam). ICPU_CFG:MEMACC_CTRL
MOV RA_DA3, #0
MOV RA_DA2, #0
; MOV RA_DA1, #0
MOV RA_DA0, #001H
; MOV RA_AD3, #070H
; MOV RA_AD2, #0
; MOV RA_AD1, #0
MOV RA_AD0_WR, #074H ; this write start the AHB write!
$ENDIF
; Errata, clear SFR register 0x8E prior to mapping internal memory.
MOV 8EH, #000H
; Enable mapping of onchip memory, note that we use SFR reg - not the CSR
; counterpart, this means that if the 8051 is reset (without resetting the
; the AHB system), then we will again load from external FLASH!
MOV MMAP, #0AFH ; map all accesses to onchip memory (until 8051 reset)
RET
END
|
; A157915: a(n) = 625*n^2 + 25.
; 650,2525,5650,10025,15650,22525,30650,40025,50650,62525,75650,90025,105650,122525,140650,160025,180650,202525,225650,250025,275650,302525,330650,360025,390650,422525,455650,490025,525650,562525,600650,640025,680650,722525,765650,810025,855650,902525,950650,1000025,1050650,1102525,1155650,1210025,1265650,1322525,1380650,1440025,1500650,1562525,1625650,1690025,1755650,1822525,1890650,1960025,2030650,2102525,2175650,2250025,2325650,2402525,2480650,2560025,2640650,2722525,2805650,2890025,2975650
mov $1,2
add $1,$0
mul $1,$0
mul $1,625
add $1,650
mov $0,$1
|
; A337843: a(n) is n + the number of digits in the decimal expansion of n.
; 1,2,3,4,5,6,7,8,9,10,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69
mov $1,9
bin $1,$0
cmp $1,0
add $1,$0
add $1,1
mov $0,$1
|
//------------------------------------------------------------------------------
//
// Copyright 2018-2019 Fetch.AI Limited
//
// 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 "ml/ops/add.hpp"
#include "math/tensor.hpp"
#include "vectorise/fixed_point/fixed_point.hpp"
#include "gtest/gtest.h"
template <typename T>
class AddTest : public ::testing::Test
{
};
using MyTypes = ::testing::Types<fetch::math::Tensor<float>, fetch::math::Tensor<double>,
fetch::math::Tensor<fetch::fixed_point::fp32_t>,
fetch::math::Tensor<fetch::fixed_point::fp64_t>>;
TYPED_TEST_CASE(AddTest, MyTypes);
TYPED_TEST(AddTest, forward_test)
{
using ArrayType = TypeParam;
using DataType = typename TypeParam::Type;
ArrayType data_1 = ArrayType::FromString(
"1, -2, 3,-4, 5,-6, 7,-8;"
"1, 2, 3, 4, 5, 6, 7, 8");
ArrayType data_2 = ArrayType::FromString(
"8;"
"-8");
ArrayType gt = ArrayType::FromString(
"9, 6, 11, 4, 13, 2, 15, 0;"
"-7, -6, -5, -4, -3, -2, -1, 0");
fetch::ml::ops::Add<ArrayType> op;
TypeParam prediction(op.ComputeOutputShape({data_1, data_2}));
op.Forward({data_1, data_2}, prediction);
// test correct values
ASSERT_TRUE(prediction.AllClose(gt, fetch::math::function_tolerance<DataType>(),
fetch::math::function_tolerance<DataType>()));
}
TYPED_TEST(AddTest, backward_test)
{
using DataType = typename TypeParam::Type;
using ArrayType = TypeParam;
ArrayType data_1 = ArrayType::FromString(
"1, -2, 3,-4, 5,-6, 7,-8;"
"1, 2, 3, 4, 5, 6, 7, 8");
ArrayType data_2 = ArrayType::FromString(
"8;"
"-8");
ArrayType gt_1 = ArrayType::FromString(
"1, -1, 2, -2, 3, -3, 4, 4;"
"5, -5, 6, -6, 7, -7, 8, 8");
ArrayType gt_2 = ArrayType::FromString(
"8;"
"16");
ArrayType error = ArrayType::FromString(
"1, -1, 2, -2, 3, -3, 4, 4;"
"5, -5, 6, -6, 7, -7, 8, 8");
fetch::ml::ops::Add<ArrayType> op;
std::vector<ArrayType> prediction = op.Backward({data_1, data_2}, error);
// test correct values
ASSERT_TRUE(prediction[0].AllClose(gt_1, fetch::math::function_tolerance<DataType>(),
fetch::math::function_tolerance<DataType>()));
ASSERT_TRUE(prediction[1].AllClose(gt_2, fetch::math::function_tolerance<DataType>(),
fetch::math::function_tolerance<DataType>()));
}
|
;
; Copyright (c) 2022, suncloudsmoon and the Simple-Cpp-Kernel contributors.
;
; 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.
;
; 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 "boot/macros.asm"
; Parameters needed: ch (track number), cl (sector number), dh (head number), al (number of sectors) es:bx
read_hdd_manual:
pusha
mov ah, 02
mov dl, 0x80
int 13h
jc error
popa
ret
error:
outch 'e'
outch 'r'
outch 'r'
outch 'o'
outch 'r'
outch '!'
cli
hlt
|
;******************************************************************************
;
; (c) 2013 by BECK IPC GmbH
; http://www.beck-ipc.com
;
;******************************************************************************
;
; Module: cry43.asm
; Function: Dynamic linking of TCPI/IP API Function Crypt_SHA256_Init()
;
;
;******************************************************************************
;
; $Header$
;
;******************************************************************************
INCLUDE tcpipapi.def
_TEXT SEGMENT BYTE PUBLIC 'CODE'
ASSUME CS:_TEXT, DS:NOTHING, ES:NOTHING, SS:NOTHING
;******************************************************************************
; Prototypes
;******************************************************************************
PUBLIC _Crypt_SHA256_Init
;******************************************************************************
; Crypt_SHA256_Init()
;******************************************************************************
_Crypt_SHA256_Init PROC FAR
LINKER_PATCH ; Will be replaced by dynamic linking code
MOV AX, TCPIP_DYN_LINK_Crypt_SHA256_Init ; AH = 0, AL = Function number
INT TCPIP_SWI
; IP-Register will be adjusted on return from software interrupt so that the
; new code is executed immediately.
_Crypt_SHA256_Init ENDP
_TEXT ENDS
END
; End of file
|
; A144328: A002260 preceded by a column of 1's: a (1, 1, 2, 3, 4, 5,...) crescendo triangle by rows.
; 1,1,1,1,1,2,1,1,2,3,1,1,2,3,4,1,1,2,3,4,5,1,1,2,3,4,5,6,1,1,2,3,4,5,6,7,1,1,2,3,4,5,6,7,8,1,1,2,3,4,5,6,7,8,9,1,1,2,3,4,5,6,7,8,9,10,1,1,2,3,4,5,6,7,8,9,10,11,1,1,2,3,4,5,6,7,8,9,10,11,12,1,1,2,3,4,5,6,7,8,9,10,11,12,13,1,1,2,3,4,5,6,7,8,9,10,11,12,13,14,1,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,1,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,1,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,1,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,1,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,1,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,1,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18
lpb $0,1
trn $0,2
mov $1,$0
trn $0,$2
add $2,1
lpe
add $1,1
|
; A174347: Expansion of (1 - 2*x - sqrt(1 - 8*x + 8*x^2))/(2*x*(1-x)).
; Submitted by Christian Krause
; 1,3,11,47,223,1135,6063,33535,190399,1103231,6497407,38779647,234043647,1425869567,8757326591,54163521535,337060285439,2108928587775,13258969458687,83720567447551,530692157964287,3375836610256895,21543201449893887,137882426581123071,884855151096922111,5692556558056554495,36705605591861428223,237177966798100955135,1535564355292627927039,9959899907166108319743,64711662462629570609151,421117419196955737718783,2744566742946621288087551,17912454875440743454343167,117060768950541039444688895
lpb $0
mov $2,$0
sub $0,1
seq $2,166229 ; Expansion of (1-2x-sqrt(1-8x+8x^2))/(2x).
add $1,$2
lpe
mov $0,$1
add $0,1
|
#include "lexicalAnalyzer.h"
struct tokenCollection{
node** collection;
int n;
int k;
};
struct node{
int line;
char* lexer;
char* token;
};
bool isDelimiter(char ch) {
if (ch == ' ' || ch == ',' || ch == ';' || ch == '(' || ch == ')' || ch == '[' || ch == ']' || ch == '{' || ch == '}'){
return (true);
}
return (false);
}
bool isScopeConstruction(char* str) {
if (!strcmp(str, "begin") || !strcmp(str, "end")){
return (true);
}
return (false);
}
bool isLogicalOperator(char* str) {
if (!strcmp(str, "&&") || !strcmp(str, "||") || !strcmp(str, "!")){
return (true);
}
return (false);
}
bool isArithmeticOperator(char* str) {
if (!strcmp(str, "+") || !strcmp(str, "-") || !strcmp(str, "*") || !strcmp(str, "/") || !strcmp(str, "**")
|| !strcmp(str, "%")){
return (true);
}
return (false);
}
bool isRelationalOperator(char* str) {
if (!strcmp(str, "<") || !strcmp(str, ">") || !strcmp(str, "==") || !strcmp(str, "<=") || !strcmp(str, "!=")
|| !strcmp(str, ">=") || !strcmp(str, "===") || !strcmp(str, "!==")){
return (true);
}
return (false);
}
bool validIdentifier(char* str) {
if (str[0] == '0' || str[0] == '1' || str[0] == '2' || str[0] == '3' || str[0] == '4' || str[0] == '5' ||
str[0] == '6' || str[0] == '7' || str[0] == '8' || str[0] == '9' || isDelimiter(str[0]) == true){
return (false);
}
if(str[(strlen(str))-1] == '@'){
return (false);
}
if(str[0] == '@'){
return (false);
}
if(str[0] == '#'){
return (false);
}
return (true);
}
bool isKeyword(char* str) {
if (!strcmp(str, "if") || !strcmp(str, "else") || !strcmp(str, "const") || !strcmp(str, "def") || !strcmp(str, "main")
|| !strcmp(str, "int") || !strcmp(str, "float") || !strcmp(str, "string") || !strcmp(str, "bool")){
return (true);
}
return (false);
}
bool isInteger(char* str) {
int i, len = strlen(str);
if (len == 0){
return (false);
}
for (i = 0; i < len; i++) {
if (str[i] != '0' && str[i] != '1' && str[i] != '2' && str[i] != '3' && str[i] != '4' && str[i] != '5'
&& str[i] != '6' && str[i] != '7' && str[i] != '8' && str[i] != '9' || (str[i] == '-' && i > 0)){
return (false);
}
}
return (true);
}
bool isRealNumber(char* str) {
int i, len = strlen(str);
bool hasDecimal = false;
if (len == 0)
return (false);
for (i = 0; i < len; i++) {
if (str[i] != '0' && str[i] != '1' && str[i] != '2' && str[i] != '3' && str[i] != '4' && str[i] != '5'
&& str[i] != '6' && str[i] != '7' && str[i] != '8' && str[i] != '9' && str[i] != '.' || (str[i] == '-' && i > 0)){
return (false);
}
if (str[i] == '.'){
hasDecimal = true;
}
}
return (hasDecimal);
}
bool isString(char* str) {
char first = str[0];
int len = strlen(str);
char last = str[len-1];
if (('#' == first) && ('#' == last)) {
return (true);
}
return (false);
}
bool isBoolean(char* str) {
if (!strcmp(str, "false") || !strcmp(str, "true")){
return (true);
}
return (false);
}
char* subString(char* str, int left, int right) {
int i;
char* subStr = (char*)malloc(sizeof(char) * (right - left + 2));
for (i = left; i <= right; i++){
subStr[i - left] = str[i];
}
subStr[right - left + 1] = '\0';
return (subStr);
}
bool isFormingCharacter(char* str) {
if (!strcmp(str, "\n") || !strcmp(str, "\t") || !strcmp(str, "\v") || !strcmp(str, "\b") || !strcmp(str, "\f")){
return (true);
}
return (false);
}
void isExpression(TokenCol* col, char* str, char* subStrLeft, char* subStrRight, int line) {
char* lex;
if (isLogicalOperator(subStrRight) == true){
if (validIdentifier(subStrLeft) == true && (validIdentifier(str) == true)){
printf(" | LOGICAL_EXPRESSION | %s %s %s | %d \n", subStrLeft, subStrRight, str, line);
}
}
else if (isArithmeticOperator(subStrRight) == true){
if (validIdentifier(subStrLeft) == true && (validIdentifier(str) == true)){
printf(" | ARITHMETIC_EXPRESSION | %s %s %s | %d \n", subStrLeft, subStrRight, str, line);
}
}
else if (isRelationalOperator(subStrRight) == true){
if (validIdentifier(subStrLeft) == true && (validIdentifier(str) == true)){
printf(" | RELATIONAL_EXPRESSION | %s %s %s | %d \n", subStrLeft, subStrRight, str, line);
}
}
}
TokenCol* tokenizer(char* str, TokenCol* col) {
int left = 0, right = 0;
int len = strlen(str);
int line = 1;
char* subStrLeft = (char*)malloc(sizeof(char));
char* subStrRight = (char*)malloc(sizeof(char));
printf("\n | ------- Token ------- | ------- Lexema ------- | ------- Linha ------- | \n");
printf(" | ---------------------------------------------------------------------- | \n");
while (right <= len && left <= right) {
if (isDelimiter(str[right]) == false){
right++;
}
if (isDelimiter(str[right]) == true && str[right] != ' ') {
if(str[right] == ','){
printf(" | DELIM_COMMA | %c | %d \n", str[right], line);
add(col, line, ",", "DELIM_COMMA");
}
else if(str[right] == ';'){
printf(" | DELIM_SEMICOLON | %c | %d \n", str[right], line);
add(col, line, ";", "DELIM_SEMICOLON");
}
else if(str[right] == '('){
printf(" | DELIM_O_PARENTHESES | %c | %d \n", str[right], line);
add(col, line, "(", "DELIM_O_PARENTHESES");
}
else if(str[right] == ')'){
printf(" | DELIM_C_PARENTHESES | %c | %d \n", str[right], line);
add(col, line, ")", "DELIM_C_PARENTHESES");
}
else if(str[right] == '['){
printf(" | DELIM_O_SQ_BRACKET | %c | %d \n", str[right], line);
add(col, line, "[", "DELIM_O_SQ_BRACKET");
}
else if(str[right] == ']'){
printf(" | DELIM_C_SQ_BRACKET | %c | %d \n", str[right], line);
add(col, line, "]", "DELIM_C_SQ_BRACKET");
}
else if(str[right] == '{'){
printf(" | DELIM_O_BRACKET | %c | %d \n", str[right], line);
add(col, line, "{", "DELIM_O_BRACKET");
}
else if(str[right] == '}'){
printf(" | DELIM_C_BRACKET | %c | %d \n", str[right], line);
add(col, line, "}", "DELIM_C_BRACKET");
}
}
if (isDelimiter(str[right]) == true && left == right) {
right++;
left = right;
}
else if (isDelimiter(str[right]) == true && left != right || (right == len && left != right)) {
char* subStr = subString(str, left, right - 1);
isExpression(col, subStr, subStrLeft, subStrRight, line);
if(subStr[0] == '@'){
for(int j = left + 1; j <= strlen(str); j++){
if(str[j] == '@'){
right = j+1;
}
}
}
if (isFormingCharacter(subStr) == true){
if (!strcmp(subStr, "\n")){
line++;
}
}
else if (isLogicalOperator(subStr) == true){
if(!strcmp(subStr, "&&")){
printf(" | L_O_AND | %s | %d \n", subStr, line);
add(col, line, subStr, "L_O_AND");
}
else if(!strcmp(subStr, "||")){
printf(" | L_O_OR | %s | %d \n", subStr, line);
add(col, line, subStr, "L_O_OR");
}
else if(!strcmp(subStr, "!")){
printf(" | L_O_DENIAL | %s | %d \n", subStr, line);
add(col, line, subStr, "L_O_DENIAL");
}
}
else if (isArithmeticOperator(subStr) == true){
if(!strcmp(subStr, "+")){
printf(" | A_O_PLUS | %s | %d \n", subStr, line);
add(col, line, subStr, "A_O_PLUS");
}
else if(!strcmp(subStr, "-")){
printf(" | A_O_MINUS | %s | %d \n", subStr, line);
add(col, line, subStr, "A_O_MINUS");
}
else if(!strcmp(subStr, "/")){
printf(" | A_O_DIVISION | %s | %d \n", subStr, line);
add(col, line, subStr, "A_O_DIVISION");
}
else if(!strcmp(subStr, "%")){
printf(" | A_O_MOD | %s | %d \n", subStr, line);
add(col, line, subStr, "A_O_MOD");
}
else if(!strcmp(subStr, "/*")){
printf(" | A_O_MULTIPLICATION | %s | %d \n", subStr, line);
add(col, line, subStr, "A_O_MULTIPLICATION");
}
else if(!strcmp(subStr, "**")){
printf(" | A_O_POW | %s | %d \n", subStr, line);
add(col, line, subStr, "A_O_POW");
}
}
else if (isRelationalOperator(subStr) == true){
if(subStr[0] == '>'){
if(subStr[1] == '='){
printf(" | R_O_BIGGER_EQUAL | %s | %d \n", subStr, line);
add(col, line, subStr, "R_O_BIGGER_EQUAL");
}
else{
printf(" | R_O_BIGGER | %s | %d \n", subStr, line);
add(col, line, subStr, "R_O_BIGGER");
}
}
else if(subStr[0] == '<'){
if(subStr[1] == '='){
printf(" | R_O_LESS_EQUAL | %s | %d \n", subStr, line);
add(col, line, subStr, "R_O_LESS_EQUAL");
}
else{
printf(" | R_O_LESS | %s | %d \n", subStr, line);
add(col, line, subStr, "R_O_LESS");
}
}
else if(subStr[0] == '='){
if(subStr[1] == '=' && subStr[2] != '='){
printf(" | R_O_EQUAL | %s | %d \n", subStr, line);
add(col, line, subStr, "R_O_EQUAL");
}
else if(subStr[1] == '=' && subStr[2] == '='){
printf(" | R_O_EXACTLY_EQUAL | %s | %d \n", subStr, line);
add(col, line, subStr, "R_O_EXACTLY_EQUAL");
}
}
else if(subStr[0] == '!'){
if(subStr[1] == '=' && subStr[2] != '='){
printf(" | R_O_DIFFERENT | %s | %d \n", subStr, line);
add(col, line, subStr, "R_O_DIFFERENT");
}
else if(subStr[1] == '=' && subStr[2] == '='){
printf(" | R_O_EXACTLY_DIFFERENT | %s | %d \n", subStr, line);
add(col, line, subStr, "R_O_EXACTLY_DIFFERENT");
}
}
}
else if (!strcmp(subStr, "=")){
printf(" | ASSIGNMENT_COMMAND | %s | %d \n", subStr, line);
add(col, line, subStr, "ASSIGNMENT_COMMAND");
}
else if (isScopeConstruction(subStr) == true){
if(!strcmp(subStr, "begin")){
printf(" | SCOPE_C_BEGIN | %s | %d \n", subStr, line);
add(col, line, subStr, "SCOPE_C_BEGIN");
}
else if(!strcmp(subStr, "end")){
printf(" | SCOPE_C_END | %s | %d \n", subStr, line);
add(col, line, subStr, "SCOPE_C_END");
}
}
else if (isBoolean(subStr) == true){
printf(" | DT_BOOL | %s | %d \n", subStr, line);
add(col, line, subStr, "DT_BOOL");
}
else if (isString(subStr) == true){
printf(" | DT_STRING | %s | %d \n", subStr, line);
add(col, line, subStr, "DT_STRING");
}
else if (isInteger(subStr) == true){
printf(" | DT_INT | %s | %d \n", subStr, line);
add(col, line, subStr, "DT_INT");
}
else if (isRealNumber(subStr) == true){
printf(" | DT_FLOAT | %s | %d \n", subStr, line);
add(col, line, subStr, "DT_FLOAT");
}
else if (isKeyword(subStr) == true){
if(!strcmp(subStr, "if")){
printf(" | KEYWORD_COND_IF | %s | %d \n", subStr, line);
add(col, line, subStr, "KEYWORD_COND_IF");
}
else if(!strcmp(subStr, "else")){
printf(" | KEYWORD_COND_ELSE | %s | %d \n", subStr, line);
add(col, line, subStr, "KEYWORD_COND_ELSE");
}
else if(!strcmp(subStr, "const")){
printf(" | IDENTIFIER_CONST | %s | %d \n", subStr, line);
add(col, line, subStr, "IDENTIFIER_CONST");
}
else if(!strcmp(subStr, "def")){
printf(" | KEYWORD_DEF | %s | %d \n", subStr, line);
add(col, line, subStr, "KEYWORD_DEF");
}
else if(!strcmp(subStr, "main")){
printf(" | KEYWORD_MAIN | %s | %d \n", subStr, line);
add(col, line, subStr, "KEYWORD_MAIN");
}
else if(!strcmp(subStr, "int")){
printf(" | IDENTIFIER_INT | %s | %d \n", subStr, line);
add(col, line, subStr, "IDENTIFIER_INT");
}
else if(!strcmp(subStr, "float")){
printf(" | IDENTIFIER_FLOAT | %s | %d \n", subStr, line);
add(col, line, subStr, "IDENTIFIER_FLOAT");
}
else if(!strcmp(subStr, "string")){
printf(" | IDENTIFIER_STRING | %s | %d \n", subStr, line);
add(col, line, subStr, "IDENTIFIER_STRING");
}
else if(!strcmp(subStr, "bool")){
printf(" | IDENTIFIER_BOOL | %s | %d \n", subStr, line);
add(col, line, subStr, "IDENTIFIER_BOOL");
}
}
else if (validIdentifier(subStr) == true && isDelimiter(str[right - 1]) == false){
printf(" | IDENTIFIER | %s | %d \n", subStr, line);
add(col, line, subStr, "IDENTIFIER");
}
subStrLeft = subStrRight;
subStrRight = subString(str, left, right - 1);
left = right;
}
}
printf(" | ---------------------------------------------------------------------- | \n");
return col;
}
bool hasError(char* str) {
int left = 0, right = 0;
int len = strlen(str);
int line = 1;
while (right <= len && left <= right) {
if (isDelimiter(str[right]) == false){
right++;
}
if (isDelimiter(str[right]) == true && left == right) {
right++;
left = right;
}
else if (isDelimiter(str[right]) == true && left != right || (right == len && left != right)) {
char* subStr = subString(str, left, right - 1);
if(subStr[0] == '@'){
int aux = 0;
for(int j = left + 1; j <= strlen(str); j++){
if(str[j] == '@'){
right = j+1;
aux = 1;
}
}
if(aux == 0){
printf("\n ----- ERROR! You didn't close a Comment! - LINE: %d -----\n", line);
return true;
}
}
else if (isString(subStr) == false && isInteger(subStr) == false && isRealNumber(subStr) == false){
if (validIdentifier(subStr) == false && isDelimiter(str[right - 1]) == false){
printf("\n ----- ERROR! Invalid Language Symbol - %s - LINE: %d -----\n", subStr, line);
return true;
}
}
left = right;
}
}
return false;
}
TokenCol* createCollection(int n){
TokenCol* col = (TokenCol*) malloc(sizeof(TokenCol));
col->n = n;
col->k = 0;
col->collection = (node**) malloc(sizeof(node*) * n+1);
return col;
}
int add(TokenCol* col, int line, char* lexer, char* token){
if((col != NULL) && (col->k < col->n)) {
Nod *no = createNode(line, lexer, token);
col->collection[col->k] = no;
col->k++;
return 1;
}
else{
return 0;
}
}
Nod* createNode(int line, char* lexer, char* token){
Nod *no = (Nod*) malloc(sizeof(Nod));
no->line = line;
no->lexer = lexer;
no->token = token;
return no;
}
void printCollection(TokenCol* col){
int i = 0;
if((col!=NULL) && (col->k>0)){
printf("\nLista:\n");
for(i=0; i<col->k; i++){
printf("\n [%d] | [%s] | [%s] ", col->collection[i]->line, col->collection[i]->lexer, col->collection[i]->token);
}
}
else{
printf("\nLista Vazia!");
}
}
|
/*
* Copyright (c) 2020 Samsung Electronics Co., Ltd. All rights reserved.
* 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 <float.h>
#include <math.h>
#include "tvgFill.h"
/************************************************************************/
/* Internal Class Implementation */
/************************************************************************/
struct LinearGradient::Impl
{
float x1 = 0;
float y1 = 0;
float x2 = 0;
float y2 = 0;
Fill* duplicate()
{
auto ret = LinearGradient::gen();
if (!ret) return nullptr;
ret->pImpl->x1 = x1;
ret->pImpl->y1 = y1;
ret->pImpl->x2 = x2;
ret->pImpl->y2 = y2;
return ret.release();
}
};
/************************************************************************/
/* External Class Implementation */
/************************************************************************/
LinearGradient::LinearGradient():pImpl(new Impl())
{
_id = FILL_ID_LINEAR;
Fill::pImpl->method(new FillDup<LinearGradient::Impl>(pImpl));
}
LinearGradient::~LinearGradient()
{
delete(pImpl);
}
Result LinearGradient::linear(float x1, float y1, float x2, float y2) noexcept
{
if (fabsf(x2 - x1) < FLT_EPSILON && fabsf(y2 - y1) < FLT_EPSILON)
return Result::InvalidArguments;
pImpl->x1 = x1;
pImpl->y1 = y1;
pImpl->x2 = x2;
pImpl->y2 = y2;
return Result::Success;
}
Result LinearGradient::linear(float* x1, float* y1, float* x2, float* y2) const noexcept
{
if (x1) *x1 = pImpl->x1;
if (x2) *x2 = pImpl->x2;
if (y1) *y1 = pImpl->y1;
if (y2) *y2 = pImpl->y2;
return Result::Success;
}
unique_ptr<LinearGradient> LinearGradient::gen() noexcept
{
return unique_ptr<LinearGradient>(new LinearGradient);
} |
.global s_prepare_buffers
s_prepare_buffers:
push %r10
push %r13
push %r15
push %r9
push %rax
push %rcx
push %rdi
push %rdx
push %rsi
lea addresses_A_ht+0x18204, %r15
nop
nop
nop
and %rdx, %rdx
mov $0x6162636465666768, %rdi
movq %rdi, %xmm7
vmovups %ymm7, (%r15)
nop
dec %rdx
lea addresses_UC_ht+0x145a4, %r10
nop
nop
nop
add $17845, %r9
movw $0x6162, (%r10)
nop
nop
inc %r15
lea addresses_normal_ht+0x1e484, %r15
nop
nop
nop
dec %r13
mov (%r15), %rax
nop
nop
nop
nop
sub %r9, %r9
lea addresses_A_ht+0x13204, %r15
xor $23045, %r9
mov (%r15), %r13d
nop
nop
sub %r10, %r10
lea addresses_D_ht+0x184, %rdx
nop
nop
and %r15, %r15
mov $0x6162636465666768, %rdi
movq %rdi, %xmm7
movups %xmm7, (%rdx)
nop
nop
nop
nop
and $39116, %rax
lea addresses_A_ht+0xb204, %r15
nop
nop
nop
nop
nop
add $65294, %r10
movb (%r15), %r9b
nop
nop
nop
nop
xor $46868, %rdi
lea addresses_WT_ht+0x10d04, %r15
add %r9, %r9
movl $0x61626364, (%r15)
nop
nop
nop
dec %r9
lea addresses_UC_ht+0x9c84, %rsi
lea addresses_normal_ht+0x17f04, %rdi
dec %r15
mov $127, %rcx
rep movsw
dec %rcx
lea addresses_A_ht+0x65a8, %rsi
lea addresses_WT_ht+0x1cf64, %rdi
nop
nop
nop
nop
nop
cmp $36108, %r15
mov $32, %rcx
rep movsw
nop
nop
nop
and %r10, %r10
lea addresses_D_ht+0x8304, %rsi
nop
nop
nop
nop
add $55417, %rdx
mov (%rsi), %rdi
nop
nop
nop
nop
nop
cmp %r13, %r13
lea addresses_D_ht+0xe484, %rsi
lea addresses_UC_ht+0x800c, %rdi
nop
nop
add %r10, %r10
mov $66, %rcx
rep movsb
nop
nop
nop
nop
nop
sub %r10, %r10
lea addresses_normal_ht+0x19782, %rsi
lea addresses_A_ht+0x1b804, %rdi
clflush (%rsi)
nop
nop
nop
nop
nop
dec %r13
mov $56, %rcx
rep movsb
nop
nop
nop
nop
and %rdx, %rdx
lea addresses_UC_ht+0xa157, %r9
nop
nop
nop
nop
nop
cmp %rcx, %rcx
movb (%r9), %r10b
nop
nop
nop
nop
sub %rdx, %rdx
lea addresses_D_ht+0x4cd6, %rsi
lea addresses_UC_ht+0x7944, %rdi
clflush (%rsi)
nop
nop
sub $37071, %r15
mov $1, %rcx
rep movsw
nop
nop
add %r13, %r13
lea addresses_D_ht+0x8604, %rsi
lea addresses_WT_ht+0x1e884, %rdi
nop
nop
nop
nop
nop
dec %r9
mov $16, %rcx
rep movsb
nop
nop
nop
nop
nop
cmp %rdx, %rdx
pop %rsi
pop %rdx
pop %rdi
pop %rcx
pop %rax
pop %r9
pop %r15
pop %r13
pop %r10
ret
.global s_faulty_load
s_faulty_load:
push %r12
push %r15
push %r8
push %rcx
push %rdx
// Faulty Load
lea addresses_WC+0x14204, %rdx
nop
nop
nop
sub %r15, %r15
movups (%rdx), %xmm7
vpextrq $1, %xmm7, %r8
lea oracles, %r15
and $0xff, %r8
shlq $12, %r8
mov (%r15,%r8,1), %r8
pop %rdx
pop %rcx
pop %r8
pop %r15
pop %r12
ret
/*
<gen_faulty_load>
[REF]
{'src': {'type': 'addresses_WC', 'same': False, 'size': 4, 'congruent': 0, 'NT': False, 'AVXalign': False}, 'OP': 'LOAD'}
[Faulty Load]
{'src': {'type': 'addresses_WC', 'same': True, 'size': 16, 'congruent': 0, 'NT': False, 'AVXalign': False}, 'OP': 'LOAD'}
<gen_prepare_buffer>
{'dst': {'type': 'addresses_A_ht', 'same': True, 'size': 32, 'congruent': 10, 'NT': False, 'AVXalign': False}, 'OP': 'STOR'}
{'dst': {'type': 'addresses_UC_ht', 'same': False, 'size': 2, 'congruent': 5, 'NT': False, 'AVXalign': False}, 'OP': 'STOR'}
{'src': {'type': 'addresses_normal_ht', 'same': False, 'size': 8, 'congruent': 7, 'NT': False, 'AVXalign': False}, 'OP': 'LOAD'}
{'src': {'type': 'addresses_A_ht', 'same': False, 'size': 4, 'congruent': 11, 'NT': False, 'AVXalign': False}, 'OP': 'LOAD'}
{'dst': {'type': 'addresses_D_ht', 'same': True, 'size': 16, 'congruent': 7, 'NT': False, 'AVXalign': False}, 'OP': 'STOR'}
{'src': {'type': 'addresses_A_ht', 'same': False, 'size': 1, 'congruent': 11, 'NT': False, 'AVXalign': False}, 'OP': 'LOAD'}
{'dst': {'type': 'addresses_WT_ht', 'same': False, 'size': 4, 'congruent': 7, 'NT': False, 'AVXalign': True}, 'OP': 'STOR'}
{'src': {'type': 'addresses_UC_ht', 'congruent': 7, 'same': False}, 'dst': {'type': 'addresses_normal_ht', 'congruent': 6, 'same': False}, 'OP': 'REPM'}
{'src': {'type': 'addresses_A_ht', 'congruent': 0, 'same': False}, 'dst': {'type': 'addresses_WT_ht', 'congruent': 5, 'same': True}, 'OP': 'REPM'}
{'src': {'type': 'addresses_D_ht', 'same': True, 'size': 8, 'congruent': 8, 'NT': False, 'AVXalign': False}, 'OP': 'LOAD'}
{'src': {'type': 'addresses_D_ht', 'congruent': 3, 'same': False}, 'dst': {'type': 'addresses_UC_ht', 'congruent': 2, 'same': False}, 'OP': 'REPM'}
{'src': {'type': 'addresses_normal_ht', 'congruent': 0, 'same': False}, 'dst': {'type': 'addresses_A_ht', 'congruent': 7, 'same': True}, 'OP': 'REPM'}
{'src': {'type': 'addresses_UC_ht', 'same': False, 'size': 1, 'congruent': 0, 'NT': False, 'AVXalign': False}, 'OP': 'LOAD'}
{'src': {'type': 'addresses_D_ht', 'congruent': 1, 'same': False}, 'dst': {'type': 'addresses_UC_ht', 'congruent': 6, 'same': False}, 'OP': 'REPM'}
{'src': {'type': 'addresses_D_ht', 'congruent': 10, 'same': False}, 'dst': {'type': 'addresses_WT_ht', 'congruent': 4, 'same': False}, 'OP': 'REPM'}
{'38': 21829}
38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38
*/
|
//MIT License
//Copyright 2017 Patrick Laughrea
#pragma once
#include "entityManager.hpp"
#include "tagIterator.hpp"
#include "structures/entity.hpp"
namespace webss
{
//for all these functions, the tag iterator must be on the expand tag
Entity parseExpandEntity(TagIterator& tagit, const EntityManager& ents);
const Dictionary& parseExpandDictionary(TagIterator& tagit, const EntityManager& ents);
const List& parseExpandList(TagIterator& tagit, const EntityManager& ents);
const Tuple& parseExpandTuple(TagIterator& tagit, const EntityManager& ents);
void expandDictionary(Dictionary& dict, TagIterator& tagit, const EntityManager& ents);
void expandList(List& list, TagIterator& tagit, const EntityManager& ents);
void expandTuple(Tuple& tuple, TagIterator& tagit, const EntityManager& ents);
void expandNamespace(Namespace& nspace, TagIterator& tagit, const EntityManager& ents);
void expandEnum(Enum& tEnum, TagIterator& tagit, const EntityManager& ents);
} |
; A105723: a(n) = 3^n - (-1)^n.
; 0,4,8,28,80,244,728,2188,6560,19684,59048,177148,531440,1594324,4782968,14348908,43046720,129140164,387420488,1162261468,3486784400,10460353204,31381059608,94143178828,282429536480,847288609444,2541865828328,7625597484988,22876792454960,68630377364884,205891132094648,617673396283948,1853020188851840,5559060566555524,16677181699666568,50031545098999708,150094635296999120,450283905890997364,1350851717672992088,4052555153018976268,12157665459056928800,36472996377170786404,109418989131512359208,328256967394537077628,984770902183611232880,2954312706550833698644,8862938119652501095928,26588814358957503287788,79766443076872509863360,239299329230617529590084,717897987691852588770248,2153693963075557766310748,6461081889226673298932240,19383245667680019896796724,58149737003040059690390168,174449211009120179071170508,523347633027360537213511520,1570042899082081611640534564,4710128697246244834921603688,14130386091738734504764811068,42391158275216203514294433200,127173474825648610542883299604,381520424476945831628649898808,1144561273430837494885949696428,3433683820292512484657849089280,10301051460877537453973547267844,30903154382632612361920641803528,92709463147897837085761925410588,278128389443693511257285776231760,834385168331080533771857328695284,2503155504993241601315571986085848,7509466514979724803946715958257548,22528399544939174411840147874772640,67585198634817523235520443624317924,202755595904452569706561330872953768,608266787713357709119683992618861308
mov $1,3
pow $1,$0
add $1,1
div $1,4
mul $1,4
mov $0,$1
|
; A110286: a(n) = 15*2^n.
; 15,30,60,120,240,480,960,1920,3840,7680,15360,30720,61440,122880,245760,491520,983040,1966080,3932160,7864320,15728640,31457280,62914560,125829120,251658240,503316480,1006632960,2013265920,4026531840,8053063680,16106127360,32212254720,64424509440,128849018880,257698037760,515396075520,1030792151040,2061584302080,4123168604160,8246337208320,16492674416640,32985348833280,65970697666560,131941395333120,263882790666240,527765581332480,1055531162664960,2111062325329920,4222124650659840,8444249301319680,16888498602639360,33776997205278720,67553994410557440,135107988821114880,270215977642229760,540431955284459520,1080863910568919040,2161727821137838080,4323455642275676160,8646911284551352320,17293822569102704640,34587645138205409280,69175290276410818560,138350580552821637120,276701161105643274240,553402322211286548480,1106804644422573096960,2213609288845146193920,4427218577690292387840,8854437155380584775680,17708874310761169551360,35417748621522339102720,70835497243044678205440,141670994486089356410880,283341988972178712821760,566683977944357425643520,1133367955888714851287040,2266735911777429702574080,4533471823554859405148160,9066943647109718810296320,18133887294219437620592640,36267774588438875241185280,72535549176877750482370560,145071098353755500964741120,290142196707511001929482240,580284393415022003858964480,1160568786830044007717928960,2321137573660088015435857920,4642275147320176030871715840,9284550294640352061743431680,18569100589280704123486863360,37138201178561408246973726720,74276402357122816493947453440,148552804714245632987894906880,297105609428491265975789813760,594211218856982531951579627520,1188422437713965063903159255040,2376844875427930127806318510080,4753689750855860255612637020160,9507379501711720511225274040320
mov $1,2
pow $1,$0
mul $1,15
mov $0,$1
|
; A295822: Number of coprime pairs (a,b) with -n <= a <= n, -3 <= b <= 3.
; 2,16,24,32,40,52,56,68,76,84,92,104,108,120,128,136,144,156,160,172,180,188,196,208,212,224,232,240,248,260,264,276,284,292,300,312,316,328,336,344,352,364,368,380,388,396,404,416,420,432,440,448,456,468
seq $0,49637 ; Congruent to 2, 3, 6, 8, 10 or 12 mod 13, but not equal to 3.
mul $0,2
sub $0,4
mov $2,$0
cmp $2,0
add $0,$2
mul $0,2
|
dnl PowerPC-64 mpn_sqr_diagonal.
dnl Copyright 2001-2003, 2005, 2006, 20010 Free Software Foundation, Inc.
dnl This file is part of the GNU MP Library.
dnl
dnl The GNU MP Library is free software; you can redistribute it and/or modify
dnl it under the terms of either:
dnl
dnl * the GNU Lesser General Public License as published by the Free
dnl Software Foundation; either version 3 of the License, or (at your
dnl option) any later version.
dnl
dnl or
dnl
dnl * the GNU General Public License as published by the Free Software
dnl Foundation; either version 2 of the License, or (at your option) any
dnl later version.
dnl
dnl or both in parallel, as here.
dnl
dnl The GNU MP Library is distributed in the hope that it will be useful, but
dnl WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
dnl or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
dnl for more details.
dnl
dnl You should have received copies of the GNU General Public License and the
dnl GNU Lesser General Public License along with the GNU MP Library. If not,
dnl see https://www.gnu.org/licenses/.
include(`../config.m4')
C cycles/limb
C POWER3/PPC630 18
C POWER4/PPC970 ?
C POWER5 7.25
C POWER6 9.5
C INPUT PARAMETERS
define(`rp', r3)
define(`up', r4)
define(`n', r5)
ASM_START()
PROLOGUE(mpn_sqr_diagonal)
ifdef(`HAVE_ABI_mode32',
` rldicl n, n, 0, 32') C zero extend n
rldicl. r0, n, 0,62 C r0 = n & 3, set cr0
addi n, n, 3 C compute count...
cmpdi cr6, r0, 2
srdi n, n, 2 C ...for ctr
mtctr n C copy count into ctr
beq cr0, L(b00)
blt cr6, L(b01)
beq cr6, L(b10)
L(b11): ld r0, 0(up)
ld r10, 8(up)
ld r12, 16(up)
addi rp, rp, -16
mulld r7, r0, r0
mulhdu r8, r0, r0
mulld r9, r10, r10
mulhdu r10, r10, r10
mulld r11, r12, r12
mulhdu r12, r12, r12
addi up, up, 24
b L(11)
ALIGN(16)
L(b01): ld r0, 0(up)
addi rp, rp, -48
addi up, up, 8
mulld r11, r0, r0
mulhdu r12, r0, r0
b L(01)
ALIGN(16)
L(b10): ld r0, 0(up)
ld r12, 8(up)
addi rp, rp, -32
addi up, up, 16
mulld r9, r0, r0
mulhdu r10, r0, r0
mulld r11, r12, r12
mulhdu r12, r12, r12
b L(10)
ALIGN(32)
L(b00):
L(top): ld r0, 0(up)
ld r8, 8(up)
ld r10, 16(up)
ld r12, 24(up)
mulld r5, r0, r0
mulhdu r6, r0, r0
mulld r7, r8, r8
mulhdu r8, r8, r8
mulld r9, r10, r10
mulhdu r10, r10, r10
mulld r11, r12, r12
mulhdu r12, r12, r12
addi up, up, 32
std r5, 0(rp)
std r6, 8(rp)
L(11): std r7, 16(rp)
std r8, 24(rp)
L(10): std r9, 32(rp)
std r10, 40(rp)
L(01): std r11, 48(rp)
std r12, 56(rp)
addi rp, rp, 64
bdnz L(top)
blr
EPILOGUE()
|
; void *sms_memset_vram_unsafe(void *dst, unsigned char c, unsigned int n)
SECTION code_clib
SECTION code_arch
PUBLIC _sms_memset_vram_unsafe
EXTERN asm_sms_memset_vram_unsafe
_sms_memset_vram_unsafe:
pop hl
pop de
dec sp
pop af
pop bc
push bc
push af
inc sp
push de
push hl
jp asm_sms_memset_vram_unsafe
|
;
; Sprite Rendering Routine
; original code by Patrick Davidson (TI 85)
; modified by Stefano Bodrato - Jan 2001
;
PUBLIC putsprite
EXTERN cpygraph
EXTERN pixeladdress
INCLUDE "graphics/grafix.inc"
;
; $Id: putsprite.asm,v 1.5 2015/01/19 01:32:51 pauloscustodio Exp $
;
; coords: d,e (vert-horz)
; sprite: (ix)
.offsets_table
defb 128,64,32,16,8,4,2,1
.putsprite
ld hl,2
add hl,sp
ld e,(hl)
inc hl
ld d,(hl) ;sprite address
push de
pop ix
inc hl
ld e,(hl)
inc hl
inc hl
ld d,(hl) ; x and y coords
inc hl
inc hl
ld a,(hl) ; and/or/xor mode
ld (ortype+1),a ; Self modifying code
ld (ortype2+1),a ; Self modifying code
inc hl
ld a,(hl)
ld (ortype),a ; Self modifying code
ld (ortype2),a ; Self modifying code
ld h,d
ld l,e
call pixeladdress
xor 7
ld hl,offsets_table
ld c,a
ld b,0
add hl,bc
ld a,(hl)
ld (wsmc1+1),a
ld (wsmc2+1),a
ld (_smc1+1),a
ld h,d
ld l,e
ld a,(ix+0)
cp 9
jr nc,putspritew
ld d,(ix+0)
ld b,(ix+1)
._oloop push bc ;Save # of rows
push hl ;Save screen address
ld b,d ;Load width
ld c,(ix+2) ;Load one line of image
inc ix
._smc1 ld a,1 ;Load pixel mask
._iloop sla c ;Test leftmost pixel
jr nc,_noplot ;See if a plot is needed
ld e,a
.ortype
nop ; changed into nop / cpl
nop ; changed into and/or/xor (hl)
ld (hl),a
ld a,e
._noplot rrca
jr nc,_notedge ;Test if edge of byte reached
inc hl ;Go to next byte
._notedge djnz _iloop
pop hl ;Restore address
ld bc,row_bytes ;Go to next line
add hl,bc
pop bc ;Restore data
djnz _oloop
;ret
jp cpygraph
.putspritew
ld d,(ix+0)
ld b,(ix+1)
.woloop push bc ;Save # of rows
push hl ;Save screen address
ld b,d ;Load width
ld c,(ix+2) ;Load one line of image
inc ix
.wsmc1 ld a,1 ;Load pixel mask
.wiloop sla c ;Test leftmost pixel
jr nc,wnoplot ;See if a plot is needed
ld e,a
.ortype2
nop ; changed into nop / cpl
nop ; changed into and/or/xor (hl)
ld (hl),a
ld a,e
.wnoplot rrca
jr nc,wnotedge ;Test if edge of byte reached
inc hl ;Go to next byte
.wnotedge
.wsmc2 cp 1
jr z,wover_1
djnz wiloop
pop hl ;Restore address
ld bc,row_bytes ;Go to next line
add hl,bc
pop bc ;Restore data
djnz woloop
;ret
jp cpygraph
.wover_1 ld c,(ix+2)
inc ix
djnz wiloop
dec ix
pop hl
ld bc,row_bytes
add hl,bc
pop bc
djnz woloop
;ret
jp cpygraph
|
; #########################################################################
.386
.model flat, stdcall
option casemap :none ; case sensitive
; #########################################################################
; kernel32.dll
includelib kernel32.lib
ExitProcess PROTO :DWORD
; shell32.dll
includelib shell32.lib
SHRunDialog PROTO :DWORD,:DWORD,:DWORD,:DWORD,:DWORD,:DWORD
; #########################################################################
.code
start:
invoke SHRunDialog, 0, 0, 0, 0, 0, 0
invoke ExitProcess, 0
end start
|
COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
Copyright (c) Berkeley Softworks 1988 -- All Rights Reserved
PROJECT: PC GEOS
MODULE: Swat -- Kernel -> Swat communications
FILE: kernel.asm
AUTHOR: Adam de Boor, Nov 18, 1988
ROUTINES:
Name Description
---- -----------
KernelDOS MS-DOS interceptor
KernelMemory DebugMemory interceptor
KernelProcess DebugProcess interceptor
KernelLoadRes DebugLoadResource interceptor
Kernel_Hello Rpc server for RPC_HELLO call
Kernel_Goodbye Detach from the kernel
Kernel_ReadMem Read from a handle
Kernel_WriteMem Write to a handle
Kernel_FillMem Fill in a handle
Kernel_ReadAbs Read from absolute memory
Kernel_WriteAbs Write to absolute memory
Kernel_FillAbs Fill in absolute memory
Kernel_BlockInfo Return info on a given handle
Kernel_BlockFind Locate a block covering an address
Kernel_ReadRegs Read registers for a thread
Kernel_WriteRegs Write registers for a thread
Kernel_AttachMem Attach to a block
Kernel_DetachMem Detach from a block
scode: (was stubInit)
Kernel_Load Load the kernel in
REVISION HISTORY:
Name Date Description
---- ---- -----------
Adam 11/18/88 Initial revision
DESCRIPTION:
The functions in this file implement the interface between the GEOS
kernel and Swat. They intercept the calls to the various Debug
vectors, transforming the passed information into arguments for the
proper RPC calls.
$Id: kernel.asm,v 2.71 97/02/13 15:20:10 guggemos Exp $
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@
_Kernel = 1
KERNEL = 1
include stub.def
include geos.def ;for Semaphore
include ec.def ;for FatalErrors
include heap.def ;for HeapFlags
include geode.def
include Internal/geodeStr.def
include Internal/debug.def
include thread.def ;for ThreadPriority
include Internal/heapInt.def ; HandleMem/ThreadBlockState
include Internal/dos.def ;for PSP_userStack
include system.def ;for things needed by kLoader
include Internal/kLoader.def
include Internal/fileInt.def
include Internal/fileStr.def
include Internal/xip.def
.386
sstack segment
extrn tpd:ThreadPrivateData
sstack ends
scode segment
assume cs:scode,ds:cgroup,es:cgroup,ss:sstack
kernelHeader ExeHeader <>
kernelSSSelector word 0ffffh
kernelCSSelector word 0ffffh
kernelDSSelector word 0ffffh
kernelPSPSelector word 0ffffh
kernelBIOSSelector word 0ffffh
stubCSSelector word scode
stubDSSelector word scode
loaderStackSize word 0
kernelVersion byte 0
;
; these table are in place of the tables that did not get into
; early releases of the product. They are tables of nptrs to
; internal routines and variables in the various kernels
;
InternalVectorTable struct
IVT_checksum word ; checksum of kcode that
; indicates the table should
; be used
IVT_table nptr.SwatVectorTable ; the table to use
InternalVectorTable ends
internalTables InternalVectorTable \
<923ch, upgradeTable>,
<5b36h, wizardECTable>,
<8451h, wizardTable>,
<3067h, zoomerECTable>,
<7830h, zoomerTable>
kernelVectors label SwatVectorTable ; overlay this static one with the
; real one
upgradeTable SwatVectorTable \
<
0d76h, 0f0eh, 0d7ch, 0d63h, 0a34h, 0000h, 0005h, 000ah, 6922h,
019bh, 0a410h, 09e3h, 0a16h, 0000h, 0000h, 0000h, 0dcah, 0041h,
01051h, 0000h, 0155h, 0198h, 850dh, 85beh, 8672h, 88ffh, 874ch,
8770h, 8618h, 862ch, 862dh, 8638h, 861ah, 862ch, 17b9h, 17beh,
169ah, 17b6h, 954ah, 9550h, 956ah, 956eh, 955bh, 9564h, 0a11fh,
0a158h
>
wizardTable SwatVectorTable \
<
0d76h, 0f0eh, 0d7ch, 0d63h, 0a34h, 0000h, 0005h, 000ah, 696fh,
01fah, 0a496h, 0a43h, 0a76h, 0000h, 0000h, 0000h,
0dcah, 0041h, 10b1h, 1154h, 01b4h, 01f7h, 856bh, 861ch, 87aah, 87c2h,
086d0h, 0895ch, 8676h, 868ah, 868bh, 8696h, 8678h, 868ah, 17f2h,
17f4h, 16d3h, 17efh, 95aeh, 95b4h, 95cah, 95c9h, 95bfh, 95c9h,
0a1a5h, 0a1deh
>
wizardECTable SwatVectorTable \
<
0dc0h, 0f5ah, 0d6ch, 0dadh, 0a78h, 0000h, 0005h, 000ah, 7945h,
0215h, 0c3e2h, 0bdch, 0c1dh, 0c91h, 0c93h, 0c8fh,
0e16h, 0041h, 14cah, 1589h, 1c2h, 0214h, 9dc0h, 9e95h, 0a11fh, 0a13fh,
0a003h, 0a32fh, 09f81h, 09f86h, 9f98h, 9fa2h, 9f87h, 9f97h, 1ceah,
1cf4h, 1bc4h, 1ce7h, 0b21eh, 0b224h, 0b23eh, 0b242h, 0b22fh, 0b239h,
0c038h, 0c071h
>
zoomerTable SwatVectorTable \
<
0d76h, 0f0eh, 0d7ch, 0d63h, 0a34h, 0000h, 0005h, 000ah, 06902h,
019bh, 0a423h, 09d8h, 0a0bh, 0000h, 0000h, 0000h,
0dcah, 0041h, 1046h, 10dfh, 0155h, 019ah, 084feh, 085afh, 0873dh, 08755h,
8663h, 88f9h, 8609h, 861dh, 861eh, 8629h, 860bh, 0861dh, 1785h,
1787h, 1666h, 1782h, 9541h, 9547h, 9561h, 9565h, 9552h, 955ch,
0a132h, 0a16bh
>
zoomerECTable SwatVectorTable \
<
0dc0h, 0f5ah, 0dc6h, 0dadh, 0a78h, 0000h, 0005h, 000ah, 78d8h,
01b6h, 0c36fh, 0b71h, 0bb2h, 0c91h, 0c93h, 0c8fh,
0e16h, 0041h, 145fh, 151eh, 0163h, 01b5h, 9d53h, 9328h, 0a0b2h, 0a0d2h,
9f96h, 0a2c1h, 9f14h, 9f19h, 9f2bh, 9f35h, 9f1ah, 9f2ah, 1c7dh,
1c87h, 1b57h, 1c7ah, 0b1b1h, 0b1b7h, 0b1d1h, 0b1d5h, 0b1c2h, 0b1cch,
0bfc5h, 0bffeh
>
previousReadOnlyES word
kernelCore hptr ; Handle of kernel's core block
loaderBase sptr ; Current base of the loader
lastHandle word ; End of handle table
HandleTable word ; Start of handle table
resourceBeingLoaded hptr ; Handle of resource currently being
; loaded so the Kernel_SegmentToHandle
; finds the resource, rather than
; the block to which the resource
; was loaded.
xipHeader word 0 ; segment value fo xipHeader
oldXIPPage word BPT_NOT_XIP ; save old page number for when
; swat pages in a new page
xipPageSize word 0
;xipPageAddr equ <kernelVectors.SVT_MAPPING_PAGE_ADDRESS>
xipPageAddr word 0
;MAPPING_PAGE_SIZE = 4000h
;MAPPING_PAGE_ADDRESS = 0c800h
if TRACK_INT_21
int21Counts word 256 dup(?)
bytesRead dword 0
endif
;
; Macro to create an IRET frame on the stack w/o writing to memory. Needed
; since we might be running in write-protected RAM.
;
; DISABLES INTERRUPTS
;
CreateNearFrame macro
push cs:[kcodeSeg] ; PUSH CS
pushf ; Save flags
push bp ; And BP
mov bp, sp ; so we can play with the stack
push ax ; Save temp register
mov ax, 2[bp] ; Fetch flags word
xchg ax, 6[bp] ; Exchange with IP that was saved
; on near call to our far jump
mov 2[bp], ax ; Store IP in proper place. Stack
; now holds FLAGS:CS:IP:BP:AX
pop ax ; Recover saved registers
pop bp
dsi
endm
CreateFarFrame macro
pushf ; save flags
push bp ; and BP
mov bp, sp ; so we can play with the stack
push ax ; save our temp reisger
mov ax, 2[bp] ; fetch the flags
xchg ax, 6[bp] ; ax = code seg, flags put on stack
xchg ax, 4[bp] ; ax = IP, code seg put on stack
mov 2[bp], ax ; IP put on stack, stack now holds
; FLAGS:CS:IP:BP:AX
pop ax ; recover saved registers
pop bp
dsi
endm
;
; Stuff for DOS interception
;
;dosAddr fptr.far -1 ; INT 21h handler
;dosThread word ; Thread in dos
;dosSP word ; SP of thread in dos
;dosSS word ; SS of thread in dos
;
; Kernel things -- from the HelloArgs packet
;
kdata word ; Segment address of kdata segment
;NOTE!!! Need to convert to selector at some point
heapSemOff equ <kernelVectors.SVT_heapSem>
sysECLevelOff equ <kernelVectors.SVT_sysECLevel>
DebugProcessOff equ <kernelVectors.SVT_DebugProcess>
BlockOnLongQueueOff equ <kernelVectors.SVT_BlockOnLongQueue>
sysECBlockOff equ <kernelVectors.SVT_sysECBlock>
sysECChecksumOff equ <kernelVectors.SVT_sysECCheckSum>
MemLockVec fptr.far ; Vector to MemLock routine
FileReadVec fptr.far ; Offset to FileRead routine
FilePosVec fptr.far ; Offset to FilePos routine
MapXIPPageVec fptr.far
SysCSVec fptr.far
readGeodeSem byte 0
topLevelPath PathName <""> ; save KLV_topLevelPath here to use in
; RPC_FIND_GEODE and RPC_SEND_FILE
ReloadStates etype byte
RS_IGNORE enum ReloadStates,0 ; Kernel reload not pending
RS_WATCH_EXEC enum ReloadStates ; Look for load/exec as signal of
; kernel reload
RS_INTERCEPT enum ReloadStates ; load/exec seen; intercept when
; DOS returns
reloadState ReloadStates RS_IGNORE
COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
KernelFindMaxSP
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
SYNOPSIS: Given the stack segment for a thread, locate its maximum
SP.
CALLED BY: KernelProcess, Kernel_Hello
PASS: ES = kdata
DS = scode
AX = stack segment
RETURN: AX = maximum SP
DESTROYED:
PSEUDO CODE/STRATEGY:
KNOWN BUGS/SIDE EFFECTS/IDEAS:
REVISION HISTORY:
Name Date Description
---- ---- -----------
ardeb 9/25/89 Initial version
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@
KernelFindMaxSP proc near
push ds, bx, cx
mov ds, ax
;
; Assume the SS is correct and fetch the handle that should
; be at TPD_blockHandle in the segment
;
mov bx, ds:TPD_blockHandle
test bx, 0fh ; Valid handle?
jnz SomethingHuge ; No
mov_tr cx, ax ; save ax in cx
call Kernel_GetHandleAddress
cmp ax, cx
jne SomethingHuge ; No
mov ax, es:[bx].HM_size ; Convert size to bytes
shl ax, 1 ; from paragraphs
shl ax, 1
shl ax, 1
shl ax, 1
KFMSPRet:
pop ds, bx, cx
ret
SomethingHuge:
;
; On the theory that it is better to see some useful frames
; and then spend a lot of time doing useless searches, as
; opposed to getting an immediate "frame not valid" error,
; we return -2 as the maximum SP for something whose block
; we cannot find.
;
mov ax, 0fffeh
jmp KFMSPRet
KernelFindMaxSP endp
if INT21_INTERCEPT
COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
KernelReloadSys
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
SYNOPSIS: Notify Swat that the system is reloading
CALLED BY: KernelDOS
PASS: flags on stack
RETURN: nothing
DESTROYED: nothing
PSEUDO CODE/STRATEGY:
KNOWN BUGS/SIDE EFFECTS/IDEAS:
REVISION HISTORY:
Name Date Description
---- ---- -----------
ardeb 5/11/92 Initial version
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@
KernelReloadSys proc far ; must be far to establish proper
; interrupt frame
.enter
call SaveState
;
; Stick in our hook at the base of the loader code segment
;
push es
mov es, ds:[kernelHeader].exe_cs
call Kernel_EnsureESWritable ; ax <- token
mov {word}es:[0], 0x9a9c ; PUSHF / CALL FAR PTR
mov {word}es:[2], offset KernelLoader
mov {word}es:[4], cs
call Kernel_RestoreWriteProtect
mov ds:[kernelCore], 0 ; kernel core block
; unknown
mov ax, es
pop es
mov {word}ds:rpc_ToHost, ax
mov ax, RPC_RELOAD_SYS
mov bx, offset rpc_ToHost
mov cx, size word
andnf ds:sysFlags, not (mask dosexec or mask nomap)
call Rpc_Call
call RestoreState
; NO WRITES UNTIL POP_PROTECT -- RestoreState write-protects
.leave
ret
KernelReloadSys endp
COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
KernelDOS
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
SYNOPSIS: Intercept DOS calls to record the ID and SS:SP of the thread
currently in DOS, as well as to catch the exit of PC GEOS.
CALLED BY: INT 21h
PASS: ...
RETURN: ...
DESTROYED: Nothing
PSEUDO CODE/STRATEGY:
KNOWN BUGS/SIDE EFFECTS/IDEAS:
REVISION HISTORY:
Name Date Description
---- ---- -----------
ardeb 2/ 6/89 Initial version
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@
KernelDOS proc far
test cs:[sysFlags], mask connected
jz checkExit
;
; Save registers we need
;
push ds
push ax
push bx
;
; Turn off write-protect so we can play. We're careful to
; maintain the state of the write-protect bit because we
; also intercept the function 52h call in Kernel_Hello (we
; can't just avoid intercepting DOS until later b/c the user's
; Swat may die and be restarted, causing us to attach w/o
; having detached first).
;
PUSH_ENABLE
DA DEBUG_DOS, <push ax>
DPC DEBUG_DOS, 'd'
DA DEBUG_DOS, <pop ax>
DPW DEBUG_DOS, ax
;
; Fetch the current thread from the kernel and save it in
; dosThread.
;
mov ds, cs:kdata
mov bx, cs:currentThreadOff
mov ax, ds:[bx]
push ds
PointDSAtStub
mov ds:dosThread, ax
;
; Save the SS:SP of the current thread
;
mov ax, sp
add ax, 6 ; Adjust for register still on stack
mov ds:dosSP, ax
mov ds:dosSS, ss
if TRACK_INT_21
; Make sure ds is point at scode
mov bx, sp
mov ax, ss:[bx+2] ; ah <- DOS call
mov bl, ah
clr bh
shl bx
inc ds:[int21Counts][bx]
cmp ah, MSDOS_READ_FILE
jne trackingDone
add ds:[bytesRead].low, cx
adc ds:[bytesRead].high, 0
trackingDone:
endif
pop ds
;
; Re-enable write-protect so DOS doesn't stomp us
;
POP_PROTECT
;
; Restore the registers we've abused
;
pop bx
pop ax
pop ds
;
; Handle kernel reload
;
tst cs:[reloadState]
jz checkExit
cmp ax, MSDOS_EXEC shl 8 or MSESF_LOAD_OVERLAY
jne checkExit
push ax ; Record loader's segment while we've
; got es:bx here
PUSH_ENABLE
push ds
PointDSAtStub
mov ds:reloadState, RS_INTERCEPT
mov ax, es:[bx] ; First word of argument block must be
; segment at which to load the thing
mov ds:[kernelHeader].exe_cs, ax
mov ds:[loaderBase], ax
mov ds:[kdata], ax
pop ds
POP_PROTECT
pop ax
checkExit:
;
; See if it's an exit call...
;
cmp ah, MSDOS_QUIT_APPL
je toIsExit
cmp ah, MSDOS_TSR
jne checkResize
toIsExit:
jmp isExit
checkResize:
;
; If resizing our child's PSP, we're about to run a DOS program and
; Swat needs to know about it. We could also be enlarging the PSP,
; though, to recover from the DOS exec, so check our dosexec flag
; before issuing the call...
;
cmp ah, MSDOS_RESIZE_MEM_BLK
jne checkFree
test cs:[sysFlags], mask initialized
jz passItOn ; if not intialized, this is
; us shrinking ourselves down.
push ax
mov ax, es
cmp ax, cs:[PSP]
pop ax
jne passItOn
test cs:[sysFlags], mask dosexec
jnz passItOn
push ds
PointDSAtStub
mov {word}ds:[rpc_ToHost], bx ; pass new size
; as word arg
pop ds
beginDosExec:
;
; Common code to signal to Swat that a DosExec is commencing.
;
call SaveState ; get into our context
push ax, si
call Bpt_Uninstall
pop ax, si
ornf ds:[sysFlags], mask dosexec ; flag dosexec so we
; know currentThread
; existeth not
andnf ds:[sysFlags], not mask attached; by definition, if it's
; running a DOS program
; the kernel ain't
; around
mov ds:[kernelCore], 0
test ds:[sysFlags], mask connected
jz execNotifyComplete
mov ax, RPC_DOS_RUN ; proc num
mov cx, size word ; arg size
mov bx, offset rpc_ToHost ; es:bx <- arg addr
call Rpc_Call
test ds:[sysFlags], mask dontresume ; wants to stop?
jnz stopBeforeDosExec ; yes -- do so
execNotifyComplete:
call RestoreState ; no -- continue with
jmp passItOn ; our life
stopBeforeDosExec:
jmp Rpc_Run ; everything already set up...
checkFree:
;
; If freeing kdata, we're about to run a DOS program after having
; reloaded following the launch of a TSR.
;
cmp ah, MSDOS_FREE_MEM_BLK
jne passItOn
push ds
PointDSAtStub
mov {word}ds:[rpc_ToHost], 0 ;assume so
pop ds
push ax
mov ax, es
cmp ax, cs:[kdata]
pop ax
je beginDosExec
;
; Make like we called DOS with an interrupt.
;
passItOn:
I21IFrame struct
I21IF_bp word
I21IF_ax word
I21IF_retf fptr.far
I21IF_flags word
I21IFrame ends
;
; push the flags originally passed to us so interrupts are in the
; right state when DOS returns to us.
;
push ax
push bp
mov bp, sp
mov ax, ss:[bp].I21IF_flags
xchg ax, ss:[bp].I21IF_ax
pop bp
dsi
call cs:dosAddr
push ax ; save ax from possible biffing
PUSH_ENABLE
;
; Clear out dosThread so we don't get confused.
;
push ds
PointDSAtStub
mov ds:dosThread, 0
pop ds
pushf
cmp cs:reloadState, RS_INTERCEPT
jne 20$
;
; Re-intercept the various debug vectors, then give notice
; to Swat that the kernel has been reloaded.
;
push ds
PointDSAtStub
mov ds:reloadState, RS_IGNORE
pop ds
call KernelReloadSys
;
; Test for interrupt request only now, not inside SaveState/
; RestoreState, so we can give the user a reasonable context
; if we do need to stop.
;
test cs:sysFlags, mask dontresume
jnz stop
20$:
popf
POP_PROTECT
pop ax ; restore ax after possible biffing
ret 2 ; Nuke the flags, since DOS likes
; to return things in CF...
isExit:
;
; A child process is exiting somehow. If the current process' parent
; process is the kernel, set reloadState to watch for load-overlay
;
PUSH_ENABLE
push ax, bx, es
mov ah, MSDOS_GET_PSP
pushf
dsi
call cs:[dosAddr]
mov es, bx
DPW DEBUG_DOS, bx
DA DEBUG_DOS, <mov ax, es:[PSP_parentId]>
DPW DEBUG_DOS, ax
DA DEBUG_DOS, <mov ax, cs:[PSP]>
DPW DEBUG_DOS, ax
mov ax, cs:[PSP]
cmp es:[PSP_parentId], ax
jne exitHandlingComplete
push ds
PointDSAtStub
mov ds:[reloadState], RS_WATCH_EXEC
pop ds
exitHandlingComplete:
pop ax, bx, es
POP_PROTECT
jmp passItOn
stop:
;
; Stop requested by remote. Alter the flags of our return
; address to match the flags returned by DOS so Rpc_Run can
; just to a RestoreState and iret and not fuck anything up.
; Note that we do all this weird stuff b/c we don't know
; whether PUSH_ENABLE actually pushed anything, or how much,
; if it did.
;
popf ; Fetch current flags.
POP_PROTECT ; Recover protection state
pop ax ; Recover ax
pushf ; Only way to get whole word...
push bp ; So we can address the stack
mov bp, sp
push ax ; Temporary register
mov ax, ss:[bp][2] ; Fetch flags
mov ss:[bp][8], ax ; Stuff in return. Stack is:
; bp, flags, ip, cs, flags
pop ax
pop bp
popf ; "discard"
call SaveState
jmp Rpc_Run
KernelDOS endp
endif
COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
KernelMemoryBankPage
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
SYNOPSIS: deal with a new page being banked in
CALLED BY: KernelMemory
PASS: bx = page number
RETURN: nothing
DESTROYED: Nada.
PSEUDOCODE/STRATEGY: find all pending breakpoints and deal with them
appropriately
KNOWN BUGS/SIDEFFECTS/IDEAS:
REVISION HISTORY:
Name Date Description
---- ---- -----------
jimmy 4/27/94 Initial version.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@
KernelMemoryBankPage proc near
uses es, bx
.enter
; fetch the new current page and let the breakpoint module
; do its thing
DA DEBUG_XIP, <push ax>
DPS DEBUG_XIP, BANK
DPW DEBUG_XIP, bx
DPW DEBUG_XIP, ds:[oldXIPPage]
DA DEBUG_XIP, <pop ax>
mov es, ds:[kdata]
mov bx, ds:[curXIPPageOff]
mov bx, es:[bx]
call Bpt_UpdatePending
.leave
ret
KernelMemoryBankPage endp
COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
KernelMemory
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
SYNOPSIS: HandleMem a change to the kernel's memory state
CALLED BY: Kernel functions
PASS: AL = Function code:
DEBUG_REALLOC - block reallocated
DEBUG_DISCARD - block discarded
DEBUG_SWAPOUT - block swapped out
DEBUG_SWAPIN - block swapped in
DEBUG_MOVE - block moved
DEBUG_FREE - block freed
DEBUG_MODIFY - block flags modified
DEBUG_BANK_PAGE - Bank in an XIP page
BX = affected handle (or page for DEBUG_SWAPPAGE)
DX = segment of affected block if address is needed
and [bx].HM_addr is 0
DS = kernel data segment
ES = destination segment for DEBUG_MOVE
RETURN: Nothing
DESTROYED: Nothing
PSEUDO CODE/STRATEGY:
See if the block is being debugged. If not, return right away.
Save current state.
Put together proper rpc based on function code and send it
Return.
KNOWN BUGS/SIDE EFFECTS/IDEAS:
REVISION HISTORY:
Name Date Description
---- ---- -----------
ardeb 11/18/88 Initial version
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@
KernelMemoryFar proc far
CreateFarFrame ; INT_OFF
jmp KernelMemory
KernelMemoryFar endp
KernelMemory proc near
;
; Form interrupt frame on stack in case we need to save state
;
; if its an XIP page being banked in we can skip this stuff about
; blocks changing as its not relavent for XIP pages
cmp al, DEBUG_BANK_PAGE
je KM1
;
; Deal with any breakpoints we've got set, regardless of whether the
; host cares.
;
call Bpt_BlockChange
cmp bx, HID_KDATA ; Special case kernel
; motion/resize/discard
jbe KM1
;
; If notification comes while we're on our own stack, it means
; it happened because of us, and Swat has this handle in its
; table, regardless of the HF_DEBUG bit, so we need to notify
; it...
;
push ax
mov ax, ss
cmp ax, sstack
pop ax
je KM1
test ds:[bx].HM_flags, MASK HF_DEBUG
LONG jz KMRet
KM1:
;
; Block is actually being debugged -- tell Swat what's up
;
call SaveState
;
; Load handle address into es:bx for access
;
mov bx, [bp].state_bx
mov es, ds:[kdata]
mov ax, [bp].state_ax
cmp al, DEBUG_BANK_PAGE
jne notBank
; if a new page is banked in, we need to update the pending breakpoints
; that fall in that page
call KernelMemoryBankPage
jmp KM6
notBank:
;
; All calls take handle as first arg.
;
mov {word}ds:[rpc_ToHost], bx
cmp al, DEBUG_REALLOC
jne KM2
; mov ax, es:[bx].HM_addr
call Kernel_GetHandleAddress
tst ax
jnz reallocHaveSegment
mov ax, ss:[bp].state_dx
reallocHaveSegment:
mov ({ReallocArgs}ds:[rpc_ToHost]).rea_dataAddress, ax
mov ax, es:[bx].HM_size
mov ({ReallocArgs}ds:[rpc_ToHost]).rea_paraSize, ax
mov cx, size ReallocArgs
mov ax, RPC_BLOCK_REALLOC
jmp short KMSend
KM2:
cmp al, DEBUG_SWAPOUT
jg KM3
;
; DISCARD or SWAPOUT -- load oa_discarded with ffff if discard
; and 0 if swapped (DISCARD is 1, SWAPOUT is 2...)
;
sub al, DEBUG_SWAPOUT
cbw
mov ({OutArgs}ds:[rpc_ToHost]).oa_discarded, ax
mov cx, size OutArgs
mov ax, RPC_BLOCK_OUT
jmp short KMSend
KM3:
cmp al, DEBUG_SWAPIN
jne KM4
;
; Block swapped in -- Swat needs new data address in a LoadArgs
; structure. The rpc is RPC_BLOCK_LOAD
;
; mov ax, es:[bx].HM_addr
call Kernel_GetHandleAddress
mov ({LoadArgs}ds:[rpc_ToHost]).la_dataAddress, ax
mov cx, size LoadArgs
mov ax, RPC_BLOCK_LOAD
jmp short KMSend
KM4:
cmp al, DEBUG_MOVE
jne KM5
;
; Block moved -- Swat needs new data address in a MoveArgs
; structure. The rpc is RPC_BLOCK_MOVE
;
mov ax, [bp].state_es
mov cx, [bp].state_cx
jcxz justMove
;
; For a regular block, turn the call into a DEBUG_REALLOC
; to deal with the contracting of LMem blocks by CompactHeap
;
mov ({ReallocArgs}ds:[rpc_ToHost]).rea_dataAddress, ax
mov ({ReallocArgs}ds:[rpc_ToHost]).rea_paraSize, cx
mov ax, RPC_BLOCK_REALLOC
mov cx, size ReallocArgs
jmp KMSend
justMove:
;
; No resize involved, so use a regular BLOCK_MOVE call.
;
mov ({MoveArgs}ds:[rpc_ToHost]).ma_dataAddress, ax
mov cx, size MoveArgs
mov ax, RPC_BLOCK_MOVE
jmp KMSend
KM5:
cmp al, DEBUG_FREE
jne KM6
;
; Block freed -- already have the sole argument (the handle ID)
; in the argument record. The rpc is RPC_BLOCK_FREE
;
mov cx, size hptr
mov ax, RPC_BLOCK_FREE
KMSend:
;
; Perform the actual RPC. When it returns, we're allowed to
; continue.
;
mov bx, offset rpc_ToHost
push cs
pop es
call Rpc_Call
test ds:[sysFlags], mask dontresume ; if interrupt during
jz KM6 ; call, act on it now
jmp Rpc_Run
KM6:
;
; Fall-through point for any unknown (or unhandled) function
; code. Restore state and return.
;
call RestoreState
KMRet:
;
; We created an interrupt frame up above, so use it now
;
iret
KernelMemory endp
COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
KernelProcess
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
SYNOPSIS: HandleMem calls to the kernel's DebugProcess vector
CALLED BY: Kernel for geode/thread state changes
PASS: AL = Function code:
DEBUG_EXIT_THREAD - thread death
DEBUG_EXIT_GEODE - geode death
DEBUG_CREATE_THREAD - new thread created
DEBUG_LOAD_DRIVER - new driver loaded
DEBUG_LOAD_LIBRARY - new library loaded
DEBUG_RESTART_SYSTEM- note that system is about to
restart
DEBUG_SYSTEM_EXITING- note that the system is
exiting and banking things
in will soon not be possible
BX = Thread handle (dead one for DEBUG_EXIT_THREAD,
new one for DEBUG_CREATE_THREAD) or
Geode handle (for DEBUG_EXIT_GEODE) or
DX = Exit code (DEBUG_EXIT_THREAD only)
DS = kdata for DEBUG_CREATE_THREAD
= segment of core block for DEBUG_LOAD_DRIVER,
DEBUG_LOAD_LIBRARY
RETURN: Nothing
DESTROYED: Nothing
PSEUDO CODE/STRATEGY:
Save state
Put together Rpc & deliver it.
KNOWN BUGS/SIDE EFFECTS/IDEAS:
REVISION HISTORY:
Name Date Description
---- ---- -----------
ardeb 11/18/88 Initial version
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@
;
; Set up interrupt frame for SaveState
;
KernelProcessFar proc far
CreateFarFrame
jmp KernelProcess
KernelProcessFar endp
KernelProcess proc near
call SaveState
mov ax, [bp].state_bx ; Fetch passed handle
mov {word}ds:rpc_ToHost, ax ; Store handle right away
mov bx, [bp].state_ax
clr bh
cmp bl, DebugProcessFunction
jae badCode
shl bx
jmp cs:kpJumpTable[bx]
kpJumpTable nptr.near ExitThread, ; DEBUG_EXIT_THREAD
ExitGeode, ; DEBUG_EXIT_GEODE
CreateThread, ; DEBUG_CREATE_THREAD
DLLoad, ; DEBUG_LOAD_DRIVER
DLLoad, ; DEBUG_LOAD_LIBRARY
RestartSys, ; DEBUG_RESTART_SYSTEM
SysExiting ; DEBUG_SYSTEM_EXITING
CheckHack <length kpJumpTable eq DebugProcessFunction>
badCode: jmp done
CreateThread:
;
; Need the thread's owner -- load ES:BX with the address of the
; handle, fetch the owner (owner2) field of the handle and
; stuff it, then fetch the saved SS:SP for it and stuff that.
; The rpc is RPC_SPAWN.
;
mov es, ds:[kdata]
mov ({SpawnArgs}ds:[rpc_ToHost]).sa_xipPage, BPT_NOT_XIP
mov bx, [bp].state_bx
mov ax, es:[bx].HT_owner
mov ({SpawnArgs}ds:[rpc_ToHost]).sa_owner, ax
mov ax, es:[bx].HT_saveSS
mov ({SpawnArgs}ds:[rpc_ToHost]).sa_ss, ax
call KernelFindMaxSP
mov ({SpawnArgs}ds:[rpc_ToHost]).sa_sp, ax
mov ax, RPC_SPAWN
mov cx, size SpawnArgs
jmp send ; Sendez le.
ExitThread:
;
; Retrieve the status from dx and store it in the
; ThreadExitArgs at rpc_ToHost. The rpc is RPC_THREAD_EXIT
;
mov ax, [bp].state_dx
mov ({ThreadExitArgs}ds:[rpc_ToHost]).tea_status, ax
mov ax, RPC_THREAD_EXIT
mov cx, size ThreadExitArgs
jmp send
ExitGeode:
;
; A geode is history -- need to pass the geode handle
; and the current thread (to give Swat some context).
; The rpc is RPC_GEODE_EXIT.
;
mov ax, [bp].state_bx
mov ({GeodeExitArgs}ds:[rpc_ToHost]).gea_handle, ax
mov es, ds:[kdata]
mov bx, ds:[currentThreadOff]
mov ax, es:[bx]
mov ({GeodeExitArgs}ds:[rpc_ToHost]).gea_curThread, ax
mov ax, RPC_GEODE_EXIT
mov cx, size GeodeExitArgs
jmp short send
DLLoad:
;
; Driver/Library load:
; Clear out the two fields that aren't applicable for this
; sort of object to signal that it's a library/driver
; that's been loaded. The sa_thread field gets the
; ID of the current thread in case the machine remains
; stopped.
;
mov ax, [bp].state_thread
mov ({SpawnArgs}ds:[rpc_ToHost]).sa_thread, ax
clr ax
mov ({SpawnArgs}ds:[rpc_ToHost]).sa_ss, ax
mov ({SpawnArgs}ds:[rpc_ToHost]).sa_sp, ax
push ds
mov ds, [bp].state_ds
mov ax, ds:[GH_geodeAttr]
or ax, mask GA_KEEP_FILE_OPEN
mov ds:[GH_geodeAttr], ax
mov ax, ds:GH_geodeHandle ; Fetch handle of the block
pop ds
mov ({SpawnArgs}ds:[rpc_ToHost]).sa_owner, ax
mov ax, BPT_NOT_XIP
tst ds:[xipHeader]
jz afterXIP
mov es, ds:[kdata]
mov bx, ds:[curXIPPageOff]
mov ax, es:[bx]
afterXIP:
mov ({SpawnArgs}ds:[rpc_ToHost]).sa_xipPage, ax
mov ax, RPC_SPAWN
mov cx, size SpawnArgs
jmp short send
RestartSys:
;
; Note we should be looking for 4b03 and that we're no longer attached
; to the kernel.
;
mov ds:[reloadState], RS_WATCH_EXEC
andnf ds:[sysFlags], not mask attached
mov ds:[kernelCore], 0
;
; And pass a really big size up to Swat so it knows what's going on.
;
mov {word}ds:[rpc_ToHost], -1
mov ax, RPC_DOS_RUN
mov cx, size word
.assert $ eq send
send:
;
; Load up BX for the call; make it; restore state; and return
; through the jump vector
;
push cs ; load cgroup into ES
pop es
mov bx, offset rpc_ToHost
call Rpc_Call
test ds:[sysFlags], mask dontresume
jz done
jmp Rpc_Run
SysExiting:
call Bpt_SysExiting
done:
call RestoreState
iret
KernelProcess endp
COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
KernelLoadRes
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
SYNOPSIS: Handle DebugLoadResource calls
CALLED BY: Kernel
PASS: BX = handle of loaded resource
AX = data address of resource
ES = kdata
RETURN: Nothing
DESTROYED: Nothing
PSEUDO CODE/STRATEGY:
KNOWN BUGS/SIDE EFFECTS/IDEAS:
REVISION HISTORY:
Name Date Description
---- ---- -----------
ardeb 11/18/88 Initial version
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@
;
; Set up interrupt frame for SaveState
;
KernelLoadResFar proc far
CreateFarFrame
jmp KernelLoadRes
KernelLoadResFar endp
KernelLoadRes proc near
;
; Deal with breakpoints...
;
call Bpt_ResLoad
;
; If notification comes while we're on our own stack, it means
; it happened because of us, and Swat has this handle in its
; table, regardless of the HF_DEBUG bit, so we need to notify
; it...
;
push ax
mov ax, ss
cmp ax, sstack
pop ax
je notify
;
; Make sure we're actually interested in the block -- on the
; initial load of a new process, we're not actually interested.
; To avoid annoying errors each time, we do this check.
;
test es:[bx].HM_flags, MASK HF_DEBUG
jz KLRRet
notify:
call SaveState
;
; Store the handle and selector in the rpc packet while
; we've got them handy...
;
mov es, ds:[kdata]
mov ax, [bp].state_ax
mov bx, [bp].state_bx
mov ds:[resourceBeingLoaded], bx
mov ds:({LoadArgs}rpc_ToHost).la_handle, bx
mov ds:({LoadArgs}rpc_ToHost).la_dataAddress, ax
;
; Prepare for rpc and send it
;
push cs
pop es
mov cx, size LoadArgs
mov bx, offset rpc_ToHost
mov ax, RPC_RES_LOAD
call Rpc_Call
mov ds:[resourceBeingLoaded], 0
test ds:[sysFlags], mask dontresume
jnz stop
;
; Restore previous state and return
;
call RestoreState
KLRRet:
iret
stop:
push cs
pop es ; es = cgroup again
jmp Rpc_Run
KernelLoadRes endp
COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
Kernel_CleanHandles
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
SYNOPSIS: Make sure no handle has its HF_DEBUG bit set
CALLED BY: Kernel_Hello, Kernel_Detach
PASS: DS = cgroup
RETURN: ES = kdata
DESTROYED: BX, DX, AX
PSEUDO CODE/STRATEGY:
KNOWN BUGS/SIDE EFFECTS/IDEAS:
REVISION HISTORY:
Name Date Description
---- ---- -----------
ardeb 5/ 4/89 Initial version
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@
Kernel_CleanHandles proc near
mov es, ds:[kdata]
mov dx, ds:[lastHandle] ; Locate end of table
tst dx ; Handle table set up?
jz done ; No -- DON'T DO ANYTHING
mov bx, ds:[HandleTable] ; Start at beginning
scanLoop:
tst es:[bx].HM_owner ; See if it's free
jz next ; Yes -- do nothing
cmp es:[bx].HM_addr.high, SIG_NON_MEM
jae next ; Not a memory handle
and es:[bx].HM_flags, NOT MASK HF_DEBUG
next:
add bx, size HandleMem
cmp bx, dx
jb scanLoop
done:
ret
Kernel_CleanHandles endp
COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
KernelIntercept
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
SYNOPSIS: Intercept the kernel debug vectors
CALLED BY: Kernel_Hello, KernelDos
PASS: ds = cgroup
RETURN: nothing
DESTROYED: nothing
PSEUDO CODE/STRATEGY:
KNOWN BUGS/SIDE EFFECTS/IDEAS:
; in going from version 0 to version 1 I moved the Debug
; routines from kcode to kdata for XIP purposes
; And I moved them back into kcode for PM purposes
; -dhunter 11/21/00
REVISION HISTORY:
Name Date Description
---- ---- -----------
ardeb 12/ 2/89 Initial version
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@
interceptPoints nptr.word DebugLoadResOff, DebugMemoryOff, DebugProcessOff
postSDKRoutines nptr.far KernelLoadResFar, KernelMemoryFar, KernelProcessFar
KernelIntercept proc near uses es, di, ax, si, cx
.enter
pushf
DPC <DEBUG_DOS or DEBUG_FILE_XFER>, 'I', inverse
;
; Intercept the various debugging vectors in the kernel by
; storing a direct FAR jump to our own routine.
;
mov es, ds:[kcodeSeg] ; Get kernel segment in es
mov bx, offset postSDKRoutines - offset interceptPoints
DPW DEBUG_SETUP, es
call Kernel_EnsureESWritable
push ax
FJMP = 0eah
cld
mov si, offset interceptPoints
mov cx, length interceptPoints
interceptLoop:
lodsw ; ax <- offset of variable
; holding routine offset
mov_tr di, ax
mov di, ds:[di] ; es:di <- intercept routine
mov al, FJMP
stosb
mov ax, ds:[si+bx-2] ; ax <- routine in us to call
stosw
mov es:[di], cs
loop interceptLoop
pop ax
call Kernel_RestoreWriteProtect
popf
.leave
ret
KernelIntercept endp
COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
KernelSetup
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
SYNOPSIS: get internal swat addresses needed by the stub
CALLED BY: Kernel_Setup
PASS: ES, DS = cgroup
RETURN: carry set if kernel cannot be dealt with
carry clear if we have a table:
di = -1 if kernel contains table
= 0 if had to use an internal table
table copied to "kernelVectors" variable
DESTROYED: cx, bx
PSEUDO CODE/STRATEGY:
KNOWN BUGS/SIDE EFFECTS/IDEAS:
REVISION HISTORY:
Name Date Description
---- ---- -----------
ardeb 11/19/88 Initial version
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@
KernelSetup proc near
uses si, ax
.enter
;
; Locate the kernel's library entry function. The vector table, if
; any, is pointed to by a SwatVectorDesc structure that immediately
; follows a short jump at the start of the library entry.
;
DPC DEBUG_SETUP, 'S'
DPC DEBUG_SETUP, 'S'
DPW DEBUG_SETUP, ds:[kdata]
DPW DEBUG_SETUP, ds:[kernelCore]
clr di
mov es, ds:[kdata]
mov bx, ds:[kernelCore]
mov es, es:[bx].HM_addr
mov ax, es:[GH_libEntrySegment]
DPW DEBUG_SETUP, ax
mov si, es:[GH_libEntryOff]
mov es, ax
;
; now look for the signature that says we have a swat table
;
inc si ; skip jmp instruction...
inc si ; ...and displacement
cmp {word}es:[si].SVD_signature, SWAT_VECTOR_SIG
jne noTable
DPC DEBUG_SETUP, 'v'
mov al, es:[si].SVD_version
mov ds:[kernelVersion], al
DPB DEBUG_SETUP, al
DPC DEBUG_SETUP, 'T', inv
segxchg ds, es
mov si, ds:[si].SVD_table ; ds:si <- vector table
mov di, -1 ; => table in kernel
jmp loadOffsets
noTable:
;
; Kernel is not equipped with a table for us to copy, so
; lets do a checksum in kcode to find out which kernel we have
; it better be either Zoomer, Wizard or upgrade!
; ES = kcode (where the kernel library entry resides)
;
push ds
segmov ds, es
mov si, 1000h ; random place in kcode
mov cx, 10 ; number of words to checksum with
clr di ; di = checksum
calcChecksum:
lodsw
add di, ax
loop calcChecksum
pop ds
DPC DEBUG_SETUP, 'C', inv
DPW DEBUG_SETUP, di
segmov es, ds ; es <- cgroup again
mov_tr ax, di ; ax <- checksum
mov cx, length internalTables
mov di, offset internalTables
findTableLoop:
cmp ds:[di].IVT_checksum, ax
je foundTable
add di, size InternalVectorTable
loop findTableLoop
stc
jmp done
foundTable:
mov si, ds:[di].IVT_table
clr di
loadOffsets:
;
; Copy the table into our internal data area.
; ds:si = table to copy
; es = cgroup
;
push di
mov di, offset kernelVectors
mov cx, size kernelVectors
rep movsb
pop di
segmov ds, es
DPC DEBUG_SETUP, 'x'
DPW DEBUG_SETUP, ds:[curXIPPageOff]
;
; Set up the offsets for the procedure vectors of the things we call
; in the kernel.
;
mov ax, ds:[kernelVectors].SVT_MemLock
mov ds:[MemLockVec].offset, ax
mov ax, ds:[kernelVectors].SVT_FileReadFar
mov ds:[FileReadVec].offset, ax
mov ax, ds:[kernelVectors].SVT_FilePosFar
mov ds:[FilePosVec].offset, ax
mov ax, ds:[kernelVectors].SVT_MapXIPPageFar
mov ds:[MapXIPPageVec].offset, ax
mov ax, ds:[kernelVectors].SVT_SysContextSwitch
mov ds:[SysCSVec].offset, ax
mov ax, ds:[kcodeSeg]
mov ds:[SysCSVec].segment, ax
;
; Convert the XIP page size from bytes to paragraphs
;
mov cl, 4
mov ax, ds:[kernelVectors].SVT_MAPPING_PAGE_SIZE
shr ax, cl
mov ds:[xipPageSize], ax
clc
done:
.leave
ret
KernelSetup endp
COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
Kernel_Setup
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
SYNOPSIS: send swat a list of internal kernel symbols that it might
find useful.
CALLED BY: Rpc_Wait
PASS: ES, DS = cgroup
RETURN: Nothing
DESTROYED: Probably
PSEUDO CODE/STRATEGY:
KNOWN BUGS/SIDE EFFECTS/IDEAS:
REVISION HISTORY:
Name Date Description
---- ---- -----------
jimmy 7/26/93 Initial version.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@
Kernel_Setup proc near
.enter
DPC DEBUG_SETUP, 's'
call KernelSetup
jc error
mov ({SetupReplyArgs}ds:[rpc_ToHost]).sa_kernelHasTable, di
mov cx, size SwatVectorTable/2
mov ({SetupReplyArgs}ds:[rpc_ToHost]).sa_tableSize, cx
lea di, ({SetupReplyArgs}ds:[rpc_ToHost]).sa_currentThread
mov si, offset kernelVectors
CheckHack <(size SwatVectorTable and 1) eq 0>
rep movsw
mov si, offset rpc_ToHost
mov cx, size SetupReplyArgs
DPC DEBUG_SETUP, 'y'
DPW DEBUG_SETUP, cx
call Rpc_Reply
done:
.leave
ret
error:
mov ax, RPC_INCOMPAT
call Rpc_Error
jmp done
Kernel_Setup endp
COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
Kernel_Hello
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
SYNOPSIS: Handle the receipt of an RPC_HELLO call
CALLED BY: Rpc_Wait
PASS: ES, DS = cgroup
RETURN: Nothing
DESTROYED: Probably
PSEUDO CODE/STRATEGY:
KNOWN BUGS/SIDE EFFECTS/IDEAS:
The various state variables in main.asm are set up using the
offsets passed in the HelloArgs structure
REVISION HISTORY:
Name Date Description
---- ---- -----------
ardeb 11/19/88 Initial version
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@
;
; List of interrupts/processor exceptions to catch for '286 or later processors
; single-step and breakpoint exceptions are fielded elsewhere.
;
pcATIntercepts byte RPC_HALT_DIV0,
RPC_HALT_NMI,
RPC_HALT_INTO,
RPC_HALT_BOUND,
RPC_HALT_ILLINST,
RPC_HALT_GP,
RPC_HALT_SSOVER,
RPC_HALT_NOSEG
;
; List of interrupts/processor exceptions to catch for 8088/8086 processors
; single-step and breakpoint exceptions are fielded elsewhere.
;
pcXTIntercepts byte RPC_HALT_DIV0,
RPC_HALT_NMI,
RPC_HALT_INTO
Kernel_Hello proc near
DPC DEBUG_FALK3, 'H'
;
; It seems we're getting interrupted in here, context
; switching before we can set currentThread to HID_KTHREAD
; and never making it back due to EC code in DispatchSI
; that will decide the saveSS is bogus (it's not below PSP),
; vault to FatalError and we'll never tell anyone because
; we're not attached yet.
;
; I have some doubts about this theory. E.g. if so, we should
; be able to attach again after the timeout. Also, it only
; happens with a bus mouse, which runs off the timer interrupt,
; which we intercept in SaveState, so the mouse shouldn't
; be consulted...
;
dsi
;
;
; See if the kernel's been loaded. If not, we can't return anything
; else...when the kernel loads, it'll take care of setting the
; segment portion of MemLockVec
;
; initialize value to -1, it will change when necessary
mov ({HelloReply}ds:[rpc_ToHost]).hr_curXIPPage,
BPT_NOT_XIP
tst ds:[kernelCore]
jnz KH2 ; can actually look things up
;
; Nothing running -- set hr_numGeodes, and hr_numThreads to 0.
; Claim the current thread is the kernel.
;
KH1_7:
clr ax
mov ({HelloReply}ds:[rpc_ToHost]).hr_numGeodes, ax
mov ({HelloReply}ds:[rpc_ToHost]).hr_numThreads, ax
mov ({HelloReply}ds:[rpc_ToHost]).hr_curThread, ax
mov ({HelloReply}ds:[rpc_ToHost]).hr_kernelVersion, ax
;
; Just reply with the HelloReply structure. KH3 sends the
; reply and goes into wait mode.
;
mov cx, size HelloReply
eni
jmp sendReply
KH2:
;
; Update our TPD_blockHandle, and TPD_processHandle while we've got
; kdata in es. This allows us to mimic the kernel thread.
;
mov es, ds:[kdata]
mov ax, es:[TPD_blockHandle]
mov ss:[tpd].TPD_blockHandle, ax
mov ax, es:[TPD_processHandle]
mov ss:[tpd].TPD_processHandle, ax
;
; Stuff in the current thread.
;
test ds:[sysFlags], MASK attached
jnz fetchCurThread
;
; If weren't attached before, currentThread in the kernel
; actually contains the ID of the thread at the time of the
; interruption, so fetch it and store it in the state block
; so when we continue, we don't switch to a garbage thread.
;
; Done here to handle the case where we intercepted a fatal
; error without having been attached. The saveSS of the current
; thread is unreliable in such a case, so we want to make sure
; we get the value from our state block, not from the handle.
; Also done here to make sure the thing gets transmitted to
; Swat even if ha_bootstrap is true.
;
mov bx, ds:[currentThreadOff]
mov ax, HID_KTHREAD
xchg ax, es:[bx]
mov [bp].state_thread, ax
; FALLTHRU
fetchCurThread:
;
; Fetch the current thread from the state block...
;
mov ax, [bp].state_thread
mov ({HelloReply}ds:[rpc_ToHost]).hr_curThread, ax
;
; See if Swat is bootstrapping. This is here to allow one to
; attach to a system that has too much running for an initial
; setup reply to fit.
;
DPC DEBUG_FALK3, 'h'
tst ({HelloArgs}CALLDATA).ha_bootstrap
jnz KH1_7
eni
tst ds:[xipHeader]
jz afterXIP
; at this point es = kdata
mov di, ds:[curXIPPageOff]
mov ax, es:[di]
mov ({HelloReply}ds:[rpc_ToHost]).hr_curXIPPage, ax
afterXIP:
;
; First figure the number of geodes in the system
;
mov di, offset rpc_ToHost + size HelloReply
segxchg ds, es ;es <- cgroup, ds <- kdata
assume es:cgroup, ds:nothing
clr cx
mov dx, RPC_MAX_DATA - size HelloReply
mov si, es:[geodeListPtrOff]
mov bx, ds:[si] ; Load initial geode handle into BX
KHGetGeodes:
;
; Null segment => end of chain
;
tst bx
jz KHGGDone
;
; Store the geode handle in the RPC structure
;
mov ax, bx
stosw
;
; Lock the geode (if possible). You might think that the call to
; KernelSafeLock could generate a call to the host, but it can't
; as no HF_DEBUG bit can possibly be set at this point.
;
segmov ds, es ;ds = cgroup
call KernelSafeLock
segxchg ds, es ;ds = geode, es = cgroup
jc KHGGDone
;
; Extract the handle of the next geode
;
push ds:[GH_nextGeode]
call KernelSafeUnlock
pop bx
;
; Advance the numGeodes counter and the pointer into the reply
;
inc cx
dec dx
dec dx
jnz KHGetGeodes
KHTooBig:
mov ax, RPC_TOOBIG
call Rpc_Error
ret
KHGGDone:
mov ds, es:[kdata] ; Restore kdata
mov es:[{HelloReply}rpc_ToHost].hr_numGeodes, cx
; put in the Kernel Version
mov al, es:[kernelVersion]
clr ah
mov ({HelloReply}es:[rpc_ToHost]).hr_kernelVersion, ax
;
; DI now points to the place at which to start storing thread
; information. We do a thing similar to that above to enumerate
; all the threads in the system.
;
mov si, es:[threadListPtrOff]
clr cx
sub si, offset HT_next
KHGetThreads:
mov ax, ds:[si].HT_next
tst ax ; no next thread?
jz KHGTDone ; correct -- all done here
stosw ; Store the handle itself in the
; reply buffer
xchg si, ax ; si <- next thread
inc cx
dec dx
dec dx
jnz KHGetThreads
tst ds:[si].HT_next
jnz KHTooBig
KHGTDone:
segxchg ds, es
assume ds:cgroup, es:nothing
;
; Store # of threads in system
;
mov ({HelloReply}ds:[rpc_ToHost]).hr_numThreads, cx
;
; Figure total size of reply and move it into CX
;
sub di, offset rpc_ToHost
mov cx, di
sendReply:
;
; Make sure ES contains cgroup, point SI at rpc_ToHost and
; reply to the rpc that everything's groovy.
;
push cs
pop es
mov si, offset rpc_ToHost
call Rpc_Reply
;
; Now the reply has been shipped off, catch major errors, as determined
; by the processor type.
;
test ds:[sysFlags], MASK attached
jnz KHRet ; => Already have our hooks in
DPC DEBUG_FALK3, 'p'
dsi ; No ints while catching
;
; Always catch divide by 0
;
mov bx, offset intsToIgnore
mov si, offset pcATIntercepts
mov cx, length pcATIntercepts
;test ds:[sysFlags], mask isPC
;jz catchEmAll
;mov si, offset pcXTIntercepts
;mov cx, length pcXTIntercepts
catchEmAll:
lodsb cs: ; al <- interrupt #
mov ah, al ; save it...
xlatb ; al <- intsToIgnore[al]
tst al ; ignore it?
jnz nextInt ; yes..
mov al, ah ; al <- interrupt # again
call CatchInterrupt
nextInt:
loop catchEmAll
;
; Intercept kernel debug vectors
;
call KernelIntercept
KHRet:
;
; Attach complete -- note this, please.
;
or ds:[sysFlags], MASK attached
;exit:
ret
Kernel_Hello endp
COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
Kernel_Detach
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
SYNOPSIS: Detach from the kernel.
CALLED BY: Rpc_Wait, RpcExit, RpcGoodbye
PASS: Debug* vector offsets accurate
RETURN: Nothing
DESTROYED: ...
PSEUDO CODE/STRATEGY:
Re-install near returns (0c3h) at the start of the vectors
we changed.
Clear the attached bit in sysFlags
Reply that everything's ok
KNOWN BUGS/SIDE EFFECTS/IDEAS:
REVISION HISTORY:
Name Date Description
---- ---- -----------
ardeb 11/20/88 Initial version
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@
Kernel_Detach proc near
test ds:[sysFlags], MASK attached
jz done ; Not actually attached, so don't
; detach from the kernel. We've
; not gotten our hooks into the
; interrupt vectors either...
;
; Figure where the intercept vectors lie and what their calling
; distance is. For pre-SDK kernels (kernelVersion == 0), the vectors
; lie as near routines in kcode. All other kernels have them as
; far routines in kdata.
;
push es
mov es, ds:[kcodeSeg]
mov bl, 0c3h ; retn opcode
tst ds:[kernelVersion]
jz gotSeg
mov es, ds:[kdata]
mov bl, 0cbh ; retf opcode
gotSeg:
call Kernel_EnsureESWritable
push ax
mov_tr ax, bx ; ax <- return opcode
mov bx, ds:[DebugLoadResOff]
mov byte ptr es:[bx], al
mov bx, ds:[DebugMemoryOff]
mov byte ptr es:[bx], al
mov bx, ds:[DebugProcessOff]
mov byte ptr es:[bx], al
pop ax
call Kernel_RestoreWriteProtect
call Kernel_CleanHandles
pop es
;
; Restore the various interrupt handlers to their previous
; state. IgnoreInterrupt deals with our not having actually
; hooked a vector...
;
call Kernel_ReleaseExceptions
and ds:[sysFlags], NOT MASK attached
done:
DPC DEBUG_EXIT, 'd'
ret
Kernel_Detach endp
COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
Kernel_ReleaseExceptions
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
SYNOPSIS: Ignore the processor exceptions we caught when Swat attached
CALLED BY: (EXTERNAL) Kernel_Detach, MainGeosExited
PASS: ds = cgroup
RETURN: nothing
DESTROYED: nothing
SIDE EFFECTS:
PSEUDO CODE/STRATEGY:
REVISION HISTORY:
Name Date Description
---- ---- -----------
ardeb 10/19/95 Initial version
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@
Kernel_ReleaseExceptions proc near
uses ax, bx
.enter
dsi
mov al, RPC_HALT_DIV0
call IgnoreInterrupt
mov al, RPC_HALT_NMI
call IgnoreInterrupt
;mov al, RPC_HALT_BPT Always caught
;call IgnoreInterrupt
mov al, RPC_HALT_INTO
call IgnoreInterrupt
mov al, RPC_HALT_BOUND
call IgnoreInterrupt
mov al, RPC_HALT_ILLINST
call IgnoreInterrupt
;mov al, RPC_HALT_PEXT never caught
;call IgnoreInterrupt
;mov al, RPC_HALT_INVTSS never caught
;call IgnoreInterrupt
mov al, RPC_HALT_GP
call IgnoreInterrupt
eni
.leave
ret
Kernel_ReleaseExceptions endp
COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
Kernel_IndexToOffset
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
SYNOPSIS: convert an index into the export table into an offset
CALLED BY: RPC_INDEX_TO_OFFSET
PASS: handle of core block and index into export entry table
RETURN: converted offset
DESTROYED: ax, bx, cx, dx
PSEUDOCODE/STRATEGY:
KNOWN BUGS/SIDEFFECTS/IDEAS:
REVISION HISTORY:
Name Date Description
---- ---- -----------
jimmy 7/13/93 Initial version.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@
Kernel_IndexToOffset proc near
uses es, si
.enter
DPC DEBUG_FILE_XFER, 'I'
mov bx, ({IndexToOffsetArgs}CALLDATA).ITOA_geodeHandle
mov cx, ({IndexToOffsetArgs}CALLDATA).ITOA_index
; using 1000h for now, should really be the fist handle in the
; handle table
cmp bx, 100h
jg geosHandle
; here we have a DOS handle so we must read stuff in from the
; DOS file directly, eck
; bx = DOS file handle
; cxsi = offset to read from
; di = how much to read
; ds:dx = buffer to read into
mov_tr ax, cx ; save our index
clr cx
mov si, offset GH_exportLibTabOff
mov dx, offset rpc_ToHost
mov di, size GH_exportLibTabOff
call KernelDosFileRead
LONG jc done
mov si, {word}ds:rpc_ToHost
add si, size word ; get offset from fptr
clr cx
mov di, size word
call KernelDosFileRead
mov ax, {word}ds:rpc_ToHost
jmp gotOffset
geosHandle:
call KernelSafeLock ; es = core block address
LONG jc done
DPC DEBUG_FILE_XFER, 'L'
mov si, es:[GH_exportLibTabOff]
shl cx
shl cx ; index * 4 = position in fptr table
add si, cx
mov ax, es:[si]
DPW DEBUG_FILE_XFER, ax
call KernelSafeUnlock
gotOffset:
mov cx, size IndexToOffsetReply
mov si, offset rpc_ToHost
push ds
pop es
mov ({IndexToOffsetReply}ds:rpc_ToHost).ITOR_offset, ax
DPW DEBUG_FILE_XFER, ax
call Rpc_Reply
clc
done:
.leave
ret
Kernel_IndexToOffset endp
COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
Kernel_GetNextDataBlock
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
SYNOPSIS: send the next block of data to the host
CALLED BY: Rpc_Wait
PASS: nothing
RETURN: data
DESTROYED: Nada.
PSEUDOCODE/STRATEGY:
KNOWN BUGS/SIDEFFECTS/IDEAS:
REVISION HISTORY:
Name Date Description
---- ---- -----------
jimmy 11/18/93 Initial version.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@
Kernel_GetNextDataBlock proc near
.enter
DPC DEBUG_XIP, 'n'
push ds, es
; get the size to read and store it in saved ReadGeodeArgs
mov ax, ({GetNextDataBlock}CALLDATA).GNDB_size
mov ds:[savedReadGeodeArgs].RGA_size, ax
; copy the savedReadGeodeArgs into CALLDATA so ReadGeode thinks its
; being called with those args
segmov es, ds
mov di, offset CALLDATA
PointDSAtStub
mov si, offset savedReadGeodeArgs
mov cx, size ReadGeodeArgs
rep movsb
pop ds, es
call Kernel_ReadGeode ; cx = size of data read
segmov es, ds
mov si, offset rpc_ToHost
add si, size ReadGeodeReply ; skip the reply info
call Rpc_Reply
.leave
ret
Kernel_GetNextDataBlock endp
COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
KernelGetResourceFlags
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
SYNOPSIS: get the resource flags for a geode
CALLED BY: GLOBAL
PASS: bx = geode handle
RETURN: Void.
DESTROYED: Nada.
PSEUDOCODE/STRATEGY:
KNOWN BUGS/SIDEFFECTS/IDEAS:
REVISION HISTORY:
Name Date Description
---- ---- -----------
jimmy 10/19/93 Initial version.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@
KernelGetResourceFlags proc near
.enter
DA DEBUG_XIP, <push ax>
DPC DEBUG_XIP, 'F'
DA DEBUG_XIP, <pop ax>
mov cx, offset HM_flags
; mov di, offset dataBuf
mov di, offset rpc_ToHost + size ReadGeodeReply
call KernelGetGeodeResourcesInfo
.leave
ret
KernelGetResourceFlags endp
COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
KernelGetGeodeResourcesInfo
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
SYNOPSIS: get the info of the resources for a geode
CALLED BY: GLOBAL
PASS: bx = geode handle
cx = offset of field to get (ie offset HM_addr or HM_flags)
di = offset of buffer to store data in (ds = scode)
RETURN: cx = size
carry clear (if things go ok)
DESTROYED: Nada.
PSEUDOCODE/STRATEGY:
KNOWN BUGS/SIDEFFECTS/IDEAS:
REVISION HISTORY:
Name Date Description
---- ---- -----------
jimmy 8/26/93 Initial version.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@
KernelGetGeodeResourcesInfo proc near
uses ds, es, di, dx, bp, ax, si
.enter
DA DEBUG_XIP, <push ax>
DPS DEBUG_XIP, <RI>
DA DEBUG_XIP, <pop ax>
mov bp, cx ; save away in extra register
mov dx, ds:[kdata] ; save away in dx for speed
call KernelSafeLock ; es = geode block
jc done
push bx ; save for unlock
mov si, es:[GH_resHandleOff] ; es:si <- geode handle table
mov cx, ({ReadGeodeArgs}CALLDATA).RGA_size
shr cx
cmp ds:[rpc_LastCall].RMB_header.rh_procNum, RPC_READ_GEODE
je resetState
; if we came through GET_NEXT_DATA_BLOCK then we must strart from where
; we left off
DPW DEBUG_XIP, cs:[savedReadGeodeArgs].RGA_dataValue1
add si, ds:[savedReadGeodeArgs].RGA_dataValue1
add ds:[savedReadGeodeArgs].RGA_dataValue1, \
FILE_XFER_BLOCK_SIZE - size ReadGeodeReply
jmp getInfo
resetState:
; use one of the generic values to remember where to pick from
mov ds:[savedReadGeodeArgs].RGA_dataValue1, \
FILE_XFER_BLOCK_SIZE - size ReadGeodeReply
getInfo:
segxchg ds, es ; ds:si = geode handle table, es:di = out buffer
push cx
handleloop:
push es
mov es, dx
lodsw
mov_tr bx, ax ; bx = next handle
add bx, bp ; get proper field of handle
mov ax, es:[bx] ; get flags for that handle
pop es ; restore destination buffer segment
stosw ; stuff the flags into the buffer
loop handleloop
pop cx
shl cx ; size = 2 * resCount
pop bx
call KernelSafeUnlock
DPW DEBUG_XIP, cx
clc
done:
.leave
ret
KernelGetGeodeResourcesInfo endp
COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
KernelGetHeaderInfo
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
SYNOPSIS: get all relavent header info for an XIPed geode
CALLED BY: Kernel_ReadGeode
PASS: bx = geode handle
ds = scode
RETURN: fill dataBuf with a GeodeHeader struct full of juicy details
cx = size of data
DESTROYED: Nada.
PSEUDOCODE/STRATEGY:
a geode really looks like this
GeosFileHeader
ExecutableFileHeader
GeodeFileHeader
data
now swat wants
ExecutableFileHeader
GeodeFileHeader
and for XIPed geodes we only have access to
GeodeFileHeader
so we will just send up what data we can, put into the right place
KNOWN BUGS/SIDEFFECTS/IDEAS:
REVISION HISTORY:
Name Date Description
---- ---- -----------
jimmy 11/17/93 Initial version.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@
KernelGetHeaderInfo proc near
uses ax, di, es, ds, si
.enter
DPS DEBUG_XIP, <HI>
; set up di to point to where GeodeHeader info should go
mov di, offset rpc_ToHost + size ExecutableFileHeader \
+ size ReadGeodeReply
call KernelSafeLock ; es = GeodeHeader for geode
jc done
segxchg es, ds ; es:di = place to send data
clr si ; ds:si = GeodeHeader info
mov cx, offset GH_endOfVariablesFromFile
rep movsb ; copy GeodeHeader
mov cx, size ExecutableFileHeader + \
offset GH_endOfVariablesFromFile
; note that the size we return is bigger than what we
; actually get by size ExectuableFileHeader as that
; extra data is not around in memory...
DPC DEBUG_XIP, 'h', inv
call KernelSafeUnlock
clc
done:
.leave
ret
KernelGetHeaderInfo endp
COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
KernelGetNormalData
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
SYNOPSIS: get data from a resource
CALLED BY: GLOBAL
PASS: dx = handle of resource
ax = offset
cx = number of bytes to get
RETURN: cx = size, save as cx passed in
carry set on error
DESTROYED: Nada.
PSEUDOCODE/STRATEGY:
KNOWN BUGS/SIDEFFECTS/IDEAS:
REVISION HISTORY:
Name Date Description
---- ---- -----------
jimmy 11/19/93 Initial version.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@
KernelGetNormalData proc near
uses ds, es, si, di, ax, bx, cx
push ax
DPC DEBUG_FALK3, 'K'
pop ax
.enter
mov bx, dx
mov si, ax
call KernelSafeLock
jc done
segxchg ds, es ; ds:si = data to get
mov di, offset rpc_ToHost + size ReadGeodeReply
rep movsb ; copy data
call KernelSafeUnlock
clc
done:
.leave
push ax
DPC DEBUG_FALK3, 'k'
pop ax
ret
KernelGetNormalData endp
COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
Kernel_ReadGeode
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
SYNOPSIS: read in data from a geode
CALLED BY: RPC_READ_GEODE
PASS: size of data
RETURN: cx = size of adata read if not called from RPC_READ_GEODE
DESTROYED: Nada.
PSEUDOCODE/STRATEGY:
if we can, we will gather the data from memory otherwise
call GEOS's FileRead on the geode (if geode not XIPed)
KNOWN BUGS/SIDEFFECTS/IDEAS:
REVISION HISTORY:
Name Date Description
---- ---- -----------
jimmy 6/23/93 Initial version.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@
savedReadGeodeArgs ReadGeodeArgs
DataTypeFunctions nptr offset KernelGetResourceFlags,
offset KernelGetHeaderInfo,
offset KernelGetNormalData
Kernel_ReadGeode proc near
.enter
;BRK
DPC DEBUG_FILE_XFER, 'R'
tst ds:[readGeodeSem]
jz readGeodePsem
mov ({ReadGeodeReply}ds:rpc_ToHost).RGR_ok, FILE_XFER_QUIT
mov cx, ({ReadGeodeArgs}CALLDATA).RGA_size
add cx, size ReadGeodeReply
call Rpc_Reply
DPC DEBUG_FILE_XFER, 'E', inv
stc
jmp doneNoV
readGeodePsem:
mov ds:[readGeodeSem], 1
; lets copy over the arguments in case we need them for successive calls
; to GET_NEXT_BLOCK
PointESAtStub
mov di, offset savedReadGeodeArgs
mov si, offset CALLDATA
mov cx, size ReadGeodeArgs
rep movsb
; see if the data type lends itself towards avoiding a call to fread
; or not...if so try that first
mov bx, ({ReadGeodeArgs}CALLDATA).RGA_geodeHandle
mov cx, ({ReadGeodeArgs}CALLDATA).RGA_dataType
DPC DEBUG_XIP, 'D'
DPW DEBUG_XIP, cx
sub cx, GEODE_DATA_GEODE
jb useGeode ; => nothing special
; first try to gather the data without having to read from the
; geo file...
; these data values could be useful to the specific data type routine
mov dx, ({ReadGeodeArgs}CALLDATA).RGA_dataValue1
mov ax, ({ReadGeodeArgs}CALLDATA).RGA_dataValue2
shl cx
mov si, cx
mov cx, ({ReadGeodeArgs}CALLDATA).RGA_size
call cs:[DataTypeFunctions][si]
jnc afterFileRead ; if it failed try the geode
useGeode:
call KernelReadFromGeodeFile
afterFileRead:
jc error
; send out the size of the stuff read
DPC DEBUG_FILE_XFER, 'S'
DPW DEBUG_FILE_XFER, cx
; add in the amount sent to the offset so we know where to start from
; next time
clr dx
adddw ds:[savedReadGeodeArgs].RGA_offset, dxcx
; if we weren't called from READ_GEODE then just return
cmp ds:[rpc_LastCall].RMB_header.rh_procNum, RPC_READ_GEODE
jne done
mov ({ReadGeodeReply}ds:[rpc_ToHost]).RGR_ok, FILE_XFER_SYNC
mov ({ReadGeodeReply}ds:[rpc_ToHost]).RGR_size, cx
sendReply:
add cx, size ReadGeodeReply
mov si, offset rpc_ToHost
segmov es, ds
DPW DEBUG_XIP, cx
call Rpc_Reply
done:
clr ds:[readGeodeSem]
doneNoV:
.leave
ret
error:
cmp al, FILE_XFER_QUIT
je sendError
mov al, FILE_XFER_ERROR
sendError:
mov ({ReadGeodeReply}ds:[rpc_ToHost]).RGR_ok, al
mov cx, ({ReadGeodeArgs}CALLDATA).RGA_size
jmp sendReply
Kernel_ReadGeode endp
COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
KernelReadFromGeodeFile
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
SYNOPSIS: Read bytes out of the geode file, since other methods failed
CALLED BY: (INTERNAL) Kernel_ReadGeode
PASS: ds = cgroup
rpc_FromHost = ReadGeodeArgs
RETURN: carry set on error:
ax = FileError or FILE_XFER_QUIT
carry clear if ok:
cx = # bytes read
DESTROYED: dx, si, di, es, bx
SIDE EFFECTS:
PSEUDO CODE/STRATEGY:
REVISION HISTORY:
Name Date Description
---- ---- -----------
ardeb 5/ 3/94 Initial version (extracted from
Kernel_ReadGeode)
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@
KernelReadFromGeodeFile proc near
.enter
DPC DEBUG_XIP, 'u', inv
DPW DEBUG_FILE_XFER, ({ReadGeodeArgs}CALLDATA).RGA_offset.high
DPW DEBUG_FILE_XFER, ({ReadGeodeArgs}CALLDATA).RGA_offset.low
DPW DEBUG_FILE_XFER, ({ReadGeodeArgs}CALLDATA).RGA_size
DPW DEBUG_FILE_XFER, ({ReadGeodeArgs}CALLDATA).RGA_geodeHandle
; if the handle is 1 then we are dealing with the loader so just
; return the size of the header, which should be the only thing
; that we get asked for...i hope so anyways.
mov bx, ({ReadGeodeArgs}CALLDATA).RGA_geodeHandle
cmp bx, 1
jne notLoader
mov ax, ds:[kernelHeader].exe_headerSize
DPW DEBUG_FILE_XFER, ax
mov {word}ds:[offset rpc_ToHost + size ReadGeodeReply], ax
mov cx, 2
clc
jmp done
notLoader:
call KernelSafeLock ; es <- core block segment
jc error
DPC DEBUG_FILE_XFER, 'L'
mov ax, es:[GH_geoHandle]
mov dx, es:[GH_geodeAttr]
DPW DEBUG_FILE_XFER, ax
call KernelSafeUnlock
; make sure there is a file handle and the GA_KEEP_FILE_OPEN bit
; is set as otherwise the file may have been closed and the handle
; invalid
mov_tr bx, ax ; bx <- file handle
tst bx ; make sure the file handle
jz error ; non-zero
test dx, mask GA_KEEP_FILE_OPEN
jz error
;
; Load up registers for read, regardless of type of handle:
; cx <- # bytes to read
; sidi <- offset from which to read
; ds:dx <- buffer to which to read (rpc_ToHost, right after the
; ReadGeodeReply header)
;
mov cx, ({ReadGeodeArgs}CALLDATA).RGA_size
movdw sidi, ({ReadGeodeArgs}CALLDATA).RGA_offset
mov dx, offset rpc_ToHost + size ReadGeodeReply
;
; See if handle is GEOS or DOS (using 100h for now, should really be
; the first handle in the handle table)
;
cmp bx, 100h
jb dosFileRead
call KernelSafeFileRead
jmp done
dosFileRead:
; until the DOS file system driver is loaded,
; we have a dos handle, not a GEOS handle, so just do a normal dos
; file position and file read
call KernelDosFileRead
done:
.leave
ret
error:
mov al, FILE_XFER_QUIT
stc
jmp done
KernelReadFromGeodeFile endp
COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
KernelDosFileRead
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
SYNOPSIS: read data from a dos file
CALLED BY: KernelReadFromGeodeFile
PASS: bx = DOS file handle
sidi = offset to read from
cx = how much to read
ds:dx = buffer to read into
RETURN: ds:dx = buffer full of data read in
cx = # of bytes read
DESTROYED: ax, dx, si, di
PSEUDOCODE/STRATEGY:
KNOWN BUGS/SIDEFFECTS/IDEAS:
REVISION HISTORY:
Name Date Description
---- ---- -----------
jimmy 7/ 7/93 Initial version.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@
KernelDosFileRead proc near
.enter
DPC DEBUG_FILE_XFER, 'D'
; first save away current position
push cx, dx
clr cx, dx
mov ax, MSDOS_POS_FILE shl 8 or FILE_POS_RELATIVE
int 21h
xchg di, dx
mov cx, si ; cxdx <- new position
mov_tr si, ax ; disi <- old position
; add size GeosFileHeader to the offset since we are now starting
; from the actual beginning of the file
.assert size GeosFileHeader eq 256
adddw cxdx, <size GeosFileHeader>
DPW DEBUG_FILE_XFER, dx
mov ax, MSDOS_POS_FILE shl 8 or FILE_POS_START
int 21h
pop cx, dx ; ds:dx <- buffer to read into
; cx <- # bytes
jc error
DPW DEBUG_FILE_XFER, cx
DPW DEBUG_FILE_XFER, bx
mov ah, MSDOS_READ_FILE
int 21h
jc error
DPW DEBUG_FILE_XFER, ax
; now restore old position
push ax
movdw cxdx, disi
mov ax, MSDOS_POS_FILE shl 8 or FILE_POS_START
int 21h
pop cx ; return cx = # of bytes read
DPC DEBUG_FILE_XFER, 'd'
clc
done:
DA DEBUG_FILE_XFER, <pushf>
DA DEBUG_FILE_XFER, <push ax>
DPC DEBUG_FILE_XFER, 'D', inv
DA DEBUG_FILE_XFER, <pop ax>
DA DEBUG_FILE_XFER, <popf>
.leave
ret
error:
DPC DEBUG_FILE_XFER, 'd', inv
stc
jmp done
KernelDosFileRead endp
COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
KernelSafeFileRead
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
SYNOPSIS: Read from a file using GEOS's FileRead
CALLED BY: KernelReadFromGeodeFile
PASS: BX = GEOS File Handle
DS:DX = buffer to write to
CX = number of bytes to read
SI:DI = dword offset to start reading at
RETURN: Carry set if couldn't read from the file
ax = FileError or FILE_XFER_QUIT
carry clear if read:
cx = # bytes read
DESTROYED: ax, es, dx, di
PSEUDO CODE/STRATEGY:
If block resident, call MemLock on it and return carry clear
Else, if block discarded, send error and return carry set
Else if dosSem free, call MemLock anyway and let the kernel
swap the block in (can only do this if the semaphore
is free b/c if we try to context switch out of
kernel mode [which is what we're in], the kernel
will abort)
Else send error and return carry set.
KNOWN BUGS/SIDE EFFECTS/IDEAS:
REVISION HISTORY:
Name Date Description
---- ---- -----------
ardeb 11/20/88 Initial version
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@
KernelSafeFileRead proc near
uses si, bp
.enter
;
; If not attached, kernel not loaded, so can't do anything here.
;
mov al, FILE_XFER_QUIT
tst ds:[kernelCore]
stc
LONG jz exit
mov es, ds:[kdata]
mov bp, si ; bpdi <- read start offset
; now lets turn off the EC flags
mov si, ds:[sysECLevelOff]
tst si
jz afterECset ; => we're attached to non-ec,
; so don't do this stuff
push es:[si]
mov {word}es:[si], 0 ; clear out EC flags
afterECset:
;
; If something's in DOS, we can't possibly read, so check the DOS
; semaphore first...
;
mov si, ds:[dosSemOff]
cmp es:[si].Sem_value, 0
jle KSLError ; Semaphore taken -- honk
DPW DEBUG_FILE_XFER, es:[bx].HM_owner
if 0
DA DEBUG_FILE_XFER, <push ax>
DPC DEBUG_FILE_XFER, 't'
DPB DEBUG_FILE_XFER, es:[bx].HG_data1
DPB DEBUG_FILE_XFER, es:[bx].HG_type
DPW DEBUG_FILE_XFER, es:[bx].HG_owner
DA DEBUG_FILE_XFER, <pop ax>
endif
cmp es:[bx].HG_type, SIG_FILE
jne KSLError
;
; Set the segment portion of FileReadVec & FilePosVec to match kcode.
;
mov ax, ds:[kcodeSeg]
mov ds:[FileReadVec].segment, ax
mov ds:[FilePosVec].segment, ax
;
; now we have our file handle, first we position the file pointer
; calling FilePos after saving the current position for later
; restoration.
;
push cx, dx
DPC DEBUG_FILE_XFER, 'p'
if 0
DPW DEBUG_FILE_XFER, cx
DPW DEBUG_FILE_XFER, bx
endif
; Put a signature in here so that some EC code in SysLockCommon
; can tell that this is the swat stub and not really the kernel.
call KernelSetSwatStubFlag
mov al, FILE_POS_RELATIVE
clr cx
mov dx, cx
call cs:[FilePosVec]
xchg di, dx
mov cx, bp ; cxdx <- new position
mov_tr bp, ax ; dibp <- old position
DPB DEBUG_FILE_XFER, es:[bx].HF_accessFlags
DPC DEBUG_FILE_XFER, 'P'
DPW DEBUG_FILE_XFER, cx
DPW DEBUG_FILE_XFER, dx
DPW DEBUG_FILE_XFER, bx
mov al, FILE_POS_START
call cs:[FilePosVec] ; dx:ax = new position
DPW DEBUG_FILE_XFER, dx
DPW DEBUG_FILE_XFER, ax
pop cx, dx
DPC DEBUG_FILE_XFER, 'R'
DPW DEBUG_FILE_XFER, bx
DPW DEBUG_FILE_XFER, cx
if 0
DPW DEBUG_FILE_XFER, cs:[FileReadVec].segment
DPW DEBUG_FILE_XFER, cs:[FileReadVec].offset
endif
; inform the kernel that this is really the swat stub
clr al
call cs:[FileReadVec]; Call through FileRead vector to
; read the data. Returns carry set/clear
; and ax = FileError/cx = # bytes read
;
; Restore old position regardless of success or failure of read.
;
pushf
push ax, cx
mov al, FILE_POS_START
movdw cxdx, dibp
call cs:[FilePosVec]
pop ax, cx
popf
DA DEBUG_FILE_XFER, <jc KSLError>
DPC DEBUG_FILE_XFER, 'r'
DPW DEBUG_FILE_XFER, cx
done:
;
; Restore EC flags to their previous settings before returning.
;
mov_tr dx, ax
lahf
mov si, ds:[sysECLevelOff]
tst si
jz afterECreset ; => non-ec, so didn't push
; anything
pop es:[si] ; restore old EC state
afterECreset:
sahf
mov_tr ax, dx
exit:
.leave
ret
KSLError:
mov al, FILE_XFER_QUIT
DA DEBUG_FILE_XFER, <push ax>
DPW DEBUG_FILE_XFER, ax
DPW DEBUG_FILE_XFER, cx
DPC DEBUG_FILE_XFER, 'e', inv
DA DEBUG_FILE_XFER, <pop ax>
stc
jmp done
KernelSafeFileRead endp
COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
KernelSafeLock
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
SYNOPSIS: Lock a handle in the kernel without chance of being
blown up.
CALLED BY: Kernel_ReadMem, Kernel_WriteMem, Kernel_FillMem
PASS: BX = handle ID to lock
RETURN: Carry set if couldn't lock the block. If so, an RPC_SWAPPED
error has already been returned.
ES = segment address for block if locked.
DESTROYED: ax
PSEUDO CODE/STRATEGY:
If block resident, call MemLock on it and return carry clear
Else, if block discarded, send error and return carry set
Else if dosSem free, call MemLock anyway and let the kernel
swap the block in (can only do this if the semaphore
is free b/c if we try to context switch out of
kernel mode [which is what we're in], the kernel
will abort)
Else send error and return carry set.
KNOWN BUGS/SIDE EFFECTS/IDEAS:
REVISION HISTORY:
Name Date Description
---- ---- -----------
ardeb 11/20/88 Initial version
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@
KernelSafeLock proc near
uses si, cx, dx, bx
.enter
;
; If not attached, kernel not loaded, so can't do anything here.
;
tst ds:[kernelCore]
jz KSLError
mov es, ds:[kdata]
mov ax, es:[bx].HM_addr
cmp ax, 0xF000 ; Is this a handle to something special?
jae KSLError
test es:[bx].HM_flags, MASK HF_FIXED
jz KSL1
;
; Block is fixed, so just fetch its address into ES, clear
; the carry and return.
;
KSLRetAX:
mov es, ax
clc
done:
.leave
ret
KSL1:
;
; See if the block is resident...
;
tst ax
jz KSLNonResident
cmp es:[bx].HM_lockCount, 255 ; pseudo-fixed?
je KSLRetAX
inc es:[bx].HM_lockCount ; Lock the block (for
; consistency with swapped-in
; blocks).
jmp KSLRetAX
KSLNonResident:
DPC DEBUG_XIP, 'l'
test es:[bx].HM_flags, MASK HF_SWAPPED
jnz notXIP ; swapped XIP handles should be treated
; like non-XIP handles (atw - 4/96)
; lets see if its an XIP handle, and if so, just bank it in
; rather than calling ReadMem, we must be sure to save
; away the currently banked in page number so we can
; restore in on the call to MemUnlock
call Kernel_TestForXIPHandle
cmp dx, BPT_NOT_XIP
je notXIP
call Kernel_SafeMapXIPPage ; dx is already page number
mov ax, cx
shr ax
shr ax
shr ax
shr ax
add ax, bx
jmp KSLRetAX
KSLError:
;
; Don't return an error here if the call being processed is the
; HELLO call sent down to connect to the kernel...this allows the
; user to attach even if a core block is swapped out and can't
; be swapped back in again.
;
cmp ds:[rpc_LastCall].RMB_header.rh_procNum, RPC_HELLO
je errorDone
; READ_GEODE wants to handle its own error conditions as well
cmp ds:[rpc_LastCall].RMB_header.rh_procNum, RPC_READ_GEODE
je errorDone
mov ax, RPC_SWAPPED ; Tell the host we can't access that
; block.
call Rpc_Error
errorDone:
stc
jmp done
notXIP:
;
; Non-resident. Was it discarded?
;
test es:[bx].HM_flags, MASK HF_DISCARDED
jnz KSLError ; Discarded -- honk
;
; Can we force it to be swapped in?
;
mov si, ds:[dosSemOff]
cmp es:[si].Sem_value, 0
jle KSLError ; Semaphore taken -- honk
;
; Heap semaphore already held? (i.e. will we c-switch if
; we call MemLock?)
;
mov si, ds:[heapSemOff]
cmp es:[si].Sem_value, 0
jle KSLError ; Choke -- MemLock will block.
;
; Masquerade as the block's owner so the kernel doesn't
; abort, should the block not be shareable
;
; Put a signature in here so that some EC code in SysLockCommon
; can tell that this is the swat stub and not really the kernel.
call KernelSetSwatStubFlag
push ss:[TPD_processHandle]
mov ax, es:[bx].HM_owner
mov ss:[TPD_processHandle], ax
;
; Set the segment portion of MemLockVec to match kcode.
;
mov ax, ds:[kcodeSeg]
mov ds:[MemLockVec].segment, ax
;
; Save both words of the header (XXX) so any reply knows where to
; go. We have to do this b/c the locking of a block with HF_DEBUG
; set causes a message to be sent up and responded to, overwriting
; the rpc_LastCall buffer. -- ardeb 4/20/92
;
push {word}ds:[rpc_LastCall].RMB_header,
{word}ds:[rpc_LastCall].RMB_header+2
push ds
mov ax, 0
mov ds, ax ; defeat ec +segment by not passing
; DS as ourself. ES is kdata, so it's
; fine.
call cs:[MemLockVec] ; Call through MemLock vector to lock/
; swap in the block. Returns
; dataAddress in AX and carry clear.
pop ds
pop {word}ds:[rpc_LastCall].RMB_header,
{word}ds:[rpc_LastCall].RMB_header+2
pop ss:[TPD_processHandle]
jc KSLError
jmp KSLRetAX
KernelSafeLock endp
COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
Kernel_SafeMapXIPPage
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
SYNOPSIS: map in an XIP page using the kernels routine to do so
CALLED BY: Kernel_BlockInfo
PASS: dx = page number, or BPT_NOT_XIP if restoring previous
RETURN: carry set if not attached
bx = segment of mapped page
DESTROYED: ax
PSEUDO CODE/STRATEGY:
KNOWN BUGS/SIDE EFFECTS/IDEAS:
REVISION HISTORY:
Name Date Description
---- ---- -----------
jimmy 4/94 Initial Version
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@
Kernel_SafeMapXIPPage proc near
uses di, es
.enter
;
; If not attached, kernel not loaded, so can't do anything here.
;
DPC DEBUG_XIP, 'M'
DPW DEBUG_XIP, dx
DPW DEBUG_XIP, ds
tst ds:[kernelCore]
jz error
tst ds:[xipHeader]
jz error ; => not XIP system
;
; Fetch the current page so we can save it or see if we need to do
; any further work, once we've determined what page we're trying to map
;
mov es, ds:[kdata]
mov di, ds:[curXIPPageOff]
mov di, es:[di]
cmp dx, BPT_NOT_XIP
jne saveCurPage
;
; Restoring the previous page, so fetch that out of oldXIPPage and set
; DX to that former page.
;
xchg ds:[oldXIPPage], dx
jmp havePage
saveCurPage:
;
; Record the current page for restoration.
;
mov ds:[oldXIPPage], di
havePage:
; if the new one is the same as the current one, do nothing else
DPW DEBUG_XIP, di
mov bx, ds:[xipPageAddr] ; assume same...
cmp di, dx
je done ; carry set to zero when equal
;
; Set the segment portion of MapXIPPageVec to match kcode.
;
mov ax, ds:[kcodeSeg]
mov ds:[MapXIPPageVec].segment, ax
; Put a signature in here so that some EC code in SysLockCommon
; can tell that this is the swat stub and not really the kernel.
call KernelSetSwatStubFlag
push ds
segmov ds, es ; ds is kdata for MapXIPPage
DPC DEBUG_XIP, 'p'
DPW DEBUG_XIP, cs:[MapXIPPageVec].segment
DPW DEBUG_XIP, cs:[MapXIPPageVec].offset
call cs:[MapXIPPageVec] ; bx <- map segment
pop ds
DPW DEBUG_XIP, bx
clc
done:
.leave
ret
error:
DPC DEBUG_XIP, 'm'
DPW DEBUG_XIP, dx
stc
jmp done
Kernel_SafeMapXIPPage endp
COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
KernelSafeUnlock
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
SYNOPSIS: Unlock a block safely (i.e. without making the kernel die)
CALLED BY: Kernel_ReadMem, Kernel_WriteMem, Kernel_FillMem
PASS: BX = HandleMem to unlock
RETURN: Nothing
DESTROYED: Nothing
PSEUDO CODE/STRATEGY:
KNOWN BUGS/SIDE EFFECTS/IDEAS:
REVISION HISTORY:
Name Date Description
---- ---- -----------
ardeb 11/21/88 Initial version
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@
KernelSafeUnlock proc near
uses es, di, ax, dx, ds
.enter
DPC DEBUG_XIP, 'U'
DPW DEBUG_XIP, bx
DPW DEBUG_XIP, ds
;
; S.O.R.
;
;
; If block is FIXED, no need to unlock it.
;
PointDSAtStub ; make sure ds = scode
mov es, cs:[kdata]
test es:[bx].HM_flags, MASK HF_FIXED
jnz KSURet
cmp es:[bx].HM_lockCount, 255 ; pseudo-fixed?
je KSURet
; if its already in memory, just decrement its lock count
tst es:[bx].HM_addr
jnz notXIP
; if its an XIP handle, we should bank in whatever we unbanked
; when we did the MemLock
push cx
call Kernel_TestForXIPHandle
pop cx
cmp dx, BPT_NOT_XIP
je notXIP
DPC DEBUG_XIP, 'X'
push bx
mov dx, BPT_NOT_XIP ; dx <- restore previous
call Kernel_SafeMapXIPPage
pop bx
jmp KSURet
notXIP:
;
; Decrement the lock count of the block. MemUnlock does
; other things (like updating heapCounter and the block's
; usageValue), but a) it's unnecessary and b) we (as the
; debugger) want to disturb as little as possible.
;
dec es:[bx].HM_lockCount
KSURet:
;
; R.O.R.
;
.leave
ret
KernelSafeUnlock endp
COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
Kernel_ReadMem
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
SYNOPSIS: Read memory from a handle
CALLED BY: Rpc_Wait
PASS: ReadArgs structure in CALLDATA
RETURN: Nothing
DESTROYED: SI, DI, CX, AX, BX
PSEUDO CODE/STRATEGY:
Load the handle ID into BX and lock it using KernelSafeLock
If lock unsuccessful, return
Else set up for a repeated MOVSB and do that into rpc_ToHost
Unlock the handle
Call Rpc_Reply to send the data back to the host.
KNOWN BUGS/SIDE EFFECTS/IDEAS:
REVISION HISTORY:
Name Date Description
---- ---- -----------
ardeb 11/20/88 Initial version
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@
Kernel_ReadMem proc near
push es
DPC DEBUG_FALK3, 'A'
;
; Load SI and CX with the offset and count for the transfer
; of bytes from the block. ES contains the segment, so
; all we need to do is call Rpc_Reply -- it will copy the
; bytes into the output queue...
;
clr ecx
mov si, ({ReadArgs}CALLDATA).ra_offset
mov cx, ({ReadArgs}CALLDATA).ra_numBytes
call Rpc_ReplyCCOut
mov bx, ({ReadArgs}CALLDATA).ra_handle
DPC DEBUG_XIP, 'R'
DPW DEBUG_XIP, si
DPW DEBUG_XIP, cx
DPW DEBUG_XIP, bx
call KernelSafeLock
jc done ; No access -- KernelSafeLock will have sent
; the error message for us.
push bx
mov bx, es
mov dx, si
call GPMISelectorCheckLimits ; cx adjusted to bounds
pop bx
jc selectorBad
reply:
DPC DEBUG_FALK3, 'B'
call Rpc_Reply
;
; Unlock the block -- BX still contains the handle ID
;
DPC DEBUG_FALK, 'C'
call KernelSafeUnlock
done:
DPC DEBUG_FALK, 'D'
pop es
ret
selectorBad:
; No selector? Copy nothing in the reply then
clr ecx
segmov es, cs
clr si
jmp reply
Kernel_ReadMem endp
COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
KernelCalculateBlockSum
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
SYNOPSIS: Calculate the new/current checksum for the block.
CALLED BY: KernelUndoChecksum, KernelRecalcChecksum
PASS: es = kdata
bx = block handle
ds = segment of locked block
RETURN: ax = checksum
DESTROYED: nothing
PSEUDO CODE/STRATEGY:
KNOWN BUGS/SIDE EFFECTS/IDEAS:
REVISION HISTORY:
Name Date Description
---- ---- -----------
ardeb 3/17/92 Initial version
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@
KernelCalculateBlockSum proc near
uses cx, si, di
.enter
mov cx, es:[bx].HM_size
DPW DEBUG_MEM_WRITE, bx
DPW DEBUG_MEM_WRITE, cx
; generate the checksum -- cx = # paragraphs
clr si
clr di ;di = checksum
addLoop:
lodsw ;1
add di, ax
lodsw ;2
add di, ax
lodsw ;3
add di, ax
lodsw ;4
add di, ax
lodsw ;5
add di, ax
lodsw ;6
add di, ax
lodsw ;7
add di, ax
lodsw ;8
add di, ax
loop addLoop
; di = checksum (if 0 then make 1)
tst di
jnz done
inc di
done:
mov_tr ax, di
.leave
ret
KernelCalculateBlockSum endp
COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
KernelUndoChecksum
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
SYNOPSIS: Remove the words we're about to overwrite from the EC block
checksum, if they're there.
CALLED BY: Kernel_WriteMem
PASS: es:di = start of affected range
ds = cgroup
cx = # bytes in affected range
bx = handle of block being written
RETURN: ax = checksum to pass to KernelRecalcChecksum
= 0 if checksum shouldn't be generated after the
write (if kernel hasn't generated the sum yet,
or the checksum is invalid before the write)
DESTROYED: nothing
PSEUDO CODE/STRATEGY:
KNOWN BUGS/SIDE EFFECTS/IDEAS:
REVISION HISTORY:
Name Date Description
---- ---- -----------
ardeb 3/16/92 Initial version
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@
KernelUndoChecksum proc near
uses ds, es, si
.enter
DPC DEBUG_MEM_WRITE, 'w'
DPW DEBUG_MEM_WRITE, cx
clr ax
tst ds:[sysECBlockOff]
jz done ; => non-ec
;
; See if the write falls within the current checksum block.
;
push es
mov si, ds:[sysECBlockOff]
mov es, ds:[kdata] ; es:si <- sysECBlock
cmp bx, es:[si] ; same block?
pop ds ; ds:di <- start of affected
; range
jne done ; not same block
call KernelCalculateBlockSum ; ax <- sum
DPW DEBUG_MEM_WRITE, ax
mov si, cs:[sysECChecksumOff]
cmp ax, es:[si]
je done
DA DEBUG_MEM_WRITE, <lodsw es:>
DPW DEBUG_MEM_WRITE, ax
clr ax
done:
.leave
ret
KernelUndoChecksum endp
COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
KernelRecalcChecksum
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
SYNOPSIS: Recalculate the EC block checksum using the words we just
wrote
CALLED BY: Kernel_WriteMem
PASS: es = segment of locked block
ax = checksum from which to start (0 if shouldn't
calculate a new sum)
bx = block being written to
ds = cgroup
RETURN: nothing
DESTROYED: ax, cx, si
PSEUDO CODE/STRATEGY:
KNOWN BUGS/SIDE EFFECTS/IDEAS:
REVISION HISTORY:
Name Date Description
---- ---- -----------
ardeb 3/16/92 Initial version
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@
KernelRecalcChecksum proc near
uses bx, ds, es
.enter
DA DEBUG_MEM_WRITE, <push ax>
DPC DEBUG_MEM_WRITE, 'r'
DA DEBUG_MEM_WRITE, <pop ax>
DPW DEBUG_MEM_WRITE, ax
tst ax ; are we to generate things?
jz done ; no
mov ax, ds:[kdata]
mov cx, es
mov ds, cx ; ds <- block
mov es, ax ; es <- kdata
call KernelCalculateBlockSum ; ax <- new sum
mov si, cs:[sysECChecksumOff]; es:si <- sysECChecksum
mov es:[si], ax
DPW DEBUG_MEM_WRITE, ax
done:
.leave
ret
KernelRecalcChecksum endp
COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
Kernel_WriteMem
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
SYNOPSIS: Write memory into a block via its handle
CALLED BY: Rpc_Wait
PASS: WriteArga and data in CALLDATA
number of bytes in rpc_LastCall.RMB_header.rh_length
RETURN: Nothing
DESTROYED: SI, DI, CX, AX, BX
PSEUDO CODE/STRATEGY:
KNOWN BUGS/SIDE EFFECTS/IDEAS:
REVISION HISTORY:
Name Date Description
---- ---- -----------
ardeb 11/20/88 Initial version
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@
Kernel_WriteMem proc near
uses es, dx
.enter
;
; Load DI and CX with the offset and count for the transfer
; of bytes to the block. The number of bytes to write is
; encoded in the header for the RPC as Rpc_Length() -
; size WriteArgs. The data to be written are at size WriteArgs
; bytes from the start of the argument buffer (CALLDATA)
;
mov di, ({WriteArgs}CALLDATA).wa_offset
call Rpc_Length
sub cx, size WriteArgs
mov bx, ({WriteArgs}CALLDATA).wa_handle
call KernelSafeLock
jc KWMRet ; No access -- KernelSafeLock
; will have sent the error
; message for us.
mov si, offset CALLDATA + size WriteArgs
;
; Make sure this write won't affect our state block.
;
mov ax, es
mov dx, bp
cmp ax, sstack
je checkState
cmp ax, cgroup
jne doWrite
;
; Normalize the current value of bp to be relative to cgroup,
; not sstack, for valid comparison...
;
mov dx, sstack
sub dx, cgroup
shl dx
shl dx
shl dx
shl dx
add dx, bp
checkState:
mov ax, dx
add ax, size StateBlock
cmp di, ax
jae doWrite ; => starts after state, so ok
mov ax, cx
add ax, di
cmp ax, dx
jbe doWrite ; => ends before state, so ok
mov ax, dx
sub ax, di
jb moveStart ; => state is < di, so want to
; move di beyond the end of
; the state block
mov_tr cx, ax ; else di < state, so move in
; only enough bytes to get up
; to the state block, but no
; farther
jmp doWrite
moveStart:
mov ax, dx
add ax, size StateBlock ; ax <- end of state block
sub ax, di ; ax <- # bytes to skip
add di, ax ; skip that many in dest
add si, ax ; and source
sub cx, ax ; remove that many from length
doWrite:
; XXX: In theory, the bytes following the WriteArgs structure could
; have been biffed by a transaction during the call to KernelSafeLock.
; In practice, the only thing coming down from the host will be
; an RpcHeader that is a zero-length reply to whatever call we
; sent up.
;
; Deal with the checksummed block.
;
call KernelUndoChecksum ; ax <- checksum w/o words
; about to be overwritten
push ax
call Kernel_EnsureESWritable
push ax
dsi
cld
if _WRITE_ONLY_WORDS
; For these versions, we can only WRITE WORDS out to the memory.
call Kernel_CopyMemWordAligned
else ;_WRITE_ONLY_WORDS is FALSE
test cx, 1
jz KWM2
movsb ; Move single byte
dec cx
jcxz KWM3
KWM2:
; Aha! But in Protected Mode, we need to ensure we can't write past our limits
push bx, dx
mov bx, es
mov dx, di
call GPMISelectorCheckLimits ; cx adjusted to bounds
pop bx, dx
shr cx, 1 ; Move words
rep movsw
KWM3:
endif ;_WRITE_ONLY_WORDS
eni
pop ax
call Kernel_RestoreWriteProtect
pop ax
;
; Deal with the checksummed block.
;
call KernelRecalcChecksum
;
; Send null reply.
;
clr cx
call Rpc_Reply
;
; Unlock the block -- BX still contains the handle ID
;
call KernelSafeUnlock
KWMRet:
.leave
ret
Kernel_WriteMem endp
COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
Kernel_FillMem
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
SYNOPSIS: Fill memory in a block with a byte
CALLED BY: Rpc_Wait
PASS: FillArgs structure in CALLDATA
RETURN: Nothing
DESTROYED: DI, CX, AX, BX
PSEUDO CODE/STRATEGY:
KNOWN BUGS/SIDE EFFECTS/IDEAS:
REVISION HISTORY:
Name Date Description
---- ---- -----------
ardeb 11/20/88 Initial version
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@
Kernel_FillMem proc near
push es
;
; Load DI and CX with the offset and count for the transfer
; of bytes to the block.
;
mov di, ({FillArgs}CALLDATA).fa_offset
mov cx, ({FillArgs}CALLDATA).fa_length
cld
mov bx, ({FillArgs}CALLDATA).fa_handle
call KernelSafeLock
jc KFMRet ; No access -- KernelSafeLock
; will have sent the error
; message for us.
call Kernel_EnsureESWritable
mov_tr dx, ax
mov ax, ({FillArgs}CALLDATA).fa_value
cmp ds:[rpc_LastCall].RMB_header.rh_procNum, RPC_FILL_MEM8
jne KFMWord
rep stosb
jmp short KFMDone
KFMWord:
rep stosw
KFMDone:
mov_tr ax, dx
call Kernel_RestoreWriteProtect
;
; Send null reply.
;
clr cx
call Rpc_Reply
;
; Unlock the block -- BX still contains the handle ID
;
call KernelSafeUnlock
KFMRet:
pop es
ret
Kernel_FillMem endp
COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
Kernel_ReadAbs
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
SYNOPSIS: Read from absolute memory (server for RPC_READ_ABS)
CALLED BY: Rpc_Wait
PASS: AbsReadArgs in CALLDATA
RETURN: Nothing
DESTROYED: EBX, ECX, DX, SI, DI
PSEUDO CODE/STRATEGY:
KNOWN BUGS/SIDE EFFECTS/IDEAS:
REVISION HISTORY:
Name Date Description
---- ---- -----------
ardeb 11/21/88 Initial version
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@
Kernel_ReadAbs proc near
push es
;
; Load the registers for the transfer. CX comes from the
; ara_numBytes field of the request, while ES:SI is loaded from
; the ara_offset and ara_segment fields.
;
clr ecx
mov cx, ({AbsReadArgs}CALLDATA).ara_numBytes
call Rpc_ReplyCCOut
xor edx, edx
mov bx, ({AbsReadArgs}CALLDATA).ara_segment
mov dx, ({AbsReadArgs}CALLDATA).ara_offset
.inst db 00fh, 000h, 0e3h ; verr bx
jnz selectorBad ; branch if selector unreadable
call GPMISelectorCheckLimits
jc selectorBad ; branch if GPMI objects
call GPMITestPresent
jc selectorBad ; branch if not present
les si, dword ptr ({AbsReadArgs}CALLDATA).ara_offset
dontUseSelector:
call Rpc_Reply
pop es
ret
selectorBad:
; No selector? Copy nothing in the reply then
clr ecx
segmov es, cs
clr si
jmp dontUseSelector
Kernel_ReadAbs endp
COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
Kernel_WriteAbs
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
SYNOPSIS: Write data to an absolute location
CALLED BY: Rpc_Wait
PASS: CALLDATA contains an AbsWriteArgs structure
RETURN: Null Reply
DESTROYED: ...
PSEUDO CODE/STRATEGY:
KNOWN BUGS/SIDE EFFECTS/IDEAS:
REVISION HISTORY:
Name Date Description
---- ---- -----------
ardeb 11/21/88 Initial version
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@
Kernel_WriteAbs proc near
push es
;
; Load the registers for the transfer. CX returned by
; Rpc_Length function, while ES:DI is loaded from the awa_offset
; and awa_segment fields.
;
; SI is just CALLDATA + size AbsWriteArgs since the data
; follow the args immediately.
;
call Rpc_Length
sub cx, size AbsWriteArgs
les di, dword ptr ({AbsWriteArgs}CALLDATA).awa_offset
mov si, offset CALLDATA + size AbsWriteArgs
call Kernel_EnsureESWritable
;
; Move the requested data into memory.
;
cld
dsi
if _WRITE_ONLY_WORDS
; For these versions, we can only WRITE WORDS out to the memory.
push ax
call Kernel_CopyMemWordAligned
pop ax
else ;_WRITE_ONLY_WORDS is FALSE
rep movsb
endif ;_WRITE_ONLY_WORDS
eni
call Kernel_RestoreWriteProtect
;
; Restore ES to cgroup for the reply (which is NULL)
;
pop es
clr cx
call Rpc_Reply
ret
Kernel_WriteAbs endp
COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
Kernel_CopyMemWordAligned
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
SYNOPSIS: Copies a chunk of memory but does it so that only words
are written out. This is for the stub versions where
_WRITE_ONLY_WORDS is TRUE. Some devices are incapable of
writing unaligned bytes to certain areas of memory.
CALLED BY: Kernel_WriteAbs, Kernel_WriteMem (_WRITE_ONLY_WORDS only)
PASS: ds:si = source
es:di = dest
cx = count
RETURN: nothing
DESTROYED: di, si, cx, ax
SIDE EFFECTS:
NOTE: This does NOT disable interrupts, so if you want them
disabled, do it before you call.
PSEUDO CODE/STRATEGY:
REVISION HISTORY:
Name Date Description
---- ---- -----------
JimG 3/ 2/95 Initial version
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@
if _WRITE_ONLY_WORDS
Kernel_CopyMemWordAligned proc near
.enter
test di, 1
jz evenStart
; Odd starting point. Read back the word containing the odd byte from
; SRAM. Then read the byte from the buffer into the high byte and
; write the word back out.
dec di ; back up to word bndry
mov ax, {word} es:[di]
mov ah, {byte} ds:[si]
mov {word} es:[di], ax
inc di ; move dest to next word
inc di
inc si ; move src to next byte
dec cx ; one less byte
evenStart:
tst cx
jz doneWithCopy
; Do the bulk of the copy with repsw
shr cx, 1
rep movsw
jnc doneWithCopy ; even count - done
; Odd count.. copy last byte, writing words.
mov ax, {word} es:[di]
mov al, {byte} ds:[si]
mov {word} es:[di], ax
doneWithCopy:
.leave
ret
Kernel_CopyMemWordAligned endp
endif ;_WRITE_ONLY_WORDS
COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
Kernel_FillAbs
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
SYNOPSIS: Fill a range of memory at an absolute address
CALLED BY: Rpc_Wait
PASS: AbsFillArgs structure in CALLDATA
RETURN: Null reply
DESTROYED: ...
PSEUDO CODE/STRATEGY:
KNOWN BUGS/SIDE EFFECTS/IDEAS:
REVISION HISTORY:
Name Date Description
---- ---- -----------
ardeb 11/21/88 Initial version
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@
Kernel_FillAbs proc near
push es
;
; Load the registers for the fill. CX comes from the
; afa_length field of the request, while ES:DI is
; loaded from the afa_offset and afa_segment fields.
;
mov cx, ({AbsFillArgs}CALLDATA).afa_length
les di, dword ptr ({AbsFillArgs}CALLDATA).afa_offset
cld
call Kernel_EnsureESWritable
mov_tr bx, ax
mov ax, ({AbsFillArgs}CALLDATA).afa_value
cmp ds:[rpc_LastCall].RMB_header.rh_procNum, RPC_FILL_ABS8
jne KFAWord
;
; Fill the requested area of memory.
;
rep stosb
jmp short KFADone
KFAWord:
rep stosw
KFADone:
mov_tr ax, bx
call Kernel_RestoreWriteProtect
;
; Restore ES to cgroup for the reply (which is NULL)
;
pop es
clr cx
call Rpc_Reply
ret
Kernel_FillAbs endp
COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
KernelMapOwner
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
SYNOPSIS: Deal with ownership by things other than Geodes
CALLED BY: Kernel_BlockInfo, Kernel_BlockFind
PASS: ES = kdata
AX = owner ID
RETURN: AX = owner ID to return
DESTROYED: Nothing
PSEUDO CODE/STRATEGY:
There are things in this system (e.g. VM blocks) that are
owned by a handle other than a Geode (a VM block is owned
by its corresponding VMHandle). This is not something Swat
can deal with. To get around this, we examine the owner's
signature to make sure the thing is actually a memory handle.
If it ain't, we return HID_KDATA so Swat thinks it's owned
by the kernel.
KNOWN BUGS/SIDE EFFECTS/IDEAS:
REVISION HISTORY:
Name Date Description
---- ---- -----------
ardeb 5/15/89 Initial version
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@
KernelMapOwner proc near
push bx
mov bx, ax
cmp ax, ds:[HandleTable] ; Handle font blocks and
; things owned by the kernel
; w/o having to hope that
; kdata:11h or kdata:21h
; contains a value >= f8h
jb ownedByKernel
cmp es:[bx].HM_addr.high, SIG_NON_MEM
jb KMORet ; Is memory handle, is ok
ownedByKernel:
mov ax, ds:[kernelCore]; Ewwww. Map it to kernel ownership
KMORet:
pop bx
ret
KernelMapOwner endp
COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
Kernel_XIPSegmentToHandle
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
SYNOPSIS: map a segment to a handle for an XIP handle
CALLED BY: GLOBAL
PASS: cx = segment address
ds = scode
ax = xipPage to use (BPT_NOT_XIP to use currentPage)
RETURN: carry clear if XIP:
cx = handle (may not be mapped, if ax was
BPT_NOT_XIP on entry)
ax = address of handle
dx = page number
carry set if not:
ax, cx, dx = unchanged if cx was outside the
XIP map bank. destroyed if it was
inside the map bank.
DESTROYED: Nada.
PSEUDOCODE/STRATEGY:
KNOWN BUGS/SIDEFFECTS/IDEAS:
REVISION HISTORY:
Name Date Description
---- ---- -----------
jimmy 4/26/94 Initial version.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@
Kernel_XIPSegmentToHandle proc near
uses es, bp, bx, ds, di, si
.enter
DA DEBUG_XIP, <push ax>
DPC DEBUG_XIP, 't'
DPW DEBUG_XIP, cx
DA DEBUG_XIP, <pop ax>
call Kernel_CheckXIPSegment ; ax <- page #
jnc notXIPHandle
; loop through the XIP handle table to find the offset within the
; page
DPW DEBUG_XIP, ax
mov es, ds:[xipHeader]
mov bp, ds:[HandleTable]
mov dx, ds:[xipPageAddr] ; (save for later)
mov ds, ds:[kdata]
mov bx, es:[FXIPH_handleAddresses]
; first, compute the offset of the thing within the map page
sub cx, dx
shl cx
shl cx
shl cx
shl cx
searchLoop:
cmp ax, es:[bx].high ; same xip page?
jne doNext ; no
mov di, es:[bx].low
cmp cx, di ; same offset?
jb doNext ; no
mov si, ds:[bp].HM_size ; compute first byte
shl si ; not in the resource
shl si
shl si
shl si
add si, di
cmp si, cx
ja foundXIP ; => is within resource
doNext:
add bx, size dword
add bp, size HandleMem
cmp bp, es:[FXIPH_lastXIPResource]
jbe searchLoop
notXIPHandle:
stc
jmp done
foundXIP:
mov cx, bp ; cx <- handle
DA DEBUG_XIP, <push ax>
DPC DEBUG_XIP, 'f'
DPW DEBUG_XIP, cx
DA DEBUG_XIP, <pop ax>
xchg ax, di ; ax <- actual page offset
; di <- page number
shr ax
shr ax
shr ax
shr ax
add ax, dx ; dx = segment address of XIP page from above
DPW DEBUG_XIP, ax
mov dx, di ; dx <- page number
clc
done:
.leave
ret
Kernel_XIPSegmentToHandle endp
COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
Kernel_CheckXIPSegment
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
SYNOPSIS: Check a segment to see if it falls within the XIP map bank
and return its page number if so
CALLED BY: (EXTERNAL)
PASS: ds = scode
cx = segment
ax = presumed page number if it's in the map bank
= BPT_NOT_XIP if page should be gotten from the kernel
RETURN: carry set if segment falls within map bank:
ax = page number
carry clear if segment not within map bank:
ax = unchanged
DESTROYED: nothing
SIDE EFFECTS:
PSEUDO CODE/STRATEGY:
REVISION HISTORY:
Name Date Description
---- ---- -----------
ardeb 12/21/94 Initial version
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@
Kernel_CheckXIPSegment proc near
uses es, dx, bx
.enter
tst ds:[xipHeader]
jz notXIPHandle ; => not an XIP kernel
mov dx, ds:[xipPageAddr]
cmp cx, dx
jb notXIPHandle ; => below map bank
add dx, ds:[xipPageSize]
cmp cx, dx
jae notXIPHandle ; => above map bank
cmp ax, BPT_NOT_XIP
jne gotXIPPage
mov es, ds:[kdata]
mov bx, ds:[curXIPPageOff]
mov ax, es:[bx]
gotXIPPage:
stc
done:
.leave
ret
notXIPHandle:
clc
jmp done
Kernel_CheckXIPSegment endp
COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
Kernel_GetHandleAddress
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
SYNOPSIS: get an address given a handle
CALLED BY: GLOBAL
PASS: es:bx = HandleMem
RETURN: ax = segment address of handle
DESTROYED: Nada.
PSEUDOCODE/STRATEGY: see if its an XIP handle, if so do the XIP thang
else return es:[bx].HM_addr
KNOWN BUGS/SIDEFFECTS/IDEAS:
REVISION HISTORY:
Name Date Description
---- ---- -----------
jimmy 4/26/94 Initial version.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@
Kernel_GetHandleAddress proc far
uses cx, dx
.enter
call Kernel_TestForXIPHandle
cmp dx, BPT_NOT_XIP
je notXIP
done:
.leave
ret
notXIP:
mov ax, es:[bx].HM_addr
call GPMITestPresent
jnc done
clr ax ;selector isn't present
jmp done
Kernel_GetHandleAddress endp
COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
Kernel_TestForXIPHandle
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
SYNOPSIS: see if we have an XIP handle, if so return its address
CALLED BY: GLOBAL
PASS: bx = handle
ds = scode
RETURN: ax = address of segment (or what it would be if mapped in)
dx = page number, dx = BPT_NOT_XIP if not XIP handle
cx = page offset
carry set if not an XIP handle or not mapped in
DESTROYED:
PSEUDOCODE/STRATEGY:
KNOWN BUGS/SIDEFFECTS/IDEAS:
REVISION HISTORY:
Name Date Description
---- ---- -----------
jimmy 4/26/94 Initial version.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@
Kernel_TestForXIPHandle proc far
uses es, bx, bp, ds
.enter
DPC DEBUG_XIP, 'T'
; check to see if the handle is an XIP handle
PointDSAtStub
tst ds:[xipHeader]
jz notXIP
DPC DEBUG_XIP, 't'
mov es, ds:[xipHeader]
mov cx, es:[FXIPH_lastXIPResource]
; if the handle is greater than the lastXIPResource handle then it's
; not an XIP handle
cmp bx, cx
ja notXIP
; first see if its a Fixed or psuedo fixed handle, if so it
; just acts like a NON-XIP handle
mov es, ds:[kdata]
mov ax, es:[bx].HM_addr
test es:[bx].HM_flags, mask HF_FIXED
jnz notXIP
cmp es:[bx].HM_lockCount, 0ffh
je notXIP
mov es, ds:[xipHeader]
; it IS an XIP handle so let's decode it. First fetch the page & offset
; from the FXIPH_handleAddresses table
DPC DEBUG_XIP, 'm'
push bx
sub bx, ds:[HandleTable]
shr bx ; (bx - handleTable)/16 = handle index
shr bx ; index * 4 = offset into XIP map
; so just get (bx-handleTable)/4
add bx, es:[FXIPH_handleAddresses]
movdw dxcx, es:[bx] ; dx <- page, cx <- offset w/in page
; (for return)
pop bx
; compute the segment within the bank page, for return
mov ax, cx
shr ax
shr ax
shr ax
shr ax
add ax, ds:[xipPageAddr]
; see if the thing is currently mapped in
mov es, ds:[kdata]
mov bp, ds:[curXIPPageOff]
cmp es:[bp], dx
jne notMappedIn
doneOK::
clc ; signal mapped
done:
.leave
ret
notXIP:
mov dx, BPT_NOT_XIP
notMappedIn:
stc
jmp done
Kernel_TestForXIPHandle endp
COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
Kernel_BlockInfo
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
SYNOPSIS: Return the data for a handle.
CALLED BY: Rpc_Wait
PASS: Handle ID in CALLDATA
RETURN: dataAddress, paraSize, handleFlags
DESTROYED: rpc_ToHost
PSEUDO CODE/STRATEGY:
KNOWN BUGS/SIDE EFFECTS/IDEAS:
REVISION HISTORY:
Name Date Description
---- ---- -----------
ardeb 11/21/88 Initial version
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@
Kernel_BlockInfo proc near
push es
tst ds:[kernelCore]
jz KBIBad
;
; Load ES:BX to point to the handle record
;
mov es, ds:[kdata]
mov bx, {word}CALLDATA
cmp bx, ds:[HandleTable]
jb KBIBad
cmp bx, ds:[lastHandle]
ja KBIBad
; assume non-xip handle
mov dx, BPT_NOT_XIP
tst ds:[xipHeader]
jz notXIP
tst es:[bx].HM_addr
jnz notXIP
call Kernel_TestForXIPHandle
cmp dx, BPT_NOT_XIP
jne gotAddr
notXIP:
;
; Transfer the desired fields into an InfoReply structure in
; the standard reply area.
;
mov ax, es:[bx].HM_addr
call GPMITestPresent
jnc gotAddr
clr ax ;selector isn't present
gotAddr:
mov ({InfoReply}ds:[rpc_ToHost]).ir_dataAddress, ax
tst ax
jnz KBI10
;
; No data associated with the handle. Make sure the handle
; itself isn't free (free handles have an owner of 0)
;
tst es:[bx].HM_owner
jz KBIBad ; choke
KBI10:
cmp ah, SIG_THREAD
je threadInfo
mov al, es:[bx].HM_flags
mov ({InfoReply}ds:[rpc_ToHost]).ir_flags, al
mov ax, es:[bx].HM_size
mov ({InfoReply}ds:[rpc_ToHost]).ir_paraSize, ax
mov ax, es:[bx].HM_otherInfo
mov ({InfoReply}ds:[rpc_ToHost]).ir_otherInfo, ax
storeOwner:
mov ({InfoReply}ds:[rpc_ToHost]).ir_xipPage, dx
mov ax, es:[bx].HM_owner
call KernelMapOwner
mov ({InfoReply}ds:[rpc_ToHost]).ir_owner, ax
;
; Restore ES for the reply and load up CX and SI.
;
pop es
mov cx, size InfoReply
mov si, offset rpc_ToHost
call Rpc_Reply
ret
KBIBad:
pop es
mov ax, RPC_BADARGS
call Rpc_Error
ret
threadInfo:
;
; Return special stuff if the handle being returned is for
; a thread:
; - paraSize = max sp
; - otherInfo = ss
;
mov ax, es:[bx].HT_saveSS
cmp bx, ss:[bp].state_thread
jne checkSSBounds
; If it's the current thread, use the saved SS in our state
; block, not that in the handle...much more reliable.
mov ax, ss:[bp].state_ss
checkSSBounds:
if 0
push ds, bx
mov ds, ax
mov si, ds:[TPD_blockHandle]
mov bx, si ; es:bx = HandleMem
call Kernel_GetHandleAddress ; ax = address
mov bx, ds
cmp ax, bx
pop ds, bx
endif
push ds
mov ds, ax
mov si, ds:[TPD_blockHandle]
cmp ax, es:[si].HM_addr
pop ds
jne maybeInDOS
storeSS_SP:
mov ds:[({InfoReply}rpc_ToHost)].ir_otherInfo, ax
call KernelFindMaxSP
mov ds:[({InfoReply}rpc_ToHost)].ir_paraSize, ax
jmp storeOwner
maybeInDOS:
;
; Assume the thing is in DOS and return the saved SS and SP from
; our/the kernel's PSP
;
push es
mov es, ds:[PSP]
mov ax, es:[PSP_userStack].segment
pop es
jmp storeSS_SP
Kernel_BlockInfo endp
COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
Kernel_SegmentToHandle
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
SYNOPSIS: Map a segment to its associated handle, if possible.
CALLED BY: Kernel_BlockFind, Bpt_Set
PASS: cx = segment to map
ax = xip page (or BPT_NOT_XIP if xip page not known)
RETURN: carry set if not found
carry clear if handle found:
es:bx = HandleMem
ax = address, can't use es:bx.HM_addr as it might be an XIP
resource
dx = Xip page number or BPT_NOT_XIP if none
DESTROYED:
PSEUDO CODE/STRATEGY:
KNOWN BUGS/SIDE EFFECTS/IDEAS:
REVISION HISTORY:
Name Date Description
---- ---- -----------
ardeb 4/15/92 Initial version
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@
Kernel_SegmentToHandle proc near
uses cx, si
.enter
tst ds:[kernelCore]
jz done ; (carry is clear)
mov es, ds:[kdata]
;
; Deal with resource being loaded by checking the resourceBeingLoaded
; handle first, since our hack in KernelLoadRes yields two handles
; with the same segment...
;
mov bx, ds:[resourceBeingLoaded]
tst bx
jz checkXIPHandles
cmp cx, es:[bx].HM_addr
clc
je isXip
checkXIPHandles:
call Kernel_XIPSegmentToHandle
jc scanTable
mov bx, cx
jmp isXip
scanTable:
mov dx, ds:[lastHandle] ; Load last handle into DX
mov bx, ds:[HandleTable] ; Start at beginning of table
; (This puppy's static...)
scanLoop:
;
; Make sure it's a memory handle.
;
mov ax, es:[bx].HM_addr
cmp ah, SIG_NON_MEM ; non-memory handle?
jae nextBlock ; yes -- ignore it.
test es:[bx].HM_flags, mask HF_DISCARDED or mask HF_SWAPPED
jnz nextBlock ; ignore if discarded/swapped
;
; See if it matches
;
cmp ax, cx
jne nextBlock ; Close, but no cigar
;
; It does match. make sure it's neither free nor fake.
;
mov ax, es:[bx].HM_owner
tst ax ; See if it's free
jz nextBlock ; Free -- DON'T RETURN IT EVEN
; IF IT MATCHES.
cmp ax, ds:[kernelCore]
jne found
cmp es:[bx].HM_otherInfo, FAKE_BLOCK_CODE
jne found
cmp es:[bx].HM_lockCount, 1
jne found
cmp es:[bx].HM_flags, 0
je nextBlock
found:
; found the thing. (carry set)
mov cx, es:[bx].HM_addr
stc
jmp done
nextBlock:
;
; Advance to next handle
;
add bx, size HandleMem
cmp bx, dx
jb scanLoop
; (carry is clear after a failed jb)
done:
mov dx, BPT_NOT_XIP ; not XIP handle
mov_tr ax, cx ; get segment into ax
;
; Invert the carry, as when we get here it's clear on error and
; set if found.
;
cmc
isXip:
.leave
ret
Kernel_SegmentToHandle endp
COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
Kernel_BlockFind
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
SYNOPSIS: Locate the handle of a block given its dataAddress
CALLED BY: Rpc_Wait
PASS: Segment address in CALLDATA
RETURN: FindReply in rpc_ToHost
DESTROYED: Many things.
PSEUDO CODE/STRATEGY:
KNOWN BUGS/SIDE EFFECTS/IDEAS:
REVISION HISTORY:
Name Date Description
---- ---- -----------
ardeb 11/21/88 Initial version
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@
Kernel_BlockFind proc near
push es
mov cx, ({FindArgs}CALLDATA).fa_address; Load segment
; into CX
mov ax, ({FindArgs}CALLDATA).fa_xipPage
call Kernel_SegmentToHandle
jc KBFError
; ax returned from Kernel_SegmentToHandle with address
mov ({FindReply}ds:[rpc_ToHost]).fr_id, bx
mov ({FindReply}ds:[rpc_ToHost]).fr_dataAddress, ax
mov ax, es:[bx].HM_size
mov ({FindReply}ds:[rpc_ToHost]).fr_paraSize, ax
mov ax, es:[bx].HM_owner
call KernelMapOwner
mov ({FindReply}ds:[rpc_ToHost]).fr_owner, ax
mov ax, es:[bx].HM_otherInfo
mov ({FindReply}ds:[rpc_ToHost]).fr_otherInfo, ax
mov al, es:[bx].HM_flags
mov ({FindReply}ds:[rpc_ToHost]).fr_flags, al
mov ({FindReply}ds:[rpc_ToHost]).fr_xipPage, dx
pop es
mov cx, size FindReply
mov si, offset rpc_ToHost
call Rpc_Reply
ret
KBFError:
mov ax, RPC_NOHANDLE
pop es
jmp Rpc_Error
Kernel_BlockFind endp
COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
Kernel_ReadRegs
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
SYNOPSIS: Field a READ_REGS rpc call, returning the current
registers for the given thread.
CALLED BY: Rpc_Wait
PASS: CALLDATA contains the HandleMem of the thread whose
registers are sought.
RETURN: Nothing
DESTROYED: rpc_ToHost
PSEUDO CODE/STRATEGY:
KNOWN BUGS/SIDE EFFECTS/IDEAS:
REVISION HISTORY:
Name Date Description
---- ---- -----------
ardeb 11/21/88 Initial version
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@
Kernel_ReadRegs proc near
push es ; Preserve ES...
DPC DEBUG_XIP, 'R'
test ds:[sysFlags], mask dosexec
jnz useState
tst ds:[kernelCore]
jz useState
mov bx, {word}CALLDATA ; Load thread handle whose
; registers are desired.
cmp bx, ds:[HandleTable] ; Loader thread?
jae checkStateThread
clr bx ; Yes -- map to kernel thread
; (they're effectively the
; same thing)
checkStateThread:
cmp bx, [bp].state_thread
jne KRR2
useState:
;
; Wants registers from current thread -- we've got it all in
; the current state block. Copy the registers into an IbmRegs
; structure at rpc_ToHost.
;
mov di, offset rpc_ToHost
call Rpc_LoadRegs
mov ax, BPT_NOT_XIP
tst ds:[xipHeader]
jz setXIP
mov es, ds:[kdata]
mov si, ds:[curXIPPageOff]
mov ax, es:[si]
setXIP:
mov ({IbmRegs}ds:[rpc_ToHost]).reg_xipPage, ax
jmp KRRSend
KRR2:
;
; Not the current thread. Copy in all registers but CS, IP,
; AX and BX from the ts block found at the saved SS:SP.
;
tst bx
LONG jz KRRKernelThread ; Kernel thread -- no registers
mov es, ds:[kdata]
mov ax, es:[bx].HT_saveSS
mov ({IbmRegs}ds:[rpc_ToHost]).reg_regs[reg_ss], ax
mov si, es:[bx].HT_saveSP
mov ({IbmRegs}ds:[rpc_ToHost]).reg_regs[reg_sp], si
mov es, ax
; get xipPage from the ThreadBlockState
mov ax, BPT_NOT_XIP
; if we are doing XIP stuff, the offsets of ThreadBlockState
; are all off by two, of we need to account for that
tst ds:[xipHeader]
jz gotOffset
mov ax, es:[si]; TBS_xipPage
add si, 2 ; size TBS_xipPage
gotOffset:
mov ({IbmRegs}ds:[rpc_ToHost]).reg_xipPage, ax
mov ax, es:[si].TBS_bp
mov ({IbmRegs}ds:[rpc_ToHost]).reg_regs[reg_bp], ax
mov ax, es:[si].TBS_es
mov ({IbmRegs}ds:[rpc_ToHost]).reg_regs[reg_es], ax
mov ax, es:[si].TBS_dx
mov ({IbmRegs}ds:[rpc_ToHost]).reg_regs[reg_dx], ax
mov ax, es:[si].TBS_flags
movToIbmRegFlags ds:[rpc_ToHost], ax
mov ax, es:[si].TBS_cx
mov ({IbmRegs}ds:[rpc_ToHost]).reg_regs[reg_cx], ax
mov ax, es:[si].TBS_di
mov ({IbmRegs}ds:[rpc_ToHost]).reg_regs[reg_di], ax
mov ax, es:[si].TBS_si
mov ({IbmRegs}ds:[rpc_ToHost]).reg_regs[reg_si], ax
mov ax, es:[si].TBS_ds
mov ({IbmRegs}ds:[rpc_ToHost]).reg_regs[reg_ds], ax
if _Regs_32
mov ax, es:[si].TBS_fs
mov ({IbmRegs}ds:[rpc_ToHost]).reg_regs[reg_fs], ax
mov ax, es:[si].TBS_gs
mov ({IbmRegs}ds:[rpc_ToHost]).reg_regs[reg_gs], ax
mov ax, es:[si].TBS_eaxHigh
mov ({IbmRegs}ds:[rpc_ToHost]).reg_regs[reg_ax+2], ax
mov ax, es:[si].TBS_ebxHigh
mov ({IbmRegs}ds:[rpc_ToHost]).reg_regs[reg_bx+2], ax
mov ax, es:[si].TBS_ecxHigh
mov ({IbmRegs}ds:[rpc_ToHost]).reg_regs[reg_cx+2], ax
mov ax, es:[si].TBS_edxHigh
mov ({IbmRegs}ds:[rpc_ToHost]).reg_regs[reg_dx+2], ax
mov ax, es:[si].TBS_ebpHigh
mov ({IbmRegs}ds:[rpc_ToHost]).reg_regs[reg_bp+2], ax
mov ax, es:[si].TBS_ediHigh
mov ({IbmRegs}ds:[rpc_ToHost]).reg_regs[reg_di+2], ax
mov ax, es:[si].TBS_esiHigh
mov ({IbmRegs}ds:[rpc_ToHost]).reg_regs[reg_si+2], ax
endif
;
; AX and BX are not (reliably) saved on the stack when a
; thread is blocked, so we always return BOGUS_REG for them
;
mov ax, BOGUS_REG
mov ({IbmRegs}ds:[rpc_ToHost]).reg_regs[reg_ax], ax
mov ({IbmRegs}ds:[rpc_ToHost]).reg_regs[reg_bx], ax
;
; No matter how it blocked, there's a near return address
; above the saved registers and three bytes before that
; address is a near call. To figure out in what function
; it was operating, we must add the offset of that near
; call (2 bytes before the return address) to the return
; address.
;
mov bx, es:[si].TBS_ret ; Fetch return address
mov ax, ds:[kcodeSeg] ; get kcodeSeg in ax and es
mov es, ax
cmp {byte}es:[bx-3], 0xe8 ; Near call?
jne 10$ ; Just give address to which
; Dispatch will return, since
; we can't figure out the
; blocking routine...
add bx, es:-2[bx] ; add offset to ret addr,
; giving ip of routine
; responsible for block.
10$:
;
; now have cs in ax, and ip in bx. Stuff them
;
mov ({IbmRegs}ds:[rpc_ToHost]).reg_regs[reg_cs], ax
mov ({IbmRegs}ds:[rpc_ToHost]).reg_ip, bx
KRRSend:
pop es ;Restore ES for reply
mov cx, size IbmRegs
mov si, offset rpc_ToHost
DA DEBUG_XIP, <push ax>
DPS DEBUG_XIP, <regs>
DPW DEBUG_XIP, ({IbmRegs}ds:[rpc_ToHost]).reg_xipPage
DA DEBUG_XIP, <pop ax>
call Rpc_Reply
ret
KRRKernelThread:
;
; Information requested about the kernel thread, which is
; not running (and thus there are no good values to return).
; Return random stuff
;
; Fill all the general registers with the BOGUS_REG value
; using a repeated STOSW.
;
push ds ; Shift cgroup into ES for STOSW
pop es
mov di, offset rpc_ToHost
mov cx, (size IbmRegs.reg_regs) / 2
mov ax, BOGUS_REG
rep stosw
;
; Now set up SS:SP to be the start of the handle table, which
; is where SP will start when the scheduler thread actually
; runs.
;
mov ax, ds:[kdata]
mov ({IbmRegs}ds:[rpc_ToHost]).reg_regs[reg_ss], ax
mov ax, ds:[HandleTable]
mov ({IbmRegs}ds:[rpc_ToHost]).reg_regs[reg_sp], ax
;
; CS:IP is taken to be BlockOnLongQueue for now. It makes no
; difference, as there are no stack frames to decode anyway.
;
mov ax, ds:[kcodeSeg]
mov ({IbmRegs}ds:[rpc_ToHost]).reg_regs[reg_cs], ax
mov ax, ds:[BlockOnLongQueueOff]
mov ({IbmRegs}ds:[rpc_ToHost]).reg_ip, ax
;
; No current XIP page, thanks.
;
mov ({IbmRegs}ds:[rpc_ToHost]).reg_xipPage, BPT_NOT_XIP
jmp KRRSend
Kernel_ReadRegs endp
COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
Kernel_WriteRegs
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
SYNOPSIS: Modify the registers for a thread
CALLED BY: Rpc_Wait
PASS: WriteRegsArgs structure in CALLDATA
RETURN: Nothing
DESTROYED: Everything
PSEUDO CODE/STRATEGY:
If setting for the current thread, modify our state block
Else find the ss:sp for the thread and modify the kernel
state block. If thread retreated into the kernel,
return an error.
KNOWN BUGS/SIDE EFFECTS/IDEAS:
REVISION HISTORY:
Name Date Description
---- ---- -----------
ardeb 11/21/88 Initial version
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@
Kernel_WriteRegs proc near
push es
test ds:[sysFlags], mask dosexec
jnz useState
tst ds:[kernelCore]
jz useState
mov bx, ({WriteRegsArgs}CALLDATA).wra_thread
cmp bx, ds:[HandleTable] ; Loader thread?
jae checkStateThread
clr bx ; Yes -- map to kernel thread
; (they're effectively the
; same thing)
checkStateThread:
cmp bx, [bp].state_thread
jne KWR2
useState:
;
; Modify registers for current thread -- we've got it all in
; the current state block. Copy the registers into the state
; block.
; XXX: Do the 8 general regs with a MOVSW.
;
mov ax, ({WriteRegsArgs}CALLDATA).wra_regs.reg_regs[reg_ds]
mov [bp].state_ds, ax
mov ax, ({WriteRegsArgs}CALLDATA).wra_regs.reg_regs[reg_ss]
mov [bp].state_ss, ax
mov ax, ({WriteRegsArgs}CALLDATA).wra_regs.reg_regs[reg_es]
mov [bp].state_es, ax
mov ax, ({WriteRegsArgs}CALLDATA).wra_regs.reg_regs[reg_cs]
mov [bp].state_cs, ax
if _Regs_32
mov ax, ({WriteRegsArgs}CALLDATA).wra_regs.reg_regs[reg_ax]
mov [bp].state_ax, ax
mov ax, ({WriteRegsArgs}CALLDATA).wra_regs.reg_regs[reg_ax+2]
mov [bp].state_eax.high, ax
mov ax, ({WriteRegsArgs}CALLDATA).wra_regs.reg_regs[reg_cx]
mov [bp].state_cx, ax
mov ax, ({WriteRegsArgs}CALLDATA).wra_regs.reg_regs[reg_cx+2]
mov [bp].state_ecx.high, ax
mov ax, ({WriteRegsArgs}CALLDATA).wra_regs.reg_regs[reg_dx]
mov [bp].state_dx, ax
mov ax, ({WriteRegsArgs}CALLDATA).wra_regs.reg_regs[reg_dx+2]
mov [bp].state_edx.high, ax
mov ax, ({WriteRegsArgs}CALLDATA).wra_regs.reg_regs[reg_bx]
mov [bp].state_bx, ax
mov ax, ({WriteRegsArgs}CALLDATA).wra_regs.reg_regs[reg_bx+2]
mov [bp].state_ebx.high, ax
mov ax, ({WriteRegsArgs}CALLDATA).wra_regs.reg_regs[reg_si]
mov [bp].state_si, ax
mov ax, ({WriteRegsArgs}CALLDATA).wra_regs.reg_regs[reg_si+2]
mov [bp].state_esi.high, ax
mov ax, ({WriteRegsArgs}CALLDATA).wra_regs.reg_regs[reg_di]
mov [bp].state_di, ax
mov ax, ({WriteRegsArgs}CALLDATA).wra_regs.reg_regs[reg_di+2]
mov [bp].state_edi.high, ax
mov ax, ({WriteRegsArgs}CALLDATA).wra_regs.reg_regs[reg_bp]
mov [bp].state_bp, ax
mov ax, ({WriteRegsArgs}CALLDATA).wra_regs.reg_regs[reg_bp+2]
mov [bp].state_ebp.high, ax
mov ax, ({WriteRegsArgs}CALLDATA).wra_regs.reg_regs[reg_sp]
mov [bp].state_sp, ax
mov ax, ({WriteRegsArgs}CALLDATA).wra_regs.reg_regs[reg_sp+2]
mov [bp].state_esp.high, ax
mov ax, ({WriteRegsArgs}CALLDATA).wra_regs.reg_ip
mov [bp].state_ip, ax
mov ax, ({WriteRegsArgs}CALLDATA).wra_regs.reg_regs[reg_fs]
mov [bp].state_fs, ax
mov ax, ({WriteRegsArgs}CALLDATA).wra_regs.reg_regs[reg_gs]
mov [bp].state_gs, ax
else
mov ax, ({WriteRegsArgs}CALLDATA).wra_regs.reg_regs[reg_ax]
mov [bp].state_ax, ax
mov ax, ({WriteRegsArgs}CALLDATA).wra_regs.reg_regs[reg_cx]
mov [bp].state_cx, ax
mov ax, ({WriteRegsArgs}CALLDATA).wra_regs.reg_regs[reg_dx]
mov [bp].state_dx, ax
mov ax, ({WriteRegsArgs}CALLDATA).wra_regs.reg_regs[reg_bx]
mov [bp].state_bx, ax
mov ax, ({WriteRegsArgs}CALLDATA).wra_regs.reg_regs[reg_si]
mov [bp].state_si, ax
mov ax, ({WriteRegsArgs}CALLDATA).wra_regs.reg_regs[reg_di]
mov [bp].state_di, ax
mov ax, ({WriteRegsArgs}CALLDATA).wra_regs.reg_regs[reg_bp]
mov [bp].state_bp, ax
mov ax, ({WriteRegsArgs}CALLDATA).wra_regs.reg_regs[reg_sp]
mov [bp].state_sp, ax
mov ax, ({WriteRegsArgs}CALLDATA).wra_regs.reg_ip
mov [bp].state_ip, ax
endif
movFromIbmRegFlags ax, ({WriteRegsArgs}CALLDATA).wra_regs
mov [bp].state_flags, ax
jmp short KWRRet
KWR2:
;
; Not the current thread. Copy in all registers but CS, IP,
; AX and BX to the ts block found at the saved SS:SP
; AX and BX are not (reliably) saved on the stack when a
; thread is blocked, so we can't change them.
;
tst bx
jz KWRNoRegs ; Kernel thread has no regs
mov es, ds:[kdata]
mov si, es:[bx].HT_saveSP
mov ax, es:[bx].HT_saveSS
tst ax
jz KWRNoRegs
mov es, ax
mov ax, ({WriteRegsArgs}CALLDATA).wra_regs.reg_regs[reg_bp]
mov es:[si].TBS_bp, ax
mov ax, ({WriteRegsArgs}CALLDATA).wra_regs.reg_regs[reg_es]
mov es:[si].TBS_es, ax
mov ax, ({WriteRegsArgs}CALLDATA).wra_regs.reg_regs[reg_dx]
mov es:[si].TBS_dx, ax
movFromIbmRegFlags ax, ({WriteRegsArgs}CALLDATA).wra_regs
mov es:[si].TBS_flags, ax
mov ax, ({WriteRegsArgs}CALLDATA).wra_regs.reg_regs[reg_cx]
mov es:[si].TBS_cx, ax
mov ax, ({WriteRegsArgs}CALLDATA).wra_regs.reg_regs[reg_di]
mov es:[si].TBS_di, ax
mov ax, ({WriteRegsArgs}CALLDATA).wra_regs.reg_regs[reg_si]
mov es:[si].TBS_si, ax
mov ax, ({WriteRegsArgs}CALLDATA).wra_regs.reg_regs[reg_ds]
mov es:[si].TBS_ds, ax
if _Regs_32
mov ax, ({WriteRegsArgs}CALLDATA).wra_regs.reg_regs[reg_fs]
mov es:[si].TBS_fs, ax
mov ax, ({WriteRegsArgs}CALLDATA).wra_regs.reg_regs[reg_gs]
mov es:[si].TBS_gs, ax
mov ax, ({WriteRegsArgs}CALLDATA).wra_regs.reg_regs[reg_ax+2]
mov es:[si].TBS_eaxHigh, ax
mov ax, ({WriteRegsArgs}CALLDATA).wra_regs.reg_regs[reg_bx+2]
mov es:[si].TBS_ebxHigh, ax
mov ax, ({WriteRegsArgs}CALLDATA).wra_regs.reg_regs[reg_cx+2]
mov es:[si].TBS_ecxHigh, ax
mov ax, ({WriteRegsArgs}CALLDATA).wra_regs.reg_regs[reg_dx+2]
mov es:[si].TBS_edxHigh, ax
mov ax, ({WriteRegsArgs}CALLDATA).wra_regs.reg_regs[reg_bp+2]
mov es:[si].TBS_ebpHigh, ax
mov ax, ({WriteRegsArgs}CALLDATA).wra_regs.reg_regs[reg_di+2]
mov es:[si].TBS_ediHigh, ax
mov ax, ({WriteRegsArgs}CALLDATA).wra_regs.reg_regs[reg_si+2]
mov es:[si].TBS_esiHigh, ax
endif
KWRRet:
pop es ;Restore ES for reply
clr cx
call Rpc_Reply
ret
KWRNoRegs:
;
; Restore ES and return a BADARGS error.
;
pop es
mov ax, RPC_BADARGS
call Rpc_Error
ret
Kernel_WriteRegs endp
COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
Kernel_AttachMem
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
SYNOPSIS: Attach to a memory block
CALLED BY: RPC_BLOCK_ATTACH
PASS: CALLDATA = handle ID
RETURN: Nothing
DESTROYED: AX, BX, CX
PSEUDO CODE/STRATEGY:
KNOWN BUGS/SIDE EFFECTS/IDEAS:
REVISION HISTORY:
Name Date Description
---- ---- -----------
ardeb 5/ 3/89 Initial version
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@
Kernel_AttachMem proc near
push es
mov es, ds:[kdata]
mov bx, word ptr CALLDATA
mov al, es:[bx].HM_flags
or al, MASK HF_DEBUG
mov es:[bx].HM_flags, al
;
; Send null reply
;
clr cx
call Rpc_Reply
pop es
ret
Kernel_AttachMem endp
COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
Kernel_DetachMem
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
SYNOPSIS: Detach from a memory block
CALLED BY: RPC_BLOCK_DETACH
PASS: CALLDATA = handle ID
RETURN: Nothing
DESTROYED:
PSEUDO CODE/STRATEGY:
KNOWN BUGS/SIDE EFFECTS/IDEAS:
REVISION HISTORY:
Name Date Description
---- ---- -----------
ardeb 5/ 3/89 Initial version
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@
Kernel_DetachMem proc near
push es
mov es, ds:[kdata]
mov bx, word ptr CALLDATA
mov al, es:[bx].HM_flags
and al, NOT MASK HF_DEBUG
mov es:[bx].HM_flags, al
;
; Send null reply
;
clr cx
call Rpc_Reply
pop es
ret
Kernel_DetachMem endp
COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
KernelLoader
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
SYNOPSIS: Handler for calls from the loader
CALLED BY: loader
PASS: al = DebugLoaderFunction
DEBUG_LOADER_MOVED:
es = new base segment of loader
DEBUG_KERNEL_LOADED
cx:dx = fptr.KernelLoaderVars
RETURN: nothing
DESTROYED: nothing
PSEUDO CODE/STRATEGY:
KNOWN BUGS/SIDE EFFECTS/IDEAS:
REVISION HISTORY:
Name Date Description
---- ---- -----------
ardeb 1/22/91 Initial version
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@
KernelLoader proc far
push ax
DPC DEBUG_FALK3, 'Y'
pop ax
call SaveState
DPC DEBUG_FALK3, 'X'
mov ax, ss:[bp].state_ax
cmp al, DEBUG_LOADER_MOVED
jne checkKernelLoaded
mov ax, DEBUG_MEM_LOADER_MOVED
call Bpt_BlockChange
mov ds:[{MoveArgs}rpc_ToHost].ma_handle, 0
; special signal to
; say loader moved
mov ax, ss:[bp].state_es
mov ds:[{MoveArgs}rpc_ToHost].ma_dataAddress, ax
mov ds:[loaderBase], ax ; record for possible later
; return
mov ax, RPC_BLOCK_MOVE
mov cx, size MoveArgs
jmp transmit
checkKernelLoaded:
cmp al, DEBUG_KERNEL_LOADED
LONG jne done ; que?
push es
mov es, ss:[bp].state_cx ; es:bx <- KernelLoaderVars
mov bx, ss:[bp].state_dx
DPC DEBUG_XIP, 'l'
DPW DEBUG_XIP, es
DPW DEBUG_XIP, bx
;
; Fetch the pertinent variables from the KernelLoaderVars now so we
; (a) have them, and (b) don't have to be told where the kernel's
; version of them lie...
;
mov ax, es:[bx].KLV_handleTableStart
mov ds:[HandleTable], ax
mov ax, es:[bx].KLV_lastHandle
mov ds:[lastHandle], ax
mov ax, es:[bx].KLV_dgroupSegment
mov ds:[kdata], ax
mov ax, es:[bx].KLV_kernelHandle
DPW DEBUG_XIP, ax
mov ds:[kernelCore], ax ; record for possible later
; AX must be preserved as the kernelCore as its used down below
;
; Save KLV_topLevelPath so we can use it later when we want to do
; a RPC_FIND_GEODE or RPC_SEND_FILE.
;
push si, di, cx
push ds, es
pop es, ds ; exchange segment registers
lea si, ds:[bx].KLV_topLevelPath
mov di, offset topLevelPath
mov cx, size topLevelPath
rep movsb ; copy path name
push ds, es
pop es, ds ; restore segment registers
pop si, di, cx
;
; Tell the kernel our code selector, so it can identify our comm.
; IRQ handlers when trying to un-intercept them.
;
mov es:[bx].KLV_swatKcode, cs
;
; Ask the kernel to tell us just where the f*** kcode ended up.
;
mov es:[bx].KLV_swatKcodePtr.segment, ds
mov es:[bx].KLV_swatKcodePtr.offset, offset kcodeSeg
;
; Build up a SpawnArgs for transmission to the host.
;
mov ds:[{SpawnArgs}rpc_ToHost].sa_owner, ax
clr ax
mov ds:[{SpawnArgs}rpc_ToHost].sa_thread, ax ; kernel thread
mov ds:[{SpawnArgs}rpc_ToHost].sa_ss, ax ; loading library
mov ds:[{SpawnArgs}rpc_ToHost].sa_sp, ax ; ditto
mov ax, es:[bx].KLV_mapPageAddr
mov ds:[xipPageAddr], ax
; snag this value now that es:bx are poiting to KLV in case we
; need it, we don't want to assign this unless kernelVersion is
; KV_FULL_XIP, but we won't know that until we call KernelSetup
DPC DEBUG_FALK3, 'A'
mov ax, es:[bx].KLV_xipHeader
pop es ; es <- cgroup
call KernelSetup
DA DEBUG_FALK3, <push ax>
DPC DEBUG_FALK3, 'B'
DA DEBUG_FALK3, <pop ax>
cmp ds:[kernelVersion], KV_FULL_XIP
jb findKcode
DA DEBUG_XIP, <push ax>
DPC DEBUG_XIP, 'H'
DA DEBUG_XIP, <pop ax>
DPW DEBUG_XIP, ax
mov ds:[xipHeader], ax
findKcode:
;
; now setup kcodeSeg, which we can get from the core block of
; the kernel since the KernelLibraryEntry is in kcode
;
push es
mov es, ds:[kdata]
mov bx, ds:[kernelCore]
DPW DEBUG_SETUP, bx
mov es, es:[bx].HM_addr ; es = kernel core block
mov ax, es:[GH_libEntrySegment]
pop es
mov ds:[kcodeSeg], ax
DPW DEBUG_FALK3, ax
mov cx, size SpawnArgs
mov ax, RPC_KERNEL_LOAD
transmit:
;
; Transmit the call to the host if it's connected (*not* attached)
;
test ds:[sysFlags], mask connected
jz done
mov bx, offset rpc_ToHost
call Rpc_Call
test ds:[sysFlags], mask dontresume
jz done
jmp Rpc_Run
done:
;
; Return to our caller with its original state.
;
call RestoreState
iret
KernelLoader endp
COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
Kernel_EnsureESWritable
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
SYNOPSIS: For those machines where things are write-protected,
sometimes, unprotect the memory pointed to by ES.
CALLED BY: (EXTERNAL)
PASS: es = segment about to be written
RETURN: ax = original state, to pass to Kernel_RestoreWriteProtect
DESTROYED: nothing
SIDE EFFECTS:
PSEUDO CODE/STRATEGY:
REVISION HISTORY:
Name Date Description
---- ---- -----------
ardeb 5/24/93 Initial version
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@
Kernel_EnsureESWritable proc near
uses bx, ds
.enter
PointDSAtStub
mov bx, es
mov ds:previousReadOnlyES, bx
call GPMIAlias
mov es, bx
mov ax, bx
.leave
ret
Kernel_EnsureESWritable endp
COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
Kernel_RestoreWriteProtect
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
SYNOPSIS: Restore the write-protect state as it was before a call
to Kernel_EnsureESWritable
CALLED BY: (EXTERNAL)
PASS: ax = as returned from Kernel_EnsureESWritable
RETURN: nothing
DESTROYED: ax, es = NULL
SIDE EFFECTS: ?
PSEUDO CODE/STRATEGY:
al = port number
ah = previous value
REVISION HISTORY:
Name Date Description
---- ---- -----------
ardeb 5/24/93 Initial version
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@
Kernel_RestoreWriteProtect proc near
uses ax, bx, ds
.enter
mov bx, ax
clr ax
mov es, ax ; es = NULL
call GPMIFreeAlias
PointDSAtStub
mov bx, ds:previousReadOnlyES
mov es, bx
.leave
ret
Kernel_RestoreWriteProtect endp
COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
Kernel_ReadXmsMem
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
SYNOPSIS: Read xms memory given the handle of the XMS block, the
the address of XMSReadBlockLow, and the number of
bytes to read.
CALLED BY: Rpc_ReadXmsMem
PASS: ReadXmsMemArgs
RETURN:
DESTROYED: nothing
SIDE EFFECTS:
PSEUDO CODE/STRATEGY:
REVISION HISTORY:
Name Date Description
---- ---- -----------
IP 10/12/94 Initial version
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@
XMSMoveParams struct
XMSMP_size dword ; number of bytes to move
XMSMP_sourceHandle word ;
XMSMP_sourceOffset dword ;
XMSMP_destHandle word ;
XMSMP_destOffset fptr ;
XMSMoveParams ends
Kernel_ReadXmsMem proc near
xmsMoveParams local XMSMoveParams
uses ax,bx,cx,dx,si,di,bp
.enter
;
; transfer args from swat
;
movdw xmsMoveParams.XMSMP_size, ({ReadXmsMemArgs}CALLDATA).RXMA_size, ax
mov ax, ({ReadXmsMemArgs}CALLDATA).RXMA_sourceHandle
mov xmsMoveParams.XMSMP_sourceHandle, ax
movdw xmsMoveParams.XMSMP_sourceOffset, ({ReadXmsMemArgs}CALLDATA).RXMA_sourceOffset, ax
;
; set the destination args so that the data is written to
; REPLYDATA
;
mov ax, ds
mov xmsMoveParams.XMSMP_destOffset.segment, ax
lea ax, REPLYDATA
mov xmsMoveParams.XMSMP_destOffset.offset, ax
clr xmsMoveParams.XMSMP_destHandle
;
; address of routine to call
;
mov bx, ({ReadXmsMemArgs}CALLDATA).RXMA_procOffset
DPW DEBUG_PROFILE, bx
mov es, ds:[kdata]
DPW DEBUG_PROFILE, es
mov ax, es:[bx]
DPW DEBUG_PROFILE, ax
mov ax, es:[bx+2]
DPW DEBUG_PROFILE, ax
push ds
segmov ds, ss
lea si, ss:[xmsMoveParams]
mov ah, 0x0b
DPW DEBUG_PROFILE, ax
call {fptr}(es:[bx])
pop ds
DPW DEBUG_PROFILE, ax
lea si, REPLYDATA
mov ax, ds:[si]
DPW DEBUG_PROFILE, ax
segmov es, ds
lea si, REPLYDATA
mov cx, ss:[xmsMoveParams].XMSMP_size.low
call Rpc_Reply
.leave
ret
Kernel_ReadXmsMem endp
COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
KernelSetSwatStubFlag
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
SYNOPSIS: Write a word into ThreadPrivateData so that some EC code
in SysLockCommon call tell that this is the swat stub and
not really the kernel.
CALLED BY: KernelSafeFileRead, KernelSafeLock, Kernel_SafeMapXIPPage
PASS: ds = cgroup
RETURN: nothing
DESTROYED: nothing
SIDE EFFECTS:
PSEUDO CODE/STRATEGY:
REVISION HISTORY:
Name Date Description
---- ---- -----------
Joon 5/ 7/96 Initial version
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@
KernelSetSwatStubFlag proc near
.enter
; In kernels before KV_AFTER_EXCEPTION_CHANGE, the kernel expects a
; signature (0xadeb) to be in TPD_breakPoint. This is used by EC
; code in SysLockCommon so that the system can tell that the swat
; stub and not the kernel is calling.
; In kernels after KV_AFTER_EXCEPTION_CHANGE, the EC code in
; SysLockCommon simply checks TPD_exceptionHandlers to see if it is
; NULL. Thus, the stub, in this case, does not have to do anything.
cmp ds:[kernelVersion], KV_AFTER_EXCEPTION_CHANGE
jae done
; Old version: put signature in TPD_breakPoint
mov ss:[OTPD_breakPoint].segment, 0xadeb
done:
.leave
ret
KernelSetSwatStubFlag endp
scode ends
scode segment
assume cs:scode, ds:cgroup, es:cgroup
COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
Kernel_Load
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
SYNOPSIS: Load the desired kernel at its proper place
CALLED BY: Main, after performing a PUSHF
PASS: DS=ES=cgroup
RETURN: kernelHeader filled in.
DESTROYED: Lots of things
PSEUDO CODE/STRATEGY:
KNOWN BUGS/SIDE EFFECTS/IDEAS:
REVISION HISTORY:
Name Date Description
---- ---- -----------
ardeb 11/19/88 Initial version
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@
scode segment
;
; These things needs to stay around...
;
kcodeSeg word stubInit ; Where to load it ; NOTE!!!: Need to convert to selector at some point
kernelName char "loaderec.exe",0 ; Storage for loader's name
char (64 - length kernelName) dup (?)
scode ends
defArgs byte length defArgs-1, "/s" ; Default command tail if none
; given
Kernel_Load proc far
;
; Intercept int 21h right away.
;
if INT21_INTERCEPT
; Protected mode doesn't need this watching capability
mov ax, 21h
mov bx, offset dosAddr
mov dx, offset KernelDOS
call SetInterrupt
endif
;
; Find the first blank-separated word that doesn't begin with a
; slash -- this is the kernel to use
;
mov es, es:PSP ; PSP segment into ES for SCAS
mov di, 80h ; Fetch tail length into CX
mov cl, es:[di]
inc di ; Advance to tail start
clr ch
cld ; Go forward
findLoaderLoop:
mov al, ' '
repe scasb ; Skip blanks
je useDefault ; All blanks -- no kernel. Ick.
mov ah, es:-1[di] ; Fetch first non-blank
cmp ah, '/'
jne foundLoader ; => found loader
repne scasb ; skip to next blank
je findLoaderLoop ; found a blank -- continue
useDefault:
;
; Use default kernel (already in kernelName).
; Need to load in default arguments, though.
;
mov di, 80h ; Need to store length, too
mov si, offset defArgs
push ds
PointDSAtStub ; Point DS at init variables
lodsb ; Fetch length
stosb ; Store in tail as well
mov cl, al ; Shift to CX for rep movsb
clr ch
rep movsb ; Copy rest of args
pop ds
jmp loadLoader ; Go load the kernel.
KLAbort:
if INT21_INTERCEPT
push ax
mov ax, 21h
mov bx, offset dosAddr
call ResetInterrupt
pop ax
endif
stc
ret ; return with carry set to our
; caller. ax = error code
foundLoader:
;
; Move index of kernel's name to BX (decrement required b/c
; DI points one beyond its start)
;
lea bx, [di-1]
;
; Get to end of kernel's name (AL still contains ' ')
;
repne scasb
je figureNameLength
inc di ; Stopped on last char of kernel's name --
; Point DI beyond it so copy/arithmetic
; below works out correctly. CX will still
; contain the correct number of bytes left (0)
figureNameLength:
;
; Calculate length of name in AX. Must decrement after
; subtracting BX b/c DI once again points one beyond the first
; blank.
;
mov ax, di
sub ax, bx
dec ax
;
; Store count of remaining bytes of command tail in command
; tail's length byte -- we'll make the remaining bytes into the
; entire command tail later.
;
push cx ; Save for later tail shift
;
; Copy kernel's name into kernelName for opening/loading
;
mov si, bx ; Set SI to start of kernel name
; for copy to kernelName
mov di, offset cgroup:kernelName
mov cx, ax
push ds ; Swap es and ds (storing in cgroup and
push es ; fetching from PSP...)
pop ds
pop es
rep movsb
clr al
stosb ; String must be null-terminated
;
; Copy rest of tail down to its start.
;
segmov es, ds ; PSP -> ES too.
pop cx ; Restore count
inc cx ; off-by-one...
mov byte ptr es:[80h], cl
mov di, 81h ; Start of tail
add byte ptr es:[80h], 2 ; another 2 chars in the tail
mov ax, '/' OR ('s' SHL 8) ; tell geos it's running
; under swat before copying
; down remaining tail, as
; that might contain a
; geode to load...
stosw
rep movsb ; Copy
loadLoader:
PointDSAtStub
;
; Read the exe file header into kernelHeader.
;
mov dx, offset kernelName
mov ax, (MSDOS_OPEN_FILE shl 8) or 00h ; Open read-only
int 21h
jc KLAbort ; Abort if couldn't open
mov bx, ax ; Need handle in BX
mov dx, offset kernelHeader
mov cx, size ExeHeader
mov ah, MSDOS_READ_FILE
int 21h
mov ah, MSDOS_CLOSE_FILE
int 21h
ret
Kernel_Load endp
scode ends
end
|
; A174745: y-values in the solution to x^2 - 21*y^2 = 1.
; Submitted by Jon Maiga
; 0,12,1320,145188,15969360,1756484412,193197315960,21249948271188,2337301112514720,257081872428348012,28276668666005766600,3110176471388205977988,342091135184036651812080,37626914693772643493350812,4138618525179806747616777240,455210410855084969594352145588,50069006575534166848631119237440,5507135512897903268379828763972812,605734837412193825354932532917771880,66625324979828422885774198792190933988,7328180012943714323609806934608084966800,806033176098828747174192988608097155414012
lpb $0
sub $0,1
mov $2,$0
max $2,0
seq $2,144930 ; Numbers k arising in A144929.
add $3,$2
lpe
mov $0,$3
mul $0,12
|
; A098451: One of three ordered sets of positive integers that solves the minimal magic die puzzle.
; 1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,19,20,23,43
mov $15,$0
mov $17,$0
add $17,1
lpb $17
mov $0,$15
sub $17,1
sub $0,$17
mov $11,$0
mov $13,2
lpb $13
mov $0,$11
sub $13,1
add $0,$13
sub $0,1
mov $7,$0
mov $9,2
lpb $9
clr $0,7
mov $0,$7
sub $9,1
add $0,$9
sub $0,1
mov $5,$0
sub $0,1
add $1,16
sub $1,$0
sub $5,1
lpb $0
mov $0,$1
add $0,4
mov $5,1
add $6,$0
pow $6,2
sub $6,7
mov $0,$6
div $0,2
add $0,1
add $5,$6
add $0,$5
mov $3,2
bin $5,2
mov $6,$1
pow $6,2
sub $6,2
lpe
sub $0,$5
sub $6,$3
sub $6,$0
mov $1,$6
mov $10,$9
lpb $10
mov $8,$1
sub $10,1
lpe
lpe
lpb $7
mov $7,0
sub $8,$1
lpe
mov $1,$8
mov $14,$13
lpb $14
mov $12,$1
sub $14,1
lpe
lpe
lpb $11
mov $11,0
sub $12,$1
lpe
mov $1,$12
add $1,1
add $16,$1
lpe
mov $1,$16
|
; A175787: Primes together with 4.
; 2,3,4,5,7,11,13,17,19,23,29,31,37,41,43,47,53,59,61,67,71,73,79,83,89,97,101,103,107,109,113,127,131,137,139,149,151,157,163,167,173,179,181,191,193,197,199,211,223,227,229,233,239,241,251,257,263,269,271,277
mov $1,$0
trn $1,1
seq $1,6005 ; The odd prime numbers together with 1.
sub $1,2
max $0,$1
add $0,2
|
// 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.
#include "chrome/browser/extensions/error_console/error_console.h"
#include <stddef.h>
#include <string>
#include "base/files/file_path.h"
#include "base/macros.h"
#include "base/run_loop.h"
#include "base/strings/stringprintf.h"
#include "base/strings/utf_string_conversions.h"
#include "build/build_config.h"
#include "chrome/browser/extensions/extension_action_runner.h"
#include "chrome/browser/extensions/extension_browsertest.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/ui/tabs/tab_strip_model.h"
#include "chrome/common/pref_names.h"
#include "chrome/common/url_constants.h"
#include "chrome/test/base/ui_test_utils.h"
#include "components/prefs/pref_service.h"
#include "content/public/test/browser_test.h"
#include "extensions/browser/extension_error.h"
#include "extensions/common/constants.h"
#include "extensions/common/error_utils.h"
#include "extensions/common/extension.h"
#include "extensions/common/extension_urls.h"
#include "extensions/common/manifest_constants.h"
#include "net/test/embedded_test_server/embedded_test_server.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "url/gurl.h"
using base::UTF8ToUTF16;
using std::u16string;
namespace extensions {
namespace {
const char kTestingPage[] = "/extensions/test_file.html";
const char kAnonymousFunction[] = "(anonymous function)";
const char* const kBackgroundPageName =
extensions::kGeneratedBackgroundPageFilename;
const StackTrace& GetStackTraceFromError(const ExtensionError* error) {
CHECK(error->type() == ExtensionError::RUNTIME_ERROR);
return (static_cast<const RuntimeError*>(error))->stack_trace();
}
// Verify that a given |frame| has the proper source and function name.
void CheckStackFrame(const StackFrame& frame,
const std::string& source,
const std::string& function) {
EXPECT_EQ(base::UTF8ToUTF16(source), frame.source);
EXPECT_EQ(base::UTF8ToUTF16(function), frame.function);
}
// Verify that all properties of a given |frame| are correct. Overloaded because
// we commonly do not check line/column numbers, as they are too likely
// to change.
void CheckStackFrame(const StackFrame& frame,
const std::string& source,
const std::string& function,
size_t line_number,
size_t column_number) {
CheckStackFrame(frame, source, function);
EXPECT_EQ(line_number, frame.line_number);
EXPECT_EQ(column_number, frame.column_number);
}
// Verify that all properties of a given |error| are correct.
void CheckError(const ExtensionError* error,
ExtensionError::Type type,
const std::string& id,
const std::string& source,
bool from_incognito,
const std::string& message) {
ASSERT_TRUE(error);
EXPECT_EQ(type, error->type());
EXPECT_EQ(id, error->extension_id());
EXPECT_EQ(base::UTF8ToUTF16(source), error->source());
EXPECT_EQ(from_incognito, error->from_incognito());
EXPECT_EQ(base::UTF8ToUTF16(message), error->message());
}
// Verify that all properties of a JS runtime error are correct.
void CheckRuntimeError(const ExtensionError* error,
const std::string& id,
const std::string& source,
bool from_incognito,
const std::string& message,
logging::LogSeverity level,
const GURL& context,
size_t expected_stack_size) {
CheckError(error,
ExtensionError::RUNTIME_ERROR,
id,
source,
from_incognito,
message);
const RuntimeError* runtime_error = static_cast<const RuntimeError*>(error);
EXPECT_EQ(level, runtime_error->level());
EXPECT_EQ(context, runtime_error->context_url());
EXPECT_EQ(expected_stack_size, runtime_error->stack_trace().size());
}
void CheckManifestError(const ExtensionError* error,
const std::string& id,
const std::string& message,
const std::string& manifest_key,
const std::string& manifest_specific) {
CheckError(error,
ExtensionError::MANIFEST_ERROR,
id,
// source is always the manifest for ManifestErrors.
base::FilePath(kManifestFilename).AsUTF8Unsafe(),
false, // manifest errors are never from incognito.
message);
const ManifestError* manifest_error =
static_cast<const ManifestError*>(error);
EXPECT_EQ(base::UTF8ToUTF16(manifest_key), manifest_error->manifest_key());
EXPECT_EQ(base::UTF8ToUTF16(manifest_specific),
manifest_error->manifest_specific());
}
} // namespace
class ErrorConsoleBrowserTest : public ExtensionBrowserTest {
public:
ErrorConsoleBrowserTest() : error_console_(nullptr) {}
~ErrorConsoleBrowserTest() override {}
protected:
// A helper class in order to wait for the proper number of errors to be
// caught by the ErrorConsole. This will run the MessageLoop until a given
// number of errors are observed.
// Usage:
// ...
// ErrorObserver observer(3, error_console);
// <Cause three errors...>
// observer.WaitForErrors();
// <Perform any additional checks...>
class ErrorObserver : public ErrorConsole::Observer {
public:
ErrorObserver(size_t errors_expected, ErrorConsole* error_console)
: errors_observed_(0),
errors_expected_(errors_expected),
waiting_(false),
error_console_(error_console) {
error_console_->AddObserver(this);
}
virtual ~ErrorObserver() {
if (error_console_)
error_console_->RemoveObserver(this);
}
// ErrorConsole::Observer implementation.
void OnErrorAdded(const ExtensionError* error) override {
++errors_observed_;
if (errors_observed_ >= errors_expected_) {
if (waiting_)
base::RunLoop::QuitCurrentWhenIdleDeprecated();
}
}
void OnErrorConsoleDestroyed() override { error_console_ = nullptr; }
// Spin until the appropriate number of errors have been observed.
void WaitForErrors() {
if (errors_observed_ < errors_expected_) {
waiting_ = true;
content::RunMessageLoop();
waiting_ = false;
}
}
private:
size_t errors_observed_;
size_t errors_expected_;
bool waiting_;
ErrorConsole* error_console_;
DISALLOW_COPY_AND_ASSIGN(ErrorObserver);
};
// The type of action which we take after we load an extension in order to
// cause any errors.
enum Action {
// Navigate to a (non-chrome) page to allow a content script to run.
ACTION_NAVIGATE,
// Simulate a browser action click.
ACTION_BROWSER_ACTION,
// Navigate to the new tab page.
ACTION_NEW_TAB,
// Do nothing (errors will be caused by a background script,
// or by a manifest/loading warning).
ACTION_NONE
};
void SetUpOnMainThread() override {
ExtensionBrowserTest::SetUpOnMainThread();
// Errors are only kept if we have Developer Mode enabled.
profile()->GetPrefs()->SetBoolean(prefs::kExtensionsUIDeveloperMode, true);
error_console_ = ErrorConsole::Get(profile());
CHECK(error_console_);
test_data_dir_ = test_data_dir_.AppendASCII("error_console");
}
const GURL& GetTestURL() {
if (test_url_.is_empty()) {
CHECK(embedded_test_server()->Start());
test_url_ = embedded_test_server()->GetURL(kTestingPage);
}
return test_url_;
}
// Load the extension at |path|, take the specified |action|, and wait for
// |expected_errors| errors. Populate |extension| with a pointer to the loaded
// extension.
void LoadExtensionAndCheckErrors(const std::string& path,
const LoadOptions& options,
size_t errors_expected,
Action action,
const Extension** extension) {
ErrorObserver observer(errors_expected, error_console_);
*extension = LoadExtension(test_data_dir_.AppendASCII(path), options);
ASSERT_TRUE(*extension);
switch (action) {
case ACTION_NAVIGATE: {
ui_test_utils::NavigateToURL(browser(), GetTestURL());
break;
}
case ACTION_BROWSER_ACTION: {
ExtensionActionRunner::GetForWebContents(
browser()->tab_strip_model()->GetActiveWebContents())
->RunAction(*extension, true);
break;
}
case ACTION_NEW_TAB: {
ui_test_utils::NavigateToURL(browser(),
GURL(chrome::kChromeUINewTabURL));
break;
}
case ACTION_NONE:
break;
default:
NOTREACHED();
}
observer.WaitForErrors();
// We should only have errors for a single extension, or should have no
// entries, if no errors were expected.
ASSERT_EQ(errors_expected > 0 ? 1u : 0u,
error_console()->get_num_entries_for_test());
ASSERT_EQ(
errors_expected,
error_console()->GetErrorsForExtension((*extension)->id()).size());
}
ErrorConsole* error_console() { return error_console_; }
private:
// The URL used in testing for simple page navigations.
GURL test_url_;
// Weak reference to the ErrorConsole.
ErrorConsole* error_console_;
};
// Test to ensure that we are successfully reporting manifest errors as an
// extension is installed.
IN_PROC_BROWSER_TEST_F(ErrorConsoleBrowserTest, ReportManifestErrors) {
const Extension* extension = nullptr;
// We expect two errors - one for an invalid permission, and a second for
// an unknown key.
LoadExtensionAndCheckErrors("manifest_warnings",
{.ignore_manifest_warnings = true}, 2,
ACTION_NONE, &extension);
const ErrorList& errors =
error_console()->GetErrorsForExtension(extension->id());
// Unfortunately, there's not always a hard guarantee of order in parsing the
// manifest, so there's not a definitive order in which these errors may
// occur. As such, we need to determine which error corresponds to which
// expected error.
const ExtensionError* permissions_error = nullptr;
const ExtensionError* unknown_key_error = nullptr;
const char kFakeKey[] = "not_a_real_key";
for (const auto& error : errors) {
ASSERT_EQ(ExtensionError::MANIFEST_ERROR, error->type());
std::string utf8_key = base::UTF16ToUTF8(
(static_cast<const ManifestError*>(error.get()))->manifest_key());
if (utf8_key == manifest_keys::kPermissions)
permissions_error = error.get();
else if (utf8_key == kFakeKey)
unknown_key_error = error.get();
}
ASSERT_TRUE(permissions_error);
ASSERT_TRUE(unknown_key_error);
const char kFakePermission[] = "not_a_real_permission";
CheckManifestError(permissions_error,
extension->id(),
ErrorUtils::FormatErrorMessage(
manifest_errors::kPermissionUnknownOrMalformed,
kFakePermission),
manifest_keys::kPermissions,
kFakePermission);
CheckManifestError(unknown_key_error,
extension->id(),
ErrorUtils::FormatErrorMessage(
manifest_errors::kUnrecognizedManifestKey,
kFakeKey),
kFakeKey,
std::string());
}
// Test that we do not store any errors unless the Developer Mode switch is
// toggled on the profile.
IN_PROC_BROWSER_TEST_F(ErrorConsoleBrowserTest,
DontStoreErrorsWithoutDeveloperMode) {
profile()->GetPrefs()->SetBoolean(prefs::kExtensionsUIDeveloperMode, false);
const Extension* extension = nullptr;
// Same test as ReportManifestErrors, except we don't expect any errors since
// we disable Developer Mode.
LoadExtensionAndCheckErrors("manifest_warnings",
{.ignore_manifest_warnings = true}, 0,
ACTION_NONE, &extension);
// Now if we enable developer mode, the errors should be reported...
profile()->GetPrefs()->SetBoolean(prefs::kExtensionsUIDeveloperMode, true);
EXPECT_EQ(2u, error_console()->GetErrorsForExtension(extension->id()).size());
// ... and if we disable it again, all errors which we were holding should be
// removed.
profile()->GetPrefs()->SetBoolean(prefs::kExtensionsUIDeveloperMode, false);
EXPECT_EQ(0u, error_console()->GetErrorsForExtension(extension->id()).size());
}
// Load an extension which, upon visiting any page, first sends out a console
// log, and then crashes with a JS TypeError.
IN_PROC_BROWSER_TEST_F(ErrorConsoleBrowserTest,
ContentScriptLogAndRuntimeError) {
const Extension* extension = nullptr;
LoadExtensionAndCheckErrors(
"content_script_log_and_runtime_error",
{.ignore_manifest_warnings = false},
2u, // Two errors: A log message and a JS type error.
ACTION_NAVIGATE, &extension);
std::string script_url =
extension->GetResourceURL("content_script.js").spec();
const ErrorList& errors =
error_console()->GetErrorsForExtension(extension->id());
// The extension logs a message with console.log(), then another with
// console.warn(), and then triggers a TypeError.
// There should be exactly two errors (the warning and the TypeError). The
// error console ignores logs - this would tend to be too noisy, and doesn't
// jive with the big `ERRORS` button in the UI.
// See https://crbug.com/837401.
ASSERT_EQ(2u, errors.size());
// The first error should be a console log.
CheckRuntimeError(errors[0].get(), extension->id(),
script_url, // The source should be the content script url.
false, // Not from incognito.
"warned message", // The error message is the log.
logging::LOG_WARNING,
GetTestURL(), // Content scripts run in the web page.
2u);
const StackTrace& stack_trace1 = GetStackTraceFromError(errors[0].get());
CheckStackFrame(stack_trace1[0], script_url,
"warnMessage", // function name
10u, // line number
11u /* column number */);
CheckStackFrame(stack_trace1[1], script_url, kAnonymousFunction, 14u, 1u);
// The second error should be a runtime error.
CheckRuntimeError(errors[1].get(), extension->id(), script_url,
false, // not from incognito
"Uncaught TypeError: "
"Cannot set property 'foo' of undefined",
logging::LOG_ERROR, // JS errors are always ERROR level.
GetTestURL(), 1u);
const StackTrace& stack_trace2 = GetStackTraceFromError(errors[1].get());
CheckStackFrame(stack_trace2[0], script_url, kAnonymousFunction, 17u, 1u);
}
// Catch an error from a BrowserAction; this is more complex than a content
// script error, since browser actions are routed through our own code.
IN_PROC_BROWSER_TEST_F(ErrorConsoleBrowserTest, BrowserActionRuntimeError) {
const Extension* extension = nullptr;
LoadExtensionAndCheckErrors(
"browser_action_runtime_error", {.ignore_manifest_warnings = false},
1u, // One error: A reference error from within the browser action.
ACTION_BROWSER_ACTION, &extension);
std::string script_url =
extension->GetResourceURL("browser_action.js").spec();
const ErrorList& errors =
error_console()->GetErrorsForExtension(extension->id());
// TODO(devlin): The specific event name (here, 'browserAction.onClicked')
// may or may not be worth preserving. In most cases, it's unnecessary with
// the line number, but it could be useful in some cases.
std::string message =
"Error in event handler: ReferenceError: baz is not defined";
CheckRuntimeError(errors[0].get(), extension->id(), script_url,
false, // not incognito
message, logging::LOG_ERROR,
extension->GetResourceURL(kBackgroundPageName), 1u);
const StackTrace& stack_trace = GetStackTraceFromError(errors[0].get());
// Note: This test used to have a stack trace of length 6 that contains stack
// frames in the extension code, but since crbug.com/404406 was fixed only
// stack frames within user-defined extension code are printed.
CheckStackFrame(stack_trace[0], script_url, kAnonymousFunction);
}
// Test that we can catch an error for calling an API with improper arguments.
IN_PROC_BROWSER_TEST_F(ErrorConsoleBrowserTest, BadAPIArgumentsRuntimeError) {
const Extension* extension = nullptr;
LoadExtensionAndCheckErrors(
"bad_api_arguments_runtime_error", {.ignore_manifest_warnings = false},
1, // One error: call an API with improper arguments.
ACTION_NONE, &extension);
const ErrorList& errors =
error_console()->GetErrorsForExtension(extension->id());
std::string source = extension->GetResourceURL("background.js").spec();
std::string message =
"Uncaught TypeError: Error in invocation of tabs.get"
"(integer tabId, function callback): No matching signature.";
CheckRuntimeError(errors[0].get(), extension->id(), source,
false, // not incognito
message, logging::LOG_ERROR,
extension->GetResourceURL(kBackgroundPageName), 1u);
const StackTrace& stack_trace = GetStackTraceFromError(errors[0].get());
ASSERT_EQ(1u, stack_trace.size());
CheckStackFrame(stack_trace[0], source, kAnonymousFunction);
}
// Test that we catch an error when we try to call an API method without
// permission.
IN_PROC_BROWSER_TEST_F(ErrorConsoleBrowserTest, BadAPIPermissionsRuntimeError) {
const Extension* extension = nullptr;
LoadExtensionAndCheckErrors(
"bad_api_permissions_runtime_error", {.ignore_manifest_warnings = false},
1, // One error: we try to call addUrl() on chrome.history without
// permission, which results in a TypeError.
ACTION_NONE, &extension);
std::string script_url = extension->GetResourceURL("background.js").spec();
const ErrorList& errors =
error_console()->GetErrorsForExtension(extension->id());
CheckRuntimeError(
errors[0].get(), extension->id(), script_url,
false, // not incognito
"Uncaught TypeError: Cannot read property 'addUrl' of undefined",
logging::LOG_ERROR, extension->GetResourceURL(kBackgroundPageName), 1u);
const StackTrace& stack_trace = GetStackTraceFromError(errors[0].get());
ASSERT_EQ(1u, stack_trace.size());
CheckStackFrame(stack_trace[0],
script_url,
kAnonymousFunction,
5u, 1u);
}
// Test that if there is an error in an HTML page loaded by an extension (most
// common with apps), it is caught and reported by the ErrorConsole.
IN_PROC_BROWSER_TEST_F(ErrorConsoleBrowserTest, BadExtensionPage) {
const Extension* extension = nullptr;
LoadExtensionAndCheckErrors(
"bad_extension_page", {.ignore_manifest_warnings = false},
1, // One error: the page will load JS which has a reference error.
ACTION_NEW_TAB, &extension);
}
// Test that extension errors that go to chrome.runtime.lastError are caught
// and reported by the ErrorConsole.
// TODO(crbug.com/1181558) Flaky on many builders.
IN_PROC_BROWSER_TEST_F(ErrorConsoleBrowserTest, DISABLED_CatchesLastError) {
const Extension* extension = nullptr;
LoadExtensionAndCheckErrors(
"trigger_last_error", {.ignore_manifest_warnings = false},
1, // One error, which is sent through last error when trying to remove
// a non-existent permisison.
ACTION_NONE, &extension);
const ErrorList& errors =
error_console()->GetErrorsForExtension(extension->id());
ASSERT_EQ(1u, errors.size());
// TODO(devlin): This is unfortunate. We lose a lot of context by using
// RenderFrame::AddMessageToConsole() instead of console.error(). This could
// be expanded; blink::SourceLocation knows how to capture an inspector
// stack trace.
std::string source =
extension->GetResourceURL(kGeneratedBackgroundPageFilename).spec();
// Line number '0' comes from errors that are logged to the render frame
// directly (e.g. background_age.html (0)).
size_t line_number = 0;
// Column number remains at the default specified in StackFrame (1).
size_t column_number = 1;
std::string message =
"Unchecked runtime.lastError: 'foobar' is not a recognized permission.";
CheckRuntimeError(errors[0].get(), extension->id(), source,
false, // not incognito
message, logging::LOG_ERROR,
extension->GetResourceURL(kBackgroundPageName), 1u);
const StackTrace& stack_trace = GetStackTraceFromError(errors[0].get());
ASSERT_EQ(1u, stack_trace.size());
CheckStackFrame(stack_trace[0], source, kAnonymousFunction, line_number,
column_number);
}
} // namespace extensions
|
user/_ln: 文件格式 elf64-littleriscv
Disassembly of section .text:
0000000000000000 <main>:
#include "kernel/stat.h"
#include "user/user.h"
int
main(int argc, char *argv[])
{
0: 1101 addi sp,sp,-32
2: ec06 sd ra,24(sp)
4: e822 sd s0,16(sp)
6: e426 sd s1,8(sp)
8: 1000 addi s0,sp,32
if(argc != 3){
a: 478d li a5,3
c: 02f50063 beq a0,a5,2c <main+0x2c>
fprintf(2, "Usage: ln old new\n");
10: 00000597 auipc a1,0x0
14: 7e058593 addi a1,a1,2016 # 7f0 <malloc+0xec>
18: 4509 li a0,2
1a: 00000097 auipc ra,0x0
1e: 5fe080e7 jalr 1534(ra) # 618 <fprintf>
exit(1);
22: 4505 li a0,1
24: 00000097 auipc ra,0x0
28: 2aa080e7 jalr 682(ra) # 2ce <exit>
2c: 84ae mv s1,a1
}
if(link(argv[1], argv[2]) < 0)
2e: 698c ld a1,16(a1)
30: 6488 ld a0,8(s1)
32: 00000097 auipc ra,0x0
36: 2fc080e7 jalr 764(ra) # 32e <link>
3a: 00054763 bltz a0,48 <main+0x48>
fprintf(2, "link %s %s: failed\n", argv[1], argv[2]);
exit(0);
3e: 4501 li a0,0
40: 00000097 auipc ra,0x0
44: 28e080e7 jalr 654(ra) # 2ce <exit>
fprintf(2, "link %s %s: failed\n", argv[1], argv[2]);
48: 6894 ld a3,16(s1)
4a: 6490 ld a2,8(s1)
4c: 00000597 auipc a1,0x0
50: 7bc58593 addi a1,a1,1980 # 808 <malloc+0x104>
54: 4509 li a0,2
56: 00000097 auipc ra,0x0
5a: 5c2080e7 jalr 1474(ra) # 618 <fprintf>
5e: b7c5 j 3e <main+0x3e>
0000000000000060 <strcpy>:
#include "kernel/fcntl.h"
#include "user/user.h"
char*
strcpy(char *s, const char *t)
{
60: 1141 addi sp,sp,-16
62: e422 sd s0,8(sp)
64: 0800 addi s0,sp,16
char *os;
os = s;
while((*s++ = *t++) != 0)
66: 87aa mv a5,a0
68: 0585 addi a1,a1,1
6a: 0785 addi a5,a5,1
6c: fff5c703 lbu a4,-1(a1)
70: fee78fa3 sb a4,-1(a5)
74: fb75 bnez a4,68 <strcpy+0x8>
;
return os;
}
76: 6422 ld s0,8(sp)
78: 0141 addi sp,sp,16
7a: 8082 ret
000000000000007c <strcmp>:
int
strcmp(const char *p, const char *q)
{
7c: 1141 addi sp,sp,-16
7e: e422 sd s0,8(sp)
80: 0800 addi s0,sp,16
while(*p && *p == *q)
82: 00054783 lbu a5,0(a0)
86: cb91 beqz a5,9a <strcmp+0x1e>
88: 0005c703 lbu a4,0(a1)
8c: 00f71763 bne a4,a5,9a <strcmp+0x1e>
p++, q++;
90: 0505 addi a0,a0,1
92: 0585 addi a1,a1,1
while(*p && *p == *q)
94: 00054783 lbu a5,0(a0)
98: fbe5 bnez a5,88 <strcmp+0xc>
return (uchar)*p - (uchar)*q;
9a: 0005c503 lbu a0,0(a1)
}
9e: 40a7853b subw a0,a5,a0
a2: 6422 ld s0,8(sp)
a4: 0141 addi sp,sp,16
a6: 8082 ret
00000000000000a8 <strlen>:
uint
strlen(const char *s)
{
a8: 1141 addi sp,sp,-16
aa: e422 sd s0,8(sp)
ac: 0800 addi s0,sp,16
int n;
for(n = 0; s[n]; n++)
ae: 00054783 lbu a5,0(a0)
b2: cf91 beqz a5,ce <strlen+0x26>
b4: 0505 addi a0,a0,1
b6: 87aa mv a5,a0
b8: 4685 li a3,1
ba: 9e89 subw a3,a3,a0
bc: 00f6853b addw a0,a3,a5
c0: 0785 addi a5,a5,1
c2: fff7c703 lbu a4,-1(a5)
c6: fb7d bnez a4,bc <strlen+0x14>
;
return n;
}
c8: 6422 ld s0,8(sp)
ca: 0141 addi sp,sp,16
cc: 8082 ret
for(n = 0; s[n]; n++)
ce: 4501 li a0,0
d0: bfe5 j c8 <strlen+0x20>
00000000000000d2 <memset>:
void*
memset(void *dst, int c, uint n)
{
d2: 1141 addi sp,sp,-16
d4: e422 sd s0,8(sp)
d6: 0800 addi s0,sp,16
char *cdst = (char *) dst;
int i;
for(i = 0; i < n; i++){
d8: ca19 beqz a2,ee <memset+0x1c>
da: 87aa mv a5,a0
dc: 1602 slli a2,a2,0x20
de: 9201 srli a2,a2,0x20
e0: 00a60733 add a4,a2,a0
cdst[i] = c;
e4: 00b78023 sb a1,0(a5)
for(i = 0; i < n; i++){
e8: 0785 addi a5,a5,1
ea: fee79de3 bne a5,a4,e4 <memset+0x12>
}
return dst;
}
ee: 6422 ld s0,8(sp)
f0: 0141 addi sp,sp,16
f2: 8082 ret
00000000000000f4 <strchr>:
char*
strchr(const char *s, char c)
{
f4: 1141 addi sp,sp,-16
f6: e422 sd s0,8(sp)
f8: 0800 addi s0,sp,16
for(; *s; s++)
fa: 00054783 lbu a5,0(a0)
fe: cb99 beqz a5,114 <strchr+0x20>
if(*s == c)
100: 00f58763 beq a1,a5,10e <strchr+0x1a>
for(; *s; s++)
104: 0505 addi a0,a0,1
106: 00054783 lbu a5,0(a0)
10a: fbfd bnez a5,100 <strchr+0xc>
return (char*)s;
return 0;
10c: 4501 li a0,0
}
10e: 6422 ld s0,8(sp)
110: 0141 addi sp,sp,16
112: 8082 ret
return 0;
114: 4501 li a0,0
116: bfe5 j 10e <strchr+0x1a>
0000000000000118 <gets>:
char*
gets(char *buf, int max)
{
118: 711d addi sp,sp,-96
11a: ec86 sd ra,88(sp)
11c: e8a2 sd s0,80(sp)
11e: e4a6 sd s1,72(sp)
120: e0ca sd s2,64(sp)
122: fc4e sd s3,56(sp)
124: f852 sd s4,48(sp)
126: f456 sd s5,40(sp)
128: f05a sd s6,32(sp)
12a: ec5e sd s7,24(sp)
12c: 1080 addi s0,sp,96
12e: 8baa mv s7,a0
130: 8a2e mv s4,a1
int i, cc;
char c;
for(i=0; i+1 < max; ){
132: 892a mv s2,a0
134: 4481 li s1,0
cc = read(0, &c, 1);
if(cc < 1)
break;
buf[i++] = c;
if(c == '\n' || c == '\r')
136: 4aa9 li s5,10
138: 4b35 li s6,13
for(i=0; i+1 < max; ){
13a: 89a6 mv s3,s1
13c: 2485 addiw s1,s1,1
13e: 0344d863 bge s1,s4,16e <gets+0x56>
cc = read(0, &c, 1);
142: 4605 li a2,1
144: faf40593 addi a1,s0,-81
148: 4501 li a0,0
14a: 00000097 auipc ra,0x0
14e: 19c080e7 jalr 412(ra) # 2e6 <read>
if(cc < 1)
152: 00a05e63 blez a0,16e <gets+0x56>
buf[i++] = c;
156: faf44783 lbu a5,-81(s0)
15a: 00f90023 sb a5,0(s2)
if(c == '\n' || c == '\r')
15e: 01578763 beq a5,s5,16c <gets+0x54>
162: 0905 addi s2,s2,1
164: fd679be3 bne a5,s6,13a <gets+0x22>
for(i=0; i+1 < max; ){
168: 89a6 mv s3,s1
16a: a011 j 16e <gets+0x56>
16c: 89a6 mv s3,s1
break;
}
buf[i] = '\0';
16e: 99de add s3,s3,s7
170: 00098023 sb zero,0(s3)
return buf;
}
174: 855e mv a0,s7
176: 60e6 ld ra,88(sp)
178: 6446 ld s0,80(sp)
17a: 64a6 ld s1,72(sp)
17c: 6906 ld s2,64(sp)
17e: 79e2 ld s3,56(sp)
180: 7a42 ld s4,48(sp)
182: 7aa2 ld s5,40(sp)
184: 7b02 ld s6,32(sp)
186: 6be2 ld s7,24(sp)
188: 6125 addi sp,sp,96
18a: 8082 ret
000000000000018c <stat>:
int
stat(const char *n, struct stat *st)
{
18c: 1101 addi sp,sp,-32
18e: ec06 sd ra,24(sp)
190: e822 sd s0,16(sp)
192: e426 sd s1,8(sp)
194: e04a sd s2,0(sp)
196: 1000 addi s0,sp,32
198: 892e mv s2,a1
int fd;
int r;
fd = open(n, O_RDONLY);
19a: 4581 li a1,0
19c: 00000097 auipc ra,0x0
1a0: 172080e7 jalr 370(ra) # 30e <open>
if(fd < 0)
1a4: 02054563 bltz a0,1ce <stat+0x42>
1a8: 84aa mv s1,a0
return -1;
r = fstat(fd, st);
1aa: 85ca mv a1,s2
1ac: 00000097 auipc ra,0x0
1b0: 17a080e7 jalr 378(ra) # 326 <fstat>
1b4: 892a mv s2,a0
close(fd);
1b6: 8526 mv a0,s1
1b8: 00000097 auipc ra,0x0
1bc: 13e080e7 jalr 318(ra) # 2f6 <close>
return r;
}
1c0: 854a mv a0,s2
1c2: 60e2 ld ra,24(sp)
1c4: 6442 ld s0,16(sp)
1c6: 64a2 ld s1,8(sp)
1c8: 6902 ld s2,0(sp)
1ca: 6105 addi sp,sp,32
1cc: 8082 ret
return -1;
1ce: 597d li s2,-1
1d0: bfc5 j 1c0 <stat+0x34>
00000000000001d2 <atoi>:
int
atoi(const char *s)
{
1d2: 1141 addi sp,sp,-16
1d4: e422 sd s0,8(sp)
1d6: 0800 addi s0,sp,16
int n;
n = 0;
while('0' <= *s && *s <= '9')
1d8: 00054603 lbu a2,0(a0)
1dc: fd06079b addiw a5,a2,-48
1e0: 0ff7f793 andi a5,a5,255
1e4: 4725 li a4,9
1e6: 02f76963 bltu a4,a5,218 <atoi+0x46>
1ea: 86aa mv a3,a0
n = 0;
1ec: 4501 li a0,0
while('0' <= *s && *s <= '9')
1ee: 45a5 li a1,9
n = n*10 + *s++ - '0';
1f0: 0685 addi a3,a3,1
1f2: 0025179b slliw a5,a0,0x2
1f6: 9fa9 addw a5,a5,a0
1f8: 0017979b slliw a5,a5,0x1
1fc: 9fb1 addw a5,a5,a2
1fe: fd07851b addiw a0,a5,-48
while('0' <= *s && *s <= '9')
202: 0006c603 lbu a2,0(a3)
206: fd06071b addiw a4,a2,-48
20a: 0ff77713 andi a4,a4,255
20e: fee5f1e3 bgeu a1,a4,1f0 <atoi+0x1e>
return n;
}
212: 6422 ld s0,8(sp)
214: 0141 addi sp,sp,16
216: 8082 ret
n = 0;
218: 4501 li a0,0
21a: bfe5 j 212 <atoi+0x40>
000000000000021c <memmove>:
void*
memmove(void *vdst, const void *vsrc, int n)
{
21c: 1141 addi sp,sp,-16
21e: e422 sd s0,8(sp)
220: 0800 addi s0,sp,16
char *dst;
const char *src;
dst = vdst;
src = vsrc;
if (src > dst) {
222: 02b57463 bgeu a0,a1,24a <memmove+0x2e>
while(n-- > 0)
226: 00c05f63 blez a2,244 <memmove+0x28>
22a: 1602 slli a2,a2,0x20
22c: 9201 srli a2,a2,0x20
22e: 00c507b3 add a5,a0,a2
dst = vdst;
232: 872a mv a4,a0
*dst++ = *src++;
234: 0585 addi a1,a1,1
236: 0705 addi a4,a4,1
238: fff5c683 lbu a3,-1(a1)
23c: fed70fa3 sb a3,-1(a4)
while(n-- > 0)
240: fee79ae3 bne a5,a4,234 <memmove+0x18>
src += n;
while(n-- > 0)
*--dst = *--src;
}
return vdst;
}
244: 6422 ld s0,8(sp)
246: 0141 addi sp,sp,16
248: 8082 ret
dst += n;
24a: 00c50733 add a4,a0,a2
src += n;
24e: 95b2 add a1,a1,a2
while(n-- > 0)
250: fec05ae3 blez a2,244 <memmove+0x28>
254: fff6079b addiw a5,a2,-1
258: 1782 slli a5,a5,0x20
25a: 9381 srli a5,a5,0x20
25c: fff7c793 not a5,a5
260: 97ba add a5,a5,a4
*--dst = *--src;
262: 15fd addi a1,a1,-1
264: 177d addi a4,a4,-1
266: 0005c683 lbu a3,0(a1)
26a: 00d70023 sb a3,0(a4)
while(n-- > 0)
26e: fee79ae3 bne a5,a4,262 <memmove+0x46>
272: bfc9 j 244 <memmove+0x28>
0000000000000274 <memcmp>:
int
memcmp(const void *s1, const void *s2, uint n)
{
274: 1141 addi sp,sp,-16
276: e422 sd s0,8(sp)
278: 0800 addi s0,sp,16
const char *p1 = s1, *p2 = s2;
while (n-- > 0) {
27a: ca05 beqz a2,2aa <memcmp+0x36>
27c: fff6069b addiw a3,a2,-1
280: 1682 slli a3,a3,0x20
282: 9281 srli a3,a3,0x20
284: 0685 addi a3,a3,1
286: 96aa add a3,a3,a0
if (*p1 != *p2) {
288: 00054783 lbu a5,0(a0)
28c: 0005c703 lbu a4,0(a1)
290: 00e79863 bne a5,a4,2a0 <memcmp+0x2c>
return *p1 - *p2;
}
p1++;
294: 0505 addi a0,a0,1
p2++;
296: 0585 addi a1,a1,1
while (n-- > 0) {
298: fed518e3 bne a0,a3,288 <memcmp+0x14>
}
return 0;
29c: 4501 li a0,0
29e: a019 j 2a4 <memcmp+0x30>
return *p1 - *p2;
2a0: 40e7853b subw a0,a5,a4
}
2a4: 6422 ld s0,8(sp)
2a6: 0141 addi sp,sp,16
2a8: 8082 ret
return 0;
2aa: 4501 li a0,0
2ac: bfe5 j 2a4 <memcmp+0x30>
00000000000002ae <memcpy>:
void *
memcpy(void *dst, const void *src, uint n)
{
2ae: 1141 addi sp,sp,-16
2b0: e406 sd ra,8(sp)
2b2: e022 sd s0,0(sp)
2b4: 0800 addi s0,sp,16
return memmove(dst, src, n);
2b6: 00000097 auipc ra,0x0
2ba: f66080e7 jalr -154(ra) # 21c <memmove>
}
2be: 60a2 ld ra,8(sp)
2c0: 6402 ld s0,0(sp)
2c2: 0141 addi sp,sp,16
2c4: 8082 ret
00000000000002c6 <fork>:
# generated by usys.pl - do not edit
#include "kernel/syscall.h"
.global fork
fork:
li a7, SYS_fork
2c6: 4885 li a7,1
ecall
2c8: 00000073 ecall
ret
2cc: 8082 ret
00000000000002ce <exit>:
.global exit
exit:
li a7, SYS_exit
2ce: 4889 li a7,2
ecall
2d0: 00000073 ecall
ret
2d4: 8082 ret
00000000000002d6 <wait>:
.global wait
wait:
li a7, SYS_wait
2d6: 488d li a7,3
ecall
2d8: 00000073 ecall
ret
2dc: 8082 ret
00000000000002de <pipe>:
.global pipe
pipe:
li a7, SYS_pipe
2de: 4891 li a7,4
ecall
2e0: 00000073 ecall
ret
2e4: 8082 ret
00000000000002e6 <read>:
.global read
read:
li a7, SYS_read
2e6: 4895 li a7,5
ecall
2e8: 00000073 ecall
ret
2ec: 8082 ret
00000000000002ee <write>:
.global write
write:
li a7, SYS_write
2ee: 48c1 li a7,16
ecall
2f0: 00000073 ecall
ret
2f4: 8082 ret
00000000000002f6 <close>:
.global close
close:
li a7, SYS_close
2f6: 48d5 li a7,21
ecall
2f8: 00000073 ecall
ret
2fc: 8082 ret
00000000000002fe <kill>:
.global kill
kill:
li a7, SYS_kill
2fe: 4899 li a7,6
ecall
300: 00000073 ecall
ret
304: 8082 ret
0000000000000306 <exec>:
.global exec
exec:
li a7, SYS_exec
306: 489d li a7,7
ecall
308: 00000073 ecall
ret
30c: 8082 ret
000000000000030e <open>:
.global open
open:
li a7, SYS_open
30e: 48bd li a7,15
ecall
310: 00000073 ecall
ret
314: 8082 ret
0000000000000316 <mknod>:
.global mknod
mknod:
li a7, SYS_mknod
316: 48c5 li a7,17
ecall
318: 00000073 ecall
ret
31c: 8082 ret
000000000000031e <unlink>:
.global unlink
unlink:
li a7, SYS_unlink
31e: 48c9 li a7,18
ecall
320: 00000073 ecall
ret
324: 8082 ret
0000000000000326 <fstat>:
.global fstat
fstat:
li a7, SYS_fstat
326: 48a1 li a7,8
ecall
328: 00000073 ecall
ret
32c: 8082 ret
000000000000032e <link>:
.global link
link:
li a7, SYS_link
32e: 48cd li a7,19
ecall
330: 00000073 ecall
ret
334: 8082 ret
0000000000000336 <mkdir>:
.global mkdir
mkdir:
li a7, SYS_mkdir
336: 48d1 li a7,20
ecall
338: 00000073 ecall
ret
33c: 8082 ret
000000000000033e <chdir>:
.global chdir
chdir:
li a7, SYS_chdir
33e: 48a5 li a7,9
ecall
340: 00000073 ecall
ret
344: 8082 ret
0000000000000346 <dup>:
.global dup
dup:
li a7, SYS_dup
346: 48a9 li a7,10
ecall
348: 00000073 ecall
ret
34c: 8082 ret
000000000000034e <getpid>:
.global getpid
getpid:
li a7, SYS_getpid
34e: 48ad li a7,11
ecall
350: 00000073 ecall
ret
354: 8082 ret
0000000000000356 <sbrk>:
.global sbrk
sbrk:
li a7, SYS_sbrk
356: 48b1 li a7,12
ecall
358: 00000073 ecall
ret
35c: 8082 ret
000000000000035e <sleep>:
.global sleep
sleep:
li a7, SYS_sleep
35e: 48b5 li a7,13
ecall
360: 00000073 ecall
ret
364: 8082 ret
0000000000000366 <uptime>:
.global uptime
uptime:
li a7, SYS_uptime
366: 48b9 li a7,14
ecall
368: 00000073 ecall
ret
36c: 8082 ret
000000000000036e <putc>:
static char digits[] = "0123456789ABCDEF";
static void
putc(int fd, char c)
{
36e: 1101 addi sp,sp,-32
370: ec06 sd ra,24(sp)
372: e822 sd s0,16(sp)
374: 1000 addi s0,sp,32
376: feb407a3 sb a1,-17(s0)
write(fd, &c, 1);
37a: 4605 li a2,1
37c: fef40593 addi a1,s0,-17
380: 00000097 auipc ra,0x0
384: f6e080e7 jalr -146(ra) # 2ee <write>
}
388: 60e2 ld ra,24(sp)
38a: 6442 ld s0,16(sp)
38c: 6105 addi sp,sp,32
38e: 8082 ret
0000000000000390 <printint>:
static void
printint(int fd, int xx, int base, int sgn)
{
390: 7139 addi sp,sp,-64
392: fc06 sd ra,56(sp)
394: f822 sd s0,48(sp)
396: f426 sd s1,40(sp)
398: f04a sd s2,32(sp)
39a: ec4e sd s3,24(sp)
39c: 0080 addi s0,sp,64
39e: 84aa mv s1,a0
char buf[16];
int i, neg;
uint x;
neg = 0;
if(sgn && xx < 0){
3a0: c299 beqz a3,3a6 <printint+0x16>
3a2: 0805c863 bltz a1,432 <printint+0xa2>
neg = 1;
x = -xx;
} else {
x = xx;
3a6: 2581 sext.w a1,a1
neg = 0;
3a8: 4881 li a7,0
3aa: fc040693 addi a3,s0,-64
}
i = 0;
3ae: 4701 li a4,0
do{
buf[i++] = digits[x % base];
3b0: 2601 sext.w a2,a2
3b2: 00000517 auipc a0,0x0
3b6: 47650513 addi a0,a0,1142 # 828 <digits>
3ba: 883a mv a6,a4
3bc: 2705 addiw a4,a4,1
3be: 02c5f7bb remuw a5,a1,a2
3c2: 1782 slli a5,a5,0x20
3c4: 9381 srli a5,a5,0x20
3c6: 97aa add a5,a5,a0
3c8: 0007c783 lbu a5,0(a5)
3cc: 00f68023 sb a5,0(a3)
}while((x /= base) != 0);
3d0: 0005879b sext.w a5,a1
3d4: 02c5d5bb divuw a1,a1,a2
3d8: 0685 addi a3,a3,1
3da: fec7f0e3 bgeu a5,a2,3ba <printint+0x2a>
if(neg)
3de: 00088b63 beqz a7,3f4 <printint+0x64>
buf[i++] = '-';
3e2: fd040793 addi a5,s0,-48
3e6: 973e add a4,a4,a5
3e8: 02d00793 li a5,45
3ec: fef70823 sb a5,-16(a4)
3f0: 0028071b addiw a4,a6,2
while(--i >= 0)
3f4: 02e05863 blez a4,424 <printint+0x94>
3f8: fc040793 addi a5,s0,-64
3fc: 00e78933 add s2,a5,a4
400: fff78993 addi s3,a5,-1
404: 99ba add s3,s3,a4
406: 377d addiw a4,a4,-1
408: 1702 slli a4,a4,0x20
40a: 9301 srli a4,a4,0x20
40c: 40e989b3 sub s3,s3,a4
putc(fd, buf[i]);
410: fff94583 lbu a1,-1(s2)
414: 8526 mv a0,s1
416: 00000097 auipc ra,0x0
41a: f58080e7 jalr -168(ra) # 36e <putc>
while(--i >= 0)
41e: 197d addi s2,s2,-1
420: ff3918e3 bne s2,s3,410 <printint+0x80>
}
424: 70e2 ld ra,56(sp)
426: 7442 ld s0,48(sp)
428: 74a2 ld s1,40(sp)
42a: 7902 ld s2,32(sp)
42c: 69e2 ld s3,24(sp)
42e: 6121 addi sp,sp,64
430: 8082 ret
x = -xx;
432: 40b005bb negw a1,a1
neg = 1;
436: 4885 li a7,1
x = -xx;
438: bf8d j 3aa <printint+0x1a>
000000000000043a <vprintf>:
}
// Print to the given fd. Only understands %d, %x, %p, %s.
void
vprintf(int fd, const char *fmt, va_list ap)
{
43a: 7119 addi sp,sp,-128
43c: fc86 sd ra,120(sp)
43e: f8a2 sd s0,112(sp)
440: f4a6 sd s1,104(sp)
442: f0ca sd s2,96(sp)
444: ecce sd s3,88(sp)
446: e8d2 sd s4,80(sp)
448: e4d6 sd s5,72(sp)
44a: e0da sd s6,64(sp)
44c: fc5e sd s7,56(sp)
44e: f862 sd s8,48(sp)
450: f466 sd s9,40(sp)
452: f06a sd s10,32(sp)
454: ec6e sd s11,24(sp)
456: 0100 addi s0,sp,128
char *s;
int c, i, state;
state = 0;
for(i = 0; fmt[i]; i++){
458: 0005c903 lbu s2,0(a1)
45c: 18090f63 beqz s2,5fa <vprintf+0x1c0>
460: 8aaa mv s5,a0
462: 8b32 mv s6,a2
464: 00158493 addi s1,a1,1
state = 0;
468: 4981 li s3,0
if(c == '%'){
state = '%';
} else {
putc(fd, c);
}
} else if(state == '%'){
46a: 02500a13 li s4,37
if(c == 'd'){
46e: 06400c13 li s8,100
printint(fd, va_arg(ap, int), 10, 1);
} else if(c == 'l') {
472: 06c00c93 li s9,108
printint(fd, va_arg(ap, uint64), 10, 0);
} else if(c == 'x') {
476: 07800d13 li s10,120
printint(fd, va_arg(ap, int), 16, 0);
} else if(c == 'p') {
47a: 07000d93 li s11,112
putc(fd, digits[x >> (sizeof(uint64) * 8 - 4)]);
47e: 00000b97 auipc s7,0x0
482: 3aab8b93 addi s7,s7,938 # 828 <digits>
486: a839 j 4a4 <vprintf+0x6a>
putc(fd, c);
488: 85ca mv a1,s2
48a: 8556 mv a0,s5
48c: 00000097 auipc ra,0x0
490: ee2080e7 jalr -286(ra) # 36e <putc>
494: a019 j 49a <vprintf+0x60>
} else if(state == '%'){
496: 01498f63 beq s3,s4,4b4 <vprintf+0x7a>
for(i = 0; fmt[i]; i++){
49a: 0485 addi s1,s1,1
49c: fff4c903 lbu s2,-1(s1)
4a0: 14090d63 beqz s2,5fa <vprintf+0x1c0>
c = fmt[i] & 0xff;
4a4: 0009079b sext.w a5,s2
if(state == 0){
4a8: fe0997e3 bnez s3,496 <vprintf+0x5c>
if(c == '%'){
4ac: fd479ee3 bne a5,s4,488 <vprintf+0x4e>
state = '%';
4b0: 89be mv s3,a5
4b2: b7e5 j 49a <vprintf+0x60>
if(c == 'd'){
4b4: 05878063 beq a5,s8,4f4 <vprintf+0xba>
} else if(c == 'l') {
4b8: 05978c63 beq a5,s9,510 <vprintf+0xd6>
} else if(c == 'x') {
4bc: 07a78863 beq a5,s10,52c <vprintf+0xf2>
} else if(c == 'p') {
4c0: 09b78463 beq a5,s11,548 <vprintf+0x10e>
printptr(fd, va_arg(ap, uint64));
} else if(c == 's'){
4c4: 07300713 li a4,115
4c8: 0ce78663 beq a5,a4,594 <vprintf+0x15a>
s = "(null)";
while(*s != 0){
putc(fd, *s);
s++;
}
} else if(c == 'c'){
4cc: 06300713 li a4,99
4d0: 0ee78e63 beq a5,a4,5cc <vprintf+0x192>
putc(fd, va_arg(ap, uint));
} else if(c == '%'){
4d4: 11478863 beq a5,s4,5e4 <vprintf+0x1aa>
putc(fd, c);
} else {
// Unknown % sequence. Print it to draw attention.
putc(fd, '%');
4d8: 85d2 mv a1,s4
4da: 8556 mv a0,s5
4dc: 00000097 auipc ra,0x0
4e0: e92080e7 jalr -366(ra) # 36e <putc>
putc(fd, c);
4e4: 85ca mv a1,s2
4e6: 8556 mv a0,s5
4e8: 00000097 auipc ra,0x0
4ec: e86080e7 jalr -378(ra) # 36e <putc>
}
state = 0;
4f0: 4981 li s3,0
4f2: b765 j 49a <vprintf+0x60>
printint(fd, va_arg(ap, int), 10, 1);
4f4: 008b0913 addi s2,s6,8
4f8: 4685 li a3,1
4fa: 4629 li a2,10
4fc: 000b2583 lw a1,0(s6)
500: 8556 mv a0,s5
502: 00000097 auipc ra,0x0
506: e8e080e7 jalr -370(ra) # 390 <printint>
50a: 8b4a mv s6,s2
state = 0;
50c: 4981 li s3,0
50e: b771 j 49a <vprintf+0x60>
printint(fd, va_arg(ap, uint64), 10, 0);
510: 008b0913 addi s2,s6,8
514: 4681 li a3,0
516: 4629 li a2,10
518: 000b2583 lw a1,0(s6)
51c: 8556 mv a0,s5
51e: 00000097 auipc ra,0x0
522: e72080e7 jalr -398(ra) # 390 <printint>
526: 8b4a mv s6,s2
state = 0;
528: 4981 li s3,0
52a: bf85 j 49a <vprintf+0x60>
printint(fd, va_arg(ap, int), 16, 0);
52c: 008b0913 addi s2,s6,8
530: 4681 li a3,0
532: 4641 li a2,16
534: 000b2583 lw a1,0(s6)
538: 8556 mv a0,s5
53a: 00000097 auipc ra,0x0
53e: e56080e7 jalr -426(ra) # 390 <printint>
542: 8b4a mv s6,s2
state = 0;
544: 4981 li s3,0
546: bf91 j 49a <vprintf+0x60>
printptr(fd, va_arg(ap, uint64));
548: 008b0793 addi a5,s6,8
54c: f8f43423 sd a5,-120(s0)
550: 000b3983 ld s3,0(s6)
putc(fd, '0');
554: 03000593 li a1,48
558: 8556 mv a0,s5
55a: 00000097 auipc ra,0x0
55e: e14080e7 jalr -492(ra) # 36e <putc>
putc(fd, 'x');
562: 85ea mv a1,s10
564: 8556 mv a0,s5
566: 00000097 auipc ra,0x0
56a: e08080e7 jalr -504(ra) # 36e <putc>
56e: 4941 li s2,16
putc(fd, digits[x >> (sizeof(uint64) * 8 - 4)]);
570: 03c9d793 srli a5,s3,0x3c
574: 97de add a5,a5,s7
576: 0007c583 lbu a1,0(a5)
57a: 8556 mv a0,s5
57c: 00000097 auipc ra,0x0
580: df2080e7 jalr -526(ra) # 36e <putc>
for (i = 0; i < (sizeof(uint64) * 2); i++, x <<= 4)
584: 0992 slli s3,s3,0x4
586: 397d addiw s2,s2,-1
588: fe0914e3 bnez s2,570 <vprintf+0x136>
printptr(fd, va_arg(ap, uint64));
58c: f8843b03 ld s6,-120(s0)
state = 0;
590: 4981 li s3,0
592: b721 j 49a <vprintf+0x60>
s = va_arg(ap, char*);
594: 008b0993 addi s3,s6,8
598: 000b3903 ld s2,0(s6)
if(s == 0)
59c: 02090163 beqz s2,5be <vprintf+0x184>
while(*s != 0){
5a0: 00094583 lbu a1,0(s2)
5a4: c9a1 beqz a1,5f4 <vprintf+0x1ba>
putc(fd, *s);
5a6: 8556 mv a0,s5
5a8: 00000097 auipc ra,0x0
5ac: dc6080e7 jalr -570(ra) # 36e <putc>
s++;
5b0: 0905 addi s2,s2,1
while(*s != 0){
5b2: 00094583 lbu a1,0(s2)
5b6: f9e5 bnez a1,5a6 <vprintf+0x16c>
s = va_arg(ap, char*);
5b8: 8b4e mv s6,s3
state = 0;
5ba: 4981 li s3,0
5bc: bdf9 j 49a <vprintf+0x60>
s = "(null)";
5be: 00000917 auipc s2,0x0
5c2: 26290913 addi s2,s2,610 # 820 <malloc+0x11c>
while(*s != 0){
5c6: 02800593 li a1,40
5ca: bff1 j 5a6 <vprintf+0x16c>
putc(fd, va_arg(ap, uint));
5cc: 008b0913 addi s2,s6,8
5d0: 000b4583 lbu a1,0(s6)
5d4: 8556 mv a0,s5
5d6: 00000097 auipc ra,0x0
5da: d98080e7 jalr -616(ra) # 36e <putc>
5de: 8b4a mv s6,s2
state = 0;
5e0: 4981 li s3,0
5e2: bd65 j 49a <vprintf+0x60>
putc(fd, c);
5e4: 85d2 mv a1,s4
5e6: 8556 mv a0,s5
5e8: 00000097 auipc ra,0x0
5ec: d86080e7 jalr -634(ra) # 36e <putc>
state = 0;
5f0: 4981 li s3,0
5f2: b565 j 49a <vprintf+0x60>
s = va_arg(ap, char*);
5f4: 8b4e mv s6,s3
state = 0;
5f6: 4981 li s3,0
5f8: b54d j 49a <vprintf+0x60>
}
}
}
5fa: 70e6 ld ra,120(sp)
5fc: 7446 ld s0,112(sp)
5fe: 74a6 ld s1,104(sp)
600: 7906 ld s2,96(sp)
602: 69e6 ld s3,88(sp)
604: 6a46 ld s4,80(sp)
606: 6aa6 ld s5,72(sp)
608: 6b06 ld s6,64(sp)
60a: 7be2 ld s7,56(sp)
60c: 7c42 ld s8,48(sp)
60e: 7ca2 ld s9,40(sp)
610: 7d02 ld s10,32(sp)
612: 6de2 ld s11,24(sp)
614: 6109 addi sp,sp,128
616: 8082 ret
0000000000000618 <fprintf>:
void
fprintf(int fd, const char *fmt, ...)
{
618: 715d addi sp,sp,-80
61a: ec06 sd ra,24(sp)
61c: e822 sd s0,16(sp)
61e: 1000 addi s0,sp,32
620: e010 sd a2,0(s0)
622: e414 sd a3,8(s0)
624: e818 sd a4,16(s0)
626: ec1c sd a5,24(s0)
628: 03043023 sd a6,32(s0)
62c: 03143423 sd a7,40(s0)
va_list ap;
va_start(ap, fmt);
630: fe843423 sd s0,-24(s0)
vprintf(fd, fmt, ap);
634: 8622 mv a2,s0
636: 00000097 auipc ra,0x0
63a: e04080e7 jalr -508(ra) # 43a <vprintf>
}
63e: 60e2 ld ra,24(sp)
640: 6442 ld s0,16(sp)
642: 6161 addi sp,sp,80
644: 8082 ret
0000000000000646 <printf>:
void
printf(const char *fmt, ...)
{
646: 711d addi sp,sp,-96
648: ec06 sd ra,24(sp)
64a: e822 sd s0,16(sp)
64c: 1000 addi s0,sp,32
64e: e40c sd a1,8(s0)
650: e810 sd a2,16(s0)
652: ec14 sd a3,24(s0)
654: f018 sd a4,32(s0)
656: f41c sd a5,40(s0)
658: 03043823 sd a6,48(s0)
65c: 03143c23 sd a7,56(s0)
va_list ap;
va_start(ap, fmt);
660: 00840613 addi a2,s0,8
664: fec43423 sd a2,-24(s0)
vprintf(1, fmt, ap);
668: 85aa mv a1,a0
66a: 4505 li a0,1
66c: 00000097 auipc ra,0x0
670: dce080e7 jalr -562(ra) # 43a <vprintf>
}
674: 60e2 ld ra,24(sp)
676: 6442 ld s0,16(sp)
678: 6125 addi sp,sp,96
67a: 8082 ret
000000000000067c <free>:
static Header base;
static Header *freep;
void
free(void *ap)
{
67c: 1141 addi sp,sp,-16
67e: e422 sd s0,8(sp)
680: 0800 addi s0,sp,16
Header *bp, *p;
bp = (Header*)ap - 1;
682: ff050693 addi a3,a0,-16
for(p = freep; !(bp > p && bp < p->s.ptr); p = p->s.ptr)
686: 00000797 auipc a5,0x0
68a: 1ba7b783 ld a5,442(a5) # 840 <freep>
68e: a805 j 6be <free+0x42>
if(p >= p->s.ptr && (bp > p || bp < p->s.ptr))
break;
if(bp + bp->s.size == p->s.ptr){
bp->s.size += p->s.ptr->s.size;
690: 4618 lw a4,8(a2)
692: 9db9 addw a1,a1,a4
694: feb52c23 sw a1,-8(a0)
bp->s.ptr = p->s.ptr->s.ptr;
698: 6398 ld a4,0(a5)
69a: 6318 ld a4,0(a4)
69c: fee53823 sd a4,-16(a0)
6a0: a091 j 6e4 <free+0x68>
} else
bp->s.ptr = p->s.ptr;
if(p + p->s.size == bp){
p->s.size += bp->s.size;
6a2: ff852703 lw a4,-8(a0)
6a6: 9e39 addw a2,a2,a4
6a8: c790 sw a2,8(a5)
p->s.ptr = bp->s.ptr;
6aa: ff053703 ld a4,-16(a0)
6ae: e398 sd a4,0(a5)
6b0: a099 j 6f6 <free+0x7a>
if(p >= p->s.ptr && (bp > p || bp < p->s.ptr))
6b2: 6398 ld a4,0(a5)
6b4: 00e7e463 bltu a5,a4,6bc <free+0x40>
6b8: 00e6ea63 bltu a3,a4,6cc <free+0x50>
{
6bc: 87ba mv a5,a4
for(p = freep; !(bp > p && bp < p->s.ptr); p = p->s.ptr)
6be: fed7fae3 bgeu a5,a3,6b2 <free+0x36>
6c2: 6398 ld a4,0(a5)
6c4: 00e6e463 bltu a3,a4,6cc <free+0x50>
if(p >= p->s.ptr && (bp > p || bp < p->s.ptr))
6c8: fee7eae3 bltu a5,a4,6bc <free+0x40>
if(bp + bp->s.size == p->s.ptr){
6cc: ff852583 lw a1,-8(a0)
6d0: 6390 ld a2,0(a5)
6d2: 02059813 slli a6,a1,0x20
6d6: 01c85713 srli a4,a6,0x1c
6da: 9736 add a4,a4,a3
6dc: fae60ae3 beq a2,a4,690 <free+0x14>
bp->s.ptr = p->s.ptr;
6e0: fec53823 sd a2,-16(a0)
if(p + p->s.size == bp){
6e4: 4790 lw a2,8(a5)
6e6: 02061593 slli a1,a2,0x20
6ea: 01c5d713 srli a4,a1,0x1c
6ee: 973e add a4,a4,a5
6f0: fae689e3 beq a3,a4,6a2 <free+0x26>
} else
p->s.ptr = bp;
6f4: e394 sd a3,0(a5)
freep = p;
6f6: 00000717 auipc a4,0x0
6fa: 14f73523 sd a5,330(a4) # 840 <freep>
}
6fe: 6422 ld s0,8(sp)
700: 0141 addi sp,sp,16
702: 8082 ret
0000000000000704 <malloc>:
return freep;
}
void*
malloc(uint nbytes)
{
704: 7139 addi sp,sp,-64
706: fc06 sd ra,56(sp)
708: f822 sd s0,48(sp)
70a: f426 sd s1,40(sp)
70c: f04a sd s2,32(sp)
70e: ec4e sd s3,24(sp)
710: e852 sd s4,16(sp)
712: e456 sd s5,8(sp)
714: e05a sd s6,0(sp)
716: 0080 addi s0,sp,64
Header *p, *prevp;
uint nunits;
nunits = (nbytes + sizeof(Header) - 1)/sizeof(Header) + 1;
718: 02051493 slli s1,a0,0x20
71c: 9081 srli s1,s1,0x20
71e: 04bd addi s1,s1,15
720: 8091 srli s1,s1,0x4
722: 0014899b addiw s3,s1,1
726: 0485 addi s1,s1,1
if((prevp = freep) == 0){
728: 00000517 auipc a0,0x0
72c: 11853503 ld a0,280(a0) # 840 <freep>
730: c515 beqz a0,75c <malloc+0x58>
base.s.ptr = freep = prevp = &base;
base.s.size = 0;
}
for(p = prevp->s.ptr; ; prevp = p, p = p->s.ptr){
732: 611c ld a5,0(a0)
if(p->s.size >= nunits){
734: 4798 lw a4,8(a5)
736: 02977f63 bgeu a4,s1,774 <malloc+0x70>
73a: 8a4e mv s4,s3
73c: 0009871b sext.w a4,s3
740: 6685 lui a3,0x1
742: 00d77363 bgeu a4,a3,748 <malloc+0x44>
746: 6a05 lui s4,0x1
748: 000a0b1b sext.w s6,s4
p = sbrk(nu * sizeof(Header));
74c: 004a1a1b slliw s4,s4,0x4
p->s.size = nunits;
}
freep = prevp;
return (void*)(p + 1);
}
if(p == freep)
750: 00000917 auipc s2,0x0
754: 0f090913 addi s2,s2,240 # 840 <freep>
if(p == (char*)-1)
758: 5afd li s5,-1
75a: a895 j 7ce <malloc+0xca>
base.s.ptr = freep = prevp = &base;
75c: 00000797 auipc a5,0x0
760: 0ec78793 addi a5,a5,236 # 848 <base>
764: 00000717 auipc a4,0x0
768: 0cf73e23 sd a5,220(a4) # 840 <freep>
76c: e39c sd a5,0(a5)
base.s.size = 0;
76e: 0007a423 sw zero,8(a5)
if(p->s.size >= nunits){
772: b7e1 j 73a <malloc+0x36>
if(p->s.size == nunits)
774: 02e48c63 beq s1,a4,7ac <malloc+0xa8>
p->s.size -= nunits;
778: 4137073b subw a4,a4,s3
77c: c798 sw a4,8(a5)
p += p->s.size;
77e: 02071693 slli a3,a4,0x20
782: 01c6d713 srli a4,a3,0x1c
786: 97ba add a5,a5,a4
p->s.size = nunits;
788: 0137a423 sw s3,8(a5)
freep = prevp;
78c: 00000717 auipc a4,0x0
790: 0aa73a23 sd a0,180(a4) # 840 <freep>
return (void*)(p + 1);
794: 01078513 addi a0,a5,16
if((p = morecore(nunits)) == 0)
return 0;
}
}
798: 70e2 ld ra,56(sp)
79a: 7442 ld s0,48(sp)
79c: 74a2 ld s1,40(sp)
79e: 7902 ld s2,32(sp)
7a0: 69e2 ld s3,24(sp)
7a2: 6a42 ld s4,16(sp)
7a4: 6aa2 ld s5,8(sp)
7a6: 6b02 ld s6,0(sp)
7a8: 6121 addi sp,sp,64
7aa: 8082 ret
prevp->s.ptr = p->s.ptr;
7ac: 6398 ld a4,0(a5)
7ae: e118 sd a4,0(a0)
7b0: bff1 j 78c <malloc+0x88>
hp->s.size = nu;
7b2: 01652423 sw s6,8(a0)
free((void*)(hp + 1));
7b6: 0541 addi a0,a0,16
7b8: 00000097 auipc ra,0x0
7bc: ec4080e7 jalr -316(ra) # 67c <free>
return freep;
7c0: 00093503 ld a0,0(s2)
if((p = morecore(nunits)) == 0)
7c4: d971 beqz a0,798 <malloc+0x94>
for(p = prevp->s.ptr; ; prevp = p, p = p->s.ptr){
7c6: 611c ld a5,0(a0)
if(p->s.size >= nunits){
7c8: 4798 lw a4,8(a5)
7ca: fa9775e3 bgeu a4,s1,774 <malloc+0x70>
if(p == freep)
7ce: 00093703 ld a4,0(s2)
7d2: 853e mv a0,a5
7d4: fef719e3 bne a4,a5,7c6 <malloc+0xc2>
p = sbrk(nu * sizeof(Header));
7d8: 8552 mv a0,s4
7da: 00000097 auipc ra,0x0
7de: b7c080e7 jalr -1156(ra) # 356 <sbrk>
if(p == (char*)-1)
7e2: fd5518e3 bne a0,s5,7b2 <malloc+0xae>
return 0;
7e6: 4501 li a0,0
7e8: bf45 j 798 <malloc+0x94>
|
.size 8000
.text@48
ei
jp lstatint
.text@100
jp lbegin
.data@143
c0
.text@150
lbegin:
ld a, 00
ldff(ff), a
ld a, 30
ldff(00), a
ld a, 01
ldff(4d), a
stop, 00
ld c, 44
ld b, 90
lbegin_waitly90:
ldff a, (c)
cmp a, b
jrnz lbegin_waitly90
xor a, a
ldff(40), a
ld hl, 9f00
ld b, 20
lbegin_clearvram:
dec l
ld(hl), a
jrnz lbegin_clearvram
dec h
dec b
jrnz lbegin_clearvram
ld hl, 8010
ld a, ff
ld(hl++), a
ld(hl++), a
ld(hl++), a
ld(hl++), a
ld(hl++), a
ld(hl++), a
ld(hl++), a
ld(hl++), a
ld(hl++), a
ld(hl++), a
ld(hl++), a
ld(hl++), a
ld(hl++), a
ld(hl++), a
ld(hl++), a
ld(hl++), a
ld(hl++), a
ld(hl++), a
ld hl, 9f00
ld b, 04
ld a, 01
lbegin_filluppertilemap:
dec l
ld(hl), a
jrnz lbegin_filluppertilemap
dec h
dec b
jrnz lbegin_filluppertilemap
ld a, e4
ldff(47), a
ld a, ff
ldff(48), a
ld a, 80
ldff(68), a
ld a, ff
ld c, 69
ldff(c), a
ldff(c), a
ld a, aa
ldff(c), a
ldff(c), a
ld a, 55
ldff(c), a
ldff(c), a
xor a, a
ldff(c), a
ldff(c), a
ld a, 80
ldff(6a), a
ld a, 00
ld c, 6b
ldff(c), a
ldff(c), a
ldff(c), a
ldff(c), a
ldff(c), a
ldff(c), a
ldff(c), a
ldff(c), a
ld hl, fea0
xor a, a
lbegin_fill_oam:
dec l
ld(hl), a
jrnz lbegin_fill_oam
ld a, 10
ld(hl), a
inc l
ld a, 08
ld(hl), a
ld a, 97
ldff(40), a
ld c, 41
ld b, 03
lbegin_waitm3:
ldff a, (c)
and a, b
cmp a, b
jrnz lbegin_waitm3
ld a, 20
ldff(c), a
ld a, 02
ldff(ff), a
xor a, a
ldff(0f), a
ei
.text@1000
lstatint:
nop
.text@102a
ld a, 9f
ldff(40), a
pop hl
.text@1066
ld a, 97
ldff(40), a
|
; ----------------------------------------------------------------
; Z88DK INTERFACE LIBRARY FOR NIRVANA+ ENGINE - by Einar Saukas
;
; See "nirvana+.h" for further details
; ----------------------------------------------------------------
; void NIRVANAP_printC(unsigned int ch, unsigned char *attrs, unsigned int lin, unsigned int col)
SECTION code_clib
SECTION code_nirvanap
PUBLIC NIRVANAP_printC
EXTERN asm_NIRVANAP_printC
NIRVANAP_printC:
ld hl,2
add hl,sp
ld e,(hl) ; col
inc hl
inc hl
ld d,(hl) ; lin
inc hl
inc hl
ld c,(hl)
inc hl
ld b,(hl) ; attrs
inc hl
ld a,(hl) ; ch
jp asm_NIRVANAP_printC
|
; A158561: a(n)=((2^n)*((2^n)+1) - (2^(n-1))*((2^(n-1))+1))/2, a(1)=3.
; 3,7,26,100,392,1552,6176,24640,98432,393472,1573376,6292480,25167872,100667392,402661376,1610629120,6442483712,25769869312,103079346176,412317122560,1649267965952,6597070815232,26388281163776,105553120460800,422212473454592,1688849877041152,6755399474610176
mov $1,2
pow $1,$0
mul $1,6
add $1,1
pow $1,2
sub $1,51
div $1,24
add $1,3
|
#include "opencv2/mcc.hpp"
template <>
struct pyopencvVecConverter<Ptr<mcc::CChecker>>
{
static bool to(PyObject *obj, std::vector<Ptr<mcc::CChecker>> &value,
const ArgInfo &info)
{
return pyopencv_to_generic_vec(obj, value, info);
}
static PyObject *from(const std::vector<Ptr<mcc::CChecker>> &value)
{
return pyopencv_from_generic_vec(value);
}
};
typedef std::vector<cv::Ptr<mcc::CChecker>> vector_Ptr_CChecker;
typedef dnn::Net dnn_Net;
|
; A024401: a(n) = [ (3rd elementary symmetric function of S(n))/(2nd elementary symmetric function of S(n)) ], where S(n) = {first n+2 positive integers congruent to 2 mod 3}.
; 1,3,6,11,16,22,30,38,47,58,69,81,95,109,124,141,158,176,196,216,237,260,283,307,333,359,386,415,444,474,506,538,571,606,641,677,715,753,792,833,874,916,960
mov $1,$0
div $1,3
mov $2,$0
lpb $2,1
add $1,$2
add $1,1
sub $2,1
lpe
add $1,1
|
bits 64
default rel
section .text
global pal_execute_invept_checked
pal_execute_invept_checked :
invept rdi, [rsi]
jbe pal_execute_invept_checked_failure
mov rax, 0x1
ret
pal_execute_invept_checked_failure :
mov rax, 0x0
ret
|
; A016861: a(n) = 5*n + 1.
; 1,6,11,16,21,26,31,36,41,46,51,56,61,66,71,76,81,86,91,96,101,106,111,116,121,126,131,136,141,146,151,156,161,166,171,176,181,186,191,196,201,206,211,216,221,226,231,236,241,246,251,256,261,266,271,276,281,286,291,296,301,306,311,316,321,326,331,336,341,346,351,356,361,366,371,376,381,386,391,396,401,406,411,416,421,426,431,436,441,446,451,456,461,466,471,476,481,486,491,496,501,506,511,516,521,526,531,536,541,546,551,556,561,566,571,576,581,586,591,596,601,606,611,616,621,626,631,636,641,646,651,656,661,666,671,676,681,686,691,696,701,706,711,716,721,726,731,736,741,746,751,756,761,766,771,776,781,786,791,796,801,806,811,816,821,826,831,836,841,846,851,856,861,866,871,876,881,886,891,896,901,906,911,916,921,926,931,936,941,946,951,956,961,966,971,976,981,986,991,996,1001,1006,1011,1016,1021,1026,1031,1036,1041,1046,1051,1056,1061,1066,1071,1076,1081,1086,1091,1096,1101,1106,1111,1116,1121,1126,1131,1136,1141,1146,1151,1156,1161,1166,1171,1176,1181,1186,1191,1196,1201,1206,1211,1216,1221,1226,1231,1236,1241,1246
mov $1,$0
mul $1,5
add $1,1
|
; A082903: a(n) = gcd(2^n, sigma_1(n)) = gcd(A000079(n), A000203(n)) also a(n) = gcd(2^n, sigma_3(n)) = gcd(A000079(n), A001158(n)).
; 1,1,4,1,2,4,8,1,1,2,4,4,2,8,8,1,2,1,4,2,32,4,8,4,1,2,8,8,2,8,32,1,16,2,16,1,2,4,8,2,2,32,4,4,2,8,16,4,1,1,8,2,2,8,8,8,16,2,4,8,2,32,8,1,4,16,4,2,32,16,8,1,2,2,4,4,32,8,16,2,1,2,4,32,4,4,8,4,2,2,16,8,128,16,8,4,2,1,4,1,2,8,8,2,64,2,4,8,2,8,8,8,2,16,16,2,2,4,16,8,1,2,8,32,4,8,128,1,16,4,4,16,32,4,16,2,2,32,4,16,64,8,8,1,4,2,4,2,2,4,8,4,2,32,64,8,2,16,8,2,64,1,4,2,32,4,8,32,1,4,4,4,2,8,8,4,16,2,4,2,2,16,8,8,4,128,8,16,64,8,64,4,2,2,16,1,2,4,8,1,16,2,16,8,4,8,8,2,16,64,4,2,32,4,8,8,256,2,8,8,4,8,32,8,1,2,4,16,2,16,128,2,2,2,32,4,64,16,16,8,2,1,4,2,2,8,8,32,16,4
cal $0,203 ; a(n) = sigma(n), the sum of the divisors of n. Also called sigma_1(n).
gcd $0,1073741824
mov $1,$0
|
#include "PlatformPrecomp.h"
#include "ProtonTesterGUI.h"
#include "ProtonTester.h"
#include "Entity/EntityUtils.h"
namespace ProtonTester {
void showResultOnScreen(Entity *parent)
{
string resultText = "PASS";
uint32 resultColor = MAKE_RGBA(0, 255, 0, 255);
if (GetNumFailed() > 0)
{
resultText = "FAIL";
resultColor = MAKE_RGBA(255, 0, 0, 255);
}
Entity* resultEntity = CreateTextLabelEntity(parent, "TestResult", 100, 100, resultText);
resultEntity->GetVar("color")->Set(resultColor);
string detailText = toString(GetTotalRun()) + " tests run. " + toString(GetNumFailed()) + " failed, " + toString(GetNumPassed()) + " passed.";
CreateTextLabelEntity(parent, "TestDetail", 100, 150, detailText);
if (GetNumFailed() > 0)
{
CreateTextLabelEntity(parent, "SeeConsole", 100, 200, "Check the console for details");
}
}
}
|
/*
* Copyright (c) 2017, Intel Corporation
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included
* in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
* OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR
* OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
* ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
* OTHER DEALINGS IN THE SOFTWARE.
*/
L0:
mov (8|M0) r127.0<1>:ud r0.0<8;8,1>:ud
send (1|M0) null:d r127:ub 0x27 0x02000010 {EOT} // SPAWNER wr:1, rd:0, fc: 0x10
nop
nop
nop
nop
nop
nop
nop
nop
|
;CodeVisionAVR C Compiler V3.12 Advanced
;(C) Copyright 1998-2014 Pavel Haiduc, HP InfoTech s.r.l.
;http://www.hpinfotech.com
;Build configuration : Debug
;Chip type : ATmega16
;Program type : Application
;Clock frequency : 8.000000 MHz
;Memory model : Small
;Optimize for : Size
;(s)printf features : int, width
;(s)scanf features : int, width
;External RAM size : 0
;Data Stack size : 256 byte(s)
;Heap size : 0 byte(s)
;Promote 'char' to 'int': Yes
;'char' is unsigned : Yes
;8 bit enums : Yes
;Global 'const' stored in FLASH: No
;Enhanced function parameter passing: Yes
;Enhanced core instructions: On
;Automatic register allocation for global variables: On
;Smart register allocation: On
#define _MODEL_SMALL_
#pragma AVRPART ADMIN PART_NAME ATmega16
#pragma AVRPART MEMORY PROG_FLASH 16384
#pragma AVRPART MEMORY EEPROM 512
#pragma AVRPART MEMORY INT_SRAM SIZE 1024
#pragma AVRPART MEMORY INT_SRAM START_ADDR 0x60
#define CALL_SUPPORTED 1
.LISTMAC
.EQU UDRE=0x5
.EQU RXC=0x7
.EQU USR=0xB
.EQU UDR=0xC
.EQU SPSR=0xE
.EQU SPDR=0xF
.EQU EERE=0x0
.EQU EEWE=0x1
.EQU EEMWE=0x2
.EQU EECR=0x1C
.EQU EEDR=0x1D
.EQU EEARL=0x1E
.EQU EEARH=0x1F
.EQU WDTCR=0x21
.EQU MCUCR=0x35
.EQU GICR=0x3B
.EQU SPL=0x3D
.EQU SPH=0x3E
.EQU SREG=0x3F
.DEF R0X0=R0
.DEF R0X1=R1
.DEF R0X2=R2
.DEF R0X3=R3
.DEF R0X4=R4
.DEF R0X5=R5
.DEF R0X6=R6
.DEF R0X7=R7
.DEF R0X8=R8
.DEF R0X9=R9
.DEF R0XA=R10
.DEF R0XB=R11
.DEF R0XC=R12
.DEF R0XD=R13
.DEF R0XE=R14
.DEF R0XF=R15
.DEF R0X10=R16
.DEF R0X11=R17
.DEF R0X12=R18
.DEF R0X13=R19
.DEF R0X14=R20
.DEF R0X15=R21
.DEF R0X16=R22
.DEF R0X17=R23
.DEF R0X18=R24
.DEF R0X19=R25
.DEF R0X1A=R26
.DEF R0X1B=R27
.DEF R0X1C=R28
.DEF R0X1D=R29
.DEF R0X1E=R30
.DEF R0X1F=R31
.EQU __SRAM_START=0x0060
.EQU __SRAM_END=0x045F
.EQU __DSTACK_SIZE=0x0100
.EQU __HEAP_SIZE=0x0000
.EQU __CLEAR_SRAM_SIZE=__SRAM_END-__SRAM_START+1
.MACRO __CPD1N
CPI R30,LOW(@0)
LDI R26,HIGH(@0)
CPC R31,R26
LDI R26,BYTE3(@0)
CPC R22,R26
LDI R26,BYTE4(@0)
CPC R23,R26
.ENDM
.MACRO __CPD2N
CPI R26,LOW(@0)
LDI R30,HIGH(@0)
CPC R27,R30
LDI R30,BYTE3(@0)
CPC R24,R30
LDI R30,BYTE4(@0)
CPC R25,R30
.ENDM
.MACRO __CPWRR
CP R@0,R@2
CPC R@1,R@3
.ENDM
.MACRO __CPWRN
CPI R@0,LOW(@2)
LDI R30,HIGH(@2)
CPC R@1,R30
.ENDM
.MACRO __ADDB1MN
SUBI R30,LOW(-@0-(@1))
.ENDM
.MACRO __ADDB2MN
SUBI R26,LOW(-@0-(@1))
.ENDM
.MACRO __ADDW1MN
SUBI R30,LOW(-@0-(@1))
SBCI R31,HIGH(-@0-(@1))
.ENDM
.MACRO __ADDW2MN
SUBI R26,LOW(-@0-(@1))
SBCI R27,HIGH(-@0-(@1))
.ENDM
.MACRO __ADDW1FN
SUBI R30,LOW(-2*@0-(@1))
SBCI R31,HIGH(-2*@0-(@1))
.ENDM
.MACRO __ADDD1FN
SUBI R30,LOW(-2*@0-(@1))
SBCI R31,HIGH(-2*@0-(@1))
SBCI R22,BYTE3(-2*@0-(@1))
.ENDM
.MACRO __ADDD1N
SUBI R30,LOW(-@0)
SBCI R31,HIGH(-@0)
SBCI R22,BYTE3(-@0)
SBCI R23,BYTE4(-@0)
.ENDM
.MACRO __ADDD2N
SUBI R26,LOW(-@0)
SBCI R27,HIGH(-@0)
SBCI R24,BYTE3(-@0)
SBCI R25,BYTE4(-@0)
.ENDM
.MACRO __SUBD1N
SUBI R30,LOW(@0)
SBCI R31,HIGH(@0)
SBCI R22,BYTE3(@0)
SBCI R23,BYTE4(@0)
.ENDM
.MACRO __SUBD2N
SUBI R26,LOW(@0)
SBCI R27,HIGH(@0)
SBCI R24,BYTE3(@0)
SBCI R25,BYTE4(@0)
.ENDM
.MACRO __ANDBMNN
LDS R30,@0+(@1)
ANDI R30,LOW(@2)
STS @0+(@1),R30
.ENDM
.MACRO __ANDWMNN
LDS R30,@0+(@1)
ANDI R30,LOW(@2)
STS @0+(@1),R30
LDS R30,@0+(@1)+1
ANDI R30,HIGH(@2)
STS @0+(@1)+1,R30
.ENDM
.MACRO __ANDD1N
ANDI R30,LOW(@0)
ANDI R31,HIGH(@0)
ANDI R22,BYTE3(@0)
ANDI R23,BYTE4(@0)
.ENDM
.MACRO __ANDD2N
ANDI R26,LOW(@0)
ANDI R27,HIGH(@0)
ANDI R24,BYTE3(@0)
ANDI R25,BYTE4(@0)
.ENDM
.MACRO __ORBMNN
LDS R30,@0+(@1)
ORI R30,LOW(@2)
STS @0+(@1),R30
.ENDM
.MACRO __ORWMNN
LDS R30,@0+(@1)
ORI R30,LOW(@2)
STS @0+(@1),R30
LDS R30,@0+(@1)+1
ORI R30,HIGH(@2)
STS @0+(@1)+1,R30
.ENDM
.MACRO __ORD1N
ORI R30,LOW(@0)
ORI R31,HIGH(@0)
ORI R22,BYTE3(@0)
ORI R23,BYTE4(@0)
.ENDM
.MACRO __ORD2N
ORI R26,LOW(@0)
ORI R27,HIGH(@0)
ORI R24,BYTE3(@0)
ORI R25,BYTE4(@0)
.ENDM
.MACRO __DELAY_USB
LDI R24,LOW(@0)
__DELAY_USB_LOOP:
DEC R24
BRNE __DELAY_USB_LOOP
.ENDM
.MACRO __DELAY_USW
LDI R24,LOW(@0)
LDI R25,HIGH(@0)
__DELAY_USW_LOOP:
SBIW R24,1
BRNE __DELAY_USW_LOOP
.ENDM
.MACRO __GETD1S
LDD R30,Y+@0
LDD R31,Y+@0+1
LDD R22,Y+@0+2
LDD R23,Y+@0+3
.ENDM
.MACRO __GETD2S
LDD R26,Y+@0
LDD R27,Y+@0+1
LDD R24,Y+@0+2
LDD R25,Y+@0+3
.ENDM
.MACRO __PUTD1S
STD Y+@0,R30
STD Y+@0+1,R31
STD Y+@0+2,R22
STD Y+@0+3,R23
.ENDM
.MACRO __PUTD2S
STD Y+@0,R26
STD Y+@0+1,R27
STD Y+@0+2,R24
STD Y+@0+3,R25
.ENDM
.MACRO __PUTDZ2
STD Z+@0,R26
STD Z+@0+1,R27
STD Z+@0+2,R24
STD Z+@0+3,R25
.ENDM
.MACRO __CLRD1S
STD Y+@0,R30
STD Y+@0+1,R30
STD Y+@0+2,R30
STD Y+@0+3,R30
.ENDM
.MACRO __POINTB1MN
LDI R30,LOW(@0+(@1))
.ENDM
.MACRO __POINTW1MN
LDI R30,LOW(@0+(@1))
LDI R31,HIGH(@0+(@1))
.ENDM
.MACRO __POINTD1M
LDI R30,LOW(@0)
LDI R31,HIGH(@0)
LDI R22,BYTE3(@0)
LDI R23,BYTE4(@0)
.ENDM
.MACRO __POINTW1FN
LDI R30,LOW(2*@0+(@1))
LDI R31,HIGH(2*@0+(@1))
.ENDM
.MACRO __POINTD1FN
LDI R30,LOW(2*@0+(@1))
LDI R31,HIGH(2*@0+(@1))
LDI R22,BYTE3(2*@0+(@1))
LDI R23,BYTE4(2*@0+(@1))
.ENDM
.MACRO __POINTB2MN
LDI R26,LOW(@0+(@1))
.ENDM
.MACRO __POINTW2MN
LDI R26,LOW(@0+(@1))
LDI R27,HIGH(@0+(@1))
.ENDM
.MACRO __POINTW2FN
LDI R26,LOW(2*@0+(@1))
LDI R27,HIGH(2*@0+(@1))
.ENDM
.MACRO __POINTD2FN
LDI R26,LOW(2*@0+(@1))
LDI R27,HIGH(2*@0+(@1))
LDI R24,BYTE3(2*@0+(@1))
LDI R25,BYTE4(2*@0+(@1))
.ENDM
.MACRO __POINTBRM
LDI R@0,LOW(@1)
.ENDM
.MACRO __POINTWRM
LDI R@0,LOW(@2)
LDI R@1,HIGH(@2)
.ENDM
.MACRO __POINTBRMN
LDI R@0,LOW(@1+(@2))
.ENDM
.MACRO __POINTWRMN
LDI R@0,LOW(@2+(@3))
LDI R@1,HIGH(@2+(@3))
.ENDM
.MACRO __POINTWRFN
LDI R@0,LOW(@2*2+(@3))
LDI R@1,HIGH(@2*2+(@3))
.ENDM
.MACRO __GETD1N
LDI R30,LOW(@0)
LDI R31,HIGH(@0)
LDI R22,BYTE3(@0)
LDI R23,BYTE4(@0)
.ENDM
.MACRO __GETD2N
LDI R26,LOW(@0)
LDI R27,HIGH(@0)
LDI R24,BYTE3(@0)
LDI R25,BYTE4(@0)
.ENDM
.MACRO __GETB1MN
LDS R30,@0+(@1)
.ENDM
.MACRO __GETB1HMN
LDS R31,@0+(@1)
.ENDM
.MACRO __GETW1MN
LDS R30,@0+(@1)
LDS R31,@0+(@1)+1
.ENDM
.MACRO __GETD1MN
LDS R30,@0+(@1)
LDS R31,@0+(@1)+1
LDS R22,@0+(@1)+2
LDS R23,@0+(@1)+3
.ENDM
.MACRO __GETBRMN
LDS R@0,@1+(@2)
.ENDM
.MACRO __GETWRMN
LDS R@0,@2+(@3)
LDS R@1,@2+(@3)+1
.ENDM
.MACRO __GETWRZ
LDD R@0,Z+@2
LDD R@1,Z+@2+1
.ENDM
.MACRO __GETD2Z
LDD R26,Z+@0
LDD R27,Z+@0+1
LDD R24,Z+@0+2
LDD R25,Z+@0+3
.ENDM
.MACRO __GETB2MN
LDS R26,@0+(@1)
.ENDM
.MACRO __GETW2MN
LDS R26,@0+(@1)
LDS R27,@0+(@1)+1
.ENDM
.MACRO __GETD2MN
LDS R26,@0+(@1)
LDS R27,@0+(@1)+1
LDS R24,@0+(@1)+2
LDS R25,@0+(@1)+3
.ENDM
.MACRO __PUTB1MN
STS @0+(@1),R30
.ENDM
.MACRO __PUTW1MN
STS @0+(@1),R30
STS @0+(@1)+1,R31
.ENDM
.MACRO __PUTD1MN
STS @0+(@1),R30
STS @0+(@1)+1,R31
STS @0+(@1)+2,R22
STS @0+(@1)+3,R23
.ENDM
.MACRO __PUTB1EN
LDI R26,LOW(@0+(@1))
LDI R27,HIGH(@0+(@1))
CALL __EEPROMWRB
.ENDM
.MACRO __PUTW1EN
LDI R26,LOW(@0+(@1))
LDI R27,HIGH(@0+(@1))
CALL __EEPROMWRW
.ENDM
.MACRO __PUTD1EN
LDI R26,LOW(@0+(@1))
LDI R27,HIGH(@0+(@1))
CALL __EEPROMWRD
.ENDM
.MACRO __PUTBR0MN
STS @0+(@1),R0
.ENDM
.MACRO __PUTBMRN
STS @0+(@1),R@2
.ENDM
.MACRO __PUTWMRN
STS @0+(@1),R@2
STS @0+(@1)+1,R@3
.ENDM
.MACRO __PUTBZR
STD Z+@1,R@0
.ENDM
.MACRO __PUTWZR
STD Z+@2,R@0
STD Z+@2+1,R@1
.ENDM
.MACRO __GETW1R
MOV R30,R@0
MOV R31,R@1
.ENDM
.MACRO __GETW2R
MOV R26,R@0
MOV R27,R@1
.ENDM
.MACRO __GETWRN
LDI R@0,LOW(@2)
LDI R@1,HIGH(@2)
.ENDM
.MACRO __PUTW1R
MOV R@0,R30
MOV R@1,R31
.ENDM
.MACRO __PUTW2R
MOV R@0,R26
MOV R@1,R27
.ENDM
.MACRO __ADDWRN
SUBI R@0,LOW(-@2)
SBCI R@1,HIGH(-@2)
.ENDM
.MACRO __ADDWRR
ADD R@0,R@2
ADC R@1,R@3
.ENDM
.MACRO __SUBWRN
SUBI R@0,LOW(@2)
SBCI R@1,HIGH(@2)
.ENDM
.MACRO __SUBWRR
SUB R@0,R@2
SBC R@1,R@3
.ENDM
.MACRO __ANDWRN
ANDI R@0,LOW(@2)
ANDI R@1,HIGH(@2)
.ENDM
.MACRO __ANDWRR
AND R@0,R@2
AND R@1,R@3
.ENDM
.MACRO __ORWRN
ORI R@0,LOW(@2)
ORI R@1,HIGH(@2)
.ENDM
.MACRO __ORWRR
OR R@0,R@2
OR R@1,R@3
.ENDM
.MACRO __EORWRR
EOR R@0,R@2
EOR R@1,R@3
.ENDM
.MACRO __GETWRS
LDD R@0,Y+@2
LDD R@1,Y+@2+1
.ENDM
.MACRO __PUTBSR
STD Y+@1,R@0
.ENDM
.MACRO __PUTWSR
STD Y+@2,R@0
STD Y+@2+1,R@1
.ENDM
.MACRO __MOVEWRR
MOV R@0,R@2
MOV R@1,R@3
.ENDM
.MACRO __INWR
IN R@0,@2
IN R@1,@2+1
.ENDM
.MACRO __OUTWR
OUT @2+1,R@1
OUT @2,R@0
.ENDM
.MACRO __CALL1MN
LDS R30,@0+(@1)
LDS R31,@0+(@1)+1
ICALL
.ENDM
.MACRO __CALL1FN
LDI R30,LOW(2*@0+(@1))
LDI R31,HIGH(2*@0+(@1))
CALL __GETW1PF
ICALL
.ENDM
.MACRO __CALL2EN
PUSH R26
PUSH R27
LDI R26,LOW(@0+(@1))
LDI R27,HIGH(@0+(@1))
CALL __EEPROMRDW
POP R27
POP R26
ICALL
.ENDM
.MACRO __CALL2EX
SUBI R26,LOW(-@0)
SBCI R27,HIGH(-@0)
CALL __EEPROMRDD
ICALL
.ENDM
.MACRO __GETW1STACK
IN R30,SPL
IN R31,SPH
ADIW R30,@0+1
LD R0,Z+
LD R31,Z
MOV R30,R0
.ENDM
.MACRO __GETD1STACK
IN R30,SPL
IN R31,SPH
ADIW R30,@0+1
LD R0,Z+
LD R1,Z+
LD R22,Z
MOVW R30,R0
.ENDM
.MACRO __NBST
BST R@0,@1
IN R30,SREG
LDI R31,0x40
EOR R30,R31
OUT SREG,R30
.ENDM
.MACRO __PUTB1SN
LDD R26,Y+@0
LDD R27,Y+@0+1
SUBI R26,LOW(-@1)
SBCI R27,HIGH(-@1)
ST X,R30
.ENDM
.MACRO __PUTW1SN
LDD R26,Y+@0
LDD R27,Y+@0+1
SUBI R26,LOW(-@1)
SBCI R27,HIGH(-@1)
ST X+,R30
ST X,R31
.ENDM
.MACRO __PUTD1SN
LDD R26,Y+@0
LDD R27,Y+@0+1
SUBI R26,LOW(-@1)
SBCI R27,HIGH(-@1)
CALL __PUTDP1
.ENDM
.MACRO __PUTB1SNS
LDD R26,Y+@0
LDD R27,Y+@0+1
ADIW R26,@1
ST X,R30
.ENDM
.MACRO __PUTW1SNS
LDD R26,Y+@0
LDD R27,Y+@0+1
ADIW R26,@1
ST X+,R30
ST X,R31
.ENDM
.MACRO __PUTD1SNS
LDD R26,Y+@0
LDD R27,Y+@0+1
ADIW R26,@1
CALL __PUTDP1
.ENDM
.MACRO __PUTB1PMN
LDS R26,@0
LDS R27,@0+1
SUBI R26,LOW(-@1)
SBCI R27,HIGH(-@1)
ST X,R30
.ENDM
.MACRO __PUTW1PMN
LDS R26,@0
LDS R27,@0+1
SUBI R26,LOW(-@1)
SBCI R27,HIGH(-@1)
ST X+,R30
ST X,R31
.ENDM
.MACRO __PUTD1PMN
LDS R26,@0
LDS R27,@0+1
SUBI R26,LOW(-@1)
SBCI R27,HIGH(-@1)
CALL __PUTDP1
.ENDM
.MACRO __PUTB1PMNS
LDS R26,@0
LDS R27,@0+1
ADIW R26,@1
ST X,R30
.ENDM
.MACRO __PUTW1PMNS
LDS R26,@0
LDS R27,@0+1
ADIW R26,@1
ST X+,R30
ST X,R31
.ENDM
.MACRO __PUTD1PMNS
LDS R26,@0
LDS R27,@0+1
ADIW R26,@1
CALL __PUTDP1
.ENDM
.MACRO __PUTB1RN
MOVW R26,R@0
SUBI R26,LOW(-@1)
SBCI R27,HIGH(-@1)
ST X,R30
.ENDM
.MACRO __PUTW1RN
MOVW R26,R@0
SUBI R26,LOW(-@1)
SBCI R27,HIGH(-@1)
ST X+,R30
ST X,R31
.ENDM
.MACRO __PUTD1RN
MOVW R26,R@0
SUBI R26,LOW(-@1)
SBCI R27,HIGH(-@1)
CALL __PUTDP1
.ENDM
.MACRO __PUTB1RNS
MOVW R26,R@0
ADIW R26,@1
ST X,R30
.ENDM
.MACRO __PUTW1RNS
MOVW R26,R@0
ADIW R26,@1
ST X+,R30
ST X,R31
.ENDM
.MACRO __PUTD1RNS
MOVW R26,R@0
ADIW R26,@1
CALL __PUTDP1
.ENDM
.MACRO __PUTB1RON
MOV R26,R@0
MOV R27,R@1
SUBI R26,LOW(-@2)
SBCI R27,HIGH(-@2)
ST X,R30
.ENDM
.MACRO __PUTW1RON
MOV R26,R@0
MOV R27,R@1
SUBI R26,LOW(-@2)
SBCI R27,HIGH(-@2)
ST X+,R30
ST X,R31
.ENDM
.MACRO __PUTD1RON
MOV R26,R@0
MOV R27,R@1
SUBI R26,LOW(-@2)
SBCI R27,HIGH(-@2)
CALL __PUTDP1
.ENDM
.MACRO __PUTB1RONS
MOV R26,R@0
MOV R27,R@1
ADIW R26,@2
ST X,R30
.ENDM
.MACRO __PUTW1RONS
MOV R26,R@0
MOV R27,R@1
ADIW R26,@2
ST X+,R30
ST X,R31
.ENDM
.MACRO __PUTD1RONS
MOV R26,R@0
MOV R27,R@1
ADIW R26,@2
CALL __PUTDP1
.ENDM
.MACRO __GETB1SX
MOVW R30,R28
SUBI R30,LOW(-@0)
SBCI R31,HIGH(-@0)
LD R30,Z
.ENDM
.MACRO __GETB1HSX
MOVW R30,R28
SUBI R30,LOW(-@0)
SBCI R31,HIGH(-@0)
LD R31,Z
.ENDM
.MACRO __GETW1SX
MOVW R30,R28
SUBI R30,LOW(-@0)
SBCI R31,HIGH(-@0)
LD R0,Z+
LD R31,Z
MOV R30,R0
.ENDM
.MACRO __GETD1SX
MOVW R30,R28
SUBI R30,LOW(-@0)
SBCI R31,HIGH(-@0)
LD R0,Z+
LD R1,Z+
LD R22,Z+
LD R23,Z
MOVW R30,R0
.ENDM
.MACRO __GETB2SX
MOVW R26,R28
SUBI R26,LOW(-@0)
SBCI R27,HIGH(-@0)
LD R26,X
.ENDM
.MACRO __GETW2SX
MOVW R26,R28
SUBI R26,LOW(-@0)
SBCI R27,HIGH(-@0)
LD R0,X+
LD R27,X
MOV R26,R0
.ENDM
.MACRO __GETD2SX
MOVW R26,R28
SUBI R26,LOW(-@0)
SBCI R27,HIGH(-@0)
LD R0,X+
LD R1,X+
LD R24,X+
LD R25,X
MOVW R26,R0
.ENDM
.MACRO __GETBRSX
MOVW R30,R28
SUBI R30,LOW(-@1)
SBCI R31,HIGH(-@1)
LD R@0,Z
.ENDM
.MACRO __GETWRSX
MOVW R30,R28
SUBI R30,LOW(-@2)
SBCI R31,HIGH(-@2)
LD R@0,Z+
LD R@1,Z
.ENDM
.MACRO __GETBRSX2
MOVW R26,R28
SUBI R26,LOW(-@1)
SBCI R27,HIGH(-@1)
LD R@0,X
.ENDM
.MACRO __GETWRSX2
MOVW R26,R28
SUBI R26,LOW(-@2)
SBCI R27,HIGH(-@2)
LD R@0,X+
LD R@1,X
.ENDM
.MACRO __LSLW8SX
MOVW R30,R28
SUBI R30,LOW(-@0)
SBCI R31,HIGH(-@0)
LD R31,Z
CLR R30
.ENDM
.MACRO __PUTB1SX
MOVW R26,R28
SUBI R26,LOW(-@0)
SBCI R27,HIGH(-@0)
ST X,R30
.ENDM
.MACRO __PUTW1SX
MOVW R26,R28
SUBI R26,LOW(-@0)
SBCI R27,HIGH(-@0)
ST X+,R30
ST X,R31
.ENDM
.MACRO __PUTD1SX
MOVW R26,R28
SUBI R26,LOW(-@0)
SBCI R27,HIGH(-@0)
ST X+,R30
ST X+,R31
ST X+,R22
ST X,R23
.ENDM
.MACRO __CLRW1SX
MOVW R26,R28
SUBI R26,LOW(-@0)
SBCI R27,HIGH(-@0)
ST X+,R30
ST X,R30
.ENDM
.MACRO __CLRD1SX
MOVW R26,R28
SUBI R26,LOW(-@0)
SBCI R27,HIGH(-@0)
ST X+,R30
ST X+,R30
ST X+,R30
ST X,R30
.ENDM
.MACRO __PUTB2SX
MOVW R30,R28
SUBI R30,LOW(-@0)
SBCI R31,HIGH(-@0)
ST Z,R26
.ENDM
.MACRO __PUTW2SX
MOVW R30,R28
SUBI R30,LOW(-@0)
SBCI R31,HIGH(-@0)
ST Z+,R26
ST Z,R27
.ENDM
.MACRO __PUTD2SX
MOVW R30,R28
SUBI R30,LOW(-@0)
SBCI R31,HIGH(-@0)
ST Z+,R26
ST Z+,R27
ST Z+,R24
ST Z,R25
.ENDM
.MACRO __PUTBSRX
MOVW R30,R28
SUBI R30,LOW(-@1)
SBCI R31,HIGH(-@1)
ST Z,R@0
.ENDM
.MACRO __PUTWSRX
MOVW R30,R28
SUBI R30,LOW(-@2)
SBCI R31,HIGH(-@2)
ST Z+,R@0
ST Z,R@1
.ENDM
.MACRO __PUTB1SNX
MOVW R26,R28
SUBI R26,LOW(-@0)
SBCI R27,HIGH(-@0)
LD R0,X+
LD R27,X
MOV R26,R0
SUBI R26,LOW(-@1)
SBCI R27,HIGH(-@1)
ST X,R30
.ENDM
.MACRO __PUTW1SNX
MOVW R26,R28
SUBI R26,LOW(-@0)
SBCI R27,HIGH(-@0)
LD R0,X+
LD R27,X
MOV R26,R0
SUBI R26,LOW(-@1)
SBCI R27,HIGH(-@1)
ST X+,R30
ST X,R31
.ENDM
.MACRO __PUTD1SNX
MOVW R26,R28
SUBI R26,LOW(-@0)
SBCI R27,HIGH(-@0)
LD R0,X+
LD R27,X
MOV R26,R0
SUBI R26,LOW(-@1)
SBCI R27,HIGH(-@1)
ST X+,R30
ST X+,R31
ST X+,R22
ST X,R23
.ENDM
.MACRO __MULBRR
MULS R@0,R@1
MOVW R30,R0
.ENDM
.MACRO __MULBRRU
MUL R@0,R@1
MOVW R30,R0
.ENDM
.MACRO __MULBRR0
MULS R@0,R@1
.ENDM
.MACRO __MULBRRU0
MUL R@0,R@1
.ENDM
.MACRO __MULBNWRU
LDI R26,@2
MUL R26,R@0
MOVW R30,R0
MUL R26,R@1
ADD R31,R0
.ENDM
.CSEG
.ORG 0x00
;START OF CODE MARKER
__START_OF_CODE:
;INTERRUPT VECTORS
JMP __RESET
JMP 0x00
JMP 0x00
JMP 0x00
JMP 0x00
JMP 0x00
JMP 0x00
JMP 0x00
JMP 0x00
JMP 0x00
JMP 0x00
JMP 0x00
JMP 0x00
JMP 0x00
JMP 0x00
JMP 0x00
JMP 0x00
JMP 0x00
JMP 0x00
JMP 0x00
JMP 0x00
__RESET:
CLI
CLR R30
OUT EECR,R30
;INTERRUPT VECTORS ARE PLACED
;AT THE START OF FLASH
LDI R31,1
OUT GICR,R31
OUT GICR,R30
OUT MCUCR,R30
;CLEAR R2-R14
LDI R24,(14-2)+1
LDI R26,2
CLR R27
__CLEAR_REG:
ST X+,R30
DEC R24
BRNE __CLEAR_REG
;CLEAR SRAM
LDI R24,LOW(__CLEAR_SRAM_SIZE)
LDI R25,HIGH(__CLEAR_SRAM_SIZE)
LDI R26,__SRAM_START
__CLEAR_SRAM:
ST X+,R30
SBIW R24,1
BRNE __CLEAR_SRAM
;HARDWARE STACK POINTER INITIALIZATION
LDI R30,LOW(__SRAM_END-__HEAP_SIZE)
OUT SPL,R30
LDI R30,HIGH(__SRAM_END-__HEAP_SIZE)
OUT SPH,R30
;DATA STACK POINTER INITIALIZATION
LDI R28,LOW(__SRAM_START+__DSTACK_SIZE)
LDI R29,HIGH(__SRAM_START+__DSTACK_SIZE)
JMP _main
.ESEG
.ORG 0
.DSEG
.ORG 0x160
.CSEG
;/*
; * Lab_2_Qst1.c
; *
; * Created: 3/7/2021 8:32:50 PM
; * Author: farkoo
; */
;
;#include <header.h>
#ifndef __SLEEP_DEFINED__
#define __SLEEP_DEFINED__
.EQU __se_bit=0x40
.EQU __sm_mask=0xB0
.EQU __sm_powerdown=0x20
.EQU __sm_powersave=0x30
.EQU __sm_standby=0xA0
.EQU __sm_ext_standby=0xB0
.EQU __sm_adc_noise_red=0x10
.SET power_ctrl_reg=mcucr
#endif
;#include <func1.h>
;
;void main(void)
; 0000 000C {
.CSEG
_main:
; .FSTART _main
; 0000 000D func1(6, 2, 10000);
LDI R30,LOW(6)
ST -Y,R30
LDI R30,LOW(2)
ST -Y,R30
LDI R26,LOW(10000)
LDI R27,HIGH(10000)
RCALL _func1
; 0000 000E while (1)
_0x3:
; 0000 000F {
; 0000 0010 // Please write your application code here
; 0000 0011
; 0000 0012 }
RJMP _0x3
; 0000 0013 }
_0x6:
RJMP _0x6
; .FEND
;#include <header.h>
#ifndef __SLEEP_DEFINED__
#define __SLEEP_DEFINED__
.EQU __se_bit=0x40
.EQU __sm_mask=0xB0
.EQU __sm_powerdown=0x20
.EQU __sm_powersave=0x30
.EQU __sm_standby=0xA0
.EQU __sm_ext_standby=0xB0
.EQU __sm_adc_noise_red=0x10
.SET power_ctrl_reg=mcucr
#endif
;#include <func1.h>
;
;void func1(char num, char port, int ms_delay){
; 0001 0004 void func1(char num, char port, int ms_delay){
.CSEG
_func1:
; .FSTART _func1
; 0001 0005 char i;
; 0001 0006 switch(port){
ST -Y,R27
ST -Y,R26
ST -Y,R17
; num -> Y+4
; port -> Y+3
; ms_delay -> Y+1
; i -> R17
LDD R30,Y+3
LDI R31,0
; 0001 0007 case portA:
CPI R30,LOW(0x1)
LDI R26,HIGH(0x1)
CPC R31,R26
BRNE _0x20006
; 0001 0008 DDRA = 0xFF;
LDI R30,LOW(255)
OUT 0x1A,R30
; 0001 0009 break;
RJMP _0x20005
; 0001 000A case portB:
_0x20006:
CPI R30,LOW(0x2)
LDI R26,HIGH(0x2)
CPC R31,R26
BREQ _0x2000E
; 0001 000B DDRB = 0xFF;
; 0001 000C break;
; 0001 000D case portC:
CPI R30,LOW(0x3)
LDI R26,HIGH(0x3)
CPC R31,R26
BRNE _0x20008
; 0001 000E DDRC = 0xFF;
LDI R30,LOW(255)
OUT 0x14,R30
; 0001 000F break;
RJMP _0x20005
; 0001 0010 case portD:
_0x20008:
CPI R30,LOW(0x4)
LDI R26,HIGH(0x4)
CPC R31,R26
BRNE _0x2000A
; 0001 0011 DDRD = 0xFF;
LDI R30,LOW(255)
OUT 0x11,R30
; 0001 0012 break;
RJMP _0x20005
; 0001 0013 default:
_0x2000A:
; 0001 0014 DDRB = 0xFF;
_0x2000E:
LDI R30,LOW(255)
OUT 0x17,R30
; 0001 0015 }
_0x20005:
; 0001 0016 for(i = 0; i < num; i++){
LDI R17,LOW(0)
_0x2000C:
LDD R30,Y+4
CP R17,R30
BRSH _0x2000D
; 0001 0017 PORTB = 0xFF;
LDI R30,LOW(255)
OUT 0x18,R30
; 0001 0018 delay_ms(ms_delay);
LDD R26,Y+1
LDD R27,Y+1+1
CALL _delay_ms
; 0001 0019 PORTB = 0x00;
LDI R30,LOW(0)
OUT 0x18,R30
; 0001 001A delay_ms(ms_delay);
LDD R26,Y+1
LDD R27,Y+1+1
CALL _delay_ms
; 0001 001B }
SUBI R17,-1
RJMP _0x2000C
_0x2000D:
; 0001 001C return;
LDD R17,Y+0
ADIW R28,5
RET
; 0001 001D }
; .FEND
.CSEG
.CSEG
_delay_ms:
adiw r26,0
breq __delay_ms1
__delay_ms0:
__DELAY_USW 0x7D0
wdr
sbiw r26,1
brne __delay_ms0
__delay_ms1:
ret
;END OF CODE MARKER
__END_OF_CODE:
|
; A284879: Positions of 0 in A284878; complement of A284880.
; Submitted by Jamie Morken(w4)
; 1,3,6,7,9,12,13,16,17,19,21,24,25,27,30,31,34,35,37,39,42,43,46,47,49,51,54,55,57,60,61,63,66,67,70,71,73,75,78,79,81,84,85,88,89,91,93,96,97,100,101,103,105,108,109,111,114,115,117,120,121,124,125,127,129,132,133,136,137,139,141,144,145,147,150,151,153,156,157,160,161,163,165,168,169,171,174,175,178,179,181,183,186,187,189,192,193,196,197,199
mov $2,1
mov $3,$0
lpb $2
mov $1,364
sub $1,$0
seq $1,284817 ; a(n) = 2n - 1 - A284776(n).
sub $2,1
mul $3,2
add $3,$1
lpe
mov $0,$3
add $0,1
|
//==============================================================================
// void parse(int code, char* parserAddress, WINDOW* window)
// In:
// r0: code
// r1: parser address
// r2: window
// Out:
// r0: control code length (0 if not matched)
//==============================================================================
customcodes_parse:
push {r1-r5,lr}
mov r3,0
mov r4,r0
//--------------------------------
// 60 FF XX: Add XX pixels to the renderer
cmp r4,0x60
bne @@next
// 60 FF should be treated as a renderable code
push {r0-r3}
mov r0,r2
bl handle_first_window
pop {r0-r3}
mov r3,3
// Get the current X offset
ldrh r4,[r2,2]
// Get the current X tile
ldrh r5,[r2,0x2A]
lsl r5,r5,3
add r4,r4,r5 // Current X location (in pixels)
// Get the value to add
ldrb r5,[r1,2] // Control code parameter
add r4,r4,r5 // New X location
// Store the pixel offset of the new location
@@store_x:
lsl r5,r4,29
lsr r5,r5,29
strh r5,[r2,2]
// Store the X tile of the new location
lsr r4,r4,3
strh r4,[r2,0x2A]
b @@end
@@next:
//--------------------------------
// 5F FF XX: Set the X value of the renderer
cmp r4,0x5F
bne @@next2
// 5F FF should be treated as a renderable code
push {r0-r3}
mov r0,r2
bl handle_first_window
pop {r0-r3}
mov r3,3
// Get the new X value
ldrb r4,[r1,2]
b @@store_x
@@next2:
//--------------------------------
// 5E FF XX: Load value into memory
cmp r4,0x5E
bne @@next3
mov r3,3
// Get the argument
ldrb r4,[r1,2]
cmp r4,1
bne @@end
// 01: load enemy plurality
ldr r1,=0x2025038
ldrb r1,[r1] // number of enemies at start of battle
cmp r1,4
blt @@small
mov r1,3
@@small:
mov r0,r1 // the jump table is 1-indexed
mov r4,r3
bl 0x80A334C // store to window memory
mov r3,r4
b @@end
@@next3:
//--------------------------------
// 5D FF: Print give text
cmp r4,0x5D
bne @@end
// 5D FF should be treated as a renderable code
push {r0-r3}
mov r0,r2
bl handle_first_window
pop {r0-r3}
ldr r3,=#0x30009FB
ldrb r3,[r3,#0] //Source
ldr r2,=#m2_active_window_pc //Target
ldrb r2,[r2,#0]
ldr r1,=#0x3005230
ldr r1,[r1,#0x10] //Inventory Window
ldrh r4,[r1,#0x36] //Cursor Y
ldrh r1,[r1,#0x34] //Cursor X
lsl r4,r4,#1
cmp r1,#0
beq @@continue
add r4,r4,#1 //Selected Item number in inventory
@@continue:
lsl r4,r4,#1
ldr r0,=#0x3005200
ldr r0,[r0,#0]
push {r0} //String address
ldr r0,=#0x3001D40
mov r1,#0x6C
mul r1,r3
add r0,#0x14
add r0,r0,r1 //Inventory of source
add r0,r0,r4 //Item address
ldrh r0,[r0,#0] //Item
cmp r0,#0
beq @@EndOf5D
mov r1,r2
mov r2,r3
ldr r3,=#0x3005230
ldr r3,[r3,#0x08] //Dialogue Window
bl give_print
@@EndOf5D:
pop {r0}
mov r3,#0
sub r3,r3,#1 //r3 is now -1
//--------------------------------
@@end:
mov r0,r3
pop {r1-r5,pc}
.pool
|
; A218721: a(n) = (18^n-1)/17.
; 0,1,19,343,6175,111151,2000719,36012943,648232975,11668193551,210027483919,3780494710543,68048904789775,1224880286215951,22047845151887119,396861212733968143,7143501829211426575,128583032925805678351,2314494592664502210319,41660902667961039785743,749896248023298716143375,13498132464419376890580751,242966384359548784030453519,4373394918471878112548163343,78721108532493806025866940175,1416979953584888508465604923151,25505639164527993152380888616719,459101504961503876742855995100943
mov $1,18
pow $1,$0
div $1,17
mov $0,$1
|
.global s_prepare_buffers
s_prepare_buffers:
push %r12
push %r13
push %r15
push %r8
push %r9
push %rax
push %rcx
push %rdi
push %rdx
push %rsi
lea addresses_UC_ht+0x184f7, %r8
nop
nop
nop
nop
add %r15, %r15
mov (%r8), %r12w
nop
cmp $23459, %r9
lea addresses_normal_ht+0xe093, %r13
nop
nop
nop
nop
cmp %rax, %rax
mov $0x6162636465666768, %rdx
movq %rdx, (%r13)
nop
cmp $24269, %r13
lea addresses_WC_ht+0x189a3, %r13
nop
nop
add %rax, %rax
movb (%r13), %r8b
nop
nop
nop
nop
nop
inc %rax
lea addresses_UC_ht+0x11db7, %rsi
lea addresses_normal_ht+0x5f7f, %rdi
clflush (%rsi)
clflush (%rdi)
and %r8, %r8
mov $22, %rcx
rep movsl
nop
cmp %rax, %rax
lea addresses_A_ht+0x1582f, %rax
nop
nop
nop
nop
add $10025, %r9
mov (%rax), %r15d
nop
nop
cmp %rax, %rax
lea addresses_normal_ht+0x1402f, %rsi
lea addresses_UC_ht+0x10dd9, %rdi
add %r15, %r15
mov $23, %rcx
rep movsb
xor $16059, %rdi
pop %rsi
pop %rdx
pop %rdi
pop %rcx
pop %rax
pop %r9
pop %r8
pop %r15
pop %r13
pop %r12
ret
.global s_faulty_load
s_faulty_load:
push %r10
push %r12
push %r14
push %r9
push %rax
push %rbp
push %rbx
// Store
lea addresses_RW+0xc523, %rbp
nop
nop
nop
xor %r14, %r14
mov $0x5152535455565758, %r10
movq %r10, (%rbp)
nop
sub $15289, %r9
// Store
lea addresses_WT+0x1f31a, %rax
clflush (%rax)
nop
add %rbx, %rbx
mov $0x5152535455565758, %rbp
movq %rbp, %xmm7
movups %xmm7, (%rax)
// Exception!!!
nop
nop
nop
nop
nop
mov (0), %r10
cmp %r10, %r10
// Store
lea addresses_PSE+0xba6f, %r10
nop
nop
nop
add $37019, %rbp
movw $0x5152, (%r10)
nop
nop
and $29735, %r14
// Store
lea addresses_PSE+0x1117, %rax
nop
dec %r12
mov $0x5152535455565758, %r9
movq %r9, (%rax)
nop
nop
nop
sub %r12, %r12
// Store
lea addresses_WC+0x228d, %rbx
nop
nop
nop
nop
nop
sub $3642, %r10
mov $0x5152535455565758, %r14
movq %r14, (%rbx)
nop
nop
nop
nop
nop
cmp $10945, %r9
// Store
lea addresses_normal+0xcacd, %r12
nop
nop
nop
nop
dec %r9
mov $0x5152535455565758, %rbx
movq %rbx, %xmm3
movups %xmm3, (%r12)
nop
nop
nop
add %rax, %rax
// Load
lea addresses_normal+0x196af, %rax
nop
nop
nop
and $36255, %rbp
mov (%rax), %r12d
xor $20680, %r9
// Load
lea addresses_RW+0xe76f, %rbx
nop
nop
nop
sub $36970, %r9
mov (%rbx), %r14d
nop
nop
nop
and %r12, %r12
// Store
lea addresses_UC+0x1f957, %rax
nop
nop
lfence
movw $0x5152, (%rax)
nop
inc %r12
// Store
lea addresses_PSE+0x1c42f, %rax
clflush (%rax)
nop
nop
add $25861, %r10
movl $0x51525354, (%rax)
xor %r12, %r12
// Load
lea addresses_A+0xd02b, %rbp
nop
nop
nop
xor %r9, %r9
movaps (%rbp), %xmm3
vpextrq $1, %xmm3, %rbx
nop
nop
mfence
// Store
lea addresses_US+0x1ec2f, %rbp
nop
nop
nop
and $22531, %r12
mov $0x5152535455565758, %rax
movq %rax, (%rbp)
nop
nop
nop
inc %r14
// Faulty Load
lea addresses_US+0x1ec2f, %rbx
nop
nop
nop
and %r12, %r12
mov (%rbx), %r14d
lea oracles, %r9
and $0xff, %r14
shlq $12, %r14
mov (%r9,%r14,1), %r14
pop %rbx
pop %rbp
pop %rax
pop %r9
pop %r14
pop %r12
pop %r10
ret
/*
<gen_faulty_load>
[REF]
{'src': {'type': 'addresses_US', 'same': False, 'size': 4, 'congruent': 0, 'NT': False, 'AVXalign': False}, 'OP': 'LOAD'}
{'dst': {'type': 'addresses_RW', 'same': False, 'size': 8, 'congruent': 1, 'NT': False, 'AVXalign': True}, 'OP': 'STOR'}
{'dst': {'type': 'addresses_WT', 'same': False, 'size': 16, 'congruent': 0, 'NT': False, 'AVXalign': False}, 'OP': 'STOR'}
{'dst': {'type': 'addresses_PSE', 'same': False, 'size': 2, 'congruent': 6, 'NT': False, 'AVXalign': False}, 'OP': 'STOR'}
{'dst': {'type': 'addresses_PSE', 'same': False, 'size': 8, 'congruent': 1, 'NT': False, 'AVXalign': False}, 'OP': 'STOR'}
{'dst': {'type': 'addresses_WC', 'same': False, 'size': 8, 'congruent': 0, 'NT': False, 'AVXalign': False}, 'OP': 'STOR'}
{'dst': {'type': 'addresses_normal', 'same': False, 'size': 16, 'congruent': 1, 'NT': False, 'AVXalign': False}, 'OP': 'STOR'}
{'src': {'type': 'addresses_normal', 'same': False, 'size': 4, 'congruent': 2, 'NT': False, 'AVXalign': False}, 'OP': 'LOAD'}
{'src': {'type': 'addresses_RW', 'same': False, 'size': 4, 'congruent': 6, 'NT': False, 'AVXalign': False}, 'OP': 'LOAD'}
{'dst': {'type': 'addresses_UC', 'same': False, 'size': 2, 'congruent': 3, 'NT': False, 'AVXalign': True}, 'OP': 'STOR'}
{'dst': {'type': 'addresses_PSE', 'same': False, 'size': 4, 'congruent': 11, 'NT': False, 'AVXalign': False}, 'OP': 'STOR'}
{'src': {'type': 'addresses_A', 'same': False, 'size': 16, 'congruent': 2, 'NT': False, 'AVXalign': True}, 'OP': 'LOAD'}
{'dst': {'type': 'addresses_US', 'same': True, 'size': 8, 'congruent': 0, 'NT': False, 'AVXalign': False}, 'OP': 'STOR'}
[Faulty Load]
{'src': {'type': 'addresses_US', 'same': True, 'size': 4, 'congruent': 0, 'NT': False, 'AVXalign': True}, 'OP': 'LOAD'}
<gen_prepare_buffer>
{'src': {'type': 'addresses_UC_ht', 'same': False, 'size': 2, 'congruent': 3, 'NT': False, 'AVXalign': False}, 'OP': 'LOAD'}
{'dst': {'type': 'addresses_normal_ht', 'same': False, 'size': 8, 'congruent': 2, 'NT': False, 'AVXalign': False}, 'OP': 'STOR'}
{'src': {'type': 'addresses_WC_ht', 'same': False, 'size': 1, 'congruent': 1, 'NT': False, 'AVXalign': False}, 'OP': 'LOAD'}
{'src': {'type': 'addresses_UC_ht', 'congruent': 2, 'same': False}, 'dst': {'type': 'addresses_normal_ht', 'congruent': 3, 'same': False}, 'OP': 'REPM'}
{'src': {'type': 'addresses_A_ht', 'same': False, 'size': 4, 'congruent': 9, 'NT': False, 'AVXalign': False}, 'OP': 'LOAD'}
{'src': {'type': 'addresses_normal_ht', 'congruent': 10, 'same': False}, 'dst': {'type': 'addresses_UC_ht', 'congruent': 1, 'same': False}, 'OP': 'REPM'}
{'b0': 1}
b0
*/
|
;------------------------------------------------------------------------------
;
; Copyright (c) 2006, Intel Corporation. All rights reserved.<BR>
; This program and the accompanying materials
; are licensed and made available under the terms and conditions of the BSD License
; which accompanies this distribution. The full text of the license may be found at
; http://opensource.org/licenses/bsd-license.php.
;
; THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
; WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
;
; Module Name:
;
; FxSave.Asm
;
; Abstract:
;
; AsmFxSave function
;
; Notes:
;
;------------------------------------------------------------------------------
DEFAULT REL
SECTION .text
;------------------------------------------------------------------------------
; VOID
; EFIAPI
; InternalX86FxSave (
; OUT IA32_FX_BUFFER *Buffer
; );
;------------------------------------------------------------------------------
global ASM_PFX(InternalX86FxSave)
ASM_PFX(InternalX86FxSave):
fxsave [rcx]
ret
|
;******************************************************************************
;* H.264 intra prediction asm optimizations
;* Copyright (c) 2010 Fiona Glaser
;* Copyright (c) 2010 Holger Lubitz
;* Copyright (c) 2010 Loren Merritt
;* Copyright (c) 2010 Ronald S. Bultje
;*
;* This file is part of FFmpeg.
;*
;* FFmpeg is free software; you can redistribute it and/or
;* modify it under the terms of the GNU Lesser General Public
;* License as published by the Free Software Foundation; either
;* version 2.1 of the License, or (at your option) any later version.
;*
;* FFmpeg is distributed in the hope that it will be useful,
;* but WITHOUT ANY WARRANTY; without even the implied warranty of
;* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
;* Lesser General Public License for more details.
;*
;* You should have received a copy of the GNU Lesser General Public
;* License along with FFmpeg; if not, write to the Free Software
;* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
;******************************************************************************
%include "libavutil/x86/x86util.asm"
SECTION_RODATA
tm_shuf: times 8 db 0x03, 0x80
pw_ff00: times 8 dw 0xff00
plane_shuf: db -8, -7, -6, -5, -4, -3, -2, -1
db 1, 2, 3, 4, 5, 6, 7, 8
plane8_shuf: db -4, -3, -2, -1, 0, 0, 0, 0
db 1, 2, 3, 4, 0, 0, 0, 0
pw_0to7: dw 0, 1, 2, 3, 4, 5, 6, 7
pw_1to8: dw 1, 2, 3, 4, 5, 6, 7, 8
pw_m8tom1: dw -8, -7, -6, -5, -4, -3, -2, -1
pw_m4to4: dw -4, -3, -2, -1, 1, 2, 3, 4
SECTION .text
cextern pb_1
cextern pb_3
cextern pw_4
cextern pw_8
;-----------------------------------------------------------------------------
; void ff_pred16x16_vertical_8(uint8_t *src, ptrdiff_t stride)
;-----------------------------------------------------------------------------
INIT_MMX mmx
cglobal pred16x16_vertical_8, 2,3
sub r0, r1
mov r2, 8
movq mm0, [r0+0]
movq mm1, [r0+8]
.loop:
movq [r0+r1*1+0], mm0
movq [r0+r1*1+8], mm1
movq [r0+r1*2+0], mm0
movq [r0+r1*2+8], mm1
lea r0, [r0+r1*2]
dec r2
jg .loop
REP_RET
INIT_XMM sse
cglobal pred16x16_vertical_8, 2,3
sub r0, r1
mov r2, 4
movaps xmm0, [r0]
.loop:
movaps [r0+r1*1], xmm0
movaps [r0+r1*2], xmm0
lea r0, [r0+r1*2]
movaps [r0+r1*1], xmm0
movaps [r0+r1*2], xmm0
lea r0, [r0+r1*2]
dec r2
jg .loop
REP_RET
;-----------------------------------------------------------------------------
; void ff_pred16x16_horizontal_8(uint8_t *src, ptrdiff_t stride)
;-----------------------------------------------------------------------------
%macro PRED16x16_H 0
cglobal pred16x16_horizontal_8, 2,3
mov r2, 8
%if cpuflag(ssse3)
mova m2, [pb_3]
%endif
.loop:
movd m0, [r0+r1*0-4]
movd m1, [r0+r1*1-4]
%if cpuflag(ssse3)
pshufb m0, m2
pshufb m1, m2
%else
punpcklbw m0, m0
punpcklbw m1, m1
SPLATW m0, m0, 3
SPLATW m1, m1, 3
mova [r0+r1*0+8], m0
mova [r0+r1*1+8], m1
%endif
mova [r0+r1*0], m0
mova [r0+r1*1], m1
lea r0, [r0+r1*2]
dec r2
jg .loop
REP_RET
%endmacro
INIT_MMX mmx
PRED16x16_H
INIT_MMX mmxext
PRED16x16_H
INIT_XMM ssse3
PRED16x16_H
;-----------------------------------------------------------------------------
; void ff_pred16x16_dc_8(uint8_t *src, ptrdiff_t stride)
;-----------------------------------------------------------------------------
%macro PRED16x16_DC 0
cglobal pred16x16_dc_8, 2,7
mov r4, r0
sub r0, r1
pxor mm0, mm0
pxor mm1, mm1
psadbw mm0, [r0+0]
psadbw mm1, [r0+8]
dec r0
movzx r5d, byte [r0+r1*1]
paddw mm0, mm1
movd r6d, mm0
lea r0, [r0+r1*2]
%rep 7
movzx r2d, byte [r0+r1*0]
movzx r3d, byte [r0+r1*1]
add r5d, r2d
add r6d, r3d
lea r0, [r0+r1*2]
%endrep
movzx r2d, byte [r0+r1*0]
add r5d, r6d
lea r2d, [r2+r5+16]
shr r2d, 5
%if cpuflag(ssse3)
pxor m1, m1
%endif
SPLATB_REG m0, r2, m1
%if mmsize==8
mov r3d, 8
.loop:
mova [r4+r1*0+0], m0
mova [r4+r1*0+8], m0
mova [r4+r1*1+0], m0
mova [r4+r1*1+8], m0
%else
mov r3d, 4
.loop:
mova [r4+r1*0], m0
mova [r4+r1*1], m0
lea r4, [r4+r1*2]
mova [r4+r1*0], m0
mova [r4+r1*1], m0
%endif
lea r4, [r4+r1*2]
dec r3d
jg .loop
REP_RET
%endmacro
INIT_MMX mmxext
PRED16x16_DC
INIT_XMM sse2
PRED16x16_DC
INIT_XMM ssse3
PRED16x16_DC
;-----------------------------------------------------------------------------
; void ff_pred16x16_tm_vp8_8(uint8_t *src, ptrdiff_t stride)
;-----------------------------------------------------------------------------
%macro PRED16x16_TM 0
cglobal pred16x16_tm_vp8_8, 2,5
sub r0, r1
pxor mm7, mm7
movq mm0, [r0+0]
movq mm2, [r0+8]
movq mm1, mm0
movq mm3, mm2
punpcklbw mm0, mm7
punpckhbw mm1, mm7
punpcklbw mm2, mm7
punpckhbw mm3, mm7
movzx r3d, byte [r0-1]
mov r4d, 16
.loop:
movzx r2d, byte [r0+r1-1]
sub r2d, r3d
movd mm4, r2d
SPLATW mm4, mm4, 0
movq mm5, mm4
movq mm6, mm4
movq mm7, mm4
paddw mm4, mm0
paddw mm5, mm1
paddw mm6, mm2
paddw mm7, mm3
packuswb mm4, mm5
packuswb mm6, mm7
movq [r0+r1+0], mm4
movq [r0+r1+8], mm6
add r0, r1
dec r4d
jg .loop
REP_RET
%endmacro
INIT_MMX mmx
PRED16x16_TM
INIT_MMX mmxext
PRED16x16_TM
INIT_XMM sse2
cglobal pred16x16_tm_vp8_8, 2,6,6
sub r0, r1
pxor xmm2, xmm2
movdqa xmm0, [r0]
movdqa xmm1, xmm0
punpcklbw xmm0, xmm2
punpckhbw xmm1, xmm2
movzx r4d, byte [r0-1]
mov r5d, 8
.loop:
movzx r2d, byte [r0+r1*1-1]
movzx r3d, byte [r0+r1*2-1]
sub r2d, r4d
sub r3d, r4d
movd xmm2, r2d
movd xmm4, r3d
pshuflw xmm2, xmm2, 0
pshuflw xmm4, xmm4, 0
punpcklqdq xmm2, xmm2
punpcklqdq xmm4, xmm4
movdqa xmm3, xmm2
movdqa xmm5, xmm4
paddw xmm2, xmm0
paddw xmm3, xmm1
paddw xmm4, xmm0
paddw xmm5, xmm1
packuswb xmm2, xmm3
packuswb xmm4, xmm5
movdqa [r0+r1*1], xmm2
movdqa [r0+r1*2], xmm4
lea r0, [r0+r1*2]
dec r5d
jg .loop
REP_RET
%if HAVE_AVX2_EXTERNAL
INIT_YMM avx2
cglobal pred16x16_tm_vp8_8, 2, 4, 5, dst, stride, stride3, iteration
sub dstq, strideq
pmovzxbw m0, [dstq]
vpbroadcastb xm1, [r0-1]
pmovzxbw m1, xm1
psubw m0, m1
mov iterationd, 4
lea stride3q, [strideq*3]
.loop:
vpbroadcastb xm1, [dstq+strideq*1-1]
vpbroadcastb xm2, [dstq+strideq*2-1]
vpbroadcastb xm3, [dstq+stride3q-1]
vpbroadcastb xm4, [dstq+strideq*4-1]
pmovzxbw m1, xm1
pmovzxbw m2, xm2
pmovzxbw m3, xm3
pmovzxbw m4, xm4
paddw m1, m0
paddw m2, m0
paddw m3, m0
paddw m4, m0
vpackuswb m1, m1, m2
vpackuswb m3, m3, m4
vpermq m1, m1, q3120
vpermq m3, m3, q3120
movdqa [dstq+strideq*1], xm1
vextracti128 [dstq+strideq*2], m1, 1
movdqa [dstq+stride3q*1], xm3
vextracti128 [dstq+strideq*4], m3, 1
lea dstq, [dstq+strideq*4]
dec iterationd
jg .loop
REP_RET
%endif
;-----------------------------------------------------------------------------
; void ff_pred16x16_plane_*_8(uint8_t *src, ptrdiff_t stride)
;-----------------------------------------------------------------------------
%macro H264_PRED16x16_PLANE 1
cglobal pred16x16_plane_%1_8, 2,9,7
mov r2, r1 ; +stride
neg r1 ; -stride
movh m0, [r0+r1 -1]
%if mmsize == 8
pxor m4, m4
movh m1, [r0+r1 +3 ]
movh m2, [r0+r1 +8 ]
movh m3, [r0+r1 +12]
punpcklbw m0, m4
punpcklbw m1, m4
punpcklbw m2, m4
punpcklbw m3, m4
pmullw m0, [pw_m8tom1 ]
pmullw m1, [pw_m8tom1+8]
pmullw m2, [pw_1to8 ]
pmullw m3, [pw_1to8 +8]
paddw m0, m2
paddw m1, m3
%else ; mmsize == 16
%if cpuflag(ssse3)
movhps m0, [r0+r1 +8]
pmaddubsw m0, [plane_shuf] ; H coefficients
%else ; sse2
pxor m2, m2
movh m1, [r0+r1 +8]
punpcklbw m0, m2
punpcklbw m1, m2
pmullw m0, [pw_m8tom1]
pmullw m1, [pw_1to8]
paddw m0, m1
%endif
movhlps m1, m0
%endif
paddw m0, m1
%if cpuflag(mmxext)
PSHUFLW m1, m0, 0xE
%elif cpuflag(mmx)
mova m1, m0
psrlq m1, 32
%endif
paddw m0, m1
%if cpuflag(mmxext)
PSHUFLW m1, m0, 0x1
%elif cpuflag(mmx)
mova m1, m0
psrlq m1, 16
%endif
paddw m0, m1 ; sum of H coefficients
lea r4, [r0+r2*8-1]
lea r3, [r0+r2*4-1]
add r4, r2
%if ARCH_X86_64
%define e_reg r8
%else
%define e_reg r0
%endif
movzx e_reg, byte [r3+r2*2 ]
movzx r5, byte [r4+r1 ]
sub r5, e_reg
movzx e_reg, byte [r3+r2 ]
movzx r6, byte [r4 ]
sub r6, e_reg
lea r5, [r5+r6*2]
movzx e_reg, byte [r3+r1 ]
movzx r6, byte [r4+r2*2 ]
sub r6, e_reg
lea r5, [r5+r6*4]
movzx e_reg, byte [r3 ]
%if ARCH_X86_64
movzx r7, byte [r4+r2 ]
sub r7, e_reg
%else
movzx r6, byte [r4+r2 ]
sub r6, e_reg
lea r5, [r5+r6*4]
sub r5, r6
%endif
lea e_reg, [r3+r1*4]
lea r3, [r4+r2*4]
movzx r4, byte [e_reg+r2 ]
movzx r6, byte [r3 ]
sub r6, r4
%if ARCH_X86_64
lea r6, [r7+r6*2]
lea r5, [r5+r6*2]
add r5, r6
%else
lea r5, [r5+r6*4]
lea r5, [r5+r6*2]
%endif
movzx r4, byte [e_reg ]
%if ARCH_X86_64
movzx r7, byte [r3 +r2 ]
sub r7, r4
sub r5, r7
%else
movzx r6, byte [r3 +r2 ]
sub r6, r4
lea r5, [r5+r6*8]
sub r5, r6
%endif
movzx r4, byte [e_reg+r1 ]
movzx r6, byte [r3 +r2*2]
sub r6, r4
%if ARCH_X86_64
add r6, r7
%endif
lea r5, [r5+r6*8]
movzx r4, byte [e_reg+r2*2]
movzx r6, byte [r3 +r1 ]
sub r6, r4
lea r5, [r5+r6*4]
add r5, r6 ; sum of V coefficients
%if ARCH_X86_64 == 0
mov r0, r0m
%endif
%ifidn %1, h264
lea r5, [r5*5+32]
sar r5, 6
%elifidn %1, rv40
lea r5, [r5*5]
sar r5, 6
%elifidn %1, svq3
test r5, r5
lea r6, [r5+3]
cmovs r5, r6
sar r5, 2 ; V/4
lea r5, [r5*5] ; 5*(V/4)
test r5, r5
lea r6, [r5+15]
cmovs r5, r6
sar r5, 4 ; (5*(V/4))/16
%endif
movzx r4, byte [r0+r1 +15]
movzx r3, byte [r3+r2*2 ]
lea r3, [r3+r4+1]
shl r3, 4
movd r1d, m0
movsx r1d, r1w
%ifnidn %1, svq3
%ifidn %1, h264
lea r1d, [r1d*5+32]
%else ; rv40
lea r1d, [r1d*5]
%endif
sar r1d, 6
%else ; svq3
test r1d, r1d
lea r4d, [r1d+3]
cmovs r1d, r4d
sar r1d, 2 ; H/4
lea r1d, [r1d*5] ; 5*(H/4)
test r1d, r1d
lea r4d, [r1d+15]
cmovs r1d, r4d
sar r1d, 4 ; (5*(H/4))/16
%endif
movd m0, r1d
add r1d, r5d
add r3d, r1d
shl r1d, 3
sub r3d, r1d ; a
movd m1, r5d
movd m3, r3d
SPLATW m0, m0, 0 ; H
SPLATW m1, m1, 0 ; V
SPLATW m3, m3, 0 ; a
%ifidn %1, svq3
SWAP 0, 1
%endif
mova m2, m0
%if mmsize == 8
mova m5, m0
%endif
pmullw m0, [pw_0to7] ; 0*H, 1*H, ..., 7*H (words)
%if mmsize == 16
psllw m2, 3
%else
psllw m5, 3
psllw m2, 2
mova m6, m5
paddw m6, m2
%endif
paddw m0, m3 ; a + {0,1,2,3,4,5,6,7}*H
paddw m2, m0 ; a + {8,9,10,11,12,13,14,15}*H
%if mmsize == 8
paddw m5, m0 ; a + {8,9,10,11}*H
paddw m6, m0 ; a + {12,13,14,15}*H
%endif
mov r4, 8
.loop:
mova m3, m0 ; b[0..7]
mova m4, m2 ; b[8..15]
psraw m3, 5
psraw m4, 5
packuswb m3, m4
mova [r0], m3
%if mmsize == 8
mova m3, m5 ; b[8..11]
mova m4, m6 ; b[12..15]
psraw m3, 5
psraw m4, 5
packuswb m3, m4
mova [r0+8], m3
%endif
paddw m0, m1
paddw m2, m1
%if mmsize == 8
paddw m5, m1
paddw m6, m1
%endif
mova m3, m0 ; b[0..7]
mova m4, m2 ; b[8..15]
psraw m3, 5
psraw m4, 5
packuswb m3, m4
mova [r0+r2], m3
%if mmsize == 8
mova m3, m5 ; b[8..11]
mova m4, m6 ; b[12..15]
psraw m3, 5
psraw m4, 5
packuswb m3, m4
mova [r0+r2+8], m3
%endif
paddw m0, m1
paddw m2, m1
%if mmsize == 8
paddw m5, m1
paddw m6, m1
%endif
lea r0, [r0+r2*2]
dec r4
jg .loop
REP_RET
%endmacro
INIT_MMX mmx
H264_PRED16x16_PLANE h264
H264_PRED16x16_PLANE rv40
H264_PRED16x16_PLANE svq3
INIT_MMX mmxext
H264_PRED16x16_PLANE h264
H264_PRED16x16_PLANE rv40
H264_PRED16x16_PLANE svq3
INIT_XMM sse2
H264_PRED16x16_PLANE h264
H264_PRED16x16_PLANE rv40
H264_PRED16x16_PLANE svq3
INIT_XMM ssse3
H264_PRED16x16_PLANE h264
H264_PRED16x16_PLANE rv40
H264_PRED16x16_PLANE svq3
;-----------------------------------------------------------------------------
; void ff_pred8x8_plane_8(uint8_t *src, ptrdiff_t stride)
;-----------------------------------------------------------------------------
%macro H264_PRED8x8_PLANE 0
cglobal pred8x8_plane_8, 2,9,7
mov r2, r1 ; +stride
neg r1 ; -stride
movd m0, [r0+r1 -1]
%if mmsize == 8
pxor m2, m2
movh m1, [r0+r1 +4 ]
punpcklbw m0, m2
punpcklbw m1, m2
pmullw m0, [pw_m4to4]
pmullw m1, [pw_m4to4+8]
%else ; mmsize == 16
%if cpuflag(ssse3)
movhps m0, [r0+r1 +4] ; this reads 4 bytes more than necessary
pmaddubsw m0, [plane8_shuf] ; H coefficients
%else ; sse2
pxor m2, m2
movd m1, [r0+r1 +4]
punpckldq m0, m1
punpcklbw m0, m2
pmullw m0, [pw_m4to4]
%endif
movhlps m1, m0
%endif
paddw m0, m1
%if notcpuflag(ssse3)
%if cpuflag(mmxext)
PSHUFLW m1, m0, 0xE
%elif cpuflag(mmx)
mova m1, m0
psrlq m1, 32
%endif
paddw m0, m1
%endif ; !ssse3
%if cpuflag(mmxext)
PSHUFLW m1, m0, 0x1
%elif cpuflag(mmx)
mova m1, m0
psrlq m1, 16
%endif
paddw m0, m1 ; sum of H coefficients
lea r4, [r0+r2*4-1]
lea r3, [r0 -1]
add r4, r2
%if ARCH_X86_64
%define e_reg r8
%else
%define e_reg r0
%endif
movzx e_reg, byte [r3+r2*2 ]
movzx r5, byte [r4+r1 ]
sub r5, e_reg
movzx e_reg, byte [r3 ]
%if ARCH_X86_64
movzx r7, byte [r4+r2 ]
sub r7, e_reg
sub r5, r7
%else
movzx r6, byte [r4+r2 ]
sub r6, e_reg
lea r5, [r5+r6*4]
sub r5, r6
%endif
movzx e_reg, byte [r3+r1 ]
movzx r6, byte [r4+r2*2 ]
sub r6, e_reg
%if ARCH_X86_64
add r6, r7
%endif
lea r5, [r5+r6*4]
movzx e_reg, byte [r3+r2 ]
movzx r6, byte [r4 ]
sub r6, e_reg
lea r6, [r5+r6*2]
lea r5, [r6*9+16]
lea r5, [r5+r6*8]
sar r5, 5
%if ARCH_X86_64 == 0
mov r0, r0m
%endif
movzx r3, byte [r4+r2*2 ]
movzx r4, byte [r0+r1 +7]
lea r3, [r3+r4+1]
shl r3, 4
movd r1d, m0
movsx r1d, r1w
imul r1d, 17
add r1d, 16
sar r1d, 5
movd m0, r1d
add r1d, r5d
sub r3d, r1d
add r1d, r1d
sub r3d, r1d ; a
movd m1, r5d
movd m3, r3d
SPLATW m0, m0, 0 ; H
SPLATW m1, m1, 0 ; V
SPLATW m3, m3, 0 ; a
%if mmsize == 8
mova m2, m0
%endif
pmullw m0, [pw_0to7] ; 0*H, 1*H, ..., 7*H (words)
paddw m0, m3 ; a + {0,1,2,3,4,5,6,7}*H
%if mmsize == 8
psllw m2, 2
paddw m2, m0 ; a + {4,5,6,7}*H
%endif
mov r4, 4
ALIGN 16
.loop:
%if mmsize == 16
mova m3, m0 ; b[0..7]
paddw m0, m1
psraw m3, 5
mova m4, m0 ; V+b[0..7]
paddw m0, m1
psraw m4, 5
packuswb m3, m4
movh [r0], m3
movhps [r0+r2], m3
%else ; mmsize == 8
mova m3, m0 ; b[0..3]
mova m4, m2 ; b[4..7]
paddw m0, m1
paddw m2, m1
psraw m3, 5
psraw m4, 5
mova m5, m0 ; V+b[0..3]
mova m6, m2 ; V+b[4..7]
paddw m0, m1
paddw m2, m1
psraw m5, 5
psraw m6, 5
packuswb m3, m4
packuswb m5, m6
mova [r0], m3
mova [r0+r2], m5
%endif
lea r0, [r0+r2*2]
dec r4
jg .loop
REP_RET
%endmacro
INIT_MMX mmx
H264_PRED8x8_PLANE
INIT_MMX mmxext
H264_PRED8x8_PLANE
INIT_XMM sse2
H264_PRED8x8_PLANE
INIT_XMM ssse3
H264_PRED8x8_PLANE
;-----------------------------------------------------------------------------
; void ff_pred8x8_vertical_8(uint8_t *src, ptrdiff_t stride)
;-----------------------------------------------------------------------------
INIT_MMX mmx
cglobal pred8x8_vertical_8, 2,2
sub r0, r1
movq mm0, [r0]
%rep 3
movq [r0+r1*1], mm0
movq [r0+r1*2], mm0
lea r0, [r0+r1*2]
%endrep
movq [r0+r1*1], mm0
movq [r0+r1*2], mm0
RET
;-----------------------------------------------------------------------------
; void ff_pred8x8_horizontal_8(uint8_t *src, ptrdiff_t stride)
;-----------------------------------------------------------------------------
%macro PRED8x8_H 0
cglobal pred8x8_horizontal_8, 2,3
mov r2, 4
%if cpuflag(ssse3)
mova m2, [pb_3]
%endif
.loop:
SPLATB_LOAD m0, r0+r1*0-1, m2
SPLATB_LOAD m1, r0+r1*1-1, m2
mova [r0+r1*0], m0
mova [r0+r1*1], m1
lea r0, [r0+r1*2]
dec r2
jg .loop
REP_RET
%endmacro
INIT_MMX mmx
PRED8x8_H
INIT_MMX mmxext
PRED8x8_H
INIT_MMX ssse3
PRED8x8_H
;-----------------------------------------------------------------------------
; void ff_pred8x8_top_dc_8_mmxext(uint8_t *src, ptrdiff_t stride)
;-----------------------------------------------------------------------------
INIT_MMX mmxext
cglobal pred8x8_top_dc_8, 2,5
sub r0, r1
movq mm0, [r0]
pxor mm1, mm1
pxor mm2, mm2
lea r2, [r0+r1*2]
punpckhbw mm1, mm0
punpcklbw mm0, mm2
psadbw mm1, mm2 ; s1
lea r3, [r2+r1*2]
psadbw mm0, mm2 ; s0
psrlw mm1, 1
psrlw mm0, 1
pavgw mm1, mm2
lea r4, [r3+r1*2]
pavgw mm0, mm2
pshufw mm1, mm1, 0
pshufw mm0, mm0, 0 ; dc0 (w)
packuswb mm0, mm1 ; dc0,dc1 (b)
movq [r0+r1*1], mm0
movq [r0+r1*2], mm0
lea r0, [r3+r1*2]
movq [r2+r1*1], mm0
movq [r2+r1*2], mm0
movq [r3+r1*1], mm0
movq [r3+r1*2], mm0
movq [r0+r1*1], mm0
movq [r0+r1*2], mm0
RET
;-----------------------------------------------------------------------------
; void ff_pred8x8_dc_8_mmxext(uint8_t *src, ptrdiff_t stride)
;-----------------------------------------------------------------------------
INIT_MMX mmxext
cglobal pred8x8_dc_8, 2,5
sub r0, r1
pxor m7, m7
movd m0, [r0+0]
movd m1, [r0+4]
psadbw m0, m7 ; s0
mov r4, r0
psadbw m1, m7 ; s1
movzx r2d, byte [r0+r1*1-1]
movzx r3d, byte [r0+r1*2-1]
lea r0, [r0+r1*2]
add r2d, r3d
movzx r3d, byte [r0+r1*1-1]
add r2d, r3d
movzx r3d, byte [r0+r1*2-1]
add r2d, r3d
lea r0, [r0+r1*2]
movd m2, r2d ; s2
movzx r2d, byte [r0+r1*1-1]
movzx r3d, byte [r0+r1*2-1]
lea r0, [r0+r1*2]
add r2d, r3d
movzx r3d, byte [r0+r1*1-1]
add r2d, r3d
movzx r3d, byte [r0+r1*2-1]
add r2d, r3d
movd m3, r2d ; s3
punpcklwd m0, m1
mov r0, r4
punpcklwd m2, m3
punpckldq m0, m2 ; s0, s1, s2, s3
pshufw m3, m0, 11110110b ; s2, s1, s3, s3
lea r2, [r0+r1*2]
pshufw m0, m0, 01110100b ; s0, s1, s3, s1
paddw m0, m3
lea r3, [r2+r1*2]
psrlw m0, 2
pavgw m0, m7 ; s0+s2, s1, s3, s1+s3
lea r4, [r3+r1*2]
packuswb m0, m0
punpcklbw m0, m0
movq m1, m0
punpcklbw m0, m0
punpckhbw m1, m1
movq [r0+r1*1], m0
movq [r0+r1*2], m0
movq [r2+r1*1], m0
movq [r2+r1*2], m0
movq [r3+r1*1], m1
movq [r3+r1*2], m1
movq [r4+r1*1], m1
movq [r4+r1*2], m1
RET
;-----------------------------------------------------------------------------
; void ff_pred8x8_dc_rv40_8(uint8_t *src, ptrdiff_t stride)
;-----------------------------------------------------------------------------
INIT_MMX mmxext
cglobal pred8x8_dc_rv40_8, 2,7
mov r4, r0
sub r0, r1
pxor mm0, mm0
psadbw mm0, [r0]
dec r0
movzx r5d, byte [r0+r1*1]
movd r6d, mm0
lea r0, [r0+r1*2]
%rep 3
movzx r2d, byte [r0+r1*0]
movzx r3d, byte [r0+r1*1]
add r5d, r2d
add r6d, r3d
lea r0, [r0+r1*2]
%endrep
movzx r2d, byte [r0+r1*0]
add r5d, r6d
lea r2d, [r2+r5+8]
shr r2d, 4
movd mm0, r2d
punpcklbw mm0, mm0
pshufw mm0, mm0, 0
mov r3d, 4
.loop:
movq [r4+r1*0], mm0
movq [r4+r1*1], mm0
lea r4, [r4+r1*2]
dec r3d
jg .loop
REP_RET
;-----------------------------------------------------------------------------
; void ff_pred8x8_tm_vp8_8(uint8_t *src, ptrdiff_t stride)
;-----------------------------------------------------------------------------
%macro PRED8x8_TM 0
cglobal pred8x8_tm_vp8_8, 2,6
sub r0, r1
pxor mm7, mm7
movq mm0, [r0]
movq mm1, mm0
punpcklbw mm0, mm7
punpckhbw mm1, mm7
movzx r4d, byte [r0-1]
mov r5d, 4
.loop:
movzx r2d, byte [r0+r1*1-1]
movzx r3d, byte [r0+r1*2-1]
sub r2d, r4d
sub r3d, r4d
movd mm2, r2d
movd mm4, r3d
SPLATW mm2, mm2, 0
SPLATW mm4, mm4, 0
movq mm3, mm2
movq mm5, mm4
paddw mm2, mm0
paddw mm3, mm1
paddw mm4, mm0
paddw mm5, mm1
packuswb mm2, mm3
packuswb mm4, mm5
movq [r0+r1*1], mm2
movq [r0+r1*2], mm4
lea r0, [r0+r1*2]
dec r5d
jg .loop
REP_RET
%endmacro
INIT_MMX mmx
PRED8x8_TM
INIT_MMX mmxext
PRED8x8_TM
INIT_XMM sse2
cglobal pred8x8_tm_vp8_8, 2,6,4
sub r0, r1
pxor xmm1, xmm1
movq xmm0, [r0]
punpcklbw xmm0, xmm1
movzx r4d, byte [r0-1]
mov r5d, 4
.loop:
movzx r2d, byte [r0+r1*1-1]
movzx r3d, byte [r0+r1*2-1]
sub r2d, r4d
sub r3d, r4d
movd xmm2, r2d
movd xmm3, r3d
pshuflw xmm2, xmm2, 0
pshuflw xmm3, xmm3, 0
punpcklqdq xmm2, xmm2
punpcklqdq xmm3, xmm3
paddw xmm2, xmm0
paddw xmm3, xmm0
packuswb xmm2, xmm3
movq [r0+r1*1], xmm2
movhps [r0+r1*2], xmm2
lea r0, [r0+r1*2]
dec r5d
jg .loop
REP_RET
INIT_XMM ssse3
cglobal pred8x8_tm_vp8_8, 2,3,6
sub r0, r1
movdqa xmm4, [tm_shuf]
pxor xmm1, xmm1
movq xmm0, [r0]
punpcklbw xmm0, xmm1
movd xmm5, [r0-4]
pshufb xmm5, xmm4
mov r2d, 4
.loop:
movd xmm2, [r0+r1*1-4]
movd xmm3, [r0+r1*2-4]
pshufb xmm2, xmm4
pshufb xmm3, xmm4
psubw xmm2, xmm5
psubw xmm3, xmm5
paddw xmm2, xmm0
paddw xmm3, xmm0
packuswb xmm2, xmm3
movq [r0+r1*1], xmm2
movhps [r0+r1*2], xmm2
lea r0, [r0+r1*2]
dec r2d
jg .loop
REP_RET
; dest, left, right, src, tmp
; output: %1 = (t[n-1] + t[n]*2 + t[n+1] + 2) >> 2
%macro PRED4x4_LOWPASS 5
mova %5, %2
pavgb %2, %3
pxor %3, %5
mova %1, %4
pand %3, [pb_1]
psubusb %2, %3
pavgb %1, %2
%endmacro
;-----------------------------------------------------------------------------
; void ff_pred8x8l_top_dc_8(uint8_t *src, int has_topleft, int has_topright,
; ptrdiff_t stride)
;-----------------------------------------------------------------------------
%macro PRED8x8L_TOP_DC 0
cglobal pred8x8l_top_dc_8, 4,4
sub r0, r3
pxor mm7, mm7
movq mm0, [r0-8]
movq mm3, [r0]
movq mm1, [r0+8]
movq mm2, mm3
movq mm4, mm3
PALIGNR mm2, mm0, 7, mm0
PALIGNR mm1, mm4, 1, mm4
test r1d, r1d ; top_left
jz .fix_lt_2
test r2d, r2d ; top_right
jz .fix_tr_1
jmp .body
.fix_lt_2:
movq mm5, mm3
pxor mm5, mm2
psllq mm5, 56
psrlq mm5, 56
pxor mm2, mm5
test r2d, r2d ; top_right
jnz .body
.fix_tr_1:
movq mm5, mm3
pxor mm5, mm1
psrlq mm5, 56
psllq mm5, 56
pxor mm1, mm5
.body:
PRED4x4_LOWPASS mm0, mm2, mm1, mm3, mm5
psadbw mm7, mm0
paddw mm7, [pw_4]
psrlw mm7, 3
pshufw mm7, mm7, 0
packuswb mm7, mm7
%rep 3
movq [r0+r3*1], mm7
movq [r0+r3*2], mm7
lea r0, [r0+r3*2]
%endrep
movq [r0+r3*1], mm7
movq [r0+r3*2], mm7
RET
%endmacro
INIT_MMX mmxext
PRED8x8L_TOP_DC
INIT_MMX ssse3
PRED8x8L_TOP_DC
;-----------------------------------------------------------------------------
; void ff_pred8x8l_dc_8(uint8_t *src, int has_topleft, int has_topright,
; ptrdiff_t stride)
;-----------------------------------------------------------------------------
%macro PRED8x8L_DC 0
cglobal pred8x8l_dc_8, 4,5
sub r0, r3
lea r4, [r0+r3*2]
movq mm0, [r0+r3*1-8]
punpckhbw mm0, [r0+r3*0-8]
movq mm1, [r4+r3*1-8]
punpckhbw mm1, [r0+r3*2-8]
mov r4, r0
punpckhwd mm1, mm0
lea r0, [r0+r3*4]
movq mm2, [r0+r3*1-8]
punpckhbw mm2, [r0+r3*0-8]
lea r0, [r0+r3*2]
movq mm3, [r0+r3*1-8]
punpckhbw mm3, [r0+r3*0-8]
punpckhwd mm3, mm2
punpckhdq mm3, mm1
lea r0, [r0+r3*2]
movq mm0, [r0+r3*0-8]
movq mm1, [r4]
mov r0, r4
movq mm4, mm3
movq mm2, mm3
PALIGNR mm4, mm0, 7, mm0
PALIGNR mm1, mm2, 1, mm2
test r1d, r1d
jnz .do_left
.fix_lt_1:
movq mm5, mm3
pxor mm5, mm4
psrlq mm5, 56
psllq mm5, 48
pxor mm1, mm5
jmp .do_left
.fix_lt_2:
movq mm5, mm3
pxor mm5, mm2
psllq mm5, 56
psrlq mm5, 56
pxor mm2, mm5
test r2d, r2d
jnz .body
.fix_tr_1:
movq mm5, mm3
pxor mm5, mm1
psrlq mm5, 56
psllq mm5, 56
pxor mm1, mm5
jmp .body
.do_left:
movq mm0, mm4
PRED4x4_LOWPASS mm2, mm1, mm4, mm3, mm5
movq mm4, mm0
movq mm7, mm2
PRED4x4_LOWPASS mm1, mm3, mm0, mm4, mm5
psllq mm1, 56
PALIGNR mm7, mm1, 7, mm3
movq mm0, [r0-8]
movq mm3, [r0]
movq mm1, [r0+8]
movq mm2, mm3
movq mm4, mm3
PALIGNR mm2, mm0, 7, mm0
PALIGNR mm1, mm4, 1, mm4
test r1d, r1d
jz .fix_lt_2
test r2d, r2d
jz .fix_tr_1
.body:
lea r1, [r0+r3*2]
PRED4x4_LOWPASS mm6, mm2, mm1, mm3, mm5
pxor mm0, mm0
pxor mm1, mm1
lea r2, [r1+r3*2]
psadbw mm0, mm7
psadbw mm1, mm6
paddw mm0, [pw_8]
paddw mm0, mm1
lea r4, [r2+r3*2]
psrlw mm0, 4
pshufw mm0, mm0, 0
packuswb mm0, mm0
movq [r0+r3*1], mm0
movq [r0+r3*2], mm0
movq [r1+r3*1], mm0
movq [r1+r3*2], mm0
movq [r2+r3*1], mm0
movq [r2+r3*2], mm0
movq [r4+r3*1], mm0
movq [r4+r3*2], mm0
RET
%endmacro
INIT_MMX mmxext
PRED8x8L_DC
INIT_MMX ssse3
PRED8x8L_DC
;-----------------------------------------------------------------------------
; void ff_pred8x8l_horizontal_8(uint8_t *src, int has_topleft,
; int has_topright, ptrdiff_t stride)
;-----------------------------------------------------------------------------
%macro PRED8x8L_HORIZONTAL 0
cglobal pred8x8l_horizontal_8, 4,4
sub r0, r3
lea r2, [r0+r3*2]
movq mm0, [r0+r3*1-8]
test r1d, r1d
lea r1, [r0+r3]
cmovnz r1, r0
punpckhbw mm0, [r1+r3*0-8]
movq mm1, [r2+r3*1-8]
punpckhbw mm1, [r0+r3*2-8]
mov r2, r0
punpckhwd mm1, mm0
lea r0, [r0+r3*4]
movq mm2, [r0+r3*1-8]
punpckhbw mm2, [r0+r3*0-8]
lea r0, [r0+r3*2]
movq mm3, [r0+r3*1-8]
punpckhbw mm3, [r0+r3*0-8]
punpckhwd mm3, mm2
punpckhdq mm3, mm1
lea r0, [r0+r3*2]
movq mm0, [r0+r3*0-8]
movq mm1, [r1+r3*0-8]
mov r0, r2
movq mm4, mm3
movq mm2, mm3
PALIGNR mm4, mm0, 7, mm0
PALIGNR mm1, mm2, 1, mm2
movq mm0, mm4
PRED4x4_LOWPASS mm2, mm1, mm4, mm3, mm5
movq mm4, mm0
movq mm7, mm2
PRED4x4_LOWPASS mm1, mm3, mm0, mm4, mm5
psllq mm1, 56
PALIGNR mm7, mm1, 7, mm3
movq mm3, mm7
lea r1, [r0+r3*2]
movq mm7, mm3
punpckhbw mm3, mm3
punpcklbw mm7, mm7
pshufw mm0, mm3, 0xff
pshufw mm1, mm3, 0xaa
lea r2, [r1+r3*2]
pshufw mm2, mm3, 0x55
pshufw mm3, mm3, 0x00
pshufw mm4, mm7, 0xff
pshufw mm5, mm7, 0xaa
pshufw mm6, mm7, 0x55
pshufw mm7, mm7, 0x00
movq [r0+r3*1], mm0
movq [r0+r3*2], mm1
movq [r1+r3*1], mm2
movq [r1+r3*2], mm3
movq [r2+r3*1], mm4
movq [r2+r3*2], mm5
lea r0, [r2+r3*2]
movq [r0+r3*1], mm6
movq [r0+r3*2], mm7
RET
%endmacro
INIT_MMX mmxext
PRED8x8L_HORIZONTAL
INIT_MMX ssse3
PRED8x8L_HORIZONTAL
;-----------------------------------------------------------------------------
; void ff_pred8x8l_vertical_8(uint8_t *src, int has_topleft, int has_topright,
; ptrdiff_t stride)
;-----------------------------------------------------------------------------
%macro PRED8x8L_VERTICAL 0
cglobal pred8x8l_vertical_8, 4,4
sub r0, r3
movq mm0, [r0-8]
movq mm3, [r0]
movq mm1, [r0+8]
movq mm2, mm3
movq mm4, mm3
PALIGNR mm2, mm0, 7, mm0
PALIGNR mm1, mm4, 1, mm4
test r1d, r1d ; top_left
jz .fix_lt_2
test r2d, r2d ; top_right
jz .fix_tr_1
jmp .body
.fix_lt_2:
movq mm5, mm3
pxor mm5, mm2
psllq mm5, 56
psrlq mm5, 56
pxor mm2, mm5
test r2d, r2d ; top_right
jnz .body
.fix_tr_1:
movq mm5, mm3
pxor mm5, mm1
psrlq mm5, 56
psllq mm5, 56
pxor mm1, mm5
.body:
PRED4x4_LOWPASS mm0, mm2, mm1, mm3, mm5
%rep 3
movq [r0+r3*1], mm0
movq [r0+r3*2], mm0
lea r0, [r0+r3*2]
%endrep
movq [r0+r3*1], mm0
movq [r0+r3*2], mm0
RET
%endmacro
INIT_MMX mmxext
PRED8x8L_VERTICAL
INIT_MMX ssse3
PRED8x8L_VERTICAL
;-----------------------------------------------------------------------------
; void ff_pred8x8l_down_left_8(uint8_t *src, int has_topleft,
; int has_topright, ptrdiff_t stride)
;-----------------------------------------------------------------------------
INIT_MMX mmxext
cglobal pred8x8l_down_left_8, 4,5
sub r0, r3
movq mm0, [r0-8]
movq mm3, [r0]
movq mm1, [r0+8]
movq mm2, mm3
movq mm4, mm3
PALIGNR mm2, mm0, 7, mm0
PALIGNR mm1, mm4, 1, mm4
test r1d, r1d
jz .fix_lt_2
test r2d, r2d
jz .fix_tr_1
jmp .do_top
.fix_lt_2:
movq mm5, mm3
pxor mm5, mm2
psllq mm5, 56
psrlq mm5, 56
pxor mm2, mm5
test r2d, r2d
jnz .do_top
.fix_tr_1:
movq mm5, mm3
pxor mm5, mm1
psrlq mm5, 56
psllq mm5, 56
pxor mm1, mm5
jmp .do_top
.fix_tr_2:
punpckhbw mm3, mm3
pshufw mm1, mm3, 0xFF
jmp .do_topright
.do_top:
PRED4x4_LOWPASS mm4, mm2, mm1, mm3, mm5
movq mm7, mm4
test r2d, r2d
jz .fix_tr_2
movq mm0, [r0+8]
movq mm5, mm0
movq mm2, mm0
movq mm4, mm0
psrlq mm5, 56
PALIGNR mm2, mm3, 7, mm3
PALIGNR mm5, mm4, 1, mm4
PRED4x4_LOWPASS mm1, mm2, mm5, mm0, mm4
.do_topright:
lea r1, [r0+r3*2]
movq mm6, mm1
psrlq mm1, 56
movq mm4, mm1
lea r2, [r1+r3*2]
movq mm2, mm6
PALIGNR mm2, mm7, 1, mm0
movq mm3, mm6
PALIGNR mm3, mm7, 7, mm0
PALIGNR mm4, mm6, 1, mm0
movq mm5, mm7
movq mm1, mm7
movq mm7, mm6
lea r4, [r2+r3*2]
psllq mm1, 8
PRED4x4_LOWPASS mm0, mm1, mm2, mm5, mm6
PRED4x4_LOWPASS mm1, mm3, mm4, mm7, mm6
movq [r4+r3*2], mm1
movq mm2, mm0
psllq mm1, 8
psrlq mm2, 56
psllq mm0, 8
por mm1, mm2
movq [r4+r3*1], mm1
movq mm2, mm0
psllq mm1, 8
psrlq mm2, 56
psllq mm0, 8
por mm1, mm2
movq [r2+r3*2], mm1
movq mm2, mm0
psllq mm1, 8
psrlq mm2, 56
psllq mm0, 8
por mm1, mm2
movq [r2+r3*1], mm1
movq mm2, mm0
psllq mm1, 8
psrlq mm2, 56
psllq mm0, 8
por mm1, mm2
movq [r1+r3*2], mm1
movq mm2, mm0
psllq mm1, 8
psrlq mm2, 56
psllq mm0, 8
por mm1, mm2
movq [r1+r3*1], mm1
movq mm2, mm0
psllq mm1, 8
psrlq mm2, 56
psllq mm0, 8
por mm1, mm2
movq [r0+r3*2], mm1
psllq mm1, 8
psrlq mm0, 56
por mm1, mm0
movq [r0+r3*1], mm1
RET
%macro PRED8x8L_DOWN_LEFT 0
cglobal pred8x8l_down_left_8, 4,4
sub r0, r3
movq mm0, [r0-8]
movq mm3, [r0]
movq mm1, [r0+8]
movq mm2, mm3
movq mm4, mm3
PALIGNR mm2, mm0, 7, mm0
PALIGNR mm1, mm4, 1, mm4
test r1d, r1d ; top_left
jz .fix_lt_2
test r2d, r2d ; top_right
jz .fix_tr_1
jmp .do_top
.fix_lt_2:
movq mm5, mm3
pxor mm5, mm2
psllq mm5, 56
psrlq mm5, 56
pxor mm2, mm5
test r2d, r2d ; top_right
jnz .do_top
.fix_tr_1:
movq mm5, mm3
pxor mm5, mm1
psrlq mm5, 56
psllq mm5, 56
pxor mm1, mm5
jmp .do_top
.fix_tr_2:
punpckhbw mm3, mm3
pshufw mm1, mm3, 0xFF
jmp .do_topright
.do_top:
PRED4x4_LOWPASS mm4, mm2, mm1, mm3, mm5
movq2dq xmm3, mm4
test r2d, r2d ; top_right
jz .fix_tr_2
movq mm0, [r0+8]
movq mm5, mm0
movq mm2, mm0
movq mm4, mm0
psrlq mm5, 56
PALIGNR mm2, mm3, 7, mm3
PALIGNR mm5, mm4, 1, mm4
PRED4x4_LOWPASS mm1, mm2, mm5, mm0, mm4
.do_topright:
movq2dq xmm4, mm1
psrlq mm1, 56
movq2dq xmm5, mm1
lea r1, [r0+r3*2]
pslldq xmm4, 8
por xmm3, xmm4
movdqa xmm2, xmm3
psrldq xmm2, 1
pslldq xmm5, 15
por xmm2, xmm5
lea r2, [r1+r3*2]
movdqa xmm1, xmm3
pslldq xmm1, 1
INIT_XMM cpuname
PRED4x4_LOWPASS xmm0, xmm1, xmm2, xmm3, xmm4
psrldq xmm0, 1
movq [r0+r3*1], xmm0
psrldq xmm0, 1
movq [r0+r3*2], xmm0
psrldq xmm0, 1
lea r0, [r2+r3*2]
movq [r1+r3*1], xmm0
psrldq xmm0, 1
movq [r1+r3*2], xmm0
psrldq xmm0, 1
movq [r2+r3*1], xmm0
psrldq xmm0, 1
movq [r2+r3*2], xmm0
psrldq xmm0, 1
movq [r0+r3*1], xmm0
psrldq xmm0, 1
movq [r0+r3*2], xmm0
RET
%endmacro
INIT_MMX sse2
PRED8x8L_DOWN_LEFT
INIT_MMX ssse3
PRED8x8L_DOWN_LEFT
;-----------------------------------------------------------------------------
; void ff_pred8x8l_down_right_8_mmxext(uint8_t *src, int has_topleft,
; int has_topright, ptrdiff_t stride)
;-----------------------------------------------------------------------------
INIT_MMX mmxext
cglobal pred8x8l_down_right_8, 4,5
sub r0, r3
lea r4, [r0+r3*2]
movq mm0, [r0+r3*1-8]
punpckhbw mm0, [r0+r3*0-8]
movq mm1, [r4+r3*1-8]
punpckhbw mm1, [r0+r3*2-8]
mov r4, r0
punpckhwd mm1, mm0
lea r0, [r0+r3*4]
movq mm2, [r0+r3*1-8]
punpckhbw mm2, [r0+r3*0-8]
lea r0, [r0+r3*2]
movq mm3, [r0+r3*1-8]
punpckhbw mm3, [r0+r3*0-8]
punpckhwd mm3, mm2
punpckhdq mm3, mm1
lea r0, [r0+r3*2]
movq mm0, [r0+r3*0-8]
movq mm1, [r4]
mov r0, r4
movq mm4, mm3
movq mm2, mm3
PALIGNR mm4, mm0, 7, mm0
PALIGNR mm1, mm2, 1, mm2
test r1d, r1d ; top_left
jz .fix_lt_1
.do_left:
movq mm0, mm4
PRED4x4_LOWPASS mm2, mm1, mm4, mm3, mm5
movq mm4, mm0
movq mm7, mm2
movq mm6, mm2
PRED4x4_LOWPASS mm1, mm3, mm0, mm4, mm5
psllq mm1, 56
PALIGNR mm7, mm1, 7, mm3
movq mm0, [r0-8]
movq mm3, [r0]
movq mm1, [r0+8]
movq mm2, mm3
movq mm4, mm3
PALIGNR mm2, mm0, 7, mm0
PALIGNR mm1, mm4, 1, mm4
test r1d, r1d ; top_left
jz .fix_lt_2
test r2d, r2d ; top_right
jz .fix_tr_1
.do_top:
PRED4x4_LOWPASS mm4, mm2, mm1, mm3, mm5
movq mm5, mm4
jmp .body
.fix_lt_1:
movq mm5, mm3
pxor mm5, mm4
psrlq mm5, 56
psllq mm5, 48
pxor mm1, mm5
jmp .do_left
.fix_lt_2:
movq mm5, mm3
pxor mm5, mm2
psllq mm5, 56
psrlq mm5, 56
pxor mm2, mm5
test r2d, r2d ; top_right
jnz .do_top
.fix_tr_1:
movq mm5, mm3
pxor mm5, mm1
psrlq mm5, 56
psllq mm5, 56
pxor mm1, mm5
jmp .do_top
.body:
lea r1, [r0+r3*2]
movq mm1, mm7
movq mm7, mm5
movq mm5, mm6
movq mm2, mm7
lea r2, [r1+r3*2]
PALIGNR mm2, mm6, 1, mm0
movq mm3, mm7
PALIGNR mm3, mm6, 7, mm0
movq mm4, mm7
lea r4, [r2+r3*2]
psrlq mm4, 8
PRED4x4_LOWPASS mm0, mm1, mm2, mm5, mm6
PRED4x4_LOWPASS mm1, mm3, mm4, mm7, mm6
movq [r4+r3*2], mm0
movq mm2, mm1
psrlq mm0, 8
psllq mm2, 56
psrlq mm1, 8
por mm0, mm2
movq [r4+r3*1], mm0
movq mm2, mm1
psrlq mm0, 8
psllq mm2, 56
psrlq mm1, 8
por mm0, mm2
movq [r2+r3*2], mm0
movq mm2, mm1
psrlq mm0, 8
psllq mm2, 56
psrlq mm1, 8
por mm0, mm2
movq [r2+r3*1], mm0
movq mm2, mm1
psrlq mm0, 8
psllq mm2, 56
psrlq mm1, 8
por mm0, mm2
movq [r1+r3*2], mm0
movq mm2, mm1
psrlq mm0, 8
psllq mm2, 56
psrlq mm1, 8
por mm0, mm2
movq [r1+r3*1], mm0
movq mm2, mm1
psrlq mm0, 8
psllq mm2, 56
psrlq mm1, 8
por mm0, mm2
movq [r0+r3*2], mm0
psrlq mm0, 8
psllq mm1, 56
por mm0, mm1
movq [r0+r3*1], mm0
RET
%macro PRED8x8L_DOWN_RIGHT 0
cglobal pred8x8l_down_right_8, 4,5
sub r0, r3
lea r4, [r0+r3*2]
movq mm0, [r0+r3*1-8]
punpckhbw mm0, [r0+r3*0-8]
movq mm1, [r4+r3*1-8]
punpckhbw mm1, [r0+r3*2-8]
mov r4, r0
punpckhwd mm1, mm0
lea r0, [r0+r3*4]
movq mm2, [r0+r3*1-8]
punpckhbw mm2, [r0+r3*0-8]
lea r0, [r0+r3*2]
movq mm3, [r0+r3*1-8]
punpckhbw mm3, [r0+r3*0-8]
punpckhwd mm3, mm2
punpckhdq mm3, mm1
lea r0, [r0+r3*2]
movq mm0, [r0+r3*0-8]
movq mm1, [r4]
mov r0, r4
movq mm4, mm3
movq mm2, mm3
PALIGNR mm4, mm0, 7, mm0
PALIGNR mm1, mm2, 1, mm2
test r1d, r1d
jz .fix_lt_1
jmp .do_left
.fix_lt_1:
movq mm5, mm3
pxor mm5, mm4
psrlq mm5, 56
psllq mm5, 48
pxor mm1, mm5
jmp .do_left
.fix_lt_2:
movq mm5, mm3
pxor mm5, mm2
psllq mm5, 56
psrlq mm5, 56
pxor mm2, mm5
test r2d, r2d
jnz .do_top
.fix_tr_1:
movq mm5, mm3
pxor mm5, mm1
psrlq mm5, 56
psllq mm5, 56
pxor mm1, mm5
jmp .do_top
.do_left:
movq mm0, mm4
PRED4x4_LOWPASS mm2, mm1, mm4, mm3, mm5
movq mm4, mm0
movq mm7, mm2
movq2dq xmm3, mm2
PRED4x4_LOWPASS mm1, mm3, mm0, mm4, mm5
psllq mm1, 56
PALIGNR mm7, mm1, 7, mm3
movq2dq xmm1, mm7
movq mm0, [r0-8]
movq mm3, [r0]
movq mm1, [r0+8]
movq mm2, mm3
movq mm4, mm3
PALIGNR mm2, mm0, 7, mm0
PALIGNR mm1, mm4, 1, mm4
test r1d, r1d
jz .fix_lt_2
test r2d, r2d
jz .fix_tr_1
.do_top:
PRED4x4_LOWPASS mm4, mm2, mm1, mm3, mm5
movq2dq xmm4, mm4
lea r1, [r0+r3*2]
movdqa xmm0, xmm3
pslldq xmm4, 8
por xmm3, xmm4
lea r2, [r1+r3*2]
pslldq xmm4, 1
por xmm1, xmm4
psrldq xmm0, 7
pslldq xmm0, 15
psrldq xmm0, 7
por xmm1, xmm0
lea r0, [r2+r3*2]
movdqa xmm2, xmm3
psrldq xmm2, 1
INIT_XMM cpuname
PRED4x4_LOWPASS xmm0, xmm1, xmm2, xmm3, xmm4
movdqa xmm1, xmm0
psrldq xmm1, 1
movq [r0+r3*2], xmm0
movq [r0+r3*1], xmm1
psrldq xmm0, 2
psrldq xmm1, 2
movq [r2+r3*2], xmm0
movq [r2+r3*1], xmm1
psrldq xmm0, 2
psrldq xmm1, 2
movq [r1+r3*2], xmm0
movq [r1+r3*1], xmm1
psrldq xmm0, 2
psrldq xmm1, 2
movq [r4+r3*2], xmm0
movq [r4+r3*1], xmm1
RET
%endmacro
INIT_MMX sse2
PRED8x8L_DOWN_RIGHT
INIT_MMX ssse3
PRED8x8L_DOWN_RIGHT
;-----------------------------------------------------------------------------
; void ff_pred8x8l_vertical_right_8(uint8_t *src, int has_topleft,
; int has_topright, ptrdiff_t stride)
;-----------------------------------------------------------------------------
INIT_MMX mmxext
cglobal pred8x8l_vertical_right_8, 4,5
sub r0, r3
lea r4, [r0+r3*2]
movq mm0, [r0+r3*1-8]
punpckhbw mm0, [r0+r3*0-8]
movq mm1, [r4+r3*1-8]
punpckhbw mm1, [r0+r3*2-8]
mov r4, r0
punpckhwd mm1, mm0
lea r0, [r0+r3*4]
movq mm2, [r0+r3*1-8]
punpckhbw mm2, [r0+r3*0-8]
lea r0, [r0+r3*2]
movq mm3, [r0+r3*1-8]
punpckhbw mm3, [r0+r3*0-8]
punpckhwd mm3, mm2
punpckhdq mm3, mm1
lea r0, [r0+r3*2]
movq mm0, [r0+r3*0-8]
movq mm1, [r4]
mov r0, r4
movq mm4, mm3
movq mm2, mm3
PALIGNR mm4, mm0, 7, mm0
PALIGNR mm1, mm2, 1, mm2
test r1d, r1d
jz .fix_lt_1
jmp .do_left
.fix_lt_1:
movq mm5, mm3
pxor mm5, mm4
psrlq mm5, 56
psllq mm5, 48
pxor mm1, mm5
jmp .do_left
.fix_lt_2:
movq mm5, mm3
pxor mm5, mm2
psllq mm5, 56
psrlq mm5, 56
pxor mm2, mm5
test r2d, r2d
jnz .do_top
.fix_tr_1:
movq mm5, mm3
pxor mm5, mm1
psrlq mm5, 56
psllq mm5, 56
pxor mm1, mm5
jmp .do_top
.do_left:
movq mm0, mm4
PRED4x4_LOWPASS mm2, mm1, mm4, mm3, mm5
movq mm7, mm2
movq mm0, [r0-8]
movq mm3, [r0]
movq mm1, [r0+8]
movq mm2, mm3
movq mm4, mm3
PALIGNR mm2, mm0, 7, mm0
PALIGNR mm1, mm4, 1, mm4
test r1d, r1d
jz .fix_lt_2
test r2d, r2d
jz .fix_tr_1
.do_top:
PRED4x4_LOWPASS mm6, mm2, mm1, mm3, mm5
lea r1, [r0+r3*2]
movq mm2, mm6
movq mm3, mm6
PALIGNR mm3, mm7, 7, mm0
PALIGNR mm6, mm7, 6, mm1
movq mm4, mm3
pavgb mm3, mm2
lea r2, [r1+r3*2]
PRED4x4_LOWPASS mm0, mm6, mm2, mm4, mm5
movq [r0+r3*1], mm3
movq [r0+r3*2], mm0
movq mm5, mm0
movq mm6, mm3
movq mm1, mm7
movq mm2, mm1
psllq mm2, 8
movq mm3, mm1
psllq mm3, 16
lea r4, [r2+r3*2]
PRED4x4_LOWPASS mm0, mm1, mm3, mm2, mm4
PALIGNR mm6, mm0, 7, mm2
movq [r1+r3*1], mm6
psllq mm0, 8
PALIGNR mm5, mm0, 7, mm1
movq [r1+r3*2], mm5
psllq mm0, 8
PALIGNR mm6, mm0, 7, mm2
movq [r2+r3*1], mm6
psllq mm0, 8
PALIGNR mm5, mm0, 7, mm1
movq [r2+r3*2], mm5
psllq mm0, 8
PALIGNR mm6, mm0, 7, mm2
movq [r4+r3*1], mm6
psllq mm0, 8
PALIGNR mm5, mm0, 7, mm1
movq [r4+r3*2], mm5
RET
%macro PRED8x8L_VERTICAL_RIGHT 0
cglobal pred8x8l_vertical_right_8, 4,5,7
; manually spill XMM registers for Win64 because
; the code here is initialized with INIT_MMX
WIN64_SPILL_XMM 7
sub r0, r3
lea r4, [r0+r3*2]
movq mm0, [r0+r3*1-8]
punpckhbw mm0, [r0+r3*0-8]
movq mm1, [r4+r3*1-8]
punpckhbw mm1, [r0+r3*2-8]
mov r4, r0
punpckhwd mm1, mm0
lea r0, [r0+r3*4]
movq mm2, [r0+r3*1-8]
punpckhbw mm2, [r0+r3*0-8]
lea r0, [r0+r3*2]
movq mm3, [r0+r3*1-8]
punpckhbw mm3, [r0+r3*0-8]
punpckhwd mm3, mm2
punpckhdq mm3, mm1
lea r0, [r0+r3*2]
movq mm0, [r0+r3*0-8]
movq mm1, [r4]
mov r0, r4
movq mm4, mm3
movq mm2, mm3
PALIGNR mm4, mm0, 7, mm0
PALIGNR mm1, mm2, 1, mm2
test r1d, r1d
jnz .do_left
.fix_lt_1:
movq mm5, mm3
pxor mm5, mm4
psrlq mm5, 56
psllq mm5, 48
pxor mm1, mm5
jmp .do_left
.fix_lt_2:
movq mm5, mm3
pxor mm5, mm2
psllq mm5, 56
psrlq mm5, 56
pxor mm2, mm5
test r2d, r2d
jnz .do_top
.fix_tr_1:
movq mm5, mm3
pxor mm5, mm1
psrlq mm5, 56
psllq mm5, 56
pxor mm1, mm5
jmp .do_top
.do_left:
movq mm0, mm4
PRED4x4_LOWPASS mm2, mm1, mm4, mm3, mm5
movq2dq xmm0, mm2
movq mm0, [r0-8]
movq mm3, [r0]
movq mm1, [r0+8]
movq mm2, mm3
movq mm4, mm3
PALIGNR mm2, mm0, 7, mm0
PALIGNR mm1, mm4, 1, mm4
test r1d, r1d
jz .fix_lt_2
test r2d, r2d
jz .fix_tr_1
.do_top:
PRED4x4_LOWPASS mm6, mm2, mm1, mm3, mm5
lea r1, [r0+r3*2]
movq2dq xmm4, mm6
pslldq xmm4, 8
por xmm0, xmm4
movdqa xmm6, [pw_ff00]
movdqa xmm1, xmm0
lea r2, [r1+r3*2]
movdqa xmm2, xmm0
movdqa xmm3, xmm0
pslldq xmm0, 1
pslldq xmm1, 2
pavgb xmm2, xmm0
INIT_XMM cpuname
PRED4x4_LOWPASS xmm4, xmm3, xmm1, xmm0, xmm5
pandn xmm6, xmm4
movdqa xmm5, xmm4
psrlw xmm4, 8
packuswb xmm6, xmm4
movhlps xmm4, xmm6
movhps [r0+r3*2], xmm5
movhps [r0+r3*1], xmm2
psrldq xmm5, 4
movss xmm5, xmm6
psrldq xmm2, 4
movss xmm2, xmm4
lea r0, [r2+r3*2]
psrldq xmm5, 1
psrldq xmm2, 1
movq [r0+r3*2], xmm5
movq [r0+r3*1], xmm2
psrldq xmm5, 1
psrldq xmm2, 1
movq [r2+r3*2], xmm5
movq [r2+r3*1], xmm2
psrldq xmm5, 1
psrldq xmm2, 1
movq [r1+r3*2], xmm5
movq [r1+r3*1], xmm2
RET
%endmacro
INIT_MMX sse2
PRED8x8L_VERTICAL_RIGHT
INIT_MMX ssse3
PRED8x8L_VERTICAL_RIGHT
;-----------------------------------------------------------------------------
; void ff_pred8x8l_vertical_left_8(uint8_t *src, int has_topleft,
; int has_topright, ptrdiff_t stride)
;-----------------------------------------------------------------------------
%macro PRED8x8L_VERTICAL_LEFT 0
cglobal pred8x8l_vertical_left_8, 4,4
sub r0, r3
movq mm0, [r0-8]
movq mm3, [r0]
movq mm1, [r0+8]
movq mm2, mm3
movq mm4, mm3
PALIGNR mm2, mm0, 7, mm0
PALIGNR mm1, mm4, 1, mm4
test r1d, r1d
jz .fix_lt_2
test r2d, r2d
jz .fix_tr_1
jmp .do_top
.fix_lt_2:
movq mm5, mm3
pxor mm5, mm2
psllq mm5, 56
psrlq mm5, 56
pxor mm2, mm5
test r2d, r2d
jnz .do_top
.fix_tr_1:
movq mm5, mm3
pxor mm5, mm1
psrlq mm5, 56
psllq mm5, 56
pxor mm1, mm5
jmp .do_top
.fix_tr_2:
punpckhbw mm3, mm3
pshufw mm1, mm3, 0xFF
jmp .do_topright
.do_top:
PRED4x4_LOWPASS mm4, mm2, mm1, mm3, mm5
movq2dq xmm4, mm4
test r2d, r2d
jz .fix_tr_2
movq mm0, [r0+8]
movq mm5, mm0
movq mm2, mm0
movq mm4, mm0
psrlq mm5, 56
PALIGNR mm2, mm3, 7, mm3
PALIGNR mm5, mm4, 1, mm4
PRED4x4_LOWPASS mm1, mm2, mm5, mm0, mm4
.do_topright:
movq2dq xmm3, mm1
lea r1, [r0+r3*2]
pslldq xmm3, 8
por xmm4, xmm3
movdqa xmm2, xmm4
movdqa xmm1, xmm4
movdqa xmm3, xmm4
psrldq xmm2, 1
pslldq xmm1, 1
pavgb xmm3, xmm2
lea r2, [r1+r3*2]
INIT_XMM cpuname
PRED4x4_LOWPASS xmm0, xmm1, xmm2, xmm4, xmm5
psrldq xmm0, 1
movq [r0+r3*1], xmm3
movq [r0+r3*2], xmm0
lea r0, [r2+r3*2]
psrldq xmm3, 1
psrldq xmm0, 1
movq [r1+r3*1], xmm3
movq [r1+r3*2], xmm0
psrldq xmm3, 1
psrldq xmm0, 1
movq [r2+r3*1], xmm3
movq [r2+r3*2], xmm0
psrldq xmm3, 1
psrldq xmm0, 1
movq [r0+r3*1], xmm3
movq [r0+r3*2], xmm0
RET
%endmacro
INIT_MMX sse2
PRED8x8L_VERTICAL_LEFT
INIT_MMX ssse3
PRED8x8L_VERTICAL_LEFT
;-----------------------------------------------------------------------------
; void ff_pred8x8l_horizontal_up_8(uint8_t *src, int has_topleft,
; int has_topright, ptrdiff_t stride)
;-----------------------------------------------------------------------------
%macro PRED8x8L_HORIZONTAL_UP 0
cglobal pred8x8l_horizontal_up_8, 4,4
sub r0, r3
lea r2, [r0+r3*2]
movq mm0, [r0+r3*1-8]
test r1d, r1d
lea r1, [r0+r3]
cmovnz r1, r0
punpckhbw mm0, [r1+r3*0-8]
movq mm1, [r2+r3*1-8]
punpckhbw mm1, [r0+r3*2-8]
mov r2, r0
punpckhwd mm1, mm0
lea r0, [r0+r3*4]
movq mm2, [r0+r3*1-8]
punpckhbw mm2, [r0+r3*0-8]
lea r0, [r0+r3*2]
movq mm3, [r0+r3*1-8]
punpckhbw mm3, [r0+r3*0-8]
punpckhwd mm3, mm2
punpckhdq mm3, mm1
lea r0, [r0+r3*2]
movq mm0, [r0+r3*0-8]
movq mm1, [r1+r3*0-8]
mov r0, r2
movq mm4, mm3
movq mm2, mm3
PALIGNR mm4, mm0, 7, mm0
PALIGNR mm1, mm2, 1, mm2
movq mm0, mm4
PRED4x4_LOWPASS mm2, mm1, mm4, mm3, mm5
movq mm4, mm0
movq mm7, mm2
PRED4x4_LOWPASS mm1, mm3, mm0, mm4, mm5
psllq mm1, 56
PALIGNR mm7, mm1, 7, mm3
lea r1, [r0+r3*2]
pshufw mm0, mm7, 00011011b ; l6 l7 l4 l5 l2 l3 l0 l1
psllq mm7, 56 ; l7 .. .. .. .. .. .. ..
movq mm2, mm0
psllw mm0, 8
psrlw mm2, 8
por mm2, mm0 ; l7 l6 l5 l4 l3 l2 l1 l0
movq mm3, mm2
movq mm4, mm2
movq mm5, mm2
psrlq mm2, 8
psrlq mm3, 16
lea r2, [r1+r3*2]
por mm2, mm7 ; l7 l7 l6 l5 l4 l3 l2 l1
punpckhbw mm7, mm7
por mm3, mm7 ; l7 l7 l7 l6 l5 l4 l3 l2
pavgb mm4, mm2
PRED4x4_LOWPASS mm1, mm3, mm5, mm2, mm6
movq mm5, mm4
punpcklbw mm4, mm1 ; p4 p3 p2 p1
punpckhbw mm5, mm1 ; p8 p7 p6 p5
movq mm6, mm5
movq mm7, mm5
movq mm0, mm5
PALIGNR mm5, mm4, 2, mm1
pshufw mm1, mm6, 11111001b
PALIGNR mm6, mm4, 4, mm2
pshufw mm2, mm7, 11111110b
PALIGNR mm7, mm4, 6, mm3
pshufw mm3, mm0, 11111111b
movq [r0+r3*1], mm4
movq [r0+r3*2], mm5
lea r0, [r2+r3*2]
movq [r1+r3*1], mm6
movq [r1+r3*2], mm7
movq [r2+r3*1], mm0
movq [r2+r3*2], mm1
movq [r0+r3*1], mm2
movq [r0+r3*2], mm3
RET
%endmacro
INIT_MMX mmxext
PRED8x8L_HORIZONTAL_UP
INIT_MMX ssse3
PRED8x8L_HORIZONTAL_UP
;-----------------------------------------------------------------------------
; void ff_pred8x8l_horizontal_down_8(uint8_t *src, int has_topleft,
; int has_topright, ptrdiff_t stride)
;-----------------------------------------------------------------------------
INIT_MMX mmxext
cglobal pred8x8l_horizontal_down_8, 4,5
sub r0, r3
lea r4, [r0+r3*2]
movq mm0, [r0+r3*1-8]
punpckhbw mm0, [r0+r3*0-8]
movq mm1, [r4+r3*1-8]
punpckhbw mm1, [r0+r3*2-8]
mov r4, r0
punpckhwd mm1, mm0
lea r0, [r0+r3*4]
movq mm2, [r0+r3*1-8]
punpckhbw mm2, [r0+r3*0-8]
lea r0, [r0+r3*2]
movq mm3, [r0+r3*1-8]
punpckhbw mm3, [r0+r3*0-8]
punpckhwd mm3, mm2
punpckhdq mm3, mm1
lea r0, [r0+r3*2]
movq mm0, [r0+r3*0-8]
movq mm1, [r4]
mov r0, r4
movq mm4, mm3
movq mm2, mm3
PALIGNR mm4, mm0, 7, mm0
PALIGNR mm1, mm2, 1, mm2
test r1d, r1d
jnz .do_left
.fix_lt_1:
movq mm5, mm3
pxor mm5, mm4
psrlq mm5, 56
psllq mm5, 48
pxor mm1, mm5
jmp .do_left
.fix_lt_2:
movq mm5, mm3
pxor mm5, mm2
psllq mm5, 56
psrlq mm5, 56
pxor mm2, mm5
test r2d, r2d
jnz .do_top
.fix_tr_1:
movq mm5, mm3
pxor mm5, mm1
psrlq mm5, 56
psllq mm5, 56
pxor mm1, mm5
jmp .do_top
.do_left:
movq mm0, mm4
PRED4x4_LOWPASS mm2, mm1, mm4, mm3, mm5
movq mm4, mm0
movq mm7, mm2
movq mm6, mm2
PRED4x4_LOWPASS mm1, mm3, mm0, mm4, mm5
psllq mm1, 56
PALIGNR mm7, mm1, 7, mm3
movq mm0, [r0-8]
movq mm3, [r0]
movq mm1, [r0+8]
movq mm2, mm3
movq mm4, mm3
PALIGNR mm2, mm0, 7, mm0
PALIGNR mm1, mm4, 1, mm4
test r1d, r1d
jz .fix_lt_2
test r2d, r2d
jz .fix_tr_1
.do_top:
PRED4x4_LOWPASS mm4, mm2, mm1, mm3, mm5
movq mm5, mm4
lea r1, [r0+r3*2]
psllq mm7, 56
movq mm2, mm5
movq mm3, mm6
movq mm4, mm2
PALIGNR mm2, mm6, 7, mm5
PALIGNR mm6, mm7, 7, mm0
lea r2, [r1+r3*2]
PALIGNR mm4, mm3, 1, mm7
movq mm5, mm3
pavgb mm3, mm6
PRED4x4_LOWPASS mm0, mm4, mm6, mm5, mm7
movq mm4, mm2
movq mm1, mm2
lea r4, [r2+r3*2]
psrlq mm4, 16
psrlq mm1, 8
PRED4x4_LOWPASS mm6, mm4, mm2, mm1, mm5
movq mm7, mm3
punpcklbw mm3, mm0
punpckhbw mm7, mm0
movq mm1, mm7
movq mm0, mm7
movq mm4, mm7
movq [r4+r3*2], mm3
PALIGNR mm7, mm3, 2, mm5
movq [r4+r3*1], mm7
PALIGNR mm1, mm3, 4, mm5
movq [r2+r3*2], mm1
PALIGNR mm0, mm3, 6, mm3
movq [r2+r3*1], mm0
movq mm2, mm6
movq mm3, mm6
movq [r1+r3*2], mm4
PALIGNR mm6, mm4, 2, mm5
movq [r1+r3*1], mm6
PALIGNR mm2, mm4, 4, mm5
movq [r0+r3*2], mm2
PALIGNR mm3, mm4, 6, mm4
movq [r0+r3*1], mm3
RET
%macro PRED8x8L_HORIZONTAL_DOWN 0
cglobal pred8x8l_horizontal_down_8, 4,5
sub r0, r3
lea r4, [r0+r3*2]
movq mm0, [r0+r3*1-8]
punpckhbw mm0, [r0+r3*0-8]
movq mm1, [r4+r3*1-8]
punpckhbw mm1, [r0+r3*2-8]
mov r4, r0
punpckhwd mm1, mm0
lea r0, [r0+r3*4]
movq mm2, [r0+r3*1-8]
punpckhbw mm2, [r0+r3*0-8]
lea r0, [r0+r3*2]
movq mm3, [r0+r3*1-8]
punpckhbw mm3, [r0+r3*0-8]
punpckhwd mm3, mm2
punpckhdq mm3, mm1
lea r0, [r0+r3*2]
movq mm0, [r0+r3*0-8]
movq mm1, [r4]
mov r0, r4
movq mm4, mm3
movq mm2, mm3
PALIGNR mm4, mm0, 7, mm0
PALIGNR mm1, mm2, 1, mm2
test r1d, r1d
jnz .do_left
.fix_lt_1:
movq mm5, mm3
pxor mm5, mm4
psrlq mm5, 56
psllq mm5, 48
pxor mm1, mm5
jmp .do_left
.fix_lt_2:
movq mm5, mm3
pxor mm5, mm2
psllq mm5, 56
psrlq mm5, 56
pxor mm2, mm5
test r2d, r2d
jnz .do_top
.fix_tr_1:
movq mm5, mm3
pxor mm5, mm1
psrlq mm5, 56
psllq mm5, 56
pxor mm1, mm5
jmp .do_top
.fix_tr_2:
punpckhbw mm3, mm3
pshufw mm1, mm3, 0xFF
jmp .do_topright
.do_left:
movq mm0, mm4
PRED4x4_LOWPASS mm2, mm1, mm4, mm3, mm5
movq2dq xmm0, mm2
pslldq xmm0, 8
movq mm4, mm0
PRED4x4_LOWPASS mm1, mm3, mm0, mm4, mm5
movq2dq xmm2, mm1
pslldq xmm2, 15
psrldq xmm2, 8
por xmm0, xmm2
movq mm0, [r0-8]
movq mm3, [r0]
movq mm1, [r0+8]
movq mm2, mm3
movq mm4, mm3
PALIGNR mm2, mm0, 7, mm0
PALIGNR mm1, mm4, 1, mm4
test r1d, r1d
jz .fix_lt_2
test r2d, r2d
jz .fix_tr_1
.do_top:
PRED4x4_LOWPASS mm4, mm2, mm1, mm3, mm5
movq2dq xmm1, mm4
test r2d, r2d
jz .fix_tr_2
movq mm0, [r0+8]
movq mm5, mm0
movq mm2, mm0
movq mm4, mm0
psrlq mm5, 56
PALIGNR mm2, mm3, 7, mm3
PALIGNR mm5, mm4, 1, mm4
PRED4x4_LOWPASS mm1, mm2, mm5, mm0, mm4
.do_topright:
movq2dq xmm5, mm1
pslldq xmm5, 8
por xmm1, xmm5
INIT_XMM cpuname
lea r2, [r4+r3*2]
movdqa xmm2, xmm1
movdqa xmm3, xmm1
PALIGNR xmm1, xmm0, 7, xmm4
PALIGNR xmm2, xmm0, 9, xmm5
lea r1, [r2+r3*2]
PALIGNR xmm3, xmm0, 8, xmm0
movdqa xmm4, xmm1
pavgb xmm4, xmm3
lea r0, [r1+r3*2]
PRED4x4_LOWPASS xmm0, xmm1, xmm2, xmm3, xmm5
punpcklbw xmm4, xmm0
movhlps xmm0, xmm4
movq [r0+r3*2], xmm4
movq [r2+r3*2], xmm0
psrldq xmm4, 2
psrldq xmm0, 2
movq [r0+r3*1], xmm4
movq [r2+r3*1], xmm0
psrldq xmm4, 2
psrldq xmm0, 2
movq [r1+r3*2], xmm4
movq [r4+r3*2], xmm0
psrldq xmm4, 2
psrldq xmm0, 2
movq [r1+r3*1], xmm4
movq [r4+r3*1], xmm0
RET
%endmacro
INIT_MMX sse2
PRED8x8L_HORIZONTAL_DOWN
INIT_MMX ssse3
PRED8x8L_HORIZONTAL_DOWN
;-------------------------------------------------------------------------------
; void ff_pred4x4_dc_8_mmxext(uint8_t *src, const uint8_t *topright,
; ptrdiff_t stride)
;-------------------------------------------------------------------------------
INIT_MMX mmxext
cglobal pred4x4_dc_8, 3,5
pxor mm7, mm7
mov r4, r0
sub r0, r2
movd mm0, [r0]
psadbw mm0, mm7
movzx r1d, byte [r0+r2*1-1]
movd r3d, mm0
add r3d, r1d
movzx r1d, byte [r0+r2*2-1]
lea r0, [r0+r2*2]
add r3d, r1d
movzx r1d, byte [r0+r2*1-1]
add r3d, r1d
movzx r1d, byte [r0+r2*2-1]
add r3d, r1d
add r3d, 4
shr r3d, 3
imul r3d, 0x01010101
mov [r4+r2*0], r3d
mov [r0+r2*0], r3d
mov [r0+r2*1], r3d
mov [r0+r2*2], r3d
RET
;-----------------------------------------------------------------------------
; void ff_pred4x4_tm_vp8_8_mmxext(uint8_t *src, const uint8_t *topright,
; ptrdiff_t stride)
;-----------------------------------------------------------------------------
%macro PRED4x4_TM 0
cglobal pred4x4_tm_vp8_8, 3,6
sub r0, r2
pxor mm7, mm7
movd mm0, [r0]
punpcklbw mm0, mm7
movzx r4d, byte [r0-1]
mov r5d, 2
.loop:
movzx r1d, byte [r0+r2*1-1]
movzx r3d, byte [r0+r2*2-1]
sub r1d, r4d
sub r3d, r4d
movd mm2, r1d
movd mm4, r3d
%if cpuflag(mmxext)
pshufw mm2, mm2, 0
pshufw mm4, mm4, 0
%else
punpcklwd mm2, mm2
punpcklwd mm4, mm4
punpckldq mm2, mm2
punpckldq mm4, mm4
%endif
paddw mm2, mm0
paddw mm4, mm0
packuswb mm2, mm2
packuswb mm4, mm4
movd [r0+r2*1], mm2
movd [r0+r2*2], mm4
lea r0, [r0+r2*2]
dec r5d
jg .loop
REP_RET
%endmacro
INIT_MMX mmx
PRED4x4_TM
INIT_MMX mmxext
PRED4x4_TM
INIT_XMM ssse3
cglobal pred4x4_tm_vp8_8, 3,3
sub r0, r2
movq mm6, [tm_shuf]
pxor mm1, mm1
movd mm0, [r0]
punpcklbw mm0, mm1
movd mm7, [r0-4]
pshufb mm7, mm6
lea r1, [r0+r2*2]
movd mm2, [r0+r2*1-4]
movd mm3, [r0+r2*2-4]
movd mm4, [r1+r2*1-4]
movd mm5, [r1+r2*2-4]
pshufb mm2, mm6
pshufb mm3, mm6
pshufb mm4, mm6
pshufb mm5, mm6
psubw mm0, mm7
paddw mm2, mm0
paddw mm3, mm0
paddw mm4, mm0
paddw mm5, mm0
packuswb mm2, mm2
packuswb mm3, mm3
packuswb mm4, mm4
packuswb mm5, mm5
movd [r0+r2*1], mm2
movd [r0+r2*2], mm3
movd [r1+r2*1], mm4
movd [r1+r2*2], mm5
RET
;-----------------------------------------------------------------------------
; void ff_pred4x4_vertical_vp8_8_mmxext(uint8_t *src, const uint8_t *topright,
; ptrdiff_t stride)
;-----------------------------------------------------------------------------
INIT_MMX mmxext
cglobal pred4x4_vertical_vp8_8, 3,3
sub r0, r2
movd m1, [r0-1]
movd m0, [r0]
mova m2, m0 ;t0 t1 t2 t3
punpckldq m0, [r1] ;t0 t1 t2 t3 t4 t5 t6 t7
lea r1, [r0+r2*2]
psrlq m0, 8 ;t1 t2 t3 t4
PRED4x4_LOWPASS m3, m1, m0, m2, m4
movd [r0+r2*1], m3
movd [r0+r2*2], m3
movd [r1+r2*1], m3
movd [r1+r2*2], m3
RET
;-----------------------------------------------------------------------------
; void ff_pred4x4_down_left_8_mmxext(uint8_t *src, const uint8_t *topright,
; ptrdiff_t stride)
;-----------------------------------------------------------------------------
INIT_MMX mmxext
cglobal pred4x4_down_left_8, 3,3
sub r0, r2
movq m1, [r0]
punpckldq m1, [r1]
movq m2, m1
movq m3, m1
psllq m1, 8
pxor m2, m1
psrlq m2, 8
pxor m2, m3
PRED4x4_LOWPASS m0, m1, m2, m3, m4
lea r1, [r0+r2*2]
psrlq m0, 8
movd [r0+r2*1], m0
psrlq m0, 8
movd [r0+r2*2], m0
psrlq m0, 8
movd [r1+r2*1], m0
psrlq m0, 8
movd [r1+r2*2], m0
RET
;------------------------------------------------------------------------------
; void ff_pred4x4_vertical_left_8_mmxext(uint8_t *src, const uint8_t *topright,
; ptrdiff_t stride)
;------------------------------------------------------------------------------
INIT_MMX mmxext
cglobal pred4x4_vertical_left_8, 3,3
sub r0, r2
movq m1, [r0]
punpckldq m1, [r1]
movq m3, m1
movq m2, m1
psrlq m3, 8
psrlq m2, 16
movq m4, m3
pavgb m4, m1
PRED4x4_LOWPASS m0, m1, m2, m3, m5
lea r1, [r0+r2*2]
movh [r0+r2*1], m4
movh [r0+r2*2], m0
psrlq m4, 8
psrlq m0, 8
movh [r1+r2*1], m4
movh [r1+r2*2], m0
RET
;------------------------------------------------------------------------------
; void ff_pred4x4_horizontal_up_8_mmxext(uint8_t *src, const uint8_t *topright,
; ptrdiff_t stride)
;------------------------------------------------------------------------------
INIT_MMX mmxext
cglobal pred4x4_horizontal_up_8, 3,3
sub r0, r2
lea r1, [r0+r2*2]
movd m0, [r0+r2*1-4]
punpcklbw m0, [r0+r2*2-4]
movd m1, [r1+r2*1-4]
punpcklbw m1, [r1+r2*2-4]
punpckhwd m0, m1
movq m1, m0
punpckhbw m1, m1
pshufw m1, m1, 0xFF
punpckhdq m0, m1
movq m2, m0
movq m3, m0
movq m7, m0
psrlq m2, 16
psrlq m3, 8
pavgb m7, m3
PRED4x4_LOWPASS m4, m0, m2, m3, m5
punpcklbw m7, m4
movd [r0+r2*1], m7
psrlq m7, 16
movd [r0+r2*2], m7
psrlq m7, 16
movd [r1+r2*1], m7
movd [r1+r2*2], m1
RET
;------------------------------------------------------------------------------
; void ff_pred4x4_horizontal_down_8_mmxext(uint8_t *src,
; const uint8_t *topright,
; ptrdiff_t stride)
;------------------------------------------------------------------------------
INIT_MMX mmxext
cglobal pred4x4_horizontal_down_8, 3,3
sub r0, r2
lea r1, [r0+r2*2]
movh m0, [r0-4] ; lt ..
punpckldq m0, [r0] ; t3 t2 t1 t0 lt .. .. ..
psllq m0, 8 ; t2 t1 t0 lt .. .. .. ..
movd m1, [r1+r2*2-4] ; l3
punpcklbw m1, [r1+r2*1-4] ; l2 l3
movd m2, [r0+r2*2-4] ; l1
punpcklbw m2, [r0+r2*1-4] ; l0 l1
punpckhwd m1, m2 ; l0 l1 l2 l3
punpckhdq m1, m0 ; t2 t1 t0 lt l0 l1 l2 l3
movq m0, m1
movq m2, m1
movq m5, m1
psrlq m0, 16 ; .. .. t2 t1 t0 lt l0 l1
psrlq m2, 8 ; .. t2 t1 t0 lt l0 l1 l2
pavgb m5, m2
PRED4x4_LOWPASS m3, m1, m0, m2, m4
punpcklbw m5, m3
psrlq m3, 32
PALIGNR m3, m5, 6, m4
movh [r1+r2*2], m5
psrlq m5, 16
movh [r1+r2*1], m5
psrlq m5, 16
movh [r0+r2*2], m5
movh [r0+r2*1], m3
RET
;-----------------------------------------------------------------------------
; void ff_pred4x4_vertical_right_8_mmxext(uint8_t *src,
; const uint8_t *topright,
; ptrdiff_t stride)
;-----------------------------------------------------------------------------
INIT_MMX mmxext
cglobal pred4x4_vertical_right_8, 3,3
sub r0, r2
lea r1, [r0+r2*2]
movh m0, [r0] ; ........t3t2t1t0
movq m5, m0
PALIGNR m0, [r0-8], 7, m1 ; ......t3t2t1t0lt
pavgb m5, m0
PALIGNR m0, [r0+r2*1-8], 7, m1 ; ....t3t2t1t0ltl0
movq m1, m0
PALIGNR m0, [r0+r2*2-8], 7, m2 ; ..t3t2t1t0ltl0l1
movq m2, m0
PALIGNR m0, [r1+r2*1-8], 7, m3 ; t3t2t1t0ltl0l1l2
PRED4x4_LOWPASS m3, m1, m0, m2, m4
movq m1, m3
psrlq m3, 16
psllq m1, 48
movh [r0+r2*1], m5
movh [r0+r2*2], m3
PALIGNR m5, m1, 7, m2
psllq m1, 8
movh [r1+r2*1], m5
PALIGNR m3, m1, 7, m1
movh [r1+r2*2], m3
RET
;-----------------------------------------------------------------------------
; void ff_pred4x4_down_right_8_mmxext(uint8_t *src, const uint8_t *topright,
; ptrdiff_t stride)
;-----------------------------------------------------------------------------
INIT_MMX mmxext
cglobal pred4x4_down_right_8, 3,3
sub r0, r2
lea r1, [r0+r2*2]
movq m1, [r1-8]
movq m2, [r0+r2*1-8]
punpckhbw m2, [r0-8]
movh m3, [r0]
punpckhwd m1, m2
PALIGNR m3, m1, 5, m1
movq m1, m3
PALIGNR m3, [r1+r2*1-8], 7, m4
movq m2, m3
PALIGNR m3, [r1+r2*2-8], 7, m4
PRED4x4_LOWPASS m0, m3, m1, m2, m4
movh [r1+r2*2], m0
psrlq m0, 8
movh [r1+r2*1], m0
psrlq m0, 8
movh [r0+r2*2], m0
psrlq m0, 8
movh [r0+r2*1], m0
RET
|
; A214945: Number of squarefree words of length 6 in an (n+1)-ary alphabet.
; 0,42,696,4260,16680,50190,126672,281736,569520,1068210,1886280,3169452,5108376,7947030,11991840,17621520,25297632,35575866,49118040,66704820,89249160,117810462,153609456,198043800,252704400,319392450,400137192
mov $3,$0
lpb $0
sub $0,1
add $1,$0
lpe
mul $1,4
mov $4,$3
mov $6,$3
lpb $6
add $5,$4
sub $6,1
lpe
mov $2,1
mov $4,$5
lpb $2
add $1,$4
sub $2,1
lpe
mov $5,0
mov $6,$3
lpb $6
add $5,$4
sub $6,1
lpe
mov $2,16
mov $4,$5
lpb $2
add $1,$4
sub $2,1
lpe
mov $5,0
mov $6,$3
lpb $6
add $5,$4
sub $6,1
lpe
mov $2,17
mov $4,$5
lpb $2
add $1,$4
sub $2,1
lpe
mov $5,0
mov $6,$3
lpb $6
add $5,$4
sub $6,1
lpe
mov $2,7
mov $4,$5
lpb $2
add $1,$4
sub $2,1
lpe
mov $5,0
mov $6,$3
lpb $6
add $5,$4
sub $6,1
lpe
mov $2,1
mov $4,$5
lpb $2
add $1,$4
sub $2,1
lpe
|
; A143838: Ulam's spiral (SSW spoke).
; 1,22,75,160,277,426,607,820,1065,1342,1651,1992,2365,2770,3207,3676,4177,4710,5275,5872,6501,7162,7855,8580,9337,10126,10947,11800,12685,13602,14551,15532,16545,17590,18667,19776,20917,22090,23295,24532
mov $1,16
mul $1,$0
add $1,5
mul $1,$0
add $1,1
|
db "STARLING@" ; species name
db "They flock around"
next "in mountains and"
next "fields, chasing"
page "after BUG #MON."
next "Its singing is"
next "noisy and annoying.@"
|
// Copyright 2016 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/media/webrtc/desktop_media_list_base.h"
#include <set>
#include "chrome/browser/media/webrtc/desktop_media_list_observer.h"
#include "content/public/browser/browser_thread.h"
#include "ui/gfx/image/image.h"
using content::BrowserThread;
using content::DesktopMediaID;
DesktopMediaListBase::DesktopMediaListBase(base::TimeDelta update_period)
: update_period_(update_period), weak_factory_(this) {}
DesktopMediaListBase::~DesktopMediaListBase() {}
void DesktopMediaListBase::SetUpdatePeriod(base::TimeDelta period) {
DCHECK(!observer_);
update_period_ = period;
}
void DesktopMediaListBase::SetThumbnailSize(const gfx::Size& thumbnail_size) {
thumbnail_size_ = thumbnail_size;
}
void DesktopMediaListBase::SetViewDialogWindowId(DesktopMediaID dialog_id) {
view_dialog_id_ = dialog_id;
}
void DesktopMediaListBase::StartUpdating(DesktopMediaListObserver* observer) {
DCHECK(!observer_);
observer_ = observer;
Refresh();
}
int DesktopMediaListBase::GetSourceCount() const {
return sources_.size();
}
const DesktopMediaList::Source& DesktopMediaListBase::GetSource(
int index) const {
DCHECK_GE(index, 0);
DCHECK_LT(index, static_cast<int>(sources_.size()));
return sources_[index];
}
DesktopMediaID::Type DesktopMediaListBase::GetMediaListType() const {
return type_;
}
DesktopMediaListBase::SourceDescription::SourceDescription(
DesktopMediaID id,
const base::string16& name)
: id(id), name(name) {}
void DesktopMediaListBase::UpdateSourcesList(
const std::vector<SourceDescription>& new_sources) {
typedef std::set<DesktopMediaID> SourceSet;
SourceSet new_source_set;
for (size_t i = 0; i < new_sources.size(); ++i) {
new_source_set.insert(new_sources[i].id);
}
// Iterate through the old sources to find the removed sources.
for (size_t i = 0; i < sources_.size(); ++i) {
if (new_source_set.find(sources_[i].id) == new_source_set.end()) {
sources_.erase(sources_.begin() + i);
observer_->OnSourceRemoved(this, i);
--i;
}
}
// Iterate through the new sources to find the added sources.
if (new_sources.size() > sources_.size()) {
SourceSet old_source_set;
for (size_t i = 0; i < sources_.size(); ++i) {
old_source_set.insert(sources_[i].id);
}
for (size_t i = 0; i < new_sources.size(); ++i) {
if (old_source_set.find(new_sources[i].id) == old_source_set.end()) {
sources_.insert(sources_.begin() + i, Source());
sources_[i].id = new_sources[i].id;
sources_[i].name = new_sources[i].name;
observer_->OnSourceAdded(this, i);
}
}
}
DCHECK_EQ(new_sources.size(), sources_.size());
// Find the moved/changed sources.
size_t pos = 0;
while (pos < sources_.size()) {
if (!(sources_[pos].id == new_sources[pos].id)) {
// Find the source that should be moved to |pos|, starting from |pos + 1|
// of |sources_|, because entries before |pos| should have been sorted.
size_t old_pos = pos + 1;
for (; old_pos < sources_.size(); ++old_pos) {
if (sources_[old_pos].id == new_sources[pos].id)
break;
}
DCHECK(sources_[old_pos].id == new_sources[pos].id);
// Move the source from |old_pos| to |pos|.
Source temp = sources_[old_pos];
sources_.erase(sources_.begin() + old_pos);
sources_.insert(sources_.begin() + pos, temp);
observer_->OnSourceMoved(this, old_pos, pos);
}
if (sources_[pos].name != new_sources[pos].name) {
sources_[pos].name = new_sources[pos].name;
observer_->OnSourceNameChanged(this, pos);
}
++pos;
}
}
void DesktopMediaListBase::UpdateSourceThumbnail(DesktopMediaID id,
const gfx::ImageSkia& image) {
for (size_t i = 0; i < sources_.size(); ++i) {
if (sources_[i].id == id) {
sources_[i].thumbnail = image;
observer_->OnSourceThumbnailChanged(this, i);
break;
}
}
}
void DesktopMediaListBase::ScheduleNextRefresh() {
BrowserThread::PostDelayedTask(BrowserThread::UI, FROM_HERE,
base::BindOnce(&DesktopMediaListBase::Refresh,
weak_factory_.GetWeakPtr()),
update_period_);
}
// static
uint32_t DesktopMediaListBase::GetImageHash(const gfx::Image& image) {
SkBitmap bitmap = image.AsBitmap();
uint32_t value =
base::Hash(reinterpret_cast<char*>(bitmap.getPixels()), bitmap.getSize());
return value;
}
|
.text
main:
li $v0, 10
syscall |
;
;
; Z88 Maths Routines
;
; C Interface for Small C+ Compiler
;
; 7/12/98 djm
;double asin(double)
;Number in FA..
INCLUDE "#fpp.def"
XLIB atan
LIB fsetup
LIB stkequ2
.atan
call fsetup
fpp(FP_ATN)
jp stkequ2
|
; A298788: Coordination sequence for bey tiling (or net) with respect to a trivalent node.
; 1,3,7,12,13,17,24,23,27,36,33,37,48,43,47,60,53,57,72,63,67,84,73,77,96,83,87,108,93,97,120,103,107,132,113,117,144,123,127,156,133,137,168,143,147,180,153,157,192,163,167,204,173,177,216,183,187,228,193,197,240,203,207,252,213,217,264,223,227,276,233,237,288,243,247,300,253,257,312,263,267,324,273,277,336,283,287,348,293,297,360,303,307,372,313,317,384,323,327,396
pow $1,$0
add $1,$0
mov $2,3
mov $3,$0
gcd $0,3
lpb $0
mul $1,$0
div $0,6
add $1,1
add $1,$2
div $1,$2
lpe
sub $1,1
mov $4,$3
mul $4,3
add $1,$4
mov $0,$1
|
$NOMOD51
#include "boot.h"
#define BUF_LOC 0x08
NAME BOOT_STARTUP
PUBLIC boot_otp
; Declare and locate all memory segments used by the bootloader
?BL_START SEGMENT CODE AT BL_START_ADDRESS
?BL_RSVD SEGMENT CODE AT BL_LOCK_ADDRESS-2
?BL_STACK SEGMENT IDATA
?BUFFER SEGMENT DATA AT BUF_LOC
; Create idata segment for stack
RSEG ?BL_STACK
DS 32
; Create data segment for buffer
RSEG ?BUFFER
DS PKT_MAXLEN+1
; Bootloader entry point (boot_vector)
RSEG ?BL_START
?C_STARTUP:
USING 0
; Port 0 setup
MOV P0, #0F0H
MOV P0MDOUT,#050H
; Port 1 setup
MOV P1, #0
; CRC0 setup
ORL CRC0CN0, #04H ; set ones
MOV A,RSTSRC
CJNE A,#010H,pin_test ; if not software reset, check pin
MOV A,R0
XRL A,#BL_SIGNATURE
JZ boot_start ; if R0 == signature, start bootloader
app_start:
; check app CRC
ORL CRC0CN0, #09H ; init, set pointer to MSB
MOV DPTR, #0 ; Start address = 0x0000
CLR A
MOVC A,@A+DPTR
CPL A
JZ boot_start
; 0x0000 is not 0xFF, continue with CRC check
CRC_LOOP:
CLR A
MOVC A,@A+DPTR
MOV CRC0IN, A
INC DPTR
MOV A, #01BH ; CRC16 address high byte = 0x1B
CJNE A, DPH, CRC_LOOP
MOV A, #0FEH ; CRC16 address low byte = 0xFE
CJNE A, DPL, CRC_LOOP
; CRC done
MOV R0, #2 ; 2 CRC bytes
CRC_LOOP2:
CLR A
MOVC A,@A+DPTR
CJNE A, CRC0DAT, boot_start
INC DPTR
DJNZ R0, CRC_LOOP2
LJMP 00H ; code OK, start app
; beginning of UART RX routine moved here due to jump length restrictions (saves one ACALL)
UART_RX_STORE:
MOV @R0, A ; put into buffer
INC R0
AJMP MAINLOOP
UART_RX:
JNB SCON0_RB8, RX_INIT_WAIT ; framing error
MOV A, SBUF0
JZ RX_ZERO
; Non-zero byte received
; check if there is room in buffer
CJNE R0, #?BUFFER+PKT_MAXLEN+1, UART_RX_STORE
AJMP MAINLOOP ; buffer full
SOFTRESET:
MOV R0, #0
MOV RSTSRC, #012h ; software reset
pin_test:
ANL A,#03H ; A = RSTSRC
JZ app_start ; POR or PINR only
MOV R0,#255 ; total 583 us
pin_test_loop: ; deglitch loop
JB BL_START_PIN,app_start ; +3
DJNZ R0,pin_test_loop ; +4 = 7 cycles per loop
boot_start:
; Disable watchdog
MOV WDTCN,#0DEh
MOV WDTCN,#0ADh
MOV SP, #?BL_STACK-1 ; Stack setup
; MCU is clocked from HFOSC/8 by default
ORL LFO0CN, #082H ; Start LF oscillator
; Crossbar setup
MOV XBR0,#01H
MOV XBR2,#040H
; Timer0/1 setup
MOV TMOD,#021H
MOV CKCON0,#01H
MOV TH1, #060H ; 2392 baud
MOV TL1, #060H ; 2392 baud
SETB TCON_TR1
; Clear sequence counter (R4), key registers (R6-R7)
CLR A
MOV R4, A
MOV R6, A
MOV R7, A
; Set address
MOV DPTR, #CAL_START_ADDRESS ; address at first byte of cal page
MOVC A, @A+DPTR
MOV R2, A
CPL A
JNZ RX_INIT_WAIT
MOV R2, A ; set to 0 (invalid)
RX_INIT_WAIT:
ACALL RX_WAITIDLE
RX_INIT:
SETB SCON0_REN ; Enable UART
SETB P0_B6 ; LED on
RX_RESET:
CLR SCON0_RI ; clear UART IRQ
MOV R0,#?BUFFER ; load buffer pointer
MAINLOOP:
; timeout init and reset
; ~86 msec at HFOSC/8 (SCA /4)
CLR TCON_TR0
CLR A
MOV TL0, A
MOV TH0, A
CLR TCON_TF0
SETB TCON_TR0 ; Start timeout counter
MAINLOOP_0:
; Check if soft reset is pending
JBC PSW_F1, SOFTRESET
MAINLOOP_1:
JBC SCON0_RI, UART_RX ; check if data is available in UART
JNB TCON_TF0, MAINLOOP_1 ; check if timeout elapsed
; Timeout, enter low power mode
CLR SCON0_REN ; Disable UART
CLR P0_B6 ; LED off
MOV CLKSEL, #02H ; switch to LFOSC
JB P0_B5, $ ; wait for P0.5 to go low (UART RX)
MOV CLKSEL,#030H ; Clock config (HFOSC, div by 8)
JNB P0_B5, $ ; wait for P0.5 to go high (UART RX)
AJMP RX_INIT
RX_ZERO:
MOV A, #256-(PKT_MINLEN+1)-BUF_LOC
ADD A, R0
JNC RX_RESET
RX_PKT:
; complete packet received
; calculate and store packet length
ADD A, #PKT_MINLEN
CJNE A, ?BUFFER+PKT_INDEX_LEN, RX_RESET ; check if packet length field matches actual received bytes count
MOV R3, A ; save received packet length for later use
; yes, proceed
; init CRC
ORL CRC0CN0, #09H ; init, set pointer to MSB
MOV A, R0
DEC A
MOV R6, A ; store last byte pointer
MOV R0, #?BUFFER ; load buffer pointer
MOV R1, #?BUFFER ; load COBS pointer
RX_PKT_1:
MOV A, R1
CJNE A, AR0, RX_PKT_2
; COBS pointer
; store new offset
ADD A, @R0
JC RX_RESET ; COBS pointer value too high
MOV R1, A ; store new pointer
MOV A, R6
INC A
SUBB A, R1
JC RX_RESET ; COBS pointer value too high
MOV @R0, #0 ; replace with zero in buffer
RX_PKT_2:
CJNE R0, #?BUFFER, RX_PKT_CRC ; check if this is the first byte in the packet
; yes, this is the first byte
RX_PKT_CONT:
INC R0
AJMP RX_PKT_1 ; continue decoding
RX_PKT_CRC:
MOV A, R6 ; load last byte pointer
SUBB A, R0 ; last byte ptr - current ptr
SUBB A, #2
JNC RX_PKT_NOT_CRC
; current ptr >= (last byte ptr - 1), check CRC
MOV A, CRC0DAT ; load CRC result from module
XRL A, @R0 ; Compare CRC
JNZ RX_RESET ; CRC mismatch, restart RX
AJMP RX_PKT_CHKPTR
RX_PKT_NOT_CRC:
MOV CRC0IN, @R0 ; not first byte, not CRC byte, feed CRC
RX_PKT_CHKPTR:
MOV A, R6
XRL A, R0
JNZ RX_PKT_CONT ; jump if not all bytes are decoded
RX_PKT_OK:
; Check address
MOV A, ?BUFFER+PKT_INDEX_DST
JNZ RX_PKT_OK_1 ; 0 is the failsafe mode address
JNB BL_START_PIN, RX_PKT_OK_2 ; check if BL_START_PIN is low (jumper present)
AJMP RX_RESET
RX_PKT_OK_1:
CJNE A, AR2, RX_RESET ; check address
RX_PKT_OK_2:
; check if this is a bootloader cmd
MOV R1, #?BUFFER+PKT_INDEX_CMD
MOV A, @R1
ANL A, #0C3H ; keep uppermost 2 bits (CMD MSb) and lowermost 2 bits (flags)
CJNE A, #0C0H, RX_RESET ; invalid CMD if not 0x30-0x3F
; Set reply flag
INC @R1 ; cmd (0x00) -> reply DUP (0x01)
; Load PKT_INDEX_LEN to R0 for indirect use (will save some bytes of code space)
MOV R0, #?BUFFER+PKT_INDEX_LEN
; Set default pkt len
MOV @R0, #PKT_MINLEN
; Check for duplicate packet
MOV A, ?BUFFER+PKT_INDEX_SEQ
XRL A, R4
JZ SEND_REPLY
; not duplicate packet
MOV R4, ?BUFFER+PKT_INDEX_SEQ
INC @R1 ; reply DUP (0x01) -> reply ERR (0x02)
; Process command
; reply ERR flag (0x02) will be set in @R1
CJNE @R1, #((BL_CMD_IDENT<<2)|2), CHECK_BL_CMD_RESET
; identify
INC @R0
MOV ?BUFFER+PKT_INDEX_DATA, #BL_REVISION
AJMP SEND_REPLY_OK
CHECK_BL_CMD_RESET:
CJNE @R1, #((BL_CMD_RESET<<2)|2), CHECK_BL_CMD_ERASE
; Soft reset
SETB PSW_F1 ; Reset pending flag = 1
AJMP SEND_REPLY_OK
CHECK_BL_CMD_ERASE:
CJNE @R1, #((BL_CMD_ERASE<<2)|2), CHECK_BL_CMD_READ
; BL_CMD_ERASE
CJNE R3, #(PKT_MINLEN+3), SEND_REPLY ; check that we have a large enough packet
INC @R0 ; leave flash address in reply
ACALL RW_INIT ; load keys and address
JC SEND_REPLY ; init failed if carry == 1
ACALL FLASH_ERASEBYTE ; Erase page
AJMP SEND_REPLY_OK
CHECK_BL_CMD_READ:
CJNE @R1, #((BL_CMD_READ<<2)|2), CHECK_BL_CMD_WRITE
ACALL RW_INIT_NOKEYS
JC SEND_REPLY ; init failed if carry == 1
MOV @R0, #(PKT_MINLEN+65) ; 64 bytes + flash address
MOV R0, #?BUFFER+PKT_INDEX_DATA+1 ; load data start address to R0
READ_LOOP:
CLR A
MOVC A,@A+DPTR
MOV @R0, A ; put into buffer
INC DPTR ; increase flash ptr
INC R0 ; increase buffer ptr
DJNZ R3, READ_LOOP ; decrease loop counter, check if zero
SEND_REPLY_OK:
INC @R1 ; reply ERR (0x02) -> reply OK (0x03)
SEND_REPLY:
; encode and send reply
MOV R7, ?BUFFER+PKT_INDEX_LEN ; load pkt len to R7
MOV R0, #?BUFFER+1 ; init read ptr
MOV R1, #?BUFFER ; init cobs ptr
; CRC init
ORL CRC0CN0, #09H ; init, set pointer to MSB
; run COBS encoder
MOV R6, #1 ; reset COBS counter
COBS_ENC_LOOP:
; check if data or CRC byte
MOV A, R7
ADD A, #(255-2)
JC COBS_ENC_CRC
; this is a CRC byte
MOV @R0, CRC0DAT ; update CRC in buffer before encoding
AJMP COBS_ENC_NOCRC
COBS_ENC_CRC:
; not a CRC byte
MOV CRC0IN, @R0 ; update CRC
COBS_ENC_NOCRC:
MOV A, @R0 ; load byte from buffer
JNZ COBS_ENC_NZ
; byte is zero, update COBS index
MOV @R1, AR6
MOV R6, #1 ; reset COBS counter
MOV R1, AR0 ; update COBS pointer
AJMP COBS_ENC_NEXT
COBS_ENC_NZ:
INC R6 ; increase COBS counter
COBS_ENC_NEXT:
INC R0 ; increase read ptr
DJNZ R7, COBS_ENC_LOOP
; final COBS header
MOV @R1, AR6
; COBS encoding done
ACALL RX_WAITIDLE ; add delay before TX
MOV R7, ?BUFFER+PKT_INDEX_LEN ; load pkt len to R7
INC R7 ; extra byte for COBS header
MOV R0, #?BUFFER ; init buffer ptr
ACALL TX_ZEROBYTE ; frame start
TX_LOOP:
MOV SBUF0, @R0 ; data tx
ACALL TX_WAIT ; wait for TX
INC R0
DJNZ R7, TX_LOOP
ACALL TX_ZEROBYTE ; frame end
AJMP RX_RESET ; restart RX
TX_ZEROBYTE:
MOV SBUF0, #0 ; frame end
TX_WAIT:
CLR SCON0_TI
JNB SCON0_TI, $ ; wait for TX
RET
CHECK_BL_CMD_WRITE:
CJNE @R1, #((BL_CMD_WRITE<<2)|2), SEND_REPLY
CJNE R3, #(PKT_MINLEN+64+3), SEND_REPLY ; check that we have a large enough packet
ACALL RW_INIT
JC SEND_REPLY
INC @R0 ; leave flash address in reply
MOV R0, #?BUFFER+PKT_INDEX_DATA+3 ; load data start address to R0
WRITE_LOOP:
CLR A
MOVC A,@A+DPTR ; read byte from flash
CPL A
JNZ SEND_REPLY ; fail if not erased (0xFF)
ACALL FLASH_WRITEBYTE ; write flash byte (byte to be written in @R0)
INC DPTR ; increase flash ptr
INC R0 ; increase buffer ptr
DJNZ R3, WRITE_LOOP ; decrease loop counter, check if zero
AJMP SEND_REPLY_OK
RW_INIT_FAIL:
SETB C ; key error or out of range, carry == 1
RET
RW_INIT:
; check keys
CLR A
MOV R7, ?BUFFER+PKT_INDEX_DATA+1 ; key 1 (inverted)
MOV ?BUFFER+PKT_INDEX_DATA+1, A ; delete key from buffer
CJNE R7, #05AH, RW_INIT_FAIL
MOV R6, ?BUFFER+PKT_INDEX_DATA+2 ; key 2 (inverted)
MOV ?BUFFER+PKT_INDEX_DATA+2, A ; delete key from buffer
CJNE R6, #00EH, RW_INIT_FAIL
RW_INIT_NOKEYS:
MOV A, ?BUFFER+PKT_INDEX_DATA
; Check for out-of-range address
ADD A, #(0xFF - (CAL_START_ADDRESS / 64) + 1)
JC RW_INIT_FAIL ; jump if out of range (carry bit set)
MOV A, ?BUFFER+PKT_INDEX_DATA
MOV R3, #64 ; init loop counter = 64 bytes
MOV B, R3 ;
MUL AB ; multiply by 64
MOV DPL, A ; set DPL to LSB
MOV DPH, B ; set DPH to MSB
; ok, carry == 0 (already cleared by MUL instruction)
RET
; need total of 15312 cycles for 5 ms
; loop count 2552 at 6 cycles per loop
RX_WAITIDLE:
JNB P0_B5, $ ; wait for P0.5 to go high (UART RX)
MOV R7, #10 ; 10 * 1534 + 1 = 15341 cycles = 5.0093 ms (~12 bits at 2400 baud)
RX_WAITIDLE1:
MOV R6, #255 ; 255 * 6 + 4 = 1534 cycles
RX_WAITIDLE2:
; reset counter if UART RX goes low again
JNB P0_B5, RX_WAITIDLE
DJNZ R6, RX_WAITIDLE2
DJNZ R7, RX_WAITIDLE1
RET
; Erase flash page
; Setup DPTR before calling
FLASH_ERASEBYTE:
ORL PSCTL,#02H ; Set PSEE
; Write byte to flash
; Setup DPTR before calling
; byte to be written in A
FLASH_WRITEBYTE:
MOV A, R7 ; load key 1
CPL A
MOV FLKEY, A
MOV A, R6 ; load key 2
CPL A
MOV FLKEY, A
MOV A, @R0 ; load byte to be written
ORL PSCTL,#01H ; Set PSWE
MOV VDM0CN,#080H ; Make sure voltage monitor is enabled
MOV RSTSRC,#02H ; ... and selected as a reset source
MOVX @DPTR,A
ANL PSCTL,#0FCH
RET
; Reserved Bytes (bl_revision, bl_signature, lock_byte)
RSEG ?BL_RSVD
boot_rev:
DB BL_REVISION
boot_otp:
DB BL_SIGNATURE
lock_byte:
DB 0xFF
END
|
###############################################################################
# Copyright 2018 Intel Corporation
# All Rights Reserved.
#
# If this software was obtained under the Intel Simplified Software License,
# the following terms apply:
#
# The source code, information and material ("Material") contained herein is
# owned by Intel Corporation or its suppliers or licensors, and title to such
# Material remains with Intel Corporation or its suppliers or licensors. The
# Material contains proprietary information of Intel or its suppliers and
# licensors. The Material is protected by worldwide copyright laws and treaty
# provisions. No part of the Material may be used, copied, reproduced,
# modified, published, uploaded, posted, transmitted, distributed or disclosed
# in any way without Intel's prior express written permission. No license under
# any patent, copyright or other intellectual property rights in the Material
# is granted to or conferred upon you, either expressly, by implication,
# inducement, estoppel or otherwise. Any license under such intellectual
# property rights must be express and approved by Intel in writing.
#
# Unless otherwise agreed by Intel in writing, you may not remove or alter this
# notice or any other notice embedded in Materials by Intel or Intel's
# suppliers or licensors in any way.
#
#
# If this software was obtained under the Apache License, Version 2.0 (the
# "License"), the following terms apply:
#
# You may not use this file except in compliance with the License. You may
# obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
#
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
#
# See the License for the specific language governing permissions and
# limitations under the License.
###############################################################################
.text
.p2align 5, 0x90
.globl _g9_DecryptCFB_RIJ128pipe_AES_NI
_g9_DecryptCFB_RIJ128pipe_AES_NI:
push %ebp
mov %esp, %ebp
push %ebx
push %esi
push %edi
sub $(144), %esp
movl (32)(%ebp), %eax
movdqu (%eax), %xmm4
movdqu %xmm4, (%esp)
movl (8)(%ebp), %esi
movl (12)(%ebp), %edi
movl (28)(%ebp), %edx
subl $(4), (24)(%ebp)
jl .Lshort_inputgas_1
.Lblks_loopgas_1:
lea (,%edx,4), %eax
xor %ecx, %ecx
.L__0000gas_1:
movl (%esi,%ecx), %ebx
movl %ebx, (16)(%esp,%ecx)
add $(4), %ecx
cmp %eax, %ecx
jl .L__0000gas_1
movl (20)(%ebp), %ecx
movdqa (%ecx), %xmm4
lea (%edx,%edx,2), %ebx
movdqu (%esp), %xmm0
movdqu (%esp,%edx), %xmm1
movdqu (%esp,%edx,2), %xmm2
movdqu (%esp,%ebx), %xmm3
lea (16)(%ecx), %ebx
pxor %xmm4, %xmm0
pxor %xmm4, %xmm1
pxor %xmm4, %xmm2
pxor %xmm4, %xmm3
movdqa (%ebx), %xmm4
add $(16), %ebx
movl (16)(%ebp), %eax
sub $(1), %eax
.Lcipher_loopgas_1:
aesenc %xmm4, %xmm0
aesenc %xmm4, %xmm1
aesenc %xmm4, %xmm2
aesenc %xmm4, %xmm3
movdqa (%ebx), %xmm4
add $(16), %ebx
dec %eax
jnz .Lcipher_loopgas_1
aesenclast %xmm4, %xmm0
aesenclast %xmm4, %xmm1
aesenclast %xmm4, %xmm2
aesenclast %xmm4, %xmm3
lea (%edx,%edx,2), %ebx
movdqu (16)(%esp), %xmm4
movdqu (16)(%esp,%edx), %xmm5
movdqu (16)(%esp,%edx,2), %xmm6
movdqu (16)(%esp,%ebx), %xmm7
pxor %xmm4, %xmm0
movdqu %xmm0, (80)(%esp)
pxor %xmm5, %xmm1
movdqu %xmm1, (80)(%esp,%edx)
pxor %xmm6, %xmm2
movdqu %xmm2, (80)(%esp,%edx,2)
pxor %xmm7, %xmm3
movdqu %xmm3, (80)(%esp,%ebx)
lea (,%edx,4), %eax
xor %ecx, %ecx
.L__0001gas_1:
movl (80)(%esp,%ecx), %ebx
movl %ebx, (%edi,%ecx)
add $(4), %ecx
cmp %eax, %ecx
jl .L__0001gas_1
movdqu (%esp,%eax), %xmm0
movdqu %xmm0, (%esp)
add %eax, %esi
add %eax, %edi
subl $(4), (24)(%ebp)
jge .Lblks_loopgas_1
.Lshort_inputgas_1:
addl $(4), (24)(%ebp)
jz .Lquitgas_1
lea (,%edx,2), %ebx
lea (%edx,%edx,2), %ecx
cmpl $(2), (24)(%ebp)
cmovl %edx, %ebx
cmovg %ecx, %ebx
xor %ecx, %ecx
.L__0002gas_1:
movb (%esi,%ecx), %al
movb %al, (16)(%esp,%ecx)
add $(1), %ecx
cmp %ebx, %ecx
jl .L__0002gas_1
movl (20)(%ebp), %ecx
movl (16)(%ebp), %eax
lea (,%eax,4), %esi
lea (-144)(%ecx,%esi,4), %esi
xor %eax, %eax
.Lsingle_blk_loopgas_1:
movdqu (%esp,%eax), %xmm0
pxor (%ecx), %xmm0
cmpl $(12), (16)(%ebp)
jl .Lkey_128_sgas_1
jz .Lkey_192_sgas_1
.Lkey_256_sgas_1:
aesenc (-64)(%esi), %xmm0
aesenc (-48)(%esi), %xmm0
.Lkey_192_sgas_1:
aesenc (-32)(%esi), %xmm0
aesenc (-16)(%esi), %xmm0
.Lkey_128_sgas_1:
aesenc (%esi), %xmm0
aesenc (16)(%esi), %xmm0
aesenc (32)(%esi), %xmm0
aesenc (48)(%esi), %xmm0
aesenc (64)(%esi), %xmm0
aesenc (80)(%esi), %xmm0
aesenc (96)(%esi), %xmm0
aesenc (112)(%esi), %xmm0
aesenc (128)(%esi), %xmm0
aesenclast (144)(%esi), %xmm0
movdqu (16)(%esp,%eax), %xmm1
pxor %xmm1, %xmm0
movdqu %xmm0, (80)(%esp,%eax)
add %edx, %eax
decl (24)(%ebp)
jnz .Lsingle_blk_loopgas_1
xor %ecx, %ecx
.L__0003gas_1:
movb (80)(%esp,%ecx), %al
movb %al, (%edi,%ecx)
add $(1), %ecx
cmp %ebx, %ecx
jl .L__0003gas_1
.Lquitgas_1:
add $(144), %esp
pop %edi
pop %esi
pop %ebx
pop %ebp
ret
.p2align 5, 0x90
.globl _g9_DecryptCFB32_RIJ128pipe_AES_NI
_g9_DecryptCFB32_RIJ128pipe_AES_NI:
push %ebp
mov %esp, %ebp
push %ebx
push %esi
push %edi
sub $(144), %esp
movl (32)(%ebp), %eax
movdqu (%eax), %xmm4
movdqu %xmm4, (%esp)
movl (8)(%ebp), %esi
movl (12)(%ebp), %edi
movl (28)(%ebp), %edx
subl $(4), (24)(%ebp)
jl .Lshort_inputgas_2
.Lblks_loopgas_2:
lea (,%edx,4), %eax
xor %ecx, %ecx
.L__0004gas_2:
movdqu (%esi,%ecx), %xmm0
movdqu %xmm0, (16)(%esp,%ecx)
add $(16), %ecx
cmp %eax, %ecx
jl .L__0004gas_2
movl (20)(%ebp), %ecx
movdqa (%ecx), %xmm4
lea (%edx,%edx,2), %ebx
movdqu (%esp), %xmm0
movdqu (%esp,%edx), %xmm1
movdqu (%esp,%edx,2), %xmm2
movdqu (%esp,%ebx), %xmm3
lea (16)(%ecx), %ebx
pxor %xmm4, %xmm0
pxor %xmm4, %xmm1
pxor %xmm4, %xmm2
pxor %xmm4, %xmm3
movdqa (%ebx), %xmm4
add $(16), %ebx
movl (16)(%ebp), %eax
sub $(1), %eax
.Lcipher_loopgas_2:
aesenc %xmm4, %xmm0
aesenc %xmm4, %xmm1
aesenc %xmm4, %xmm2
aesenc %xmm4, %xmm3
movdqa (%ebx), %xmm4
add $(16), %ebx
dec %eax
jnz .Lcipher_loopgas_2
aesenclast %xmm4, %xmm0
aesenclast %xmm4, %xmm1
aesenclast %xmm4, %xmm2
aesenclast %xmm4, %xmm3
lea (%edx,%edx,2), %ebx
movdqu (16)(%esp), %xmm4
movdqu (16)(%esp,%edx), %xmm5
movdqu (16)(%esp,%edx,2), %xmm6
movdqu (16)(%esp,%ebx), %xmm7
pxor %xmm4, %xmm0
movdqu %xmm0, (80)(%esp)
pxor %xmm5, %xmm1
movdqu %xmm1, (80)(%esp,%edx)
pxor %xmm6, %xmm2
movdqu %xmm2, (80)(%esp,%edx,2)
pxor %xmm7, %xmm3
movdqu %xmm3, (80)(%esp,%ebx)
lea (,%edx,4), %eax
xor %ecx, %ecx
.L__0005gas_2:
movdqu (80)(%esp,%ecx), %xmm0
movdqu %xmm0, (%edi,%ecx)
add $(16), %ecx
cmp %eax, %ecx
jl .L__0005gas_2
movdqu (%esp,%eax), %xmm0
movdqu %xmm0, (%esp)
add %eax, %esi
add %eax, %edi
subl $(4), (24)(%ebp)
jge .Lblks_loopgas_2
.Lshort_inputgas_2:
addl $(4), (24)(%ebp)
jz .Lquitgas_2
lea (,%edx,2), %ebx
lea (%edx,%edx,2), %ecx
cmpl $(2), (24)(%ebp)
cmovl %edx, %ebx
cmovg %ecx, %ebx
xor %ecx, %ecx
.L__0006gas_2:
movl (%esi,%ecx), %eax
movl %eax, (16)(%esp,%ecx)
add $(4), %ecx
cmp %ebx, %ecx
jl .L__0006gas_2
movl (20)(%ebp), %ecx
movl (16)(%ebp), %eax
lea (,%eax,4), %esi
lea (-144)(%ecx,%esi,4), %esi
xor %eax, %eax
.Lsingle_blk_loopgas_2:
movdqu (%esp,%eax), %xmm0
pxor (%ecx), %xmm0
cmpl $(12), (16)(%ebp)
jl .Lkey_128_sgas_2
jz .Lkey_192_sgas_2
.Lkey_256_sgas_2:
aesenc (-64)(%esi), %xmm0
aesenc (-48)(%esi), %xmm0
.Lkey_192_sgas_2:
aesenc (-32)(%esi), %xmm0
aesenc (-16)(%esi), %xmm0
.Lkey_128_sgas_2:
aesenc (%esi), %xmm0
aesenc (16)(%esi), %xmm0
aesenc (32)(%esi), %xmm0
aesenc (48)(%esi), %xmm0
aesenc (64)(%esi), %xmm0
aesenc (80)(%esi), %xmm0
aesenc (96)(%esi), %xmm0
aesenc (112)(%esi), %xmm0
aesenc (128)(%esi), %xmm0
aesenclast (144)(%esi), %xmm0
movdqu (16)(%esp,%eax), %xmm1
pxor %xmm1, %xmm0
movdqu %xmm0, (80)(%esp,%eax)
add %edx, %eax
decl (24)(%ebp)
jnz .Lsingle_blk_loopgas_2
xor %ecx, %ecx
.L__0007gas_2:
movl (80)(%esp,%ecx), %eax
movl %eax, (%edi,%ecx)
add $(4), %ecx
cmp %ebx, %ecx
jl .L__0007gas_2
.Lquitgas_2:
add $(144), %esp
pop %edi
pop %esi
pop %ebx
pop %ebp
ret
.p2align 5, 0x90
.globl _g9_DecryptCFB128_RIJ128pipe_AES_NI
_g9_DecryptCFB128_RIJ128pipe_AES_NI:
push %ebp
mov %esp, %ebp
push %ebx
push %esi
push %edi
movl (8)(%ebp), %esi
movl (12)(%ebp), %edi
movl (20)(%ebp), %ecx
movl (24)(%ebp), %edx
movl (28)(%ebp), %eax
movdqu (%eax), %xmm0
sub $(64), %edx
jl .Lshort_inputgas_3
.Lblks_loopgas_3:
movdqa (%ecx), %xmm7
lea (16)(%ecx), %ebx
movdqu (%esi), %xmm1
movdqu (16)(%esi), %xmm2
movdqu (32)(%esi), %xmm3
pxor %xmm7, %xmm0
pxor %xmm7, %xmm1
pxor %xmm7, %xmm2
pxor %xmm7, %xmm3
movdqa (%ebx), %xmm7
add $(16), %ebx
movl (16)(%ebp), %eax
sub $(1), %eax
.Lcipher_loopgas_3:
aesenc %xmm7, %xmm0
aesenc %xmm7, %xmm1
aesenc %xmm7, %xmm2
aesenc %xmm7, %xmm3
movdqa (%ebx), %xmm7
add $(16), %ebx
dec %eax
jnz .Lcipher_loopgas_3
aesenclast %xmm7, %xmm0
movdqu (%esi), %xmm4
aesenclast %xmm7, %xmm1
movdqu (16)(%esi), %xmm5
aesenclast %xmm7, %xmm2
movdqu (32)(%esi), %xmm6
aesenclast %xmm7, %xmm3
movdqu (48)(%esi), %xmm7
add $(64), %esi
pxor %xmm4, %xmm0
movdqu %xmm0, (%edi)
pxor %xmm5, %xmm1
movdqu %xmm1, (16)(%edi)
pxor %xmm6, %xmm2
movdqu %xmm2, (32)(%edi)
pxor %xmm7, %xmm3
movdqu %xmm3, (48)(%edi)
add $(64), %edi
movdqa %xmm7, %xmm0
sub $(64), %edx
jge .Lblks_loopgas_3
.Lshort_inputgas_3:
add $(64), %edx
jz .Lquitgas_3
movl (16)(%ebp), %eax
lea (,%eax,4), %ebx
lea (-144)(%ecx,%ebx,4), %ebx
.Lsingle_blk_loopgas_3:
pxor (%ecx), %xmm0
cmp $(12), %eax
jl .Lkey_128_sgas_3
jz .Lkey_192_sgas_3
.Lkey_256_sgas_3:
aesenc (-64)(%ebx), %xmm0
aesenc (-48)(%ebx), %xmm0
.Lkey_192_sgas_3:
aesenc (-32)(%ebx), %xmm0
aesenc (-16)(%ebx), %xmm0
.Lkey_128_sgas_3:
aesenc (%ebx), %xmm0
aesenc (16)(%ebx), %xmm0
aesenc (32)(%ebx), %xmm0
aesenc (48)(%ebx), %xmm0
aesenc (64)(%ebx), %xmm0
aesenc (80)(%ebx), %xmm0
aesenc (96)(%ebx), %xmm0
aesenc (112)(%ebx), %xmm0
aesenc (128)(%ebx), %xmm0
aesenclast (144)(%ebx), %xmm0
movdqu (%esi), %xmm1
add $(16), %esi
pxor %xmm1, %xmm0
movdqu %xmm0, (%edi)
add $(16), %edi
movdqa %xmm1, %xmm0
sub $(16), %edx
jnz .Lsingle_blk_loopgas_3
.Lquitgas_3:
pop %edi
pop %esi
pop %ebx
pop %ebp
ret
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.