code
stringlengths 3
1.05M
| repo_name
stringlengths 4
116
| path
stringlengths 3
942
| language
stringclasses 30
values | license
stringclasses 15
values | size
int32 3
1.05M
|
---|---|---|---|---|---|
package com.xeiam.xchange.anx.v2.account.polling;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;
import org.junit.Assert;
import org.junit.Test;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.xeiam.xchange.anx.v2.dto.account.polling.ANXWalletHistoryWrapper;
//import static org.fest.assertions.api.Assertions.assertThat;
/**
* Test ANXWalletHistory JSON parsing
*/
public class WalletHistoryJSONTest {
@Test
public void testUnmarshal() throws IOException {
// Read in the JSON from the example resources
InputStream is = WalletHistoryJSONTest.class.getResourceAsStream("/v2/account/example-wallethistory-response.json");
// Use Jackson to parse it
ObjectMapper mapper = new ObjectMapper();
mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
ANXWalletHistoryWrapper anxWalletHistoryWrapper = mapper.readValue(is, ANXWalletHistoryWrapper.class);
Assert.assertTrue(anxWalletHistoryWrapper.getANXWalletHistory() != null);
Assert.assertTrue(anxWalletHistoryWrapper.getANXWalletHistory().getRecords() == 104);
Assert.assertTrue(anxWalletHistoryWrapper.getANXWalletHistory().getCurrentPage() == 1);
Assert.assertTrue(anxWalletHistoryWrapper.getANXWalletHistory().getMaxPage() == 3);
Assert.assertTrue(anxWalletHistoryWrapper.getANXWalletHistory().getMaxResults() == 50);
Assert.assertTrue(anxWalletHistoryWrapper.getANXWalletHistory().getANXWalletHistoryEntries().length == 50);
Assert.assertEquals("BTC bought: [tid:264f7b7f-f70c-4fc6-ba27-2bcf33b6cd51] 10.00000000 BTC at 280.65500 HKD", anxWalletHistoryWrapper.getANXWalletHistory().getANXWalletHistoryEntries()[0]
.getInfo());
Assert.assertEquals(104, anxWalletHistoryWrapper.getANXWalletHistory().getANXWalletHistoryEntries()[0].getIndex());
Assert.assertEquals("1394594770000", anxWalletHistoryWrapper.getANXWalletHistory().getANXWalletHistoryEntries()[0].getDate());
Assert.assertEquals("fee", anxWalletHistoryWrapper.getANXWalletHistory().getANXWalletHistoryEntries()[0].getType());
Assert.assertEquals("BTC", anxWalletHistoryWrapper.getANXWalletHistory().getANXWalletHistoryEntries()[0].getValue().getCurrency());
// Assert.assertEquals(new BigDecimal(0),
// anxWalletHistoryWrapper.getANXWalletHistory().getANXWalletHistoryEntries()[0].getValue().getValue());
Assert.assertEquals(new BigDecimal("103168.75400000"), anxWalletHistoryWrapper.getANXWalletHistory().getANXWalletHistoryEntries()[0].getBalance().getValue());
Assert.assertEquals("cc496636-4849-4acf-a390-e4091a5009c3", anxWalletHistoryWrapper.getANXWalletHistory().getANXWalletHistoryEntries()[0].getTrade().getOid());
Assert.assertEquals("264f7b7f-f70c-4fc6-ba27-2bcf33b6cd51", anxWalletHistoryWrapper.getANXWalletHistory().getANXWalletHistoryEntries()[0].getTrade().getTid());
Assert.assertEquals(new BigDecimal("10.00000000"), anxWalletHistoryWrapper.getANXWalletHistory().getANXWalletHistoryEntries()[0].getTrade().getAmount().getValue());
Assert.assertEquals("market", anxWalletHistoryWrapper.getANXWalletHistory().getANXWalletHistoryEntries()[0].getTrade().getProperties());
}
}
|
Achterhoeker/XChange
|
xchange-anx/src/test/java/com/xeiam/xchange/anx/v2/account/polling/WalletHistoryJSONTest.java
|
Java
|
mit
| 3,272 |
#ifdef HAVE_WINRT
#define ICustomStreamSink StreamSink
#ifndef __cplusplus_winrt
#define __is_winrt_array(type) (type == ABI::Windows::Foundation::PropertyType::PropertyType_UInt8Array || type == ABI::Windows::Foundation::PropertyType::PropertyType_Int16Array ||\
type == ABI::Windows::Foundation::PropertyType::PropertyType_UInt16Array || type == ABI::Windows::Foundation::PropertyType::PropertyType_Int32Array ||\
type == ABI::Windows::Foundation::PropertyType::PropertyType_UInt32Array || type == ABI::Windows::Foundation::PropertyType::PropertyType_Int64Array ||\
type == ABI::Windows::Foundation::PropertyType::PropertyType_UInt64Array || type == ABI::Windows::Foundation::PropertyType::PropertyType_SingleArray ||\
type == ABI::Windows::Foundation::PropertyType::PropertyType_DoubleArray || type == ABI::Windows::Foundation::PropertyType::PropertyType_Char16Array ||\
type == ABI::Windows::Foundation::PropertyType::PropertyType_BooleanArray || type == ABI::Windows::Foundation::PropertyType::PropertyType_StringArray ||\
type == ABI::Windows::Foundation::PropertyType::PropertyType_InspectableArray || type == ABI::Windows::Foundation::PropertyType::PropertyType_DateTimeArray ||\
type == ABI::Windows::Foundation::PropertyType::PropertyType_TimeSpanArray || type == ABI::Windows::Foundation::PropertyType::PropertyType_GuidArray ||\
type == ABI::Windows::Foundation::PropertyType::PropertyType_PointArray || type == ABI::Windows::Foundation::PropertyType::PropertyType_SizeArray ||\
type == ABI::Windows::Foundation::PropertyType::PropertyType_RectArray || type == ABI::Windows::Foundation::PropertyType::PropertyType_OtherTypeArray)
template<typename _Type, bool bUnknown = std::is_base_of<IUnknown, _Type>::value>
struct winrt_type
{
};
template<typename _Type>
struct winrt_type<_Type, true>
{
static IUnknown* create(_Type* _ObjInCtx) {
return reinterpret_cast<IUnknown*>(_ObjInCtx);
}
static IID getuuid() { return __uuidof(_Type); }
static const ABI::Windows::Foundation::PropertyType _PropType = ABI::Windows::Foundation::PropertyType::PropertyType_OtherType;
};
template <typename _Type>
struct winrt_type<_Type, false>
{
static IUnknown* create(_Type* _ObjInCtx) {
Microsoft::WRL::ComPtr<IInspectable> _PObj;
Microsoft::WRL::ComPtr<IActivationFactory> objFactory;
HRESULT hr = Windows::Foundation::GetActivationFactory(Microsoft::WRL::Wrappers::HStringReference(RuntimeClass_Windows_Foundation_PropertyValue).Get(), objFactory.ReleaseAndGetAddressOf());
if (FAILED(hr)) return nullptr;
Microsoft::WRL::ComPtr<ABI::Windows::Foundation::IPropertyValueStatics> spPropVal;
if (SUCCEEDED(hr))
hr = objFactory.As(&spPropVal);
if (SUCCEEDED(hr)) {
hr = winrt_type<_Type>::create(spPropVal.Get(), _ObjInCtx, _PObj.GetAddressOf());
if (SUCCEEDED(hr))
return reinterpret_cast<IUnknown*>(_PObj.Detach());
}
return nullptr;
}
static IID getuuid() { return __uuidof(ABI::Windows::Foundation::IPropertyValue); }
static const ABI::Windows::Foundation::PropertyType _PropType = ABI::Windows::Foundation::PropertyType::PropertyType_OtherType;
};
template<>
struct winrt_type<void>
{
static HRESULT create(ABI::Windows::Foundation::IPropertyValueStatics* spPropVal, void* _ObjInCtx, IInspectable** ppInsp) {
(void)_ObjInCtx;
return spPropVal->CreateEmpty(ppInsp);
}
static const ABI::Windows::Foundation::PropertyType _PropType = ABI::Windows::Foundation::PropertyType::PropertyType_Empty;
};
#define MAKE_TYPE(Type, Name) template<>\
struct winrt_type<Type>\
{\
static HRESULT create(ABI::Windows::Foundation::IPropertyValueStatics* spPropVal, Type* _ObjInCtx, IInspectable** ppInsp) {\
return spPropVal->Create##Name(*_ObjInCtx, ppInsp);\
}\
static const ABI::Windows::Foundation::PropertyType _PropType = ABI::Windows::Foundation::PropertyType::PropertyType_##Name;\
};
template<typename _Type>
struct winrt_array_type
{
static IUnknown* create(_Type* _ObjInCtx, size_t N) {
Microsoft::WRL::ComPtr<IInspectable> _PObj;
Microsoft::WRL::ComPtr<IActivationFactory> objFactory;
HRESULT hr = Windows::Foundation::GetActivationFactory(Microsoft::WRL::Wrappers::HStringReference(RuntimeClass_Windows_Foundation_PropertyValue).Get(), objFactory.ReleaseAndGetAddressOf());
if (FAILED(hr)) return nullptr;
Microsoft::WRL::ComPtr<ABI::Windows::Foundation::IPropertyValueStatics> spPropVal;
if (SUCCEEDED(hr))
hr = objFactory.As(&spPropVal);
if (SUCCEEDED(hr)) {
hr = winrt_array_type<_Type>::create(spPropVal.Get(), N, _ObjInCtx, _PObj.GetAddressOf());
if (SUCCEEDED(hr))
return reinterpret_cast<IUnknown*>(_PObj.Detach());
}
return nullptr;
}
static const ABI::Windows::Foundation::PropertyType _PropType = ABI::Windows::Foundation::PropertyType::PropertyType_OtherTypeArray;
};
template<int>
struct winrt_prop_type {};
template <>
struct winrt_prop_type<ABI::Windows::Foundation::PropertyType_Empty> {
typedef void _Type;
};
template <>
struct winrt_prop_type<ABI::Windows::Foundation::PropertyType_OtherType> {
typedef void _Type;
};
template <>
struct winrt_prop_type<ABI::Windows::Foundation::PropertyType_OtherTypeArray> {
typedef void _Type;
};
#define MAKE_PROP(Prop, Type) template <>\
struct winrt_prop_type<ABI::Windows::Foundation::PropertyType_##Prop> {\
typedef Type _Type;\
};
#define MAKE_ARRAY_TYPE(Type, Name) MAKE_PROP(Name, Type)\
MAKE_PROP(Name##Array, Type*)\
MAKE_TYPE(Type, Name)\
template<>\
struct winrt_array_type<Type*>\
{\
static HRESULT create(ABI::Windows::Foundation::IPropertyValueStatics* spPropVal, UINT32 __valueSize, Type** _ObjInCtx, IInspectable** ppInsp) {\
return spPropVal->Create##Name##Array(__valueSize, *_ObjInCtx, ppInsp);\
}\
static const ABI::Windows::Foundation::PropertyType _PropType = ABI::Windows::Foundation::PropertyType::PropertyType_##Name##Array;\
static std::vector<Type> PropertyValueToVector(ABI::Windows::Foundation::IPropertyValue* propValue)\
{\
UINT32 uLen = 0;\
Type* pArray = nullptr;\
propValue->Get##Name##Array(&uLen, &pArray);\
return std::vector<Type>(pArray, pArray + uLen);\
}\
};
MAKE_ARRAY_TYPE(BYTE, UInt8)
MAKE_ARRAY_TYPE(INT16, Int16)
MAKE_ARRAY_TYPE(UINT16, UInt16)
MAKE_ARRAY_TYPE(INT32, Int32)
MAKE_ARRAY_TYPE(UINT32, UInt32)
MAKE_ARRAY_TYPE(INT64, Int64)
MAKE_ARRAY_TYPE(UINT64, UInt64)
MAKE_ARRAY_TYPE(FLOAT, Single)
MAKE_ARRAY_TYPE(DOUBLE, Double)
MAKE_ARRAY_TYPE(WCHAR, Char16)
//MAKE_ARRAY_TYPE(boolean, Boolean) //conflict with identical type in C++ of BYTE/UInt8
MAKE_ARRAY_TYPE(HSTRING, String)
MAKE_ARRAY_TYPE(IInspectable*, Inspectable)
MAKE_ARRAY_TYPE(GUID, Guid)
MAKE_ARRAY_TYPE(ABI::Windows::Foundation::DateTime, DateTime)
MAKE_ARRAY_TYPE(ABI::Windows::Foundation::TimeSpan, TimeSpan)
MAKE_ARRAY_TYPE(ABI::Windows::Foundation::Point, Point)
MAKE_ARRAY_TYPE(ABI::Windows::Foundation::Size, Size)
MAKE_ARRAY_TYPE(ABI::Windows::Foundation::Rect, Rect)
template < typename T >
struct DerefHelper
{
typedef T DerefType;
};
template < typename T >
struct DerefHelper<T*>
{
typedef T DerefType;
};
#define __is_valid_winrt_type(_Type) (std::is_void<_Type>::value || \
std::is_same<_Type, BYTE>::value || \
std::is_same<_Type, INT16>::value || \
std::is_same<_Type, UINT16>::value || \
std::is_same<_Type, INT32>::value || \
std::is_same<_Type, UINT32>::value || \
std::is_same<_Type, INT64>::value || \
std::is_same<_Type, UINT64>::value || \
std::is_same<_Type, FLOAT>::value || \
std::is_same<_Type, DOUBLE>::value || \
std::is_same<_Type, WCHAR>::value || \
std::is_same<_Type, boolean>::value || \
std::is_same<_Type, HSTRING>::value || \
std::is_same<_Type, IInspectable *>::value || \
std::is_base_of<Microsoft::WRL::Details::RuntimeClassBase, _Type>::value || \
std::is_base_of<IInspectable, typename DerefHelper<_Type>::DerefType>::value || \
std::is_same<_Type, GUID>::value || \
std::is_same<_Type, ABI::Windows::Foundation::DateTime>::value || \
std::is_same<_Type, ABI::Windows::Foundation::TimeSpan>::value || \
std::is_same<_Type, ABI::Windows::Foundation::Point>::value || \
std::is_same<_Type, ABI::Windows::Foundation::Size>::value || \
std::is_same<_Type, ABI::Windows::Foundation::Rect>::value || \
std::is_same<_Type, BYTE*>::value || \
std::is_same<_Type, INT16*>::value || \
std::is_same<_Type, UINT16*>::value || \
std::is_same<_Type, INT32*>::value || \
std::is_same<_Type, UINT32*>::value || \
std::is_same<_Type, INT64*>::value || \
std::is_same<_Type, UINT64*>::value || \
std::is_same<_Type, FLOAT*>::value || \
std::is_same<_Type, DOUBLE*>::value || \
std::is_same<_Type, WCHAR*>::value || \
std::is_same<_Type, boolean*>::value || \
std::is_same<_Type, HSTRING*>::value || \
std::is_same<_Type, IInspectable **>::value || \
std::is_same<_Type, GUID*>::value || \
std::is_same<_Type, ABI::Windows::Foundation::DateTime*>::value || \
std::is_same<_Type, ABI::Windows::Foundation::TimeSpan*>::value || \
std::is_same<_Type, ABI::Windows::Foundation::Point*>::value || \
std::is_same<_Type, ABI::Windows::Foundation::Size*>::value || \
std::is_same<_Type, ABI::Windows::Foundation::Rect*>::value)
#endif
#else
EXTERN_C const IID IID_ICustomStreamSink;
class DECLSPEC_UUID("4F8A1939-2FD3-46DB-AE70-DB7E0DD79B73") DECLSPEC_NOVTABLE ICustomStreamSink : public IUnknown
{
public:
virtual HRESULT Initialize() = 0;
virtual HRESULT Shutdown() = 0;
virtual HRESULT Start(MFTIME start) = 0;
virtual HRESULT Pause() = 0;
virtual HRESULT Restart() = 0;
virtual HRESULT Stop() = 0;
};
#endif
#define MF_PROP_SAMPLEGRABBERCALLBACK L"samplegrabbercallback"
#define MF_PROP_VIDTYPE L"vidtype"
#define MF_PROP_VIDENCPROPS L"videncprops"
#include <initguid.h>
// MF_MEDIASINK_SAMPLEGRABBERCALLBACK: {26957AA7-AFF4-464c-BB8B-07BA65CE11DF}
// Type: IUnknown*
DEFINE_GUID(MF_MEDIASINK_SAMPLEGRABBERCALLBACK,
0x26957aa7, 0xaff4, 0x464c, 0xbb, 0x8b, 0x7, 0xba, 0x65, 0xce, 0x11, 0xdf);
// {4BD133CC-EB9B-496E-8865-0813BFBC6FAA}
DEFINE_GUID(MF_STREAMSINK_ID, 0x4bd133cc, 0xeb9b, 0x496e, 0x88, 0x65, 0x8, 0x13, 0xbf, 0xbc, 0x6f, 0xaa);
// {C9E22A8C-6A50-4D78-9183-0834A02A3780}
DEFINE_GUID(MF_STREAMSINK_MEDIASINKINTERFACE,
0xc9e22a8c, 0x6a50, 0x4d78, 0x91, 0x83, 0x8, 0x34, 0xa0, 0x2a, 0x37, 0x80);
// {DABD13AB-26B7-47C2-97C1-4B04C187B838}
DEFINE_GUID(MF_MEDIASINK_PREFERREDTYPE,
0xdabd13ab, 0x26b7, 0x47c2, 0x97, 0xc1, 0x4b, 0x4, 0xc1, 0x87, 0xb8, 0x38);
#include <utility>
#ifdef _UNICODE
#define MAKE_MAP(e) std::map<e, std::wstring>
#define MAKE_ENUM(e) std::pair<e, std::wstring>
#define MAKE_ENUM_PAIR(e, str) std::pair<e, std::wstring>(str, L#str)
#else
#define MAKE_MAP(e) std::map<e, std::string>
#define MAKE_ENUM(e) std::pair<e, std::string>
#define MAKE_ENUM_PAIR(e, str) std::pair<e, std::string>(str, #str)
#endif
MAKE_ENUM(MediaEventType) MediaEventTypePairs[] = {
MAKE_ENUM_PAIR(MediaEventType, MEUnknown),
MAKE_ENUM_PAIR(MediaEventType, MEError),
MAKE_ENUM_PAIR(MediaEventType, MEExtendedType),
MAKE_ENUM_PAIR(MediaEventType, MENonFatalError),
MAKE_ENUM_PAIR(MediaEventType, MEGenericV1Anchor),
MAKE_ENUM_PAIR(MediaEventType, MESessionUnknown),
MAKE_ENUM_PAIR(MediaEventType, MESessionTopologySet),
MAKE_ENUM_PAIR(MediaEventType, MESessionTopologiesCleared),
MAKE_ENUM_PAIR(MediaEventType, MESessionStarted),
MAKE_ENUM_PAIR(MediaEventType, MESessionPaused),
MAKE_ENUM_PAIR(MediaEventType, MESessionStopped),
MAKE_ENUM_PAIR(MediaEventType, MESessionClosed),
MAKE_ENUM_PAIR(MediaEventType, MESessionEnded),
MAKE_ENUM_PAIR(MediaEventType, MESessionRateChanged),
MAKE_ENUM_PAIR(MediaEventType, MESessionScrubSampleComplete),
MAKE_ENUM_PAIR(MediaEventType, MESessionCapabilitiesChanged),
MAKE_ENUM_PAIR(MediaEventType, MESessionTopologyStatus),
MAKE_ENUM_PAIR(MediaEventType, MESessionNotifyPresentationTime),
MAKE_ENUM_PAIR(MediaEventType, MENewPresentation),
MAKE_ENUM_PAIR(MediaEventType, MELicenseAcquisitionStart),
MAKE_ENUM_PAIR(MediaEventType, MELicenseAcquisitionCompleted),
MAKE_ENUM_PAIR(MediaEventType, MEIndividualizationStart),
MAKE_ENUM_PAIR(MediaEventType, MEIndividualizationCompleted),
MAKE_ENUM_PAIR(MediaEventType, MEEnablerProgress),
MAKE_ENUM_PAIR(MediaEventType, MEEnablerCompleted),
MAKE_ENUM_PAIR(MediaEventType, MEPolicyError),
MAKE_ENUM_PAIR(MediaEventType, MEPolicyReport),
MAKE_ENUM_PAIR(MediaEventType, MEBufferingStarted),
MAKE_ENUM_PAIR(MediaEventType, MEBufferingStopped),
MAKE_ENUM_PAIR(MediaEventType, MEConnectStart),
MAKE_ENUM_PAIR(MediaEventType, MEConnectEnd),
MAKE_ENUM_PAIR(MediaEventType, MEReconnectStart),
MAKE_ENUM_PAIR(MediaEventType, MEReconnectEnd),
MAKE_ENUM_PAIR(MediaEventType, MERendererEvent),
MAKE_ENUM_PAIR(MediaEventType, MESessionStreamSinkFormatChanged),
MAKE_ENUM_PAIR(MediaEventType, MESessionV1Anchor),
MAKE_ENUM_PAIR(MediaEventType, MESourceUnknown),
MAKE_ENUM_PAIR(MediaEventType, MESourceStarted),
MAKE_ENUM_PAIR(MediaEventType, MEStreamStarted),
MAKE_ENUM_PAIR(MediaEventType, MESourceSeeked),
MAKE_ENUM_PAIR(MediaEventType, MEStreamSeeked),
MAKE_ENUM_PAIR(MediaEventType, MENewStream),
MAKE_ENUM_PAIR(MediaEventType, MEUpdatedStream),
MAKE_ENUM_PAIR(MediaEventType, MESourceStopped),
MAKE_ENUM_PAIR(MediaEventType, MEStreamStopped),
MAKE_ENUM_PAIR(MediaEventType, MESourcePaused),
MAKE_ENUM_PAIR(MediaEventType, MEStreamPaused),
MAKE_ENUM_PAIR(MediaEventType, MEEndOfPresentation),
MAKE_ENUM_PAIR(MediaEventType, MEEndOfStream),
MAKE_ENUM_PAIR(MediaEventType, MEMediaSample),
MAKE_ENUM_PAIR(MediaEventType, MEStreamTick),
MAKE_ENUM_PAIR(MediaEventType, MEStreamThinMode),
MAKE_ENUM_PAIR(MediaEventType, MEStreamFormatChanged),
MAKE_ENUM_PAIR(MediaEventType, MESourceRateChanged),
MAKE_ENUM_PAIR(MediaEventType, MEEndOfPresentationSegment),
MAKE_ENUM_PAIR(MediaEventType, MESourceCharacteristicsChanged),
MAKE_ENUM_PAIR(MediaEventType, MESourceRateChangeRequested),
MAKE_ENUM_PAIR(MediaEventType, MESourceMetadataChanged),
MAKE_ENUM_PAIR(MediaEventType, MESequencerSourceTopologyUpdated),
MAKE_ENUM_PAIR(MediaEventType, MESourceV1Anchor),
MAKE_ENUM_PAIR(MediaEventType, MESinkUnknown),
MAKE_ENUM_PAIR(MediaEventType, MEStreamSinkStarted),
MAKE_ENUM_PAIR(MediaEventType, MEStreamSinkStopped),
MAKE_ENUM_PAIR(MediaEventType, MEStreamSinkPaused),
MAKE_ENUM_PAIR(MediaEventType, MEStreamSinkRateChanged),
MAKE_ENUM_PAIR(MediaEventType, MEStreamSinkRequestSample),
MAKE_ENUM_PAIR(MediaEventType, MEStreamSinkMarker),
MAKE_ENUM_PAIR(MediaEventType, MEStreamSinkPrerolled),
MAKE_ENUM_PAIR(MediaEventType, MEStreamSinkScrubSampleComplete),
MAKE_ENUM_PAIR(MediaEventType, MEStreamSinkFormatChanged),
MAKE_ENUM_PAIR(MediaEventType, MEStreamSinkDeviceChanged),
MAKE_ENUM_PAIR(MediaEventType, MEQualityNotify),
MAKE_ENUM_PAIR(MediaEventType, MESinkInvalidated),
MAKE_ENUM_PAIR(MediaEventType, MEAudioSessionNameChanged),
MAKE_ENUM_PAIR(MediaEventType, MEAudioSessionVolumeChanged),
MAKE_ENUM_PAIR(MediaEventType, MEAudioSessionDeviceRemoved),
MAKE_ENUM_PAIR(MediaEventType, MEAudioSessionServerShutdown),
MAKE_ENUM_PAIR(MediaEventType, MEAudioSessionGroupingParamChanged),
MAKE_ENUM_PAIR(MediaEventType, MEAudioSessionIconChanged),
MAKE_ENUM_PAIR(MediaEventType, MEAudioSessionFormatChanged),
MAKE_ENUM_PAIR(MediaEventType, MEAudioSessionDisconnected),
MAKE_ENUM_PAIR(MediaEventType, MEAudioSessionExclusiveModeOverride),
MAKE_ENUM_PAIR(MediaEventType, MESinkV1Anchor),
#if (WINVER >= 0x0602) // Available since Win 8
MAKE_ENUM_PAIR(MediaEventType, MECaptureAudioSessionVolumeChanged),
MAKE_ENUM_PAIR(MediaEventType, MECaptureAudioSessionDeviceRemoved),
MAKE_ENUM_PAIR(MediaEventType, MECaptureAudioSessionFormatChanged),
MAKE_ENUM_PAIR(MediaEventType, MECaptureAudioSessionDisconnected),
MAKE_ENUM_PAIR(MediaEventType, MECaptureAudioSessionExclusiveModeOverride),
MAKE_ENUM_PAIR(MediaEventType, MECaptureAudioSessionServerShutdown),
MAKE_ENUM_PAIR(MediaEventType, MESinkV2Anchor),
#endif
MAKE_ENUM_PAIR(MediaEventType, METrustUnknown),
MAKE_ENUM_PAIR(MediaEventType, MEPolicyChanged),
MAKE_ENUM_PAIR(MediaEventType, MEContentProtectionMessage),
MAKE_ENUM_PAIR(MediaEventType, MEPolicySet),
MAKE_ENUM_PAIR(MediaEventType, METrustV1Anchor),
MAKE_ENUM_PAIR(MediaEventType, MEWMDRMLicenseBackupCompleted),
MAKE_ENUM_PAIR(MediaEventType, MEWMDRMLicenseBackupProgress),
MAKE_ENUM_PAIR(MediaEventType, MEWMDRMLicenseRestoreCompleted),
MAKE_ENUM_PAIR(MediaEventType, MEWMDRMLicenseRestoreProgress),
MAKE_ENUM_PAIR(MediaEventType, MEWMDRMLicenseAcquisitionCompleted),
MAKE_ENUM_PAIR(MediaEventType, MEWMDRMIndividualizationCompleted),
MAKE_ENUM_PAIR(MediaEventType, MEWMDRMIndividualizationProgress),
MAKE_ENUM_PAIR(MediaEventType, MEWMDRMProximityCompleted),
MAKE_ENUM_PAIR(MediaEventType, MEWMDRMLicenseStoreCleaned),
MAKE_ENUM_PAIR(MediaEventType, MEWMDRMRevocationDownloadCompleted),
MAKE_ENUM_PAIR(MediaEventType, MEWMDRMV1Anchor),
MAKE_ENUM_PAIR(MediaEventType, METransformUnknown),
MAKE_ENUM_PAIR(MediaEventType, METransformNeedInput),
MAKE_ENUM_PAIR(MediaEventType, METransformHaveOutput),
MAKE_ENUM_PAIR(MediaEventType, METransformDrainComplete),
MAKE_ENUM_PAIR(MediaEventType, METransformMarker),
#if (WINVER >= 0x0602) // Available since Win 8
MAKE_ENUM_PAIR(MediaEventType, MEByteStreamCharacteristicsChanged),
MAKE_ENUM_PAIR(MediaEventType, MEVideoCaptureDeviceRemoved),
MAKE_ENUM_PAIR(MediaEventType, MEVideoCaptureDevicePreempted),
#endif
MAKE_ENUM_PAIR(MediaEventType, MEReservedMax)
};
MAKE_MAP(MediaEventType) MediaEventTypeMap(MediaEventTypePairs, MediaEventTypePairs + sizeof(MediaEventTypePairs) / sizeof(MediaEventTypePairs[0]));
MAKE_ENUM(MFSTREAMSINK_MARKER_TYPE) StreamSinkMarkerTypePairs[] = {
MAKE_ENUM_PAIR(MFSTREAMSINK_MARKER_TYPE, MFSTREAMSINK_MARKER_DEFAULT),
MAKE_ENUM_PAIR(MFSTREAMSINK_MARKER_TYPE, MFSTREAMSINK_MARKER_ENDOFSEGMENT),
MAKE_ENUM_PAIR(MFSTREAMSINK_MARKER_TYPE, MFSTREAMSINK_MARKER_TICK),
MAKE_ENUM_PAIR(MFSTREAMSINK_MARKER_TYPE, MFSTREAMSINK_MARKER_EVENT)
};
MAKE_MAP(MFSTREAMSINK_MARKER_TYPE) StreamSinkMarkerTypeMap(StreamSinkMarkerTypePairs, StreamSinkMarkerTypePairs + sizeof(StreamSinkMarkerTypePairs) / sizeof(StreamSinkMarkerTypePairs[0]));
#ifdef HAVE_WINRT
#ifdef __cplusplus_winrt
#define _ContextCallback Concurrency::details::_ContextCallback
#define BEGIN_CALL_IN_CONTEXT(hr, var, ...) hr = S_OK;\
var._CallInContext([__VA_ARGS__]() {
#define END_CALL_IN_CONTEXT(hr) if (FAILED(hr)) throw Platform::Exception::CreateException(hr);\
});
#define END_CALL_IN_CONTEXT_BASE });
#else
#define _ContextCallback Concurrency_winrt::details::_ContextCallback
#define BEGIN_CALL_IN_CONTEXT(hr, var, ...) hr = var._CallInContext([__VA_ARGS__]() -> HRESULT {
#define END_CALL_IN_CONTEXT(hr) return hr;\
});
#define END_CALL_IN_CONTEXT_BASE return S_OK;\
});
#endif
#define GET_CURRENT_CONTEXT _ContextCallback::_CaptureCurrent()
#define SAVE_CURRENT_CONTEXT(var) _ContextCallback var = GET_CURRENT_CONTEXT
#define COMMA ,
#ifdef __cplusplus_winrt
#define _Object Platform::Object^
#define _ObjectObj Platform::Object^
#define _String Platform::String^
#define _StringObj Platform::String^
#define _StringReference ref new Platform::String
#define _StringReferenceObj Platform::String^
#define _DeviceInformationCollection Windows::Devices::Enumeration::DeviceInformationCollection
#define _MediaCapture Windows::Media::Capture::MediaCapture
#define _MediaCaptureVideoPreview Windows::Media::Capture::MediaCapture
#define _MediaCaptureInitializationSettings Windows::Media::Capture::MediaCaptureInitializationSettings
#define _VideoDeviceController Windows::Media::Devices::VideoDeviceController
#define _MediaDeviceController Windows::Media::Devices::VideoDeviceController
#define _MediaEncodingProperties Windows::Media::MediaProperties::IMediaEncodingProperties
#define _VideoEncodingProperties Windows::Media::MediaProperties::VideoEncodingProperties
#define _MediaStreamType Windows::Media::Capture::MediaStreamType
#define _AsyncInfo Windows::Foundation::IAsyncInfo
#define _AsyncAction Windows::Foundation::IAsyncAction
#define _AsyncOperation Windows::Foundation::IAsyncOperation
#define _DeviceClass Windows::Devices::Enumeration::DeviceClass
#define _IDeviceInformation Windows::Devices::Enumeration::DeviceInformation
#define _DeviceInformation Windows::Devices::Enumeration::DeviceInformation
#define _DeviceInformationStatics Windows::Devices::Enumeration::DeviceInformation
#define _MediaEncodingProfile Windows::Media::MediaProperties::MediaEncodingProfile
#define _StreamingCaptureMode Windows::Media::Capture::StreamingCaptureMode
#define _PropertySet Windows::Foundation::Collections::PropertySet
#define _Map Windows::Foundation::Collections::PropertySet
#define _PropertyValueStatics Windows::Foundation::PropertyValue
#define _VectorView Windows::Foundation::Collections::IVectorView
#define _StartPreviewToCustomSinkIdAsync StartPreviewToCustomSinkAsync
#define _InitializeWithSettingsAsync InitializeAsync
#define _FindAllAsyncDeviceClass FindAllAsync
#define _MediaExtension Windows::Media::IMediaExtension
#define BEGIN_CREATE_ASYNC(type, ...) (Concurrency::create_async([__VA_ARGS__]() {
#define END_CREATE_ASYNC(hr) if (FAILED(hr)) throw Platform::Exception::CreateException(hr);\
}))
#define DEFINE_TASK Concurrency::task
#define CREATE_TASK Concurrency::create_task
#define CREATE_OR_CONTINUE_TASK(_task, rettype, func) _task = (_task == Concurrency::task<rettype>()) ? Concurrency::create_task(func) : _task.then([func](rettype) -> rettype { return func(); });
#define CREATE_OR_CONTINUE_TASK_RET(_task, rettype, func) _task = (_task == Concurrency::task<rettype>()) ? Concurrency::create_task(func) : _task.then([func](rettype) -> rettype { return func(); });
#define DEFINE_RET_VAL(x)
#define DEFINE_RET_TYPE(x)
#define DEFINE_RET_FORMAL(x) x
#define RET_VAL(x) return x;
#define RET_VAL_BASE
#define MAKE_STRING(str) str
#define GET_STL_STRING(str) std::wstring(str->Data())
#define GET_STL_STRING_RAW(str) std::wstring(str->Data())
#define MAKE_WRL_OBJ(x) x^
#define MAKE_WRL_REF(x) x^
#define MAKE_OBJ_REF(x) x^
#define MAKE_WRL_AGILE_REF(x) Platform::Agile<x^>
#define MAKE_WRL_AGILE_OBJ(x) Platform::Agile<x^>
#define MAKE_PROPERTY_BACKING(Type, PropName) property Type PropName;
#define MAKE_PROPERTY(Type, PropName, PropValue)
#define MAKE_PROPERTY_STRING(Type, PropName, PropValue)
#define MAKE_READONLY_PROPERTY(Type, PropName, PropValue) property Type PropName\
{\
Type get() { return PropValue; }\
}
#define THROW_INVALID_ARG throw ref new Platform::InvalidArgumentException();
#define RELEASE_AGILE_WRL(x) x = nullptr;
#define RELEASE_WRL(x) x = nullptr;
#define GET_WRL_OBJ_FROM_REF(objtype, obj, orig, hr) objtype^ obj = orig;\
hr = S_OK;
#define GET_WRL_OBJ_FROM_OBJ(objtype, obj, orig, hr) objtype^ obj = safe_cast<objtype^>(orig);\
hr = S_OK;
#define WRL_ENUM_GET(obj, prefix, prop) obj::##prop
#define WRL_PROP_GET(obj, prop, arg, hr) arg = obj->##prop;\
hr = S_OK;
#define WRL_PROP_PUT(obj, prop, arg, hr) obj->##prop = arg;\
hr = S_OK;
#define WRL_METHOD_BASE(obj, method, ret, hr) ret = obj->##method();\
hr = S_OK;
#define WRL_METHOD(obj, method, ret, hr, ...) ret = obj->##method(__VA_ARGS__);\
hr = S_OK;
#define WRL_METHOD_NORET_BASE(obj, method, hr) obj->##method();\
hr = S_OK;
#define WRL_METHOD_NORET(obj, method, hr, ...) obj->##method(__VA_ARGS__);\
hr = S_OK;
#define REF_WRL_OBJ(obj) &obj
#define DEREF_WRL_OBJ(obj) obj
#define DEREF_AGILE_WRL_MADE_OBJ(obj) obj.Get()
#define DEREF_AGILE_WRL_OBJ(obj) obj.Get()
#define DEREF_AS_NATIVE_WRL_OBJ(type, obj) reinterpret_cast<type*>(obj)
#define PREPARE_TRANSFER_WRL_OBJ(obj) obj
#define ACTIVATE_LOCAL_OBJ_BASE(objtype) ref new objtype()
#define ACTIVATE_LOCAL_OBJ(objtype, ...) ref new objtype(__VA_ARGS__)
#define ACTIVATE_EVENT_HANDLER(objtype, ...) ref new objtype(__VA_ARGS__)
#define ACTIVATE_OBJ(rtclass, objtype, obj, hr) MAKE_WRL_OBJ(objtype) obj = ref new objtype();\
hr = S_OK;
#define ACTIVATE_STATIC_OBJ(rtclass, objtype, obj, hr) objtype obj;\
hr = S_OK;
#else
#define _Object IInspectable*
#define _ObjectObj Microsoft::WRL::ComPtr<IInspectable>
#define _String HSTRING
#define _StringObj Microsoft::WRL::Wrappers::HString
#define _StringReference Microsoft::WRL::Wrappers::HStringReference
#define _StringReferenceObj Microsoft::WRL::Wrappers::HStringReference
#define _DeviceInformationCollection ABI::Windows::Devices::Enumeration::DeviceInformationCollection
#define _MediaCapture ABI::Windows::Media::Capture::IMediaCapture
#define _MediaCaptureVideoPreview ABI::Windows::Media::Capture::IMediaCaptureVideoPreview
#define _MediaCaptureInitializationSettings ABI::Windows::Media::Capture::IMediaCaptureInitializationSettings
#define _VideoDeviceController ABI::Windows::Media::Devices::IVideoDeviceController
#define _MediaDeviceController ABI::Windows::Media::Devices::IMediaDeviceController
#define _MediaEncodingProperties ABI::Windows::Media::MediaProperties::IMediaEncodingProperties
#define _VideoEncodingProperties ABI::Windows::Media::MediaProperties::IVideoEncodingProperties
#define _MediaStreamType ABI::Windows::Media::Capture::MediaStreamType
#define _AsyncInfo ABI::Windows::Foundation::IAsyncInfo
#define _AsyncAction ABI::Windows::Foundation::IAsyncAction
#define _AsyncOperation ABI::Windows::Foundation::IAsyncOperation
#define _DeviceClass ABI::Windows::Devices::Enumeration::DeviceClass
#define _IDeviceInformation ABI::Windows::Devices::Enumeration::IDeviceInformation
#define _DeviceInformation ABI::Windows::Devices::Enumeration::DeviceInformation
#define _DeviceInformationStatics ABI::Windows::Devices::Enumeration::IDeviceInformationStatics
#define _MediaEncodingProfile ABI::Windows::Media::MediaProperties::IMediaEncodingProfile
#define _StreamingCaptureMode ABI::Windows::Media::Capture::StreamingCaptureMode
#define _PropertySet ABI::Windows::Foundation::Collections::IPropertySet
#define _Map ABI::Windows::Foundation::Collections::IMap<HSTRING, IInspectable *>
#define _PropertyValueStatics ABI::Windows::Foundation::IPropertyValueStatics
#define _VectorView ABI::Windows::Foundation::Collections::IVectorView
#define _StartPreviewToCustomSinkIdAsync StartPreviewToCustomSinkIdAsync
#define _InitializeWithSettingsAsync InitializeWithSettingsAsync
#define _FindAllAsyncDeviceClass FindAllAsyncDeviceClass
#define _MediaExtension ABI::Windows::Media::IMediaExtension
#define BEGIN_CREATE_ASYNC(type, ...) Concurrency_winrt::create_async<type>([__VA_ARGS__]() -> HRESULT {
#define END_CREATE_ASYNC(hr) return hr;\
})
#define DEFINE_TASK Concurrency_winrt::task
#define CREATE_TASK Concurrency_winrt::create_task
#define CREATE_OR_CONTINUE_TASK(_task, rettype, func) _task = (_task == Concurrency_winrt::task<rettype>()) ? Concurrency_winrt::create_task<rettype>(func) : _task.then(func);
#define CREATE_OR_CONTINUE_TASK_RET(_task, rettype, func) _task = (_task == Concurrency_winrt::task<rettype>()) ? Concurrency_winrt::create_task<rettype>(func) : _task.then([func](rettype, rettype* retVal) -> HRESULT { return func(retVal); });
#define DEFINE_RET_VAL(x) x* retVal
#define DEFINE_RET_TYPE(x) <x>
#define DEFINE_RET_FORMAL(x) HRESULT
#define RET_VAL(x) *retVal = x;\
return S_OK;
#define RET_VAL_BASE return S_OK;
#define MAKE_STRING(str) Microsoft::WRL::Wrappers::HStringReference(L##str)
#define GET_STL_STRING(str) std::wstring(str.GetRawBuffer(NULL))
#define GET_STL_STRING_RAW(str) WindowsGetStringRawBuffer(str, NULL)
#define MAKE_WRL_OBJ(x) Microsoft::WRL::ComPtr<x>
#define MAKE_WRL_REF(x) x*
#define MAKE_OBJ_REF(x) x
#define MAKE_WRL_AGILE_REF(x) x*
#define MAKE_WRL_AGILE_OBJ(x) Microsoft::WRL::ComPtr<x>
#define MAKE_PROPERTY_BACKING(Type, PropName) Type PropName;
#define MAKE_PROPERTY(Type, PropName, PropValue) STDMETHODIMP get_##PropName(Type* pVal) { if (pVal) { *pVal = PropValue; } else { return E_INVALIDARG; } return S_OK; }\
STDMETHODIMP put_##PropName(Type Val) { PropValue = Val; return S_OK; }
#define MAKE_PROPERTY_STRING(Type, PropName, PropValue) STDMETHODIMP get_##PropName(Type* pVal) { if (pVal) { return ::WindowsDuplicateString(PropValue.Get(), pVal); } else { return E_INVALIDARG; } }\
STDMETHODIMP put_##PropName(Type Val) { return PropValue.Set(Val); }
#define MAKE_READONLY_PROPERTY(Type, PropName, PropValue) STDMETHODIMP get_##PropName(Type* pVal) { if (pVal) { *pVal = PropValue; } else { return E_INVALIDARG; } return S_OK; }
#define THROW_INVALID_ARG RoOriginateError(E_INVALIDARG, nullptr);
#define RELEASE_AGILE_WRL(x) if (x) { (x)->Release(); x = nullptr; }
#define RELEASE_WRL(x) if (x) { (x)->Release(); x = nullptr; }
#define GET_WRL_OBJ_FROM_REF(objtype, obj, orig, hr) Microsoft::WRL::ComPtr<objtype> obj;\
hr = orig->QueryInterface(__uuidof(objtype), &obj);
#define GET_WRL_OBJ_FROM_OBJ(objtype, obj, orig, hr) Microsoft::WRL::ComPtr<objtype> obj;\
hr = orig.As(&obj);
#define WRL_ENUM_GET(obj, prefix, prop) obj::prefix##_##prop
#define WRL_PROP_GET(obj, prop, arg, hr) hr = obj->get_##prop(&arg);
#define WRL_PROP_PUT(obj, prop, arg, hr) hr = obj->put_##prop(arg);
#define WRL_METHOD_BASE(obj, method, ret, hr) hr = obj->##method(&ret);
#define WRL_METHOD(obj, method, ret, hr, ...) hr = obj->##method(__VA_ARGS__, &ret);
#define WRL_METHOD_NORET_BASE(obj, method, hr) hr = obj->##method();
#define REF_WRL_OBJ(obj) obj.GetAddressOf()
#define DEREF_WRL_OBJ(obj) obj.Get()
#define DEREF_AGILE_WRL_MADE_OBJ(obj) obj.Get()
#define DEREF_AGILE_WRL_OBJ(obj) obj
#define DEREF_AS_NATIVE_WRL_OBJ(type, obj) obj.Get()
#define PREPARE_TRANSFER_WRL_OBJ(obj) obj.Detach()
#define ACTIVATE_LOCAL_OBJ_BASE(objtype) Microsoft::WRL::Make<objtype>()
#define ACTIVATE_LOCAL_OBJ(objtype, ...) Microsoft::WRL::Make<objtype>(__VA_ARGS__)
#define ACTIVATE_EVENT_HANDLER(objtype, ...) Microsoft::WRL::Callback<objtype>(__VA_ARGS__).Get()
#define ACTIVATE_OBJ(rtclass, objtype, obj, hr) MAKE_WRL_OBJ(objtype) obj;\
{\
Microsoft::WRL::ComPtr<IActivationFactory> objFactory;\
hr = Windows::Foundation::GetActivationFactory(Microsoft::WRL::Wrappers::HStringReference(rtclass).Get(), objFactory.ReleaseAndGetAddressOf());\
if (SUCCEEDED(hr)) {\
Microsoft::WRL::ComPtr<IInspectable> pInsp;\
hr = objFactory->ActivateInstance(pInsp.GetAddressOf());\
if (SUCCEEDED(hr)) hr = pInsp.As(&obj);\
}\
}
#define ACTIVATE_STATIC_OBJ(rtclass, objtype, obj, hr) objtype obj;\
{\
Microsoft::WRL::ComPtr<IActivationFactory> objFactory;\
hr = Windows::Foundation::GetActivationFactory(Microsoft::WRL::Wrappers::HStringReference(rtclass).Get(), objFactory.ReleaseAndGetAddressOf());\
if (SUCCEEDED(hr)) {\
if (SUCCEEDED(hr)) hr = objFactory.As(&obj);\
}\
}
#endif
#define _ComPtr Microsoft::WRL::ComPtr
#else
#define _COM_SMARTPTR_DECLARE(T,var) T ## Ptr var
template <class T>
class ComPtr
{
public:
ComPtr() throw()
{
}
ComPtr(T* lp) throw()
{
p = lp;
}
ComPtr(_In_ const ComPtr<T>& lp) throw()
{
p = lp.p;
}
virtual ~ComPtr()
{
}
T** operator&() throw()
{
assert(p == NULL);
return p.operator&();
}
T* operator->() const throw()
{
assert(p != NULL);
return p.operator->();
}
bool operator!() const throw()
{
return p.operator==(NULL);
}
bool operator==(_In_opt_ T* pT) const throw()
{
return p.operator==(pT);
}
bool operator!=(_In_opt_ T* pT) const throw()
{
return p.operator!=(pT);
}
operator bool()
{
return p.operator!=(NULL);
}
T* const* GetAddressOf() const throw()
{
return &p;
}
T** GetAddressOf() throw()
{
return &p;
}
T** ReleaseAndGetAddressOf() throw()
{
p.Release();
return &p;
}
T* Get() const throw()
{
return p;
}
// Attach to an existing interface (does not AddRef)
void Attach(_In_opt_ T* p2) throw()
{
p.Attach(p2);
}
// Detach the interface (does not Release)
T* Detach() throw()
{
return p.Detach();
}
_Check_return_ HRESULT CopyTo(_Deref_out_opt_ T** ppT) throw()
{
assert(ppT != NULL);
if (ppT == NULL)
return E_POINTER;
*ppT = p;
if (p != NULL)
p->AddRef();
return S_OK;
}
void Reset()
{
p.Release();
}
// query for U interface
template<typename U>
HRESULT As(_Inout_ U** lp) const throw()
{
return p->QueryInterface(__uuidof(U), reinterpret_cast<void**>(lp));
}
// query for U interface
template<typename U>
HRESULT As(_Out_ ComPtr<U>* lp) const throw()
{
return p->QueryInterface(__uuidof(U), reinterpret_cast<void**>(lp->ReleaseAndGetAddressOf()));
}
private:
_COM_SMARTPTR_TYPEDEF(T, __uuidof(T));
_COM_SMARTPTR_DECLARE(T, p);
};
#define _ComPtr ComPtr
#endif
template <class TBase=IMFAttributes>
class CBaseAttributes : public TBase
{
protected:
// This version of the constructor does not initialize the
// attribute store. The derived class must call Initialize() in
// its own constructor.
CBaseAttributes()
{
}
// This version of the constructor initializes the attribute
// store, but the derived class must pass an HRESULT parameter
// to the constructor.
CBaseAttributes(HRESULT& hr, UINT32 cInitialSize = 0)
{
hr = Initialize(cInitialSize);
}
// The next version of the constructor uses a caller-provided
// implementation of IMFAttributes.
// (Sometimes you want to delegate IMFAttributes calls to some
// other object that implements IMFAttributes, rather than using
// MFCreateAttributes.)
CBaseAttributes(HRESULT& hr, IUnknown *pUnk)
{
hr = Initialize(pUnk);
}
virtual ~CBaseAttributes()
{
}
// Initializes the object by creating the standard Media Foundation attribute store.
HRESULT Initialize(UINT32 cInitialSize = 0)
{
if (_spAttributes.Get() == nullptr)
{
return MFCreateAttributes(&_spAttributes, cInitialSize);
}
else
{
return S_OK;
}
}
// Initializes this object from a caller-provided attribute store.
// pUnk: Pointer to an object that exposes IMFAttributes.
HRESULT Initialize(IUnknown *pUnk)
{
if (_spAttributes)
{
_spAttributes.Reset();
_spAttributes = nullptr;
}
return pUnk->QueryInterface(IID_PPV_ARGS(&_spAttributes));
}
public:
// IMFAttributes methods
STDMETHODIMP GetItem(REFGUID guidKey, PROPVARIANT* pValue)
{
assert(_spAttributes);
return _spAttributes->GetItem(guidKey, pValue);
}
STDMETHODIMP GetItemType(REFGUID guidKey, MF_ATTRIBUTE_TYPE* pType)
{
assert(_spAttributes);
return _spAttributes->GetItemType(guidKey, pType);
}
STDMETHODIMP CompareItem(REFGUID guidKey, REFPROPVARIANT Value, BOOL* pbResult)
{
assert(_spAttributes);
return _spAttributes->CompareItem(guidKey, Value, pbResult);
}
STDMETHODIMP Compare(
IMFAttributes* pTheirs,
MF_ATTRIBUTES_MATCH_TYPE MatchType,
BOOL* pbResult
)
{
assert(_spAttributes);
return _spAttributes->Compare(pTheirs, MatchType, pbResult);
}
STDMETHODIMP GetUINT32(REFGUID guidKey, UINT32* punValue)
{
assert(_spAttributes);
return _spAttributes->GetUINT32(guidKey, punValue);
}
STDMETHODIMP GetUINT64(REFGUID guidKey, UINT64* punValue)
{
assert(_spAttributes);
return _spAttributes->GetUINT64(guidKey, punValue);
}
STDMETHODIMP GetDouble(REFGUID guidKey, double* pfValue)
{
assert(_spAttributes);
return _spAttributes->GetDouble(guidKey, pfValue);
}
STDMETHODIMP GetGUID(REFGUID guidKey, GUID* pguidValue)
{
assert(_spAttributes);
return _spAttributes->GetGUID(guidKey, pguidValue);
}
STDMETHODIMP GetStringLength(REFGUID guidKey, UINT32* pcchLength)
{
assert(_spAttributes);
return _spAttributes->GetStringLength(guidKey, pcchLength);
}
STDMETHODIMP GetString(REFGUID guidKey, LPWSTR pwszValue, UINT32 cchBufSize, UINT32* pcchLength)
{
assert(_spAttributes);
return _spAttributes->GetString(guidKey, pwszValue, cchBufSize, pcchLength);
}
STDMETHODIMP GetAllocatedString(REFGUID guidKey, LPWSTR* ppwszValue, UINT32* pcchLength)
{
assert(_spAttributes);
return _spAttributes->GetAllocatedString(guidKey, ppwszValue, pcchLength);
}
STDMETHODIMP GetBlobSize(REFGUID guidKey, UINT32* pcbBlobSize)
{
assert(_spAttributes);
return _spAttributes->GetBlobSize(guidKey, pcbBlobSize);
}
STDMETHODIMP GetBlob(REFGUID guidKey, UINT8* pBuf, UINT32 cbBufSize, UINT32* pcbBlobSize)
{
assert(_spAttributes);
return _spAttributes->GetBlob(guidKey, pBuf, cbBufSize, pcbBlobSize);
}
STDMETHODIMP GetAllocatedBlob(REFGUID guidKey, UINT8** ppBuf, UINT32* pcbSize)
{
assert(_spAttributes);
return _spAttributes->GetAllocatedBlob(guidKey, ppBuf, pcbSize);
}
STDMETHODIMP GetUnknown(REFGUID guidKey, REFIID riid, LPVOID* ppv)
{
assert(_spAttributes);
return _spAttributes->GetUnknown(guidKey, riid, ppv);
}
STDMETHODIMP SetItem(REFGUID guidKey, REFPROPVARIANT Value)
{
assert(_spAttributes);
return _spAttributes->SetItem(guidKey, Value);
}
STDMETHODIMP DeleteItem(REFGUID guidKey)
{
assert(_spAttributes);
return _spAttributes->DeleteItem(guidKey);
}
STDMETHODIMP DeleteAllItems()
{
assert(_spAttributes);
return _spAttributes->DeleteAllItems();
}
STDMETHODIMP SetUINT32(REFGUID guidKey, UINT32 unValue)
{
assert(_spAttributes);
return _spAttributes->SetUINT32(guidKey, unValue);
}
STDMETHODIMP SetUINT64(REFGUID guidKey,UINT64 unValue)
{
assert(_spAttributes);
return _spAttributes->SetUINT64(guidKey, unValue);
}
STDMETHODIMP SetDouble(REFGUID guidKey, double fValue)
{
assert(_spAttributes);
return _spAttributes->SetDouble(guidKey, fValue);
}
STDMETHODIMP SetGUID(REFGUID guidKey, REFGUID guidValue)
{
assert(_spAttributes);
return _spAttributes->SetGUID(guidKey, guidValue);
}
STDMETHODIMP SetString(REFGUID guidKey, LPCWSTR wszValue)
{
assert(_spAttributes);
return _spAttributes->SetString(guidKey, wszValue);
}
STDMETHODIMP SetBlob(REFGUID guidKey, const UINT8* pBuf, UINT32 cbBufSize)
{
assert(_spAttributes);
return _spAttributes->SetBlob(guidKey, pBuf, cbBufSize);
}
STDMETHODIMP SetUnknown(REFGUID guidKey, IUnknown* pUnknown)
{
assert(_spAttributes);
return _spAttributes->SetUnknown(guidKey, pUnknown);
}
STDMETHODIMP LockStore()
{
assert(_spAttributes);
return _spAttributes->LockStore();
}
STDMETHODIMP UnlockStore()
{
assert(_spAttributes);
return _spAttributes->UnlockStore();
}
STDMETHODIMP GetCount(UINT32* pcItems)
{
assert(_spAttributes);
return _spAttributes->GetCount(pcItems);
}
STDMETHODIMP GetItemByIndex(UINT32 unIndex, GUID* pguidKey, PROPVARIANT* pValue)
{
assert(_spAttributes);
return _spAttributes->GetItemByIndex(unIndex, pguidKey, pValue);
}
STDMETHODIMP CopyAllItems(IMFAttributes* pDest)
{
assert(_spAttributes);
return _spAttributes->CopyAllItems(pDest);
}
// Helper functions
HRESULT SerializeToStream(DWORD dwOptions, IStream* pStm)
// dwOptions: Flags from MF_ATTRIBUTE_SERIALIZE_OPTIONS
{
assert(_spAttributes);
return MFSerializeAttributesToStream(_spAttributes.Get(), dwOptions, pStm);
}
HRESULT DeserializeFromStream(DWORD dwOptions, IStream* pStm)
{
assert(_spAttributes);
return MFDeserializeAttributesFromStream(_spAttributes.Get(), dwOptions, pStm);
}
// SerializeToBlob: Stores the attributes in a byte array.
//
// ppBuf: Receives a pointer to the byte array.
// pcbSize: Receives the size of the byte array.
//
// The caller must free the array using CoTaskMemFree.
HRESULT SerializeToBlob(UINT8 **ppBuffer, UINT *pcbSize)
{
assert(_spAttributes);
if (ppBuffer == NULL)
{
return E_POINTER;
}
if (pcbSize == NULL)
{
return E_POINTER;
}
HRESULT hr = S_OK;
UINT32 cbSize = 0;
BYTE *pBuffer = NULL;
CHECK_HR(hr = MFGetAttributesAsBlobSize(_spAttributes.Get(), &cbSize));
pBuffer = (BYTE*)CoTaskMemAlloc(cbSize);
if (pBuffer == NULL)
{
CHECK_HR(hr = E_OUTOFMEMORY);
}
CHECK_HR(hr = MFGetAttributesAsBlob(_spAttributes.Get(), pBuffer, cbSize));
*ppBuffer = pBuffer;
*pcbSize = cbSize;
done:
if (FAILED(hr))
{
*ppBuffer = NULL;
*pcbSize = 0;
CoTaskMemFree(pBuffer);
}
return hr;
}
HRESULT DeserializeFromBlob(const UINT8* pBuffer, UINT cbSize)
{
assert(_spAttributes);
return MFInitAttributesFromBlob(_spAttributes.Get(), pBuffer, cbSize);
}
HRESULT GetRatio(REFGUID guidKey, UINT32* pnNumerator, UINT32* punDenominator)
{
assert(_spAttributes);
return MFGetAttributeRatio(_spAttributes.Get(), guidKey, pnNumerator, punDenominator);
}
HRESULT SetRatio(REFGUID guidKey, UINT32 unNumerator, UINT32 unDenominator)
{
assert(_spAttributes);
return MFSetAttributeRatio(_spAttributes.Get(), guidKey, unNumerator, unDenominator);
}
// Gets an attribute whose value represents the size of something (eg a video frame).
HRESULT GetSize(REFGUID guidKey, UINT32* punWidth, UINT32* punHeight)
{
assert(_spAttributes);
return MFGetAttributeSize(_spAttributes.Get(), guidKey, punWidth, punHeight);
}
// Sets an attribute whose value represents the size of something (eg a video frame).
HRESULT SetSize(REFGUID guidKey, UINT32 unWidth, UINT32 unHeight)
{
assert(_spAttributes);
return MFSetAttributeSize (_spAttributes.Get(), guidKey, unWidth, unHeight);
}
protected:
_ComPtr<IMFAttributes> _spAttributes;
};
class StreamSink :
#ifdef HAVE_WINRT
public Microsoft::WRL::RuntimeClass<
Microsoft::WRL::RuntimeClassFlags< Microsoft::WRL::RuntimeClassType::ClassicCom>,
IMFStreamSink,
IMFMediaEventGenerator,
IMFMediaTypeHandler,
CBaseAttributes<> >
#else
public IMFStreamSink,
public IMFMediaTypeHandler,
public CBaseAttributes<>,
public ICustomStreamSink
#endif
{
public:
// IUnknown methods
#if defined(_MSC_VER) && _MSC_VER >= 1700 // '_Outptr_result_nullonfailure_' SAL is avaialable since VS 2012
STDMETHOD(QueryInterface)(REFIID riid, _Outptr_result_nullonfailure_ void **ppv)
#else
STDMETHOD(QueryInterface)(REFIID riid, void **ppv)
#endif
{
if (ppv == nullptr) {
return E_POINTER;
}
(*ppv) = nullptr;
HRESULT hr = S_OK;
if (riid == IID_IMarshal) {
return MarshalQI(riid, ppv);
} else {
#ifdef HAVE_WINRT
hr = RuntimeClassT::QueryInterface(riid, ppv);
#else
if (riid == IID_IUnknown || riid == IID_IMFStreamSink) {
*ppv = static_cast<IMFStreamSink*>(this);
AddRef();
} else if (riid == IID_IMFMediaEventGenerator) {
*ppv = static_cast<IMFMediaEventGenerator*>(this);
AddRef();
} else if (riid == IID_IMFMediaTypeHandler) {
*ppv = static_cast<IMFMediaTypeHandler*>(this);
AddRef();
} else if (riid == IID_IMFAttributes) {
*ppv = static_cast<IMFAttributes*>(this);
AddRef();
} else if (riid == IID_ICustomStreamSink) {
*ppv = static_cast<ICustomStreamSink*>(this);
AddRef();
} else
hr = E_NOINTERFACE;
#endif
}
return hr;
}
#ifdef HAVE_WINRT
STDMETHOD(RuntimeClassInitialize)() { return S_OK; }
#else
ULONG STDMETHODCALLTYPE AddRef()
{
return InterlockedIncrement(&m_cRef);
}
ULONG STDMETHODCALLTYPE Release()
{
ULONG cRef = InterlockedDecrement(&m_cRef);
if (cRef == 0)
{
delete this;
}
return cRef;
}
#endif
HRESULT MarshalQI(REFIID riid, LPVOID* ppv)
{
HRESULT hr = S_OK;
if (m_spFTM == nullptr) {
EnterCriticalSection(&m_critSec);
if (m_spFTM == nullptr) {
hr = CoCreateFreeThreadedMarshaler((IMFStreamSink*)this, &m_spFTM);
}
LeaveCriticalSection(&m_critSec);
}
if (SUCCEEDED(hr)) {
if (m_spFTM == nullptr) {
hr = E_UNEXPECTED;
}
else {
hr = m_spFTM.Get()->QueryInterface(riid, ppv);
}
}
return hr;
}
enum State
{
State_TypeNotSet = 0, // No media type is set
State_Ready, // Media type is set, Start has never been called.
State_Started,
State_Stopped,
State_Paused,
State_Count // Number of states
};
StreamSink() : m_IsShutdown(false),
m_StartTime(0), m_fGetStartTimeFromSample(false), m_fWaitingForFirstSample(false),
m_state(State_TypeNotSet), m_pParent(nullptr),
m_imageWidthInPixels(0), m_imageHeightInPixels(0) {
#ifdef HAVE_WINRT
m_token.value = 0;
#else
m_bConnected = false;
#endif
InitializeCriticalSectionEx(&m_critSec, 3000, 0);
ZeroMemory(&m_guiCurrentSubtype, sizeof(m_guiCurrentSubtype));
CBaseAttributes::Initialize(0U);
DebugPrintOut(L"StreamSink::StreamSink\n");
}
virtual ~StreamSink() {
DeleteCriticalSection(&m_critSec);
assert(m_IsShutdown);
DebugPrintOut(L"StreamSink::~StreamSink\n");
}
HRESULT Initialize()
{
HRESULT hr;
// Create the event queue helper.
hr = MFCreateEventQueue(&m_spEventQueue);
if (SUCCEEDED(hr))
{
_ComPtr<IMFMediaSink> pMedSink;
hr = CBaseAttributes<>::GetUnknown(MF_STREAMSINK_MEDIASINKINTERFACE, __uuidof(IMFMediaSink), (LPVOID*)pMedSink.GetAddressOf());
assert(pMedSink.Get() != NULL);
if (SUCCEEDED(hr)) {
hr = pMedSink.Get()->QueryInterface(IID_PPV_ARGS(&m_pParent));
}
}
return hr;
}
HRESULT CheckShutdown() const
{
if (m_IsShutdown)
{
return MF_E_SHUTDOWN;
}
else
{
return S_OK;
}
}
// Called when the presentation clock starts.
HRESULT Start(MFTIME start)
{
HRESULT hr = S_OK;
EnterCriticalSection(&m_critSec);
if (m_state != State_TypeNotSet) {
if (start != PRESENTATION_CURRENT_POSITION)
{
m_StartTime = start; // Cache the start time.
m_fGetStartTimeFromSample = false;
}
else
{
m_fGetStartTimeFromSample = true;
}
m_state = State_Started;
GUID guiMajorType;
m_fWaitingForFirstSample = SUCCEEDED(m_spCurrentType->GetMajorType(&guiMajorType)) && (guiMajorType == MFMediaType_Video);
hr = QueueEvent(MEStreamSinkStarted, GUID_NULL, hr, NULL);
if (SUCCEEDED(hr)) {
hr = QueueEvent(MEStreamSinkRequestSample, GUID_NULL, hr, NULL);
}
}
else hr = MF_E_NOT_INITIALIZED;
LeaveCriticalSection(&m_critSec);
return hr;
}
// Called when the presentation clock pauses.
HRESULT Pause()
{
EnterCriticalSection(&m_critSec);
HRESULT hr = S_OK;
if (m_state != State_Stopped && m_state != State_TypeNotSet) {
m_state = State_Paused;
hr = QueueEvent(MEStreamSinkPaused, GUID_NULL, hr, NULL);
} else if (hr == State_TypeNotSet)
hr = MF_E_NOT_INITIALIZED;
else
hr = MF_E_INVALIDREQUEST;
LeaveCriticalSection(&m_critSec);
return hr;
}
// Called when the presentation clock restarts.
HRESULT Restart()
{
EnterCriticalSection(&m_critSec);
HRESULT hr = S_OK;
if (m_state == State_Paused) {
m_state = State_Started;
hr = QueueEvent(MEStreamSinkStarted, GUID_NULL, hr, NULL);
if (SUCCEEDED(hr)) {
hr = QueueEvent(MEStreamSinkRequestSample, GUID_NULL, hr, NULL);
}
} else if (hr == State_TypeNotSet)
hr = MF_E_NOT_INITIALIZED;
else
hr = MF_E_INVALIDREQUEST;
LeaveCriticalSection(&m_critSec);
return hr;
}
// Called when the presentation clock stops.
HRESULT Stop()
{
EnterCriticalSection(&m_critSec);
HRESULT hr = S_OK;
if (m_state != State_TypeNotSet) {
m_state = State_Stopped;
hr = QueueEvent(MEStreamSinkStopped, GUID_NULL, hr, NULL);
}
else hr = MF_E_NOT_INITIALIZED;
LeaveCriticalSection(&m_critSec);
return hr;
}
// Shuts down the stream sink.
HRESULT Shutdown()
{
_ComPtr<IMFSampleGrabberSinkCallback> pSampleCallback;
HRESULT hr = S_OK;
assert(!m_IsShutdown);
hr = m_pParent->GetUnknown(MF_MEDIASINK_SAMPLEGRABBERCALLBACK, IID_IMFSampleGrabberSinkCallback, (LPVOID*)pSampleCallback.GetAddressOf());
if (SUCCEEDED(hr)) {
hr = pSampleCallback->OnShutdown();
}
if (m_spEventQueue) {
hr = m_spEventQueue->Shutdown();
}
if (m_pParent)
m_pParent->Release();
m_spCurrentType.Reset();
m_IsShutdown = TRUE;
return hr;
}
//IMFStreamSink
HRESULT STDMETHODCALLTYPE GetMediaSink(
/* [out] */ __RPC__deref_out_opt IMFMediaSink **ppMediaSink) {
if (ppMediaSink == NULL)
{
return E_INVALIDARG;
}
EnterCriticalSection(&m_critSec);
HRESULT hr = CheckShutdown();
if (SUCCEEDED(hr))
{
_ComPtr<IMFMediaSink> pMedSink;
hr = CBaseAttributes<>::GetUnknown(MF_STREAMSINK_MEDIASINKINTERFACE, __uuidof(IMFMediaSink), (LPVOID*)pMedSink.GetAddressOf());
if (SUCCEEDED(hr)) {
*ppMediaSink = pMedSink.Detach();
}
}
LeaveCriticalSection(&m_critSec);
DebugPrintOut(L"StreamSink::GetMediaSink: HRESULT=%i\n", hr);
return hr;
}
HRESULT STDMETHODCALLTYPE GetIdentifier(
/* [out] */ __RPC__out DWORD *pdwIdentifier) {
if (pdwIdentifier == NULL)
{
return E_INVALIDARG;
}
EnterCriticalSection(&m_critSec);
HRESULT hr = CheckShutdown();
if (SUCCEEDED(hr))
{
hr = GetUINT32(MF_STREAMSINK_ID, (UINT32*)pdwIdentifier);
}
LeaveCriticalSection(&m_critSec);
DebugPrintOut(L"StreamSink::GetIdentifier: HRESULT=%i\n", hr);
return hr;
}
HRESULT STDMETHODCALLTYPE GetMediaTypeHandler(
/* [out] */ __RPC__deref_out_opt IMFMediaTypeHandler **ppHandler) {
if (ppHandler == NULL)
{
return E_INVALIDARG;
}
EnterCriticalSection(&m_critSec);
HRESULT hr = CheckShutdown();
// This stream object acts as its own type handler, so we QI ourselves.
if (SUCCEEDED(hr))
{
hr = QueryInterface(IID_IMFMediaTypeHandler, (void**)ppHandler);
}
LeaveCriticalSection(&m_critSec);
DebugPrintOut(L"StreamSink::GetMediaTypeHandler: HRESULT=%i\n", hr);
return hr;
}
HRESULT STDMETHODCALLTYPE ProcessSample(IMFSample *pSample) {
_ComPtr<IMFMediaBuffer> pInput;
_ComPtr<IMFSampleGrabberSinkCallback> pSampleCallback;
BYTE *pSrc = NULL; // Source buffer.
// Stride if the buffer does not support IMF2DBuffer
LONGLONG hnsTime = 0;
LONGLONG hnsDuration = 0;
DWORD cbMaxLength;
DWORD cbCurrentLength = 0;
GUID guidMajorType;
if (pSample == NULL)
{
return E_INVALIDARG;
}
HRESULT hr = S_OK;
EnterCriticalSection(&m_critSec);
if (m_state != State_Started && m_state != State_Paused) {
if (m_state == State_TypeNotSet)
hr = MF_E_NOT_INITIALIZED;
else
hr = MF_E_INVALIDREQUEST;
}
if (SUCCEEDED(hr))
hr = CheckShutdown();
if (SUCCEEDED(hr)) {
hr = pSample->ConvertToContiguousBuffer(&pInput);
if (SUCCEEDED(hr)) {
hr = pSample->GetSampleTime(&hnsTime);
}
if (SUCCEEDED(hr)) {
hr = pSample->GetSampleDuration(&hnsDuration);
}
if (SUCCEEDED(hr)) {
hr = GetMajorType(&guidMajorType);
}
if (SUCCEEDED(hr)) {
hr = m_pParent->GetUnknown(MF_MEDIASINK_SAMPLEGRABBERCALLBACK, IID_IMFSampleGrabberSinkCallback, (LPVOID*)pSampleCallback.GetAddressOf());
}
if (SUCCEEDED(hr)) {
hr = pInput->Lock(&pSrc, &cbMaxLength, &cbCurrentLength);
}
if (SUCCEEDED(hr)) {
hr = pSampleCallback->OnProcessSample(guidMajorType, 0, hnsTime, hnsDuration, pSrc, cbCurrentLength);
pInput->Unlock();
}
if (SUCCEEDED(hr)) {
hr = QueueEvent(MEStreamSinkRequestSample, GUID_NULL, S_OK, NULL);
}
}
LeaveCriticalSection(&m_critSec);
return hr;
}
HRESULT STDMETHODCALLTYPE PlaceMarker(
/* [in] */ MFSTREAMSINK_MARKER_TYPE eMarkerType,
/* [in] */ __RPC__in const PROPVARIANT * /*pvarMarkerValue*/,
/* [in] */ __RPC__in const PROPVARIANT * /*pvarContextValue*/) {
eMarkerType;
EnterCriticalSection(&m_critSec);
HRESULT hr = S_OK;
if (m_state == State_TypeNotSet)
hr = MF_E_NOT_INITIALIZED;
if (SUCCEEDED(hr))
hr = CheckShutdown();
if (SUCCEEDED(hr))
{
//at shutdown will receive MFSTREAMSINK_MARKER_ENDOFSEGMENT
hr = QueueEvent(MEStreamSinkRequestSample, GUID_NULL, S_OK, NULL);
}
LeaveCriticalSection(&m_critSec);
DebugPrintOut(L"StreamSink::PlaceMarker: HRESULT=%i %s\n", hr, StreamSinkMarkerTypeMap.at(eMarkerType).c_str());
return hr;
}
HRESULT STDMETHODCALLTYPE Flush(void) {
EnterCriticalSection(&m_critSec);
HRESULT hr = CheckShutdown();
if (SUCCEEDED(hr))
{
}
LeaveCriticalSection(&m_critSec);
DebugPrintOut(L"StreamSink::Flush: HRESULT=%i\n", hr);
return hr;
}
//IMFMediaEventGenerator
HRESULT STDMETHODCALLTYPE GetEvent(
DWORD dwFlags, IMFMediaEvent **ppEvent) {
// NOTE:
// GetEvent can block indefinitely, so we don't hold the lock.
// This requires some juggling with the event queue pointer.
HRESULT hr = S_OK;
_ComPtr<IMFMediaEventQueue> pQueue;
{
EnterCriticalSection(&m_critSec);
// Check shutdown
hr = CheckShutdown();
// Get the pointer to the event queue.
if (SUCCEEDED(hr))
{
pQueue = m_spEventQueue.Get();
}
LeaveCriticalSection(&m_critSec);
}
// Now get the event.
if (SUCCEEDED(hr))
{
hr = pQueue->GetEvent(dwFlags, ppEvent);
}
MediaEventType meType = MEUnknown;
if (SUCCEEDED(hr) && SUCCEEDED((*ppEvent)->GetType(&meType)) && meType == MEStreamSinkStopped) {
}
HRESULT hrStatus = S_OK;
if (SUCCEEDED(hr))
hr = (*ppEvent)->GetStatus(&hrStatus);
if (SUCCEEDED(hr))
DebugPrintOut(L"StreamSink::GetEvent: HRESULT=%i %s\n", hrStatus, MediaEventTypeMap.at(meType).c_str());
else
DebugPrintOut(L"StreamSink::GetEvent: HRESULT=%i\n", hr);
return hr;
}
HRESULT STDMETHODCALLTYPE BeginGetEvent(
IMFAsyncCallback *pCallback, IUnknown *punkState) {
HRESULT hr = S_OK;
EnterCriticalSection(&m_critSec);
hr = CheckShutdown();
if (SUCCEEDED(hr))
{
hr = m_spEventQueue->BeginGetEvent(pCallback, punkState);
}
LeaveCriticalSection(&m_critSec);
DebugPrintOut(L"StreamSink::BeginGetEvent: HRESULT=%i\n", hr);
return hr;
}
HRESULT STDMETHODCALLTYPE EndGetEvent(
IMFAsyncResult *pResult, IMFMediaEvent **ppEvent) {
HRESULT hr = S_OK;
EnterCriticalSection(&m_critSec);
hr = CheckShutdown();
if (SUCCEEDED(hr))
{
hr = m_spEventQueue->EndGetEvent(pResult, ppEvent);
}
MediaEventType meType = MEUnknown;
if (SUCCEEDED(hr) && SUCCEEDED((*ppEvent)->GetType(&meType)) && meType == MEStreamSinkStopped) {
}
LeaveCriticalSection(&m_critSec);
HRESULT hrStatus = S_OK;
if (SUCCEEDED(hr))
hr = (*ppEvent)->GetStatus(&hrStatus);
if (SUCCEEDED(hr))
DebugPrintOut(L"StreamSink::EndGetEvent: HRESULT=%i %s\n", hrStatus, MediaEventTypeMap.at(meType).c_str());
else
DebugPrintOut(L"StreamSink::EndGetEvent: HRESULT=%i\n", hr);
return hr;
}
HRESULT STDMETHODCALLTYPE QueueEvent(
MediaEventType met, REFGUID guidExtendedType,
HRESULT hrStatus, const PROPVARIANT *pvValue) {
HRESULT hr = S_OK;
EnterCriticalSection(&m_critSec);
hr = CheckShutdown();
if (SUCCEEDED(hr))
{
hr = m_spEventQueue->QueueEventParamVar(met, guidExtendedType, hrStatus, pvValue);
}
LeaveCriticalSection(&m_critSec);
DebugPrintOut(L"StreamSink::QueueEvent: HRESULT=%i %s\n", hrStatus, MediaEventTypeMap.at(met).c_str());
DebugPrintOut(L"StreamSink::QueueEvent: HRESULT=%i\n", hr);
return hr;
}
/// IMFMediaTypeHandler methods
// Check if a media type is supported.
STDMETHODIMP IsMediaTypeSupported(
/* [in] */ IMFMediaType *pMediaType,
/* [out] */ IMFMediaType **ppMediaType)
{
if (pMediaType == nullptr)
{
return E_INVALIDARG;
}
EnterCriticalSection(&m_critSec);
GUID majorType = GUID_NULL;
HRESULT hr = CheckShutdown();
if (SUCCEEDED(hr))
{
hr = pMediaType->GetGUID(MF_MT_MAJOR_TYPE, &majorType);
}
// First make sure it's video or audio type.
if (SUCCEEDED(hr))
{
if (majorType != MFMediaType_Video && majorType != MFMediaType_Audio)
{
hr = MF_E_INVALIDTYPE;
}
}
if (SUCCEEDED(hr) && m_spCurrentType != nullptr)
{
GUID guiNewSubtype;
if (FAILED(pMediaType->GetGUID(MF_MT_SUBTYPE, &guiNewSubtype)) ||
guiNewSubtype != m_guiCurrentSubtype)
{
hr = MF_E_INVALIDTYPE;
}
}
// We don't return any "close match" types.
if (ppMediaType)
{
*ppMediaType = nullptr;
}
if (ppMediaType && SUCCEEDED(hr)) {
_ComPtr<IMFMediaType> pType;
hr = MFCreateMediaType(ppMediaType);
if (SUCCEEDED(hr)) {
hr = m_pParent->GetUnknown(MF_MEDIASINK_PREFERREDTYPE, __uuidof(IMFMediaType), (LPVOID*)&pType);
}
if (SUCCEEDED(hr)) {
hr = pType->LockStore();
}
bool bLocked = false;
if (SUCCEEDED(hr)) {
bLocked = true;
UINT32 uiCount;
UINT32 uiTotal;
hr = pType->GetCount(&uiTotal);
for (uiCount = 0; SUCCEEDED(hr) && uiCount < uiTotal; uiCount++) {
GUID guid;
PROPVARIANT propval;
hr = pType->GetItemByIndex(uiCount, &guid, &propval);
if (SUCCEEDED(hr) && (guid == MF_MT_FRAME_SIZE || guid == MF_MT_MAJOR_TYPE || guid == MF_MT_PIXEL_ASPECT_RATIO ||
guid == MF_MT_ALL_SAMPLES_INDEPENDENT || guid == MF_MT_INTERLACE_MODE || guid == MF_MT_SUBTYPE)) {
hr = (*ppMediaType)->SetItem(guid, propval);
PropVariantClear(&propval);
}
}
}
if (bLocked) {
hr = pType->UnlockStore();
}
}
LeaveCriticalSection(&m_critSec);
DebugPrintOut(L"StreamSink::IsMediaTypeSupported: HRESULT=%i\n", hr);
return hr;
}
// Return the number of preferred media types.
STDMETHODIMP GetMediaTypeCount(DWORD *pdwTypeCount)
{
if (pdwTypeCount == nullptr)
{
return E_INVALIDARG;
}
EnterCriticalSection(&m_critSec);
HRESULT hr = CheckShutdown();
if (SUCCEEDED(hr))
{
// We've got only one media type
*pdwTypeCount = 1;
}
LeaveCriticalSection(&m_critSec);
DebugPrintOut(L"StreamSink::GetMediaTypeCount: HRESULT=%i\n", hr);
return hr;
}
// Return a preferred media type by index.
STDMETHODIMP GetMediaTypeByIndex(
/* [in] */ DWORD dwIndex,
/* [out] */ IMFMediaType **ppType)
{
if (ppType == NULL) {
return E_INVALIDARG;
}
EnterCriticalSection(&m_critSec);
HRESULT hr = CheckShutdown();
if (dwIndex > 0)
{
hr = MF_E_NO_MORE_TYPES;
} else {
//return preferred type based on media capture library 6 elements preferred preview type
//hr = m_spCurrentType.CopyTo(ppType);
if (SUCCEEDED(hr)) {
_ComPtr<IMFMediaType> pType;
hr = MFCreateMediaType(ppType);
if (SUCCEEDED(hr)) {
hr = m_pParent->GetUnknown(MF_MEDIASINK_PREFERREDTYPE, __uuidof(IMFMediaType), (LPVOID*)&pType);
}
if (SUCCEEDED(hr)) {
hr = pType->LockStore();
}
bool bLocked = false;
if (SUCCEEDED(hr)) {
bLocked = true;
UINT32 uiCount;
UINT32 uiTotal;
hr = pType->GetCount(&uiTotal);
for (uiCount = 0; SUCCEEDED(hr) && uiCount < uiTotal; uiCount++) {
GUID guid;
PROPVARIANT propval;
hr = pType->GetItemByIndex(uiCount, &guid, &propval);
if (SUCCEEDED(hr) && (guid == MF_MT_FRAME_SIZE || guid == MF_MT_MAJOR_TYPE || guid == MF_MT_PIXEL_ASPECT_RATIO ||
guid == MF_MT_ALL_SAMPLES_INDEPENDENT || guid == MF_MT_INTERLACE_MODE || guid == MF_MT_SUBTYPE)) {
hr = (*ppType)->SetItem(guid, propval);
PropVariantClear(&propval);
}
}
}
if (bLocked) {
hr = pType->UnlockStore();
}
}
}
LeaveCriticalSection(&m_critSec);
DebugPrintOut(L"StreamSink::GetMediaTypeByIndex: HRESULT=%i\n", hr);
return hr;
}
// Set the current media type.
STDMETHODIMP SetCurrentMediaType(IMFMediaType *pMediaType)
{
if (pMediaType == NULL) {
return E_INVALIDARG;
}
EnterCriticalSection(&m_critSec);
HRESULT hr = S_OK;
if (m_state != State_TypeNotSet && m_state != State_Ready)
hr = MF_E_INVALIDREQUEST;
if (SUCCEEDED(hr))
hr = CheckShutdown();
// We don't allow format changes after streaming starts.
// We set media type already
if (m_state >= State_Ready)
{
if (SUCCEEDED(hr))
{
hr = IsMediaTypeSupported(pMediaType, NULL);
}
}
if (SUCCEEDED(hr))
{
hr = MFCreateMediaType(m_spCurrentType.ReleaseAndGetAddressOf());
if (SUCCEEDED(hr))
{
hr = pMediaType->CopyAllItems(m_spCurrentType.Get());
}
if (SUCCEEDED(hr))
{
hr = m_spCurrentType->GetGUID(MF_MT_SUBTYPE, &m_guiCurrentSubtype);
}
GUID guid;
if (SUCCEEDED(hr)) {
hr = m_spCurrentType->GetMajorType(&guid);
}
if (SUCCEEDED(hr) && guid == MFMediaType_Video) {
hr = MFGetAttributeSize(m_spCurrentType.Get(), MF_MT_FRAME_SIZE, &m_imageWidthInPixels, &m_imageHeightInPixels);
}
if (SUCCEEDED(hr))
{
m_state = State_Ready;
}
}
LeaveCriticalSection(&m_critSec);
DebugPrintOut(L"StreamSink::SetCurrentMediaType: HRESULT=%i\n", hr);
return hr;
}
// Return the current media type, if any.
STDMETHODIMP GetCurrentMediaType(IMFMediaType **ppMediaType)
{
if (ppMediaType == NULL) {
return E_INVALIDARG;
}
EnterCriticalSection(&m_critSec);
HRESULT hr = CheckShutdown();
if (SUCCEEDED(hr)) {
if (m_spCurrentType == nullptr) {
hr = MF_E_NOT_INITIALIZED;
}
}
if (SUCCEEDED(hr)) {
hr = m_spCurrentType.CopyTo(ppMediaType);
}
LeaveCriticalSection(&m_critSec);
DebugPrintOut(L"StreamSink::GetCurrentMediaType: HRESULT=%i\n", hr);
return hr;
}
// Return the major type GUID.
STDMETHODIMP GetMajorType(GUID *pguidMajorType)
{
HRESULT hr;
if (pguidMajorType == nullptr) {
return E_INVALIDARG;
}
_ComPtr<IMFMediaType> pType;
hr = m_pParent->GetUnknown(MF_MEDIASINK_PREFERREDTYPE, __uuidof(IMFMediaType), (LPVOID*)&pType);
if (SUCCEEDED(hr)) {
hr = pType->GetMajorType(pguidMajorType);
}
DebugPrintOut(L"StreamSink::GetMajorType: HRESULT=%i\n", hr);
return hr;
}
private:
#ifdef HAVE_WINRT
EventRegistrationToken m_token;
#else
bool m_bConnected;
#endif
bool m_IsShutdown; // Flag to indicate if Shutdown() method was called.
CRITICAL_SECTION m_critSec;
#ifndef HAVE_WINRT
long m_cRef;
#endif
IMFAttributes* m_pParent;
_ComPtr<IMFMediaType> m_spCurrentType;
_ComPtr<IMFMediaEventQueue> m_spEventQueue; // Event queue
_ComPtr<IUnknown> m_spFTM;
State m_state;
bool m_fGetStartTimeFromSample;
bool m_fWaitingForFirstSample;
MFTIME m_StartTime; // Presentation time when the clock started.
GUID m_guiCurrentSubtype;
UINT32 m_imageWidthInPixels;
UINT32 m_imageHeightInPixels;
};
// Notes:
//
// The List class template implements a simple double-linked list.
// It uses STL's copy semantics.
// There are two versions of the Clear() method:
// Clear(void) clears the list w/out cleaning up the object.
// Clear(FN fn) takes a functor object that releases the objects, if they need cleanup.
// The List class supports enumeration. Example of usage:
//
// List<T>::POSIITON pos = list.GetFrontPosition();
// while (pos != list.GetEndPosition())
// {
// T item;
// hr = list.GetItemPos(&item);
// pos = list.Next(pos);
// }
// The ComPtrList class template derives from List<> and implements a list of COM pointers.
template <class T>
struct NoOp
{
void operator()(T& /*t*/)
{
}
};
template <class T>
class List
{
protected:
// Nodes in the linked list
struct Node
{
Node *prev;
Node *next;
T item;
Node() : prev(nullptr), next(nullptr)
{
}
Node(T item) : prev(nullptr), next(nullptr)
{
this->item = item;
}
T Item() const { return item; }
};
public:
// Object for enumerating the list.
class POSITION
{
friend class List<T>;
public:
POSITION() : pNode(nullptr)
{
}
bool operator==(const POSITION &p) const
{
return pNode == p.pNode;
}
bool operator!=(const POSITION &p) const
{
return pNode != p.pNode;
}
private:
const Node *pNode;
POSITION(Node *p) : pNode(p)
{
}
};
protected:
Node m_anchor; // Anchor node for the linked list.
DWORD m_count; // Number of items in the list.
Node* Front() const
{
return m_anchor.next;
}
Node* Back() const
{
return m_anchor.prev;
}
virtual HRESULT InsertAfter(T item, Node *pBefore)
{
if (pBefore == nullptr)
{
return E_POINTER;
}
Node *pNode = new Node(item);
if (pNode == nullptr)
{
return E_OUTOFMEMORY;
}
Node *pAfter = pBefore->next;
pBefore->next = pNode;
pAfter->prev = pNode;
pNode->prev = pBefore;
pNode->next = pAfter;
m_count++;
return S_OK;
}
virtual HRESULT GetItem(const Node *pNode, T* ppItem)
{
if (pNode == nullptr || ppItem == nullptr)
{
return E_POINTER;
}
*ppItem = pNode->item;
return S_OK;
}
// RemoveItem:
// Removes a node and optionally returns the item.
// ppItem can be nullptr.
virtual HRESULT RemoveItem(Node *pNode, T *ppItem)
{
if (pNode == nullptr)
{
return E_POINTER;
}
assert(pNode != &m_anchor); // We should never try to remove the anchor node.
if (pNode == &m_anchor)
{
return E_INVALIDARG;
}
T item;
// The next node's previous is this node's previous.
pNode->next->prev = pNode->prev;
// The previous node's next is this node's next.
pNode->prev->next = pNode->next;
item = pNode->item;
delete pNode;
m_count--;
if (ppItem)
{
*ppItem = item;
}
return S_OK;
}
public:
List()
{
m_anchor.next = &m_anchor;
m_anchor.prev = &m_anchor;
m_count = 0;
}
virtual ~List()
{
Clear();
}
// Insertion functions
HRESULT InsertBack(T item)
{
return InsertAfter(item, m_anchor.prev);
}
HRESULT InsertFront(T item)
{
return InsertAfter(item, &m_anchor);
}
HRESULT InsertPos(POSITION pos, T item)
{
if (pos.pNode == nullptr)
{
return InsertBack(item);
}
return InsertAfter(item, pos.pNode->prev);
}
// RemoveBack: Removes the tail of the list and returns the value.
// ppItem can be nullptr if you don't want the item back. (But the method does not release the item.)
HRESULT RemoveBack(T *ppItem)
{
if (IsEmpty())
{
return E_FAIL;
}
else
{
return RemoveItem(Back(), ppItem);
}
}
// RemoveFront: Removes the head of the list and returns the value.
// ppItem can be nullptr if you don't want the item back. (But the method does not release the item.)
HRESULT RemoveFront(T *ppItem)
{
if (IsEmpty())
{
return E_FAIL;
}
else
{
return RemoveItem(Front(), ppItem);
}
}
// GetBack: Gets the tail item.
HRESULT GetBack(T *ppItem)
{
if (IsEmpty())
{
return E_FAIL;
}
else
{
return GetItem(Back(), ppItem);
}
}
// GetFront: Gets the front item.
HRESULT GetFront(T *ppItem)
{
if (IsEmpty())
{
return E_FAIL;
}
else
{
return GetItem(Front(), ppItem);
}
}
// GetCount: Returns the number of items in the list.
DWORD GetCount() const { return m_count; }
bool IsEmpty() const
{
return (GetCount() == 0);
}
// Clear: Takes a functor object whose operator()
// frees the object on the list.
template <class FN>
void Clear(FN& clear_fn)
{
Node *n = m_anchor.next;
// Delete the nodes
while (n != &m_anchor)
{
clear_fn(n->item);
Node *tmp = n->next;
delete n;
n = tmp;
}
// Reset the anchor to point at itself
m_anchor.next = &m_anchor;
m_anchor.prev = &m_anchor;
m_count = 0;
}
// Clear: Clears the list. (Does not delete or release the list items.)
virtual void Clear()
{
NoOp<T> clearOp;
Clear<>(clearOp);
}
// Enumerator functions
POSITION FrontPosition()
{
if (IsEmpty())
{
return POSITION(nullptr);
}
else
{
return POSITION(Front());
}
}
POSITION EndPosition() const
{
return POSITION();
}
HRESULT GetItemPos(POSITION pos, T *ppItem)
{
if (pos.pNode)
{
return GetItem(pos.pNode, ppItem);
}
else
{
return E_FAIL;
}
}
POSITION Next(const POSITION pos)
{
if (pos.pNode && (pos.pNode->next != &m_anchor))
{
return POSITION(pos.pNode->next);
}
else
{
return POSITION(nullptr);
}
}
// Remove an item at a position.
// The item is returns in ppItem, unless ppItem is nullptr.
// NOTE: This method invalidates the POSITION object.
HRESULT Remove(POSITION& pos, T *ppItem)
{
if (pos.pNode)
{
// Remove const-ness temporarily...
Node *pNode = const_cast<Node*>(pos.pNode);
pos = POSITION();
return RemoveItem(pNode, ppItem);
}
else
{
return E_INVALIDARG;
}
}
};
// Typical functors for Clear method.
// ComAutoRelease: Releases COM pointers.
// MemDelete: Deletes pointers to new'd memory.
class ComAutoRelease
{
public:
void operator()(IUnknown *p)
{
if (p)
{
p->Release();
}
}
};
class MemDelete
{
public:
void operator()(void *p)
{
if (p)
{
delete p;
}
}
};
// ComPtrList class
// Derived class that makes it safer to store COM pointers in the List<> class.
// It automatically AddRef's the pointers that are inserted onto the list
// (unless the insertion method fails).
//
// T must be a COM interface type.
// example: ComPtrList<IUnknown>
//
// NULLABLE: If true, client can insert nullptr pointers. This means GetItem can
// succeed but return a nullptr pointer. By default, the list does not allow nullptr
// pointers.
#ifdef _MSC_VER
#pragma warning(push)
#pragma warning(disable: 4127) // constant expression
#endif
template <class T, bool NULLABLE = FALSE>
class ComPtrList : public List<T*>
{
public:
typedef T* Ptr;
void Clear()
{
ComAutoRelease car;
List<Ptr>::Clear(car);
}
~ComPtrList()
{
Clear();
}
protected:
HRESULT InsertAfter(Ptr item, Node *pBefore)
{
// Do not allow nullptr item pointers unless NULLABLE is true.
if (item == nullptr && !NULLABLE)
{
return E_POINTER;
}
if (item)
{
item->AddRef();
}
HRESULT hr = List<Ptr>::InsertAfter(item, pBefore);
if (FAILED(hr) && item != nullptr)
{
item->Release();
}
return hr;
}
HRESULT GetItem(const Node *pNode, Ptr* ppItem)
{
Ptr pItem = nullptr;
// The base class gives us the pointer without AddRef'ing it.
// If we return the pointer to the caller, we must AddRef().
HRESULT hr = List<Ptr>::GetItem(pNode, &pItem);
if (SUCCEEDED(hr))
{
assert(pItem || NULLABLE);
if (pItem)
{
*ppItem = pItem;
(*ppItem)->AddRef();
}
}
return hr;
}
HRESULT RemoveItem(Node *pNode, Ptr *ppItem)
{
// ppItem can be nullptr, but we need to get the
// item so that we can release it.
// If ppItem is not nullptr, we will AddRef it on the way out.
Ptr pItem = nullptr;
HRESULT hr = List<Ptr>::RemoveItem(pNode, &pItem);
if (SUCCEEDED(hr))
{
assert(pItem || NULLABLE);
if (ppItem && pItem)
{
*ppItem = pItem;
(*ppItem)->AddRef();
}
if (pItem)
{
pItem->Release();
pItem = nullptr;
}
}
return hr;
}
};
#ifdef _MSC_VER
#pragma warning(pop)
#endif
/* Be sure to declare webcam device capability in manifest
For better media capture support, add the following snippet with correct module name to the project manifest
(highgui needs DLL activation class factoryentry points):
<Extensions>
<Extension Category="windows.activatableClass.inProcessServer">
<InProcessServer>
<Path>modulename</Path>
<ActivatableClass ActivatableClassId="cv.MediaSink" ThreadingModel="both" />
</InProcessServer>
</Extension>
</Extensions>*/
extern const __declspec(selectany) WCHAR RuntimeClass_CV_MediaSink[] = L"cv.MediaSink";
class MediaSink :
#ifdef HAVE_WINRT
public Microsoft::WRL::RuntimeClass<
Microsoft::WRL::RuntimeClassFlags< Microsoft::WRL::RuntimeClassType::WinRtClassicComMix >,
Microsoft::WRL::Implements<ABI::Windows::Media::IMediaExtension>,
IMFMediaSink,
IMFClockStateSink,
Microsoft::WRL::FtmBase,
CBaseAttributes<>>
#else
public IMFMediaSink, public IMFClockStateSink, public CBaseAttributes<>
#endif
{
#ifdef HAVE_WINRT
InspectableClass(RuntimeClass_CV_MediaSink, BaseTrust)
public:
#else
public:
ULONG STDMETHODCALLTYPE AddRef()
{
return InterlockedIncrement(&m_cRef);
}
ULONG STDMETHODCALLTYPE Release()
{
ULONG cRef = InterlockedDecrement(&m_cRef);
if (cRef == 0)
{
delete this;
}
return cRef;
}
#if defined(_MSC_VER) && _MSC_VER >= 1700 // '_Outptr_result_nullonfailure_' SAL is avaialable since VS 2012
STDMETHOD(QueryInterface)(REFIID riid, _Outptr_result_nullonfailure_ void **ppv)
#else
STDMETHOD(QueryInterface)(REFIID riid, void **ppv)
#endif
{
if (ppv == nullptr) {
return E_POINTER;
}
(*ppv) = nullptr;
HRESULT hr = S_OK;
if (riid == IID_IUnknown ||
riid == IID_IMFMediaSink) {
(*ppv) = static_cast<IMFMediaSink*>(this);
AddRef();
} else if (riid == IID_IMFClockStateSink) {
(*ppv) = static_cast<IMFClockStateSink*>(this);
AddRef();
} else if (riid == IID_IMFAttributes) {
(*ppv) = static_cast<IMFAttributes*>(this);
AddRef();
} else {
hr = E_NOINTERFACE;
}
return hr;
}
#endif
MediaSink() : m_IsShutdown(false), m_llStartTime(0) {
CBaseAttributes<>::Initialize(0U);
InitializeCriticalSectionEx(&m_critSec, 3000, 0);
DebugPrintOut(L"MediaSink::MediaSink\n");
}
virtual ~MediaSink() {
DebugPrintOut(L"MediaSink::~MediaSink\n");
DeleteCriticalSection(&m_critSec);
assert(m_IsShutdown);
}
HRESULT CheckShutdown() const
{
if (m_IsShutdown)
{
return MF_E_SHUTDOWN;
}
else
{
return S_OK;
}
}
#ifdef HAVE_WINRT
STDMETHODIMP SetProperties(ABI::Windows::Foundation::Collections::IPropertySet *pConfiguration)
{
HRESULT hr = S_OK;
if (pConfiguration) {
Microsoft::WRL::ComPtr<IInspectable> spInsp;
Microsoft::WRL::ComPtr<ABI::Windows::Foundation::Collections::IMap<HSTRING, IInspectable *>> spSetting;
Microsoft::WRL::ComPtr<ABI::Windows::Foundation::IPropertyValue> spPropVal;
Microsoft::WRL::ComPtr<ABI::Windows::Media::MediaProperties::IMediaEncodingProperties> pMedEncProps;
UINT32 uiType = ABI::Windows::Media::Capture::MediaStreamType_VideoPreview;
hr = pConfiguration->QueryInterface(IID_PPV_ARGS(&spSetting));
if (FAILED(hr)) {
hr = E_FAIL;
}
if (SUCCEEDED(hr)) {
hr = spSetting->Lookup(Microsoft::WRL::Wrappers::HStringReference(MF_PROP_SAMPLEGRABBERCALLBACK).Get(), spInsp.ReleaseAndGetAddressOf());
if (FAILED(hr)) {
hr = E_INVALIDARG;
}
if (SUCCEEDED(hr)) {
hr = SetUnknown(MF_MEDIASINK_SAMPLEGRABBERCALLBACK, spInsp.Get());
}
}
if (SUCCEEDED(hr)) {
hr = spSetting->Lookup(Microsoft::WRL::Wrappers::HStringReference(MF_PROP_VIDTYPE).Get(), spInsp.ReleaseAndGetAddressOf());
if (FAILED(hr)) {
hr = E_INVALIDARG;
}
if (SUCCEEDED(hr)) {
if (SUCCEEDED(hr = spInsp.As(&spPropVal))) {
hr = spPropVal->GetUInt32(&uiType);
}
}
}
if (SUCCEEDED(hr)) {
hr = spSetting->Lookup(Microsoft::WRL::Wrappers::HStringReference(MF_PROP_VIDENCPROPS).Get(), spInsp.ReleaseAndGetAddressOf());
if (FAILED(hr)) {
hr = E_INVALIDARG;
}
if (SUCCEEDED(hr)) {
hr = spInsp.As(&pMedEncProps);
}
}
if (SUCCEEDED(hr)) {
hr = SetMediaStreamProperties((ABI::Windows::Media::Capture::MediaStreamType)uiType, pMedEncProps.Get());
}
}
return hr;
}
static DWORD GetStreamId(ABI::Windows::Media::Capture::MediaStreamType mediaStreamType)
{
return 3 - mediaStreamType;
}
static HRESULT AddAttribute(_In_ GUID guidKey, _In_ ABI::Windows::Foundation::IPropertyValue *pValue, _In_ IMFAttributes* pAttr)
{
HRESULT hr = S_OK;
PROPVARIANT var;
ABI::Windows::Foundation::PropertyType type;
hr = pValue->get_Type(&type);
ZeroMemory(&var, sizeof(var));
if (SUCCEEDED(hr))
{
switch (type)
{
case ABI::Windows::Foundation::PropertyType_UInt8Array:
{
UINT32 cbBlob;
BYTE *pbBlog = nullptr;
hr = pValue->GetUInt8Array(&cbBlob, &pbBlog);
if (SUCCEEDED(hr))
{
if (pbBlog == nullptr)
{
hr = E_INVALIDARG;
}
else
{
hr = pAttr->SetBlob(guidKey, pbBlog, cbBlob);
}
}
CoTaskMemFree(pbBlog);
}
break;
case ABI::Windows::Foundation::PropertyType_Double:
{
DOUBLE value;
hr = pValue->GetDouble(&value);
if (SUCCEEDED(hr))
{
hr = pAttr->SetDouble(guidKey, value);
}
}
break;
case ABI::Windows::Foundation::PropertyType_Guid:
{
GUID value;
hr = pValue->GetGuid(&value);
if (SUCCEEDED(hr))
{
hr = pAttr->SetGUID(guidKey, value);
}
}
break;
case ABI::Windows::Foundation::PropertyType_String:
{
Microsoft::WRL::Wrappers::HString value;
hr = pValue->GetString(value.GetAddressOf());
if (SUCCEEDED(hr))
{
UINT32 len = 0;
LPCWSTR szValue = WindowsGetStringRawBuffer(value.Get(), &len);
hr = pAttr->SetString(guidKey, szValue);
}
}
break;
case ABI::Windows::Foundation::PropertyType_UInt32:
{
UINT32 value;
hr = pValue->GetUInt32(&value);
if (SUCCEEDED(hr))
{
pAttr->SetUINT32(guidKey, value);
}
}
break;
case ABI::Windows::Foundation::PropertyType_UInt64:
{
UINT64 value;
hr = pValue->GetUInt64(&value);
if (SUCCEEDED(hr))
{
hr = pAttr->SetUINT64(guidKey, value);
}
}
break;
case ABI::Windows::Foundation::PropertyType_Inspectable:
{
Microsoft::WRL::ComPtr<IInspectable> value;
hr = TYPE_E_TYPEMISMATCH;
if (SUCCEEDED(hr))
{
pAttr->SetUnknown(guidKey, value.Get());
}
}
break;
// ignore unknown values
}
}
return hr;
}
static HRESULT ConvertPropertiesToMediaType(_In_ ABI::Windows::Media::MediaProperties::IMediaEncodingProperties *pMEP, _Outptr_ IMFMediaType **ppMT)
{
HRESULT hr = S_OK;
_ComPtr<IMFMediaType> spMT;
Microsoft::WRL::ComPtr<ABI::Windows::Foundation::Collections::IMap<GUID, IInspectable*>> spMap;
Microsoft::WRL::ComPtr<ABI::Windows::Foundation::Collections::IIterable<ABI::Windows::Foundation::Collections::IKeyValuePair<GUID, IInspectable*>*>> spIterable;
Microsoft::WRL::ComPtr<ABI::Windows::Foundation::Collections::IIterator<ABI::Windows::Foundation::Collections::IKeyValuePair<GUID, IInspectable*>*>> spIterator;
if (pMEP == nullptr || ppMT == nullptr)
{
return E_INVALIDARG;
}
*ppMT = nullptr;
hr = pMEP->get_Properties(spMap.GetAddressOf());
if (SUCCEEDED(hr))
{
hr = spMap.As(&spIterable);
}
if (SUCCEEDED(hr))
{
hr = spIterable->First(&spIterator);
}
if (SUCCEEDED(hr))
{
MFCreateMediaType(spMT.ReleaseAndGetAddressOf());
}
boolean hasCurrent = false;
if (SUCCEEDED(hr))
{
hr = spIterator->get_HasCurrent(&hasCurrent);
}
while (hasCurrent)
{
Microsoft::WRL::ComPtr<ABI::Windows::Foundation::Collections::IKeyValuePair<GUID, IInspectable*> > spKeyValuePair;
Microsoft::WRL::ComPtr<IInspectable> spValue;
Microsoft::WRL::ComPtr<ABI::Windows::Foundation::IPropertyValue> spPropValue;
GUID guidKey;
hr = spIterator->get_Current(&spKeyValuePair);
if (FAILED(hr))
{
break;
}
hr = spKeyValuePair->get_Key(&guidKey);
if (FAILED(hr))
{
break;
}
hr = spKeyValuePair->get_Value(&spValue);
if (FAILED(hr))
{
break;
}
hr = spValue.As(&spPropValue);
if (FAILED(hr))
{
break;
}
hr = AddAttribute(guidKey, spPropValue.Get(), spMT.Get());
if (FAILED(hr))
{
break;
}
hr = spIterator->MoveNext(&hasCurrent);
if (FAILED(hr))
{
break;
}
}
if (SUCCEEDED(hr))
{
Microsoft::WRL::ComPtr<IInspectable> spValue;
Microsoft::WRL::ComPtr<ABI::Windows::Foundation::IPropertyValue> spPropValue;
GUID guiMajorType;
hr = spMap->Lookup(MF_MT_MAJOR_TYPE, spValue.GetAddressOf());
if (SUCCEEDED(hr))
{
hr = spValue.As(&spPropValue);
}
if (SUCCEEDED(hr))
{
hr = spPropValue->GetGuid(&guiMajorType);
}
if (SUCCEEDED(hr))
{
if (guiMajorType != MFMediaType_Video && guiMajorType != MFMediaType_Audio)
{
hr = E_UNEXPECTED;
}
}
}
if (SUCCEEDED(hr))
{
*ppMT = spMT.Detach();
}
return hr;
}
//this should be passed through SetProperties!
HRESULT SetMediaStreamProperties(ABI::Windows::Media::Capture::MediaStreamType MediaStreamType,
_In_opt_ ABI::Windows::Media::MediaProperties::IMediaEncodingProperties *mediaEncodingProperties)
{
HRESULT hr = S_OK;
_ComPtr<IMFMediaType> spMediaType;
if (MediaStreamType != ABI::Windows::Media::Capture::MediaStreamType_VideoPreview &&
MediaStreamType != ABI::Windows::Media::Capture::MediaStreamType_VideoRecord &&
MediaStreamType != ABI::Windows::Media::Capture::MediaStreamType_Audio)
{
return E_INVALIDARG;
}
RemoveStreamSink(GetStreamId(MediaStreamType));
if (mediaEncodingProperties != nullptr)
{
_ComPtr<IMFStreamSink> spStreamSink;
hr = ConvertPropertiesToMediaType(mediaEncodingProperties, &spMediaType);
if (SUCCEEDED(hr))
{
hr = AddStreamSink(GetStreamId(MediaStreamType), nullptr, spStreamSink.GetAddressOf());
}
if (SUCCEEDED(hr)) {
hr = SetUnknown(MF_MEDIASINK_PREFERREDTYPE, spMediaType.Detach());
}
}
return hr;
}
#endif
//IMFMediaSink
HRESULT STDMETHODCALLTYPE GetCharacteristics(
/* [out] */ __RPC__out DWORD *pdwCharacteristics) {
HRESULT hr;
if (pdwCharacteristics == NULL) return E_INVALIDARG;
EnterCriticalSection(&m_critSec);
if (SUCCEEDED(hr = CheckShutdown())) {
//if had an activation object for the sink, shut down would be managed and MF_STREAM_SINK_SUPPORTS_ROTATION appears to be setable to TRUE
*pdwCharacteristics = MEDIASINK_FIXED_STREAMS;// | MEDIASINK_REQUIRE_REFERENCE_MEDIATYPE;
}
LeaveCriticalSection(&m_critSec);
DebugPrintOut(L"MediaSink::GetCharacteristics: HRESULT=%i\n", hr);
return hr;
}
HRESULT STDMETHODCALLTYPE AddStreamSink(
DWORD dwStreamSinkIdentifier, IMFMediaType * /*pMediaType*/, IMFStreamSink **ppStreamSink) {
_ComPtr<IMFStreamSink> spMFStream;
_ComPtr<ICustomStreamSink> pStream;
EnterCriticalSection(&m_critSec);
HRESULT hr = CheckShutdown();
if (SUCCEEDED(hr))
{
hr = GetStreamSinkById(dwStreamSinkIdentifier, &spMFStream);
}
if (SUCCEEDED(hr))
{
hr = MF_E_STREAMSINK_EXISTS;
}
else
{
hr = S_OK;
}
if (SUCCEEDED(hr))
{
#ifdef HAVE_WINRT
pStream = Microsoft::WRL::Make<StreamSink>();
if (pStream == nullptr) {
hr = E_OUTOFMEMORY;
}
if (SUCCEEDED(hr))
hr = pStream.As<IMFStreamSink>(&spMFStream);
#else
StreamSink* pSink = new StreamSink();
if (pSink) {
hr = pSink->QueryInterface(IID_IMFStreamSink, (void**)spMFStream.GetAddressOf());
if (SUCCEEDED(hr)) {
hr = spMFStream.As(&pStream);
}
if (FAILED(hr)) delete pSink;
}
#endif
}
// Initialize the stream.
_ComPtr<IMFAttributes> pAttr;
if (SUCCEEDED(hr)) {
hr = pStream.As(&pAttr);
}
if (SUCCEEDED(hr)) {
hr = pAttr->SetUINT32(MF_STREAMSINK_ID, dwStreamSinkIdentifier);
if (SUCCEEDED(hr)) {
hr = pAttr->SetUnknown(MF_STREAMSINK_MEDIASINKINTERFACE, (IMFMediaSink*)this);
}
}
if (SUCCEEDED(hr)) {
hr = pStream->Initialize();
}
if (SUCCEEDED(hr))
{
ComPtrList<IMFStreamSink>::POSITION pos = m_streams.FrontPosition();
ComPtrList<IMFStreamSink>::POSITION posEnd = m_streams.EndPosition();
// Insert in proper position
for (; pos != posEnd; pos = m_streams.Next(pos))
{
DWORD dwCurrId;
_ComPtr<IMFStreamSink> spCurr;
hr = m_streams.GetItemPos(pos, &spCurr);
if (FAILED(hr))
{
break;
}
hr = spCurr->GetIdentifier(&dwCurrId);
if (FAILED(hr))
{
break;
}
if (dwCurrId > dwStreamSinkIdentifier)
{
break;
}
}
if (SUCCEEDED(hr))
{
hr = m_streams.InsertPos(pos, spMFStream.Get());
}
}
if (SUCCEEDED(hr))
{
*ppStreamSink = spMFStream.Detach();
}
LeaveCriticalSection(&m_critSec);
DebugPrintOut(L"MediaSink::AddStreamSink: HRESULT=%i\n", hr);
return hr;
}
HRESULT STDMETHODCALLTYPE RemoveStreamSink(DWORD dwStreamSinkIdentifier) {
EnterCriticalSection(&m_critSec);
HRESULT hr = CheckShutdown();
ComPtrList<IMFStreamSink>::POSITION pos = m_streams.FrontPosition();
ComPtrList<IMFStreamSink>::POSITION endPos = m_streams.EndPosition();
_ComPtr<IMFStreamSink> spStream;
if (SUCCEEDED(hr))
{
for (; pos != endPos; pos = m_streams.Next(pos))
{
hr = m_streams.GetItemPos(pos, &spStream);
DWORD dwId;
if (FAILED(hr))
{
break;
}
hr = spStream->GetIdentifier(&dwId);
if (FAILED(hr) || dwId == dwStreamSinkIdentifier)
{
break;
}
}
if (pos == endPos)
{
hr = MF_E_INVALIDSTREAMNUMBER;
}
}
if (SUCCEEDED(hr))
{
hr = m_streams.Remove(pos, nullptr);
_ComPtr<ICustomStreamSink> spCustomSink;
#ifdef HAVE_WINRT
spCustomSink = static_cast<StreamSink*>(spStream.Get());
hr = S_OK;
#else
hr = spStream.As(&spCustomSink);
#endif
if (SUCCEEDED(hr))
hr = spCustomSink->Shutdown();
}
LeaveCriticalSection(&m_critSec);
DebugPrintOut(L"MediaSink::RemoveStreamSink: HRESULT=%i\n", hr);
return hr;
}
HRESULT STDMETHODCALLTYPE GetStreamSinkCount(DWORD *pStreamSinkCount) {
if (pStreamSinkCount == NULL)
{
return E_INVALIDARG;
}
EnterCriticalSection(&m_critSec);
HRESULT hr = CheckShutdown();
if (SUCCEEDED(hr))
{
*pStreamSinkCount = m_streams.GetCount();
}
LeaveCriticalSection(&m_critSec);
DebugPrintOut(L"MediaSink::GetStreamSinkCount: HRESULT=%i\n", hr);
return hr;
}
HRESULT STDMETHODCALLTYPE GetStreamSinkByIndex(
DWORD dwIndex, IMFStreamSink **ppStreamSink) {
if (ppStreamSink == NULL)
{
return E_INVALIDARG;
}
_ComPtr<IMFStreamSink> spStream;
EnterCriticalSection(&m_critSec);
DWORD cStreams = m_streams.GetCount();
if (dwIndex >= cStreams)
{
return MF_E_INVALIDINDEX;
}
HRESULT hr = CheckShutdown();
if (SUCCEEDED(hr))
{
ComPtrList<IMFStreamSink>::POSITION pos = m_streams.FrontPosition();
ComPtrList<IMFStreamSink>::POSITION endPos = m_streams.EndPosition();
DWORD dwCurrent = 0;
for (; pos != endPos && dwCurrent < dwIndex; pos = m_streams.Next(pos), ++dwCurrent)
{
// Just move to proper position
}
if (pos == endPos)
{
hr = MF_E_UNEXPECTED;
}
else
{
hr = m_streams.GetItemPos(pos, &spStream);
}
}
if (SUCCEEDED(hr))
{
*ppStreamSink = spStream.Detach();
}
LeaveCriticalSection(&m_critSec);
DebugPrintOut(L"MediaSink::GetStreamSinkByIndex: HRESULT=%i\n", hr);
return hr;
}
HRESULT STDMETHODCALLTYPE GetStreamSinkById(
DWORD dwStreamSinkIdentifier, IMFStreamSink **ppStreamSink) {
if (ppStreamSink == NULL)
{
return E_INVALIDARG;
}
EnterCriticalSection(&m_critSec);
HRESULT hr = CheckShutdown();
_ComPtr<IMFStreamSink> spResult;
if (SUCCEEDED(hr))
{
ComPtrList<IMFStreamSink>::POSITION pos = m_streams.FrontPosition();
ComPtrList<IMFStreamSink>::POSITION endPos = m_streams.EndPosition();
for (; pos != endPos; pos = m_streams.Next(pos))
{
_ComPtr<IMFStreamSink> spStream;
hr = m_streams.GetItemPos(pos, &spStream);
DWORD dwId;
if (FAILED(hr))
{
break;
}
hr = spStream->GetIdentifier(&dwId);
if (FAILED(hr))
{
break;
}
else if (dwId == dwStreamSinkIdentifier)
{
spResult = spStream;
break;
}
}
if (pos == endPos)
{
hr = MF_E_INVALIDSTREAMNUMBER;
}
}
if (SUCCEEDED(hr))
{
assert(spResult);
*ppStreamSink = spResult.Detach();
}
LeaveCriticalSection(&m_critSec);
DebugPrintOut(L"MediaSink::GetStreamSinkById: HRESULT=%i\n", hr);
return hr;
}
HRESULT STDMETHODCALLTYPE SetPresentationClock(
IMFPresentationClock *pPresentationClock) {
EnterCriticalSection(&m_critSec);
HRESULT hr = CheckShutdown();
// If we already have a clock, remove ourselves from that clock's
// state notifications.
if (SUCCEEDED(hr)) {
if (m_spClock) {
hr = m_spClock->RemoveClockStateSink(this);
}
}
// Register ourselves to get state notifications from the new clock.
if (SUCCEEDED(hr)) {
if (pPresentationClock) {
hr = pPresentationClock->AddClockStateSink(this);
}
}
_ComPtr<IMFSampleGrabberSinkCallback> pSampleCallback;
if (SUCCEEDED(hr)) {
// Release the pointer to the old clock.
// Store the pointer to the new clock.
m_spClock = pPresentationClock;
hr = GetUnknown(MF_MEDIASINK_SAMPLEGRABBERCALLBACK, IID_IMFSampleGrabberSinkCallback, (LPVOID*)pSampleCallback.GetAddressOf());
}
LeaveCriticalSection(&m_critSec);
if (SUCCEEDED(hr))
hr = pSampleCallback->OnSetPresentationClock(pPresentationClock);
DebugPrintOut(L"MediaSink::SetPresentationClock: HRESULT=%i\n", hr);
return hr;
}
HRESULT STDMETHODCALLTYPE GetPresentationClock(
IMFPresentationClock **ppPresentationClock) {
if (ppPresentationClock == NULL) {
return E_INVALIDARG;
}
EnterCriticalSection(&m_critSec);
HRESULT hr = CheckShutdown();
if (SUCCEEDED(hr)) {
if (!m_spClock) {
hr = MF_E_NO_CLOCK; // There is no presentation clock.
} else {
// Return the pointer to the caller.
hr = m_spClock.CopyTo(ppPresentationClock);
}
}
LeaveCriticalSection(&m_critSec);
DebugPrintOut(L"MediaSink::GetPresentationClock: HRESULT=%i\n", hr);
return hr;
}
HRESULT STDMETHODCALLTYPE Shutdown(void) {
EnterCriticalSection(&m_critSec);
HRESULT hr = CheckShutdown();
if (SUCCEEDED(hr)) {
ForEach(m_streams, ShutdownFunc());
m_streams.Clear();
m_spClock.ReleaseAndGetAddressOf();
_ComPtr<IMFMediaType> pType;
hr = CBaseAttributes<>::GetUnknown(MF_MEDIASINK_PREFERREDTYPE, __uuidof(IMFMediaType), (LPVOID*)pType.GetAddressOf());
if (SUCCEEDED(hr)) {
hr = DeleteItem(MF_MEDIASINK_PREFERREDTYPE);
}
m_IsShutdown = true;
}
LeaveCriticalSection(&m_critSec);
DebugPrintOut(L"MediaSink::Shutdown: HRESULT=%i\n", hr);
return hr;
}
class ShutdownFunc
{
public:
HRESULT operator()(IMFStreamSink *pStream) const
{
_ComPtr<ICustomStreamSink> spCustomSink;
HRESULT hr;
#ifdef HAVE_WINRT
spCustomSink = static_cast<StreamSink*>(pStream);
#else
hr = pStream->QueryInterface(IID_PPV_ARGS(spCustomSink.GetAddressOf()));
if (FAILED(hr)) return hr;
#endif
hr = spCustomSink->Shutdown();
return hr;
}
};
class StartFunc
{
public:
StartFunc(LONGLONG llStartTime)
: _llStartTime(llStartTime)
{
}
HRESULT operator()(IMFStreamSink *pStream) const
{
_ComPtr<ICustomStreamSink> spCustomSink;
HRESULT hr;
#ifdef HAVE_WINRT
spCustomSink = static_cast<StreamSink*>(pStream);
#else
hr = pStream->QueryInterface(IID_PPV_ARGS(spCustomSink.GetAddressOf()));
if (FAILED(hr)) return hr;
#endif
hr = spCustomSink->Start(_llStartTime);
return hr;
}
LONGLONG _llStartTime;
};
class StopFunc
{
public:
HRESULT operator()(IMFStreamSink *pStream) const
{
_ComPtr<ICustomStreamSink> spCustomSink;
HRESULT hr;
#ifdef HAVE_WINRT
spCustomSink = static_cast<StreamSink*>(pStream);
#else
hr = pStream->QueryInterface(IID_PPV_ARGS(spCustomSink.GetAddressOf()));
if (FAILED(hr)) return hr;
#endif
hr = spCustomSink->Stop();
return hr;
}
};
template <class T, class TFunc>
HRESULT ForEach(ComPtrList<T> &col, TFunc fn)
{
ComPtrList<T>::POSITION pos = col.FrontPosition();
ComPtrList<T>::POSITION endPos = col.EndPosition();
HRESULT hr = S_OK;
for (; pos != endPos; pos = col.Next(pos))
{
_ComPtr<T> spStream;
hr = col.GetItemPos(pos, &spStream);
if (FAILED(hr))
{
break;
}
hr = fn(spStream.Get());
}
return hr;
}
//IMFClockStateSink
HRESULT STDMETHODCALLTYPE OnClockStart(
MFTIME hnsSystemTime,
LONGLONG llClockStartOffset) {
EnterCriticalSection(&m_critSec);
HRESULT hr = CheckShutdown();
if (SUCCEEDED(hr))
{
// Start each stream.
m_llStartTime = llClockStartOffset;
hr = ForEach(m_streams, StartFunc(llClockStartOffset));
}
_ComPtr<IMFSampleGrabberSinkCallback> pSampleCallback;
if (SUCCEEDED(hr))
hr = GetUnknown(MF_MEDIASINK_SAMPLEGRABBERCALLBACK, IID_IMFSampleGrabberSinkCallback, (LPVOID*)pSampleCallback.GetAddressOf());
LeaveCriticalSection(&m_critSec);
if (SUCCEEDED(hr))
hr = pSampleCallback->OnClockStart(hnsSystemTime, llClockStartOffset);
DebugPrintOut(L"MediaSink::OnClockStart: HRESULT=%i\n", hr);
return hr;
}
HRESULT STDMETHODCALLTYPE OnClockStop(
MFTIME hnsSystemTime) {
EnterCriticalSection(&m_critSec);
HRESULT hr = CheckShutdown();
if (SUCCEEDED(hr))
{
// Stop each stream
hr = ForEach(m_streams, StopFunc());
}
_ComPtr<IMFSampleGrabberSinkCallback> pSampleCallback;
if (SUCCEEDED(hr))
hr = GetUnknown(MF_MEDIASINK_SAMPLEGRABBERCALLBACK, IID_IMFSampleGrabberSinkCallback, (LPVOID*)pSampleCallback.GetAddressOf());
LeaveCriticalSection(&m_critSec);
if (SUCCEEDED(hr))
hr = pSampleCallback->OnClockStop(hnsSystemTime);
DebugPrintOut(L"MediaSink::OnClockStop: HRESULT=%i\n", hr);
return hr;
}
HRESULT STDMETHODCALLTYPE OnClockPause(
MFTIME hnsSystemTime) {
HRESULT hr;
_ComPtr<IMFSampleGrabberSinkCallback> pSampleCallback;
hr = GetUnknown(MF_MEDIASINK_SAMPLEGRABBERCALLBACK, IID_IMFSampleGrabberSinkCallback, (LPVOID*)pSampleCallback.GetAddressOf());
if (SUCCEEDED(hr))
hr = pSampleCallback->OnClockPause(hnsSystemTime);
DebugPrintOut(L"MediaSink::OnClockPause: HRESULT=%i\n", hr);
return hr;
}
HRESULT STDMETHODCALLTYPE OnClockRestart(
MFTIME hnsSystemTime) {
HRESULT hr;
_ComPtr<IMFSampleGrabberSinkCallback> pSampleCallback;
hr = GetUnknown(MF_MEDIASINK_SAMPLEGRABBERCALLBACK, IID_IMFSampleGrabberSinkCallback, (LPVOID*)pSampleCallback.GetAddressOf());
if (SUCCEEDED(hr))
hr = pSampleCallback->OnClockRestart(hnsSystemTime);
DebugPrintOut(L"MediaSink::OnClockRestart: HRESULT=%i\n", hr);
return hr;
}
HRESULT STDMETHODCALLTYPE OnClockSetRate(
MFTIME hnsSystemTime,
float flRate) {
HRESULT hr;
_ComPtr<IMFSampleGrabberSinkCallback> pSampleCallback;
hr = GetUnknown(MF_MEDIASINK_SAMPLEGRABBERCALLBACK, IID_IMFSampleGrabberSinkCallback, (LPVOID*)pSampleCallback.GetAddressOf());
if (SUCCEEDED(hr))
hr = pSampleCallback->OnClockSetRate(hnsSystemTime, flRate);
DebugPrintOut(L"MediaSink::OnClockSetRate: HRESULT=%i\n", hr);
return hr;
}
private:
#ifndef HAVE_WINRT
long m_cRef;
#endif
CRITICAL_SECTION m_critSec;
bool m_IsShutdown;
ComPtrList<IMFStreamSink> m_streams;
_ComPtr<IMFPresentationClock> m_spClock;
LONGLONG m_llStartTime;
};
#ifdef HAVE_WINRT
ActivatableClass(MediaSink);
#endif
|
liangfu/dnn
|
modules/highgui/src/cap_msmf.hpp
|
C++
|
mit
| 111,855 |
#money
Node.js module to perform precise common money calculations.
This library is a partial javascript implementation of the [Money Pattern](http://martinfowler.com/eaaCatalog/money.html) as described by Martin Fowler in his book *Patterns of Enterprise Application Architecture*.
## Using the library
```javascript
var money = require('path/to/lib/money.js');
// Show me those monies
var inheritance = money.dollar(1234567.89);
// Subtract taxes
var TAXMAN = 0.69;
var netSum = inheritance.mult(TAXMAN);
console.log(netSum.toNumber());
// 851851.84
// Hand out loot to heirs.
// The oldest will receive 40% of the money, the next one 30% etc.
var heirs = netSum.allocate([4,3,2,1]);
heirs.forEach(function(heir) { console.log(heir.toNumber()); });
// 340740.74
// 255555.56
// 170370.36
// 85185.18
var addBack = heirs[0].add(heirs[1]).add(heirs[2]).add(heirs[3]);
assert.deepEqual(addBack, netSum);
// undefined (wow so money much precise)
```
## Running the tests (*nix only)
1. Clone and install [node-jscoverage](https://github.com/visionmedia/node-jscoverage) in your system
2. Enter the money repository and run `jscoverage lib/ lib-cov/` to instrument the library
3. Install [Mocha](http://mochajs.org/) as a command via npm `sudo npm install -g mocha`
* a. To run the tests execute the following command: `mocha --ui tdd test/test.js`
* b. To view a coverage report use the `html-cov` reporter: `mocha --ui tdd -R html-cov test/test.js > report.html` and open the HTML file with your browser of choice.
|
Jautenim/money
|
README.md
|
Markdown
|
mit
| 1,530 |
angular.module('starter.controllers', [])
// A simple controller that fetches a list of data from a service
.controller('PetIndexCtrl', function($scope, PetService) {
// "Pets" is a service returning mock data (services.js)
$scope.pets = PetService.all();
})
// A simple controller that shows a tapped item's data
.controller('PetDetailCtrl', function($scope, $stateParams, PetService) {
// "Pets" is a service returning mock data (services.js)
$scope.pet = PetService.get($stateParams.petId);
})
// getting fake favor data
.controller('FavorIndexCtrl', function($scope, FavorService) {
$scope.favors = FavorService.all();
})
// A simple controller that shows a tapped item's data
.controller('FavorDetailCtrl', function($scope, $stateParams, FavorService) {
// "Pets" is a service returning mock data (services.js)
$scope.favor = FavorService.get($stateParams.favorId);
});
|
robwormald/favor-app
|
www/js/controllers.js
|
JavaScript
|
mit
| 899 |
<html lang="en">
<head>
<title>Native - Debugging with GDB</title>
<meta http-equiv="Content-Type" content="text/html">
<meta name="description" content="Debugging with GDB">
<meta name="generator" content="makeinfo 4.11">
<link title="Top" rel="start" href="index.html#Top">
<link rel="up" href="Configurations.html#Configurations" title="Configurations">
<link rel="next" href="Embedded-OS.html#Embedded-OS" title="Embedded OS">
<link href="http://www.gnu.org/software/texinfo/" rel="generator-home" title="Texinfo Homepage">
<!--
Copyright (C) 1988-2014 Free Software Foundation, Inc.
Permission is granted to copy, distribute and/or modify this document
under the terms of the GNU Free Documentation License, Version 1.3 or
any later version published by the Free Software Foundation; with the
Invariant Sections being ``Free Software'' and ``Free Software Needs
Free Documentation'', with the Front-Cover Texts being ``A GNU Manual,''
and with the Back-Cover Texts as in (a) below.
(a) The FSF's Back-Cover Text is: ``You are free to copy and modify
this GNU Manual. Buying copies from GNU Press supports the FSF in
developing GNU and promoting software freedom.''
-->
<meta http-equiv="Content-Style-Type" content="text/css">
<style type="text/css"><!--
pre.display { font-family:inherit }
pre.format { font-family:inherit }
pre.smalldisplay { font-family:inherit; font-size:smaller }
pre.smallformat { font-family:inherit; font-size:smaller }
pre.smallexample { font-size:smaller }
pre.smalllisp { font-size:smaller }
span.sc { font-variant:small-caps }
span.roman { font-family:serif; font-weight:normal; }
span.sansserif { font-family:sans-serif; font-weight:normal; }
--></style>
</head>
<body>
<div class="node">
<p>
<a name="Native"></a>
Next: <a rel="next" accesskey="n" href="Embedded-OS.html#Embedded-OS">Embedded OS</a>,
Up: <a rel="up" accesskey="u" href="Configurations.html#Configurations">Configurations</a>
<hr>
</div>
<h3 class="section">21.1 Native</h3>
<p>This section describes details specific to particular native
configurations.
<ul class="menu">
<li><a accesskey="1" href="HP_002dUX.html#HP_002dUX">HP-UX</a>: HP-UX
<li><a accesskey="2" href="BSD-libkvm-Interface.html#BSD-libkvm-Interface">BSD libkvm Interface</a>: Debugging BSD kernel memory images
<li><a accesskey="3" href="SVR4-Process-Information.html#SVR4-Process-Information">SVR4 Process Information</a>: SVR4 process information
<li><a accesskey="4" href="DJGPP-Native.html#DJGPP-Native">DJGPP Native</a>: Features specific to the DJGPP port
<li><a accesskey="5" href="Cygwin-Native.html#Cygwin-Native">Cygwin Native</a>: Features specific to the Cygwin port
<li><a accesskey="6" href="Hurd-Native.html#Hurd-Native">Hurd Native</a>: Features specific to <span class="sc">gnu</span> Hurd
<li><a accesskey="7" href="Darwin.html#Darwin">Darwin</a>: Features specific to Darwin
</ul>
</body></html>
|
trfiladelfo/tdk
|
gcc-arm-none-eabi/share/doc/gcc-arm-none-eabi/html/gdb/Native.html
|
HTML
|
mit
| 3,000 |
//
// FXCachePlist.h
// FancyMall
//
// Created by fancy on 16/1/14.
// Copyright © 2016年 FancyMall. All rights reserved.
//
#import <Foundation/Foundation.h>
@interface FXCachePlist : NSObject
+(instancetype)sharedPlist;
-(NSString *)needRemoveFileName;
-(void)dataForDataArrayWithUrl:(NSString *)url withMark:(NSString *)mark;
-(void)removeOldFileAndOldFileName;
-(NSMutableArray *)readArrayFramePlist;
//-(void)creatFileWithWithList;
/**将数据写入到文件中去*/
//-(void)dataToPlist:(NSMutableArray *)mutArray;
/**将数据进行删除*/
-(void)removeFileByLabel:(NSString *)label;
@end
|
STT-Ocean/FXWebViewCache
|
FXWebViewCache/FXCachePlist.h
|
C
|
mit
| 616 |
// Copyright 2011, Google Inc.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
var kDefaultNumberOfResampleRanges = 11;
function WaveTable(name, context) {
this.name = name;
this.context = context;
this.sampleRate = context.sampleRate;
this.url = "wave-tables/" + this.name;
this.waveTableSize = 4096; // hard-coded for now
this.buffer = 0;
this.numberOfResampleRanges = kDefaultNumberOfResampleRanges;
}
WaveTable.prototype.getWaveDataForPitch = function(pitchFrequency) {
var nyquist = 0.5 * this.sampleRate;
var lowestNumPartials = this.getNumberOfPartialsForRange(0);
var lowestFundamental = nyquist / lowestNumPartials;
// Find out pitch range
var ratio = pitchFrequency / lowestFundamental;
var pitchRange = ratio == 0.0 ? 0 : Math.floor(Math.log(ratio) / Math.LN2);
if (pitchRange < 0)
pitchRange = 0;
// Too bad, we'll alias if pitch is greater than around 5KHz :)
if (pitchRange >= this.numberOfResampleRanges)
pitchRange = this.numberOfResampleRanges - 1;
return this.buffers[pitchRange];
}
WaveTable.prototype.getNumberOfPartialsForRange = function(j) {
// goes from 1024 -> 4 @ 44.1KHz (and do same for 48KHz)
// goes from 2048 -> 8 @ 96KHz
var npartials = Math.pow(2, 1 + this.numberOfResampleRanges - j);
if (this.getSampleRate() > 48000.0)
npartials *= 2; // high sample rate allows more harmonics at given fundamental
return npartials;
}
WaveTable.prototype.getWaveTableSize = function() {
return this.waveTableSize;
}
WaveTable.prototype.getSampleRate = function() {
return this.sampleRate;
}
WaveTable.prototype.getRateScale = function() {
return this.getWaveTableSize() / this.getSampleRate();
}
WaveTable.prototype.getNumberOfResampleRanges = function() {
this.numberOfResampleRanges;
}
WaveTable.prototype.getName = function() {
return this.name;
}
WaveTable.prototype.load = function(callback) {
var request = new XMLHttpRequest();
request.open("GET", this.url, true);
var wave = this;
request.onload = function() {
// Get the frequency-domain waveform data.
var f = eval('(' + request.responseText + ')');
// Copy into more efficient Float32Arrays.
var n = f.real.length;
frequencyData = { "real": new Float32Array(n), "imag": new Float32Array(n) };
wave.frequencyData = frequencyData;
for (var i = 0; i < n; ++i) {
frequencyData.real[i] = f.real[i];
frequencyData.imag[i] = f.imag[i];
}
wave.createBuffers();
if (callback)
callback(wave);
};
request.onerror = function() {
alert("error loading: " + wave.url);
};
request.send();
}
WaveTable.prototype.print = function() {
var f = this.frequencyData;
var info = document.getElementById("info");
var s = "";
for (var i = 0; i < 2048; ++i) {
s += "{" + f.real[i] + ", " + f.imag[i] + "}, <br>";
}
info.innerHTML = s;
}
WaveTable.prototype.printBuffer = function(buffer) {
var info = document.getElementById("info");
var s = "";
for (var i = 0; i < 4096; ++i) {
s += buffer[i] + "<br>";
}
info.innerHTML = s;
}
// WaveTable.prototype.createBuffers = function() {
// var f = this.frequencyData;
//
// var n = 4096;
//
// var fft = new FFT(n, 44100);
//
// // Copy from loaded frequency data and scale.
// for (var i = 0; i < n / 2; ++i) {
// fft.real[i] = 4096 * f.real[i];
// fft.imag[i] = 4096 * f.imag[i];
// }
//
// // Now do inverse FFT
// this.data = fft.inverse();
// var data = this.data;
//
// this.buffer = context.createBuffer(1, data.length, 44100);
//
// // Copy data to the buffer.
// var p = this.buffer.getChannelData(0);
// for (var i = 0; i < data.length; ++i) {
// p[i] = data[i];
// }
// }
// Convert into time-domain wave tables.
// We actually create several of them for non-aliasing playback at different playback rates.
WaveTable.prototype.createBuffers = function() {
// resample ranges
//
// let's divide up versions of our waves based on the maximum fundamental frequency we're
// resampling at. Let's use fundamental frequencies based on dividing Nyquist by powers of two.
// For example for 44.1KHz sample-rate we have:
//
// ranges
// ----------------------------------
// 21Hz, 43Hz, 86Hz, 172Hz, 344Hz, 689Hz, 1378Hz, 2756Hz, 5512Hz, 11025Hz, 22050Hz <-- 44.1KHz
// 23Hz, 47Hz, 94Hz, 187Hz, 375Hz, 750Hz, 1500Hz, 3000Hz, 6000Hz, 12000Hz, 24000Hz, 48000Hz <-- 96KHz
//
// and number of partials:
//
// 1024, 512, 256, 128, 64, 32, 16, 8, 4, 2, 1
// 2048, 1024, 512, 256, 128, 64, 32, 16, 8, 4, 2, 1
//
// But it's probably OK if we skip the very highest fundamental frequencies and only
// go up to 5512Hz, so we have a total of 9 resample ranges
//
// 0 1 2 3 4 5 6 7 8
// The FFT size needs to be at least 2048 @ 44.1KHz and 4096 @ 96KHz
//
// So let's try to use FFT size of 4096 all the time and pull out the harmonics we want
//
this.buffers = new Array();
var finalScale = 1.0;
for (var j = 0; j < this.numberOfResampleRanges; ++j) {
var n = this.waveTableSize;
var frame = new FFT(n, this.sampleRate);
// Copy from loaded frequency data and scale.
var f = this.frequencyData;
var scale = n;
for (var i = 0; i < n / 2; ++i) {
frame.real[i] = scale * f.real[i];
frame.imag[i] = scale * f.imag[i];
}
var realP = frame.real;
var imagP = frame.imag;
// Find the starting bin where we should start clearing out
// (we need to clear out the highest frequencies to band-limit the waveform)
var fftSize = n;
var halfSize = fftSize / 2;
var npartials = this.getNumberOfPartialsForRange(j);
// Now, go through and cull out the aliasing harmonics...
for (var i = npartials + 1; i < halfSize; i++) {
realP[i] = 0.0;
imagP[i] = 0.0;
}
// Clear packed-nyquist if necessary
if (npartials < halfSize)
imagP[0] = 0.0;
// Clear any DC-offset
realP[0] = 0.0;
// For the first resample range, find power and compute scale.
if (j == 0) {
var power = 0;
for (var i = 1; i < halfSize; ++i) {
x = realP[i];
y = imagP[i];
power += x * x + y * y;
}
power = Math.sqrt(power) / fftSize;
finalScale = 0.5 / power;
// window.console.log("power = " + power);
}
// Great, now do inverse FFT into our wavetable...
var data = frame.inverse();
// Create mono AudioBuffer.
var buffer = this.context.createBuffer(1, data.length, this.sampleRate);
// Copy data to the buffer.
var p = buffer.getChannelData(0);
for (var i = 0; i < data.length; ++i) {
p[i] = finalScale * data[i];
}
this.buffers[j] = buffer;
}
}
WaveTable.prototype.displayWaveData = function() {
var data = this.data;
var n = data.length;
var s = "";
for (var i = 0; i < n; ++i) {
s += data[i].toFixed(3) + "<br> ";
}
var info = document.getElementById("info");
info.innerHTML = s;
}
|
hems/-labs
|
examples/audio/lib/wavetable.js
|
JavaScript
|
mit
| 8,974 |
/**
* Created by maomao on 2020/4/20.
*/
Java.perform(function() {
var cn = "android.telephony.SubscriptionManager";
var target = Java.use(cn);
if (target) {
target.addOnSubscriptionsChangedListener.overloads[0].implementation = function(dest) {
var myArray=new Array()
myArray[0] = "SENSITIVE" //INTERESTED & SENSITIVE
myArray[1] = cn + "." + "addOnSubscriptionsChangedListener";
myArray[2] = Java.use("android.util.Log").getStackTraceString(Java.use("java.lang.Exception").$new()).split('\n\tat');
send(myArray);
return this.addOnSubscriptionsChangedListener.overloads[0].apply(this, arguments);
};
// target.addOnSubscriptionsChangedListener.overloads[1].implementation = function(dest) {
// var myArray=new Array()
// myArray[0] = "SENSITIVE" //INTERESTED & SENSITIVE
// myArray[1] = cn + "." + "addOnSubscriptionsChangedListener";
// myArray[2] = Java.use("android.util.Log").getStackTraceString(Java.use("java.lang.Exception").$new()).split('\n\tat');
// send(myArray);
// return this.addOnSubscriptionsChangedListener.overloads[1].apply(this, arguments);
// };
target.getActiveSubscriptionInfo.overloads[0].implementation = function(dest) {
var myArray=new Array()
myArray[0] = "SENSITIVE" //INTERESTED & SENSITIVE
myArray[1] = cn + "." + "getActiveSubscriptionInfo";
myArray[2] = Java.use("android.util.Log").getStackTraceString(Java.use("java.lang.Exception").$new()).split('\n\tat');
send(myArray);
return this.getActiveSubscriptionInfo.overloads[0].apply(this, arguments);
};
// target.getActiveSubscriptionInfo.overloads[1].implementation = function(dest) {
// var myArray=new Array()
// myArray[0] = "SENSITIVE" //INTERESTED & SENSITIVE
// myArray[1] = cn + "." + "getActiveSubscriptionInfo";
// myArray[2] = Java.use("android.util.Log").getStackTraceString(Java.use("java.lang.Exception").$new()).split('\n\tat');
// send(myArray);
// return this.getActiveSubscriptionInfo.overloads[1].apply(this, arguments);
// };
target.getActiveSubscriptionInfoCount.implementation = function(dest) {
var myArray=new Array()
myArray[0] = "SENSITIVE" //INTERESTED & SENSITIVE
myArray[1] = cn + "." + "getActiveSubscriptionInfoCount";
myArray[2] = Java.use("android.util.Log").getStackTraceString(Java.use("java.lang.Exception").$new()).split('\n\tat');
send(myArray);
return this.getActiveSubscriptionInfoCount.apply(this, arguments);
};
target.getActiveSubscriptionInfoForSimSlotIndex.implementation = function(dest) {
var myArray=new Array()
myArray[0] = "SENSITIVE" //INTERESTED & SENSITIVE
myArray[1] = cn + "." + "getActiveSubscriptionInfoForSimSlotIndex";
myArray[2] = Java.use("android.util.Log").getStackTraceString(Java.use("java.lang.Exception").$new()).split('\n\tat');
send(myArray);
return this.getActiveSubscriptionInfoForSimSlotIndex.apply(this, arguments);
};
target.getActiveSubscriptionInfoList.implementation = function(dest) {
var myArray=new Array()
myArray[0] = "SENSITIVE" //INTERESTED & SENSITIVE
myArray[1] = cn + "." + "getActiveSubscriptionInfoList";
myArray[2] = Java.use("android.util.Log").getStackTraceString(Java.use("java.lang.Exception").$new()).split('\n\tat');
send(myArray);
return this.getActiveSubscriptionInfoList.apply(this, arguments);
};
}
});
|
honeynet/droidbot
|
droidbot/resources/scripts/telephony/SubscriptionManager.js
|
JavaScript
|
mit
| 3,831 |
#!/bin/bash
FN="HsAgilentDesign026652.db_3.2.3.tar.gz"
URLS=(
"https://bioconductor.org/packages/3.11/data/annotation/src/contrib/HsAgilentDesign026652.db_3.2.3.tar.gz"
"https://bioarchive.galaxyproject.org/HsAgilentDesign026652.db_3.2.3.tar.gz"
"https://depot.galaxyproject.org/software/bioconductor-hsagilentdesign026652.db/bioconductor-hsagilentdesign026652.db_3.2.3_src_all.tar.gz"
"https://depot.galaxyproject.org/software/bioconductor-hsagilentdesign026652.db/bioconductor-hsagilentdesign026652.db_3.2.3_src_all.tar.gz"
)
MD5="dcd2c748bf9d7c002611cd5cf2ff38c0"
# Use a staging area in the conda dir rather than temp dirs, both to avoid
# permission issues as well as to have things downloaded in a predictable
# manner.
STAGING=$PREFIX/share/$PKG_NAME-$PKG_VERSION-$PKG_BUILDNUM
mkdir -p $STAGING
TARBALL=$STAGING/$FN
SUCCESS=0
for URL in ${URLS[@]}; do
curl $URL > $TARBALL
[[ $? == 0 ]] || continue
# Platform-specific md5sum checks.
if [[ $(uname -s) == "Linux" ]]; then
if md5sum -c <<<"$MD5 $TARBALL"; then
SUCCESS=1
break
fi
else if [[ $(uname -s) == "Darwin" ]]; then
if [[ $(md5 $TARBALL | cut -f4 -d " ") == "$MD5" ]]; then
SUCCESS=1
break
fi
fi
fi
done
if [[ $SUCCESS != 1 ]]; then
echo "ERROR: post-link.sh was unable to download any of the following URLs with the md5sum $MD5:"
printf '%s\n' "${URLS[@]}"
exit 1
fi
# Install and clean up
R CMD INSTALL --library=$PREFIX/lib/R/library $TARBALL
rm $TARBALL
rmdir $STAGING
|
roryk/recipes
|
recipes/bioconductor-hsagilentdesign026652.db/post-link.sh
|
Shell
|
mit
| 1,510 |
#import <UIKit/UIKit.h>
#import "OLCVideoPlayer.h"
FOUNDATION_EXPORT double OLCVideoPlayerVersionNumber;
FOUNDATION_EXPORT const unsigned char OLCVideoPlayerVersionString[];
|
LakithaRav/OLCVideoPlayer
|
Example/Pods/Target Support Files/Pods-OLCVideoPlayer_Tests-OLCVideoPlayer/Pods-OLCVideoPlayer_Tests-OLCVideoPlayer-umbrella.h
|
C
|
mit
| 177 |
"use strict";
const chalk = require("chalk");
const readline = require("readline");
/**
* Fill screen with blank lines, move to "0" afterwards and clear screen afterwards.
* Note that it is still possible to "scroll back" afterwards.
*
* Function performs nothing in case the stdout is NOT a TTY.
*/
exports.cls = function() {
if (process.stdout.isTTY) {
const blank = "\n".repeat(process.stdout.rows);
console.log(blank);
readline.cursorTo(process.stdout, 0, 0);
readline.clearScreenDown(process.stdout);
}
};
/**
* A less soft version of `cls` above which completely clears out the screen,
* without leaving the option to scroll up again.
*
* Function performs nothing in case the stdout is NOT a TTY.
*/
exports.hardCls = function() {
if (process.stdout.isTTY) {
process.stdout.write(
process.platform === "win32" ? "\x1Bc" : "\x1B[2J\x1B[3J\x1B[H"
);
}
};
exports.formatFirstLineMessage = function(text) {
return chalk.bgWhite.black(text);
};
|
DorianGrey/ng2-webpack-template
|
scripts/util/formatUtil.js
|
JavaScript
|
mit
| 1,001 |
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8"/><!-- using block title in layout.dt--><!-- using block ddox.defs in ddox.layout.dt--><!-- using block ddox.title in ddox.layout.dt-->
<title>Method AssetAnimation.convertVectorArray</title>
<link rel="stylesheet" type="text/css" href="../../styles/ddox.css"/>
<link rel="stylesheet" href="../../prettify/prettify.css" type="text/css"/>
<script type="text/javascript" src="../../scripts/jquery.js">/**/</script>
<script type="text/javascript" src="../../prettify/prettify.js">/**/</script>
<script type="text/javascript" src="../../scripts/ddox.js">/**/</script>
</head>
<body onload="prettyPrint(); setupDdox();">
<nav id="main-nav"><!-- using block navigation in layout.dt-->
<ul class="tree-view">
<li class=" tree-view">
<a href="#" class="package">components</a>
<ul class="tree-view">
<li>
<a href="../../components/animation.html" class="selected module">animation</a>
</li>
<li>
<a href="../../components/assets.html" class=" module">assets</a>
</li>
<li>
<a href="../../components/behavior.html" class=" module">behavior</a>
</li>
<li>
<a href="../../components/camera.html" class=" module">camera</a>
</li>
<li>
<a href="../../components/icomponent.html" class=" module">icomponent</a>
</li>
<li>
<a href="../../components/lights.html" class=" module">lights</a>
</li>
<li>
<a href="../../components/material.html" class=" module">material</a>
</li>
<li>
<a href="../../components/mesh.html" class=" module">mesh</a>
</li>
<li>
<a href="../../components/userinterface.html" class=" module">userinterface</a>
</li>
</ul>
</li>
<li class="collapsed tree-view">
<a href="#" class="package">core</a>
<ul class="tree-view">
<li>
<a href="../../core/dgame.html" class=" module">dgame</a>
</li>
<li>
<a href="../../core/gameobject.html" class=" module">gameobject</a>
</li>
<li>
<a href="../../core/prefabs.html" class=" module">prefabs</a>
</li>
<li>
<a href="../../core/properties.html" class=" module">properties</a>
</li>
<li>
<a href="../../core/reflection.html" class=" module">reflection</a>
</li>
<li>
<a href="../../core/scene.html" class=" module">scene</a>
</li>
</ul>
</li>
<li class="collapsed tree-view">
<a href="#" class="package">graphics</a>
<ul class="tree-view">
<li class="collapsed tree-view">
<a href="#" class="package">adapters</a>
<ul class="tree-view">
<li>
<a href="../../graphics/adapters/adapter.html" class=" module">adapter</a>
</li>
<li>
<a href="../../graphics/adapters/linux.html" class=" module">linux</a>
</li>
<li>
<a href="../../graphics/adapters/mac.html" class=" module">mac</a>
</li>
<li>
<a href="../../graphics/adapters/win32.html" class=" module">win32</a>
</li>
</ul>
</li>
<li class="collapsed tree-view">
<a href="#" class="package">shaders</a>
<ul class="tree-view">
<li class="collapsed tree-view">
<a href="#" class="package">glsl</a>
<ul class="tree-view">
<li>
<a href="../../graphics/shaders/glsl/ambientlight.html" class=" module">ambientlight</a>
</li>
<li>
<a href="../../graphics/shaders/glsl/animatedgeometry.html" class=" module">animatedgeometry</a>
</li>
<li>
<a href="../../graphics/shaders/glsl/directionallight.html" class=" module">directionallight</a>
</li>
<li>
<a href="../../graphics/shaders/glsl/geometry.html" class=" module">geometry</a>
</li>
<li>
<a href="../../graphics/shaders/glsl/pointlight.html" class=" module">pointlight</a>
</li>
<li>
<a href="../../graphics/shaders/glsl/userinterface.html" class=" module">userinterface</a>
</li>
</ul>
</li>
<li>
<a href="../../graphics/shaders/glsl.html" class=" module">glsl</a>
</li>
<li>
<a href="../../graphics/shaders/shaders.html" class=" module">shaders</a>
</li>
</ul>
</li>
<li>
<a href="../../graphics/adapters.html" class=" module">adapters</a>
</li>
<li>
<a href="../../graphics/graphics.html" class=" module">graphics</a>
</li>
<li>
<a href="../../graphics/shaders.html" class=" module">shaders</a>
</li>
</ul>
</li>
<li class="collapsed tree-view">
<a href="#" class="package">utility</a>
<ul class="tree-view">
<li>
<a href="../../utility/array.html" class=" module">array</a>
</li>
<li>
<a href="../../utility/awesomium.html" class=" module">awesomium</a>
</li>
<li>
<a href="../../utility/concurrency.html" class=" module">concurrency</a>
</li>
<li>
<a href="../../utility/config.html" class=" module">config</a>
</li>
<li>
<a href="../../utility/filepath.html" class=" module">filepath</a>
</li>
<li>
<a href="../../utility/input.html" class=" module">input</a>
</li>
<li>
<a href="../../utility/output.html" class=" module">output</a>
</li>
<li>
<a href="../../utility/string.html" class=" module">string</a>
</li>
<li>
<a href="../../utility/tasks.html" class=" module">tasks</a>
</li>
<li>
<a href="../../utility/time.html" class=" module">time</a>
</li>
</ul>
</li>
<li>
<a href="../../components.html" class=" module">components</a>
</li>
<li>
<a href="../../core.html" class=" module">core</a>
</li>
<li>
<a href="../../graphics.html" class=" module">graphics</a>
</li>
<li>
<a href="../../utility.html" class=" module">utility</a>
</li>
</ul>
<noscript>
<p style="color: red">The search functionality needs JavaScript enabled</p>
</noscript>
<div id="symbolSearchPane" style="display: none">
<p>
<input id="symbolSearch" type="text" placeholder="Search for symbols" onchange="performSymbolSearch(24);" onkeypress="this.onchange();" onpaste="this.onchange();" oninput="this.onchange();"/>
</p>
<ul id="symbolSearchResults" style="display: none"></ul>
<script type="application/javascript" src="../../symbols.js"></script>
<script type="application/javascript">
//<![CDATA[
var symbolSearchRootDir = "../../"; $('#symbolSearchPane').show();
//]]>
</script>
</div>
</nav>
<div id="main-contents">
<h1>Method AssetAnimation.convertVectorArray</h1><!-- using block body in layout.dt--><!-- Default block ddox.description in ddox.layout.dt--><!-- Default block ddox.sections in ddox.layout.dt--><!-- using block ddox.members in ddox.layout.dt-->
<p> Converts a aiVectorKey[] to vec3[].
</p>
<section></section>
<section>
<h2>Prototype</h2>
<pre class="code prettyprint lang-d prototype">
shared(gl3n.linalg.Vector!(float,3)[]) convertVectorArray(
const(derelict.assimp3.types.aiVectorKey*) vectors,
int numKeys
) shared;</pre>
</section>
<section><h2>Parameters</h2>
<table><col class="caption"><tr><th>Name</th><th>Description</th></tr>
<tr><td id="quaternions">quaternions</td><td> aiVectorKey[] to be converted</td></tr>
<tr><td id="numKeys">numKeys</td><td> Number of keys in vector array</td></tr>
</table>
</section>
<section><h2>Returns</h2>
<p>The <a href="../../components/animation/AssetAnimation.convertVectorArray.html#vectors"><code class="prettyprint lang-d">vectors</code></a> in vector[] format
</p>
</section>
<section>
<h2>Authors</h2><!-- using block ddox.authors in ddox.layout.dt-->
</section>
<section>
<h2>Copyright</h2><!-- using block ddox.copyright in ddox.layout.dt-->
</section>
<section>
<h2>License</h2><!-- using block ddox.license in ddox.layout.dt-->
</section>
</div>
</body>
</html>
|
Circular-Studios/Dash-Docs
|
api/v0.7.1/components/animation/AssetAnimation.convertVectorArray.html
|
HTML
|
mit
| 8,388 |
module Locomotive
class SitePolicy < ApplicationPolicy
class Scope < Scope
def resolve
if membership.account.super_admin?
scope.all
else
membership.account.sites
end
end
end
def index?
true
end
def show?
true
end
def create?
true
end
def update?
super_admin? || site_staff?
end
def destroy?
super_admin? || site_admin?
end
def point?
super_admin? || site_admin?
end
def update_advanced?
super_admin? || site_admin?
end
def show_developers_documentation?
super_admin? || site_admin?
end
def permitted_attributes
plain = [:name, :handle, :picture, :remove_picture, :seo_title, :meta_keywords, :meta_description, :timezone_name, :robots_txt]
hash = { domains: [], locales: [] }
unless update_advanced?
plain -= [:timezone_name, :robots_txt]
hash.delete(:locales)
end
unless point?
plain -= [:handle]
hash.delete(:domains)
end
plain << hash
end
end
end
|
slavajacobson/engine
|
app/policies/locomotive/site_policy.rb
|
Ruby
|
mit
| 1,128 |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
import time
import string
import json
import config
import helper
import busses
def log_message(msg):
#log format: time type message
time_str = str(time.time())
line = time_str[:time_str.find(".")]
line = line.rjust(10, str(" "))
line += " "
busses.status_bus["latest_messages"][msg.chat_id] = msg
msg_type = helper.get_message_type(msg)
if msg_type == "text" and msg.text.startswith("/"):
msg_type = "command"
appendix = "ERROR"
if msg_type == "text":
appendix = msg.text
elif msg_type == "command":
appendix = msg.text[1:]
elif msg_type == "location":
location_data = msg.location.to_dict()
appendix = str(location_data["latitude"]) + "°, " + str(location_data["longitude"]) + "°"
elif msg_type == "contact":
appendix = str(msg.contact.user_id) + " " + msg.contact.first_name + " " + msg.contact.last_name
elif msg_type == "new_user":
appendix = str(msg.new_chat_member.id) + " " + str(msg.new_chat_member.first_name) + " " + str(msg.new_chat_member.last_name)
elif msg_type in ["audio", "document", "game", "photo", "sticker", "video", "voice", "video_note", "unknown"]:
appendix = ""
msg_type = msg_type.rjust(10, str(" "))
appendix = appendix.replace("\n", "\\n").rjust(40, str(" "))
line += msg_type + " " + appendix + " "
line += str(msg.chat_id) + "," + str(msg.message_id)
line += "\n"
with open(config.msg_log_file_path, "a") as log_file:
log_file.write(line.encode("utf-8"))
def complete_log(update):
with open(config.complete_log_file_path, "a") as log_file:
data = update.to_dict()
data.update({"time": time.time()})
json_data = json.dumps(data)
log_file.write(str(json_data).replace("\n", "\\n") + "\n".encode("utf-8"))
|
Pixdigit/Saufbot
|
logger.py
|
Python
|
mit
| 1,904 |
<div layout="vertical">
<md-sidenav class="md-sidenav-left md-whiteframe-z2"
md-component-id="left"
md-is-locked-open="$mdMedia('gt-sm')">
<md-toolbar>
<h1>Characters</h1>
</md-toolbar>
<char-list></char-list>
</md-sidenav>
</div>
|
iwatts/iwatts.github.io
|
fb/sidenav/sidenav.template.html
|
HTML
|
mit
| 306 |
public class LeetCode0363 {
public int maxSumSubmatrix(int[][] matrix, int k) {
int m = matrix.length, n = matrix[0].length, ans = Integer.MIN_VALUE;
long[] sum = new long[m + 1];
for (int i = 0; i < n; ++i) {
long[] sumInRow = new long[m];
for (int j = i; j < n; ++j) {
for (int p = 0; p < m; ++p) {
sumInRow[p] += matrix[p][j];
sum[p + 1] = sum[p] + sumInRow[p];
}
ans = Math.max(ans, mergeSort(sum, 0, m + 1, k));
if (ans == k)
return k;
}
}
return ans;
}
int mergeSort(long[] sum, int start, int end, int k) {
if (end == start + 1)
return Integer.MIN_VALUE;
int mid = start + (end - start) / 2, cnt = 0;
int ans = mergeSort(sum, start, mid, k);
if (ans == k)
return k;
ans = Math.max(ans, mergeSort(sum, mid, end, k));
if (ans == k)
return k;
long[] cache = new long[end - start];
for (int i = start, j = mid, p = mid; i < mid; ++i) {
while (j < end && sum[j] - sum[i] <= k){
++j;
}
if (j - 1 >= mid) {
ans = Math.max(ans, (int) (sum[j - 1] - sum[i]));
if (ans == k){
return k;
}
}
while (p < end && sum[p] < sum[i]){
cache[cnt++] = sum[p++];
}
cache[cnt++] = sum[i];
}
System.arraycopy(cache, 0, sum, start, cnt);
return ans;
}
}
|
dunso/algorithm
|
Java/Devide/LeetCode0363.java
|
Java
|
mit
| 1,278 |
<?php
/*
* This file is part of the PHPExifTool package.
*
* (c) Alchemy <[email protected]>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace PHPExiftool\Driver\Tag\DICOM;
use JMS\Serializer\Annotation\ExclusionPolicy;
use PHPExiftool\Driver\AbstractTag;
/**
* @ExclusionPolicy("all")
*/
class FilmBoxContentSequence extends AbstractTag
{
protected $Id = '2130,0030';
protected $Name = 'FilmBoxContentSequence';
protected $FullName = 'DICOM::Main';
protected $GroupName = 'DICOM';
protected $g0 = 'DICOM';
protected $g1 = 'DICOM';
protected $g2 = 'Image';
protected $Type = '?';
protected $Writable = false;
protected $Description = 'Film Box Content Sequence';
}
|
bburnichon/PHPExiftool
|
lib/PHPExiftool/Driver/Tag/DICOM/FilmBoxContentSequence.php
|
PHP
|
mit
| 820 |
<?php
namespace Cascade\Mapper\Map;
use Cascade\Mapper\Mapping\MappingInterface;
class Map implements MapInterface
{
/**
* @var MappingInterface[]
*/
private $mappings = [];
/**
* @param MappingInterface[] $mappings
*/
public function __construct($mappings)
{
foreach ($mappings as $mapping) {
$this->addMapping($mapping);
}
}
public function getMappings()
{
return $this->mappings;
}
/**
* @param MappingInterface $mapping
*/
private function addMapping(MappingInterface $mapping)
{
$this->mappings[] = $mapping;
}
}
|
cascademedia/php-object-mapper
|
src/Map/Map.php
|
PHP
|
mit
| 650 |
# Cisco Spark React Audio Component _(@ciscospark/react-component-audio)_
## WARNING
We renamed this module to [@webex/react-component-audio](https://www.npmjs.com/package/@webex/react-component-audio). Please install it instead.
## License
© 2016-2020 Cisco and/or its affiliates. All Rights Reserved.
|
adamweeks/react-ciscospark-1
|
packages/node_modules/@ciscospark/react-component-audio/README.md
|
Markdown
|
mit
| 308 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
import time
import numpy as np
import matplotlib
matplotlib.use('GTKAgg')
from matplotlib import pyplot as plt
from koheron import connect
from drivers import Spectrum
from drivers import Laser
host = os.getenv('HOST','192.168.1.100')
client = connect(host, name='spectrum')
driver = Spectrum(client)
laser = Laser(client)
laser.start()
current = 30 # mA
laser.set_current(current)
# driver.reset_acquisition()
wfm_size = 4096
decimation_factor = 1
index_low = 0
index_high = wfm_size / 2
signal = driver.get_decimated_data(decimation_factor, index_low, index_high)
print('Signal')
print(signal)
mhz = 1e6
sampling_rate = 125e6
freq_min = 0
freq_max = sampling_rate / mhz / 2
# Plot parameters
fig = plt.figure()
ax = fig.add_subplot(111)
x = np.linspace(freq_min, freq_max, (wfm_size / 2))
print('X')
print(len(x))
y = 10*np.log10(signal)
print('Y')
print(len(y))
li, = ax.plot(x, y)
fig.canvas.draw()
ax.set_xlim((x[0],x[-1]))
ax.set_ylim((0,200))
ax.set_xlabel('Frequency (MHz)')
ax.set_ylabel('Power spectral density (dB)')
while True:
try:
signal = driver.get_decimated_data(decimation_factor, index_low, index_high)
li.set_ydata(10*np.log10(signal))
fig.canvas.draw()
plt.pause(0.001)
except KeyboardInterrupt:
# Save last spectrum in a csv file
np.savetxt("psd.csv", signal, delimiter=",")
laser.stop()
driver.close()
break
|
Koheron/lase
|
examples/spectrum_analyzer.py
|
Python
|
mit
| 1,482 |
const assert = require('assert')
const crypto = require('crypto')
const { createRequest } = require("../util/util")
describe('测试搜索是否正常', () => {
it('获取到的数据的 name 应该和搜索关键词一致', done => {
const keywords = "海阔天空"
const type = 1
const limit = 30
const data = 's=' + keywords + '&limit=' + limit + '&type=' + type + '&offset=0'
createRequest('/api/search/pc/', 'POST', data)
.then(result => {
console.log(JSON.parse(result).result.songs[0].mp3Url)
assert(JSON.parse(result).result.songs[0].name === '海阔天空')
done()
})
.catch(err => {
done(err)
})
})
})
|
linguokang/NeteaseCloudMusic
|
test/search.test.js
|
JavaScript
|
mit
| 692 |
<footer class="site-footer">
<div class="container">
<small class="pull-right">Made with <a href="http://jekyllrb.com/" target="_blank">Jekyll</a></small>
</div>
</footer>
|
bkzhang/bkzhang.github.io
|
_includes/footer.html
|
HTML
|
mit
| 180 |
<!DOCTYPE html>
<html>
{% include head.html %}
<body>
{%include banner.html%}
{%include middle.html%}
<!-- <script src="{{ site.baseurl }}/js/index.js"></script> -->
</body>
<footer></footer>
</html>
|
huangyuanyazi/huangyuanyazi.github.io
|
_layouts/show.html
|
HTML
|
mit
| 215 |
export default function collapseDuplicateDeclarations() {
return (root) => {
root.walkRules((node) => {
let seen = new Map()
let droppable = new Set([])
node.walkDecls((decl) => {
// This could happen if we have nested selectors. In that case the
// parent will loop over all its declarations but also the declarations
// of nested rules. With this we ensure that we are shallowly checking
// declarations.
if (decl.parent !== node) {
return
}
if (seen.has(decl.prop)) {
droppable.add(seen.get(decl.prop))
}
seen.set(decl.prop, decl)
})
for (let decl of droppable) {
decl.remove()
}
})
}
}
|
tailwindcss/tailwindcss
|
src/lib/collapseDuplicateDeclarations.js
|
JavaScript
|
mit
| 742 |
module.exports = {
"env": {
"browser": true,
"commonjs": true,
"es6": true,
"jasmine" : true
},
"extends": "eslint:recommended",
"parserOptions": {
"sourceType": "module"
},
"rules": {
"no-mixed-spaces-and-tabs": [2, "smart-tabs"],
"linebreak-style": [
"error",
"unix"
],
"quotes": [
"error",
"single"
],
"semi": [
"error",
"always"
]
}
};
|
raavr/angularjs-todo-webpack
|
.eslintrc.js
|
JavaScript
|
mit
| 536 |
import * as debug from 'debug';
import Resolver from '../../resolver';
import { IRemoteUser } from '../../../../models/user';
import acceptFollow from './follow';
import { IAccept, IFollow } from '../../type';
const log = debug('misskey:activitypub');
export default async (actor: IRemoteUser, activity: IAccept): Promise<void> => {
const uri = activity.id || activity;
log(`Accept: ${uri}`);
const resolver = new Resolver();
let object;
try {
object = await resolver.resolve(activity.object);
} catch (e) {
log(`Resolution failed: ${e}`);
throw e;
}
switch (object.type) {
case 'Follow':
acceptFollow(actor, object as IFollow);
break;
default:
console.warn(`Unknown accept type: ${object.type}`);
break;
}
};
|
ha-dai/Misskey
|
src/remote/activitypub/kernel/accept/index.ts
|
TypeScript
|
mit
| 744 |
version https://git-lfs.github.com/spec/v1
oid sha256:42fcecf8fdabe110af986ac81bb56b598f5a3fa59c6d0c4cc8b80daa2dca0473
size 1121
|
yogeshsaroya/new-cdnjs
|
ajax/libs/dojo/1.4.6/_base/_loader/hostenv_spidermonkey.js
|
JavaScript
|
mit
| 129 |
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=US-ASCII">
<title>Function template make_managed_shared_ptr</title>
<link rel="stylesheet" href="../../../../doc/src/boostbook.css" type="text/css">
<meta name="generator" content="DocBook XSL Stylesheets V1.78.1">
<link rel="home" href="../../index.html" title="The Boost C++ Libraries BoostBook Documentation Subset">
<link rel="up" href="../../interprocess/acknowledgements_notes.html#header.boost.interprocess.smart_ptr.shared_ptr_hpp" title="Header <boost/interprocess/smart_ptr/shared_ptr.hpp>">
<link rel="prev" href="make_managed_s_idp50535792.html" title="Function template make_managed_shared_ptr">
<link rel="next" href="unique_ptr.html" title="Class template unique_ptr">
</head>
<body bgcolor="white" text="black" link="#0000FF" vlink="#840084" alink="#0000FF">
<table cellpadding="2" width="100%"><tr>
<td valign="top"><img alt="Boost C++ Libraries" width="277" height="86" src="../../../../boost.png"></td>
<td align="center"><a href="../../../../index.html">Home</a></td>
<td align="center"><a href="../../../../libs/libraries.htm">Libraries</a></td>
<td align="center"><a href="http://www.boost.org/users/people.html">People</a></td>
<td align="center"><a href="http://www.boost.org/users/faq.html">FAQ</a></td>
<td align="center"><a href="../../../../more/index.htm">More</a></td>
</tr></table>
<hr>
<div class="spirit-nav">
<a accesskey="p" href="make_managed_s_idp50535792.html"><img src="../../../../doc/src/images/prev.png" alt="Prev"></a><a accesskey="u" href="../../interprocess/acknowledgements_notes.html#header.boost.interprocess.smart_ptr.shared_ptr_hpp"><img src="../../../../doc/src/images/up.png" alt="Up"></a><a accesskey="h" href="../../index.html"><img src="../../../../doc/src/images/home.png" alt="Home"></a><a accesskey="n" href="unique_ptr.html"><img src="../../../../doc/src/images/next.png" alt="Next"></a>
</div>
<div class="refentry">
<a name="boost.interprocess.make_managed_s_idp50540304"></a><div class="titlepage"></div>
<div class="refnamediv">
<h2><span class="refentrytitle">Function template make_managed_shared_ptr</span></h2>
<p>boost::interprocess::make_managed_shared_ptr</p>
</div>
<h2 xmlns:rev="http://www.cs.rpi.edu/~gregod/boost/tools/doc/revision" class="refsynopsisdiv-title">Synopsis</h2>
<div xmlns:rev="http://www.cs.rpi.edu/~gregod/boost/tools/doc/revision" class="refsynopsisdiv"><pre class="synopsis"><span class="comment">// In header: <<a class="link" href="../../interprocess/acknowledgements_notes.html#header.boost.interprocess.smart_ptr.shared_ptr_hpp" title="Header <boost/interprocess/smart_ptr/shared_ptr.hpp>">boost/interprocess/smart_ptr/shared_ptr.hpp</a>>
</span>
<span class="keyword">template</span><span class="special"><</span><span class="keyword">typename</span> T<span class="special">,</span> <span class="keyword">typename</span> ManagedMemory<span class="special">></span>
<a class="link" href="managed_shared_ptr.html" title="Struct template managed_shared_ptr">managed_shared_ptr</a><span class="special"><</span> <span class="identifier">T</span><span class="special">,</span> <span class="identifier">ManagedMemory</span> <span class="special">></span><span class="special">::</span><span class="identifier">type</span>
<span class="identifier">make_managed_shared_ptr</span><span class="special">(</span><span class="identifier">T</span> <span class="special">*</span> constructed_object<span class="special">,</span>
<span class="identifier">ManagedMemory</span> <span class="special">&</span> managed_memory<span class="special">,</span> <span class="identifier">std</span><span class="special">::</span><span class="identifier">nothrow_t</span><span class="special">)</span><span class="special">;</span></pre></div>
<div class="refsect1">
<a name="idp253351568"></a><h2>Description</h2>
<p>Returns an instance of a shared pointer constructed with the default allocator and deleter from a pointer of type T that has been allocated in the passed managed segment. Does not throw, return null shared pointer in error. </p>
</div>
</div>
<table xmlns:rev="http://www.cs.rpi.edu/~gregod/boost/tools/doc/revision" width="100%"><tr>
<td align="left"></td>
<td align="right"><div class="copyright-footer">Copyright © 2005-2012 Ion Gaztanaga<p>
Distributed under the Boost Software License, Version 1.0. (See accompanying
file LICENSE_1_0.txt or copy at <a href="http://www.boost.org/LICENSE_1_0.txt" target="_top">http://www.boost.org/LICENSE_1_0.txt</a>)
</p>
</div></td>
</tr></table>
<hr>
<div class="spirit-nav">
<a accesskey="p" href="make_managed_s_idp50535792.html"><img src="../../../../doc/src/images/prev.png" alt="Prev"></a><a accesskey="u" href="../../interprocess/acknowledgements_notes.html#header.boost.interprocess.smart_ptr.shared_ptr_hpp"><img src="../../../../doc/src/images/up.png" alt="Up"></a><a accesskey="h" href="../../index.html"><img src="../../../../doc/src/images/home.png" alt="Home"></a><a accesskey="n" href="unique_ptr.html"><img src="../../../../doc/src/images/next.png" alt="Next"></a>
</div>
</body>
</html>
|
rkq/cxxexp
|
third-party/src/boost_1_56_0/doc/html/boost/interprocess/make_managed_s_idp50540304.html
|
HTML
|
mit
| 5,203 |
/**
\brief A timer module with only a single compare value. Can be used to replace
the "bsp_timer" and "radiotimer" modules with the help of abstimer.
\author Xavi Vilajosana <[email protected]>, May 2012.
\author Thomas Watteyne <[email protected]>, May 2012.
*/
#include "sctimer.h"
#include "msp430x26x.h"
//=========================== defines =========================================
//=========================== variables =======================================
typedef struct {
uint8_t running;
uint16_t taiv;
} sctimers_vars_t;
sctimers_vars_t sctimers_vars;
//=========================== prototypes ======================================
void sctimer_setup();
void sctimer_start();
//=========================== public ==========================================
void sctimer_init() {
sctimer_setup();
}
void sctimer_stop() {
sctimer_setup();
}
void sctimer_schedule(uint16_t val) {
if (sctimers_vars.running==0) {
sctimers_vars.running=1;
sctimer_start();
}
// load when to fire
TACCR1 = val;
// enable interrupt
TACCTL1 = CCIE;
}
uint16_t sctimer_getValue() {
return TAR;
}
void sctimer_setCb(sctimer_cbt cb){
// does nothing as it is done by IAR -- look at board.c
}
void sctimer_clearISR() {
sctimers_vars.taiv = TAIV;//read taiv to clear the flags.
}
//=========================== private =========================================
void sctimer_setup() {
// clear local variables
memset(&sctimers_vars,0,sizeof(sctimers_vars_t));
// ACLK sources from external 32kHz
BCSCTL3 |= LFXT1S_0;
// disable all compares
TACCTL0 = 0;
TACCR0 = 0;
// CCR1 in compare mode (disabled for now)
TACCTL1 = 0;
TACCR1 = 0;
// CCR2 in capture mode
TACCTL2 = 0;
TACCR2 = 0;
// reset couter
TAR = 0;
}
void sctimer_start() {
// start counting
TACTL = MC_2+TASSEL_1; // continuous mode, clocked from ACLK
}
|
barriquello/iotstack
|
openwsn-fw-work/firmware/openos/bsp/boards/gina/sctimer.c
|
C
|
mit
| 2,026 |
$(document).ready(function(){
var Previewer = {
preview: function(content, output) {
$.ajax({
type: 'POST',
url: "/govspeak",
data: { govspeak: content.val() },
dataType: 'json'
}).success(function(data){
output.html(data['govspeak']);
});
}
};
$("[data-preview]").each(function(){
var source_field = $($(this).data('preview-for'));
var render_area = $(this);
source_field.keyup(function() {
Previewer.preview(source_field, render_area);
})
});
$('textarea').autosize();
});
|
alphagov/trade-tariff-admin
|
app/assets/javascripts/preview.js
|
JavaScript
|
mit
| 576 |
__version__ = '0.8.1'
__author__ = "Massimiliano Pippi & Federico Frenguelli"
VERSION = __version__ # synonym
|
ramcn/demo3
|
venv/lib/python3.4/site-packages/oauth2_provider/__init__.py
|
Python
|
mit
| 113 |
/**
* @author Richard Davey <[email protected]>
* @copyright 2020 Photon Storm Ltd.
* @license {@link https://opensource.org/licenses/MIT|MIT License}
*/
/**
* @namespace Phaser.Structs
*/
module.exports = {
List: require('./List'),
Map: require('./Map'),
ProcessQueue: require('./ProcessQueue'),
RTree: require('./RTree'),
Set: require('./Set'),
Size: require('./Size')
};
|
TukekeSoft/phaser
|
src/structs/index.js
|
JavaScript
|
mit
| 425 |
#! /usr/bin/env python
"""Show file statistics by extension."""
import os
import sys
class Stats:
def __init__(self):
self.stats = {}
def statargs(self, args):
for arg in args:
if os.path.isdir(arg):
self.statdir(arg)
elif os.path.isfile(arg):
self.statfile(arg)
else:
sys.stderr.write("Can't find %s\n" % file)
self.addstats("<???>", "unknown", 1)
def statdir(self, dir):
self.addstats("<dir>", "dirs", 1)
try:
names = os.listdir(dir)
except os.error, err:
sys.stderr.write("Can't list %s: %s\n" % (file, err))
self.addstats(ext, "unlistable", 1)
return
names.sort()
for name in names:
if name.startswith(".#"):
continue # Skip CVS temp files
if name.endswith("~"):
continue# Skip Emacs backup files
full = os.path.join(dir, name)
if os.path.islink(full):
self.addstats("<lnk>", "links", 1)
elif os.path.isdir(full):
self.statdir(full)
else:
self.statfile(full)
def statfile(self, file):
head, ext = os.path.splitext(file)
head, base = os.path.split(file)
if ext == base:
ext = "" # E.g. .cvsignore is deemed not to have an extension
ext = os.path.normcase(ext)
if not ext:
ext = "<none>"
self.addstats(ext, "files", 1)
try:
f = open(file, "rb")
except IOError, err:
sys.stderr.write("Can't open %s: %s\n" % (file, err))
self.addstats(ext, "unopenable", 1)
return
data = f.read()
f.close()
self.addstats(ext, "bytes", len(data))
if '\0' in data:
self.addstats(ext, "binary", 1)
return
if not data:
self.addstats(ext, "empty", 1)
#self.addstats(ext, "chars", len(data))
lines = data.splitlines()
self.addstats(ext, "lines", len(lines))
del lines
words = data.split()
self.addstats(ext, "words", len(words))
def addstats(self, ext, key, n):
d = self.stats.setdefault(ext, {})
d[key] = d.get(key, 0) + n
def report(self):
exts = self.stats.keys()
exts.sort()
# Get the column keys
columns = {}
for ext in exts:
columns.update(self.stats[ext])
cols = columns.keys()
cols.sort()
colwidth = {}
colwidth["ext"] = max([len(ext) for ext in exts])
minwidth = 6
self.stats["TOTAL"] = {}
for col in cols:
total = 0
cw = max(minwidth, len(col))
for ext in exts:
value = self.stats[ext].get(col)
if value is None:
w = 0
else:
w = len("%d" % value)
total += value
cw = max(cw, w)
cw = max(cw, len(str(total)))
colwidth[col] = cw
self.stats["TOTAL"][col] = total
exts.append("TOTAL")
for ext in exts:
self.stats[ext]["ext"] = ext
cols.insert(0, "ext")
def printheader():
for col in cols:
print "%*s" % (colwidth[col], col),
print
printheader()
for ext in exts:
for col in cols:
value = self.stats[ext].get(col, "")
print "%*s" % (colwidth[col], value),
print
printheader() # Another header at the bottom
def main():
args = sys.argv[1:]
if not args:
args = [os.curdir]
s = Stats()
s.statargs(args)
s.report()
if __name__ == "__main__":
main()
|
OS2World/APP-INTERNET-torpak_2
|
Tools/scripts/byext.py
|
Python
|
mit
| 3,894 |
package com.ocdsoft.bacta.swg.shared.localization;
/**
* Created by crush on 11/21/2015.
*/
public class LocalizedString {
}
|
bacta/pre-cu
|
src/main/java/com/ocdsoft/bacta/swg/shared/localization/LocalizedString.java
|
Java
|
mit
| 128 |
# Contributing
## Mailing list
The main communication tool in use is the Yocto Project mailing list:
* <[email protected]>
* <https://lists.yoctoproject.org/listinfo/yocto>
Feel free to ask any kind of questions but please always prepend your email
subject with `[meta-raspberrypi]` as this is the global *Yocto* mailing
list and not a dedicated *meta-raspberrypi* mailing list.
## Formatting patches
First and foremost, all of the contributions to the layer must be compliant
with the standard openembedded patch guidelines:
* <http://www.openembedded.org/wiki/Commit_Patch_Message_Guidelines>
In summary, your commit log messages should be formatted as follows:
<layer-component>: <short log/statement of what needed to be changed>
(Optional pointers to external resources, such as defect tracking)
The intent of your change.
(Optional: if it's not clear from above, how your change resolves
the issues in the first part)
Signed-off-by: Your Name <[email protected]>
The `<layer-component>` is the layer component name that your changes affect.
It is important that you choose it correctly. A simple guide for selecting a
a good component name is the following:
* For changes that affect *layer recipes*, please just use the **base names**
of the affected recipes, separated by commas (`,`), as the component name.
For example: use `omxplayer` instead of `omxplayer_git.bb`. If you are
adding new recipe(s), just use the new recipe(s) base name(s). An example
for changes to multiple recipes would be `userland,vc-graphics,wayland`.
* For changes that affect the *layer documentation*, please just use `docs`
as the component name.
* For changes that affect *other files*, i.e. under the `conf` directory,
please use the full path as the component name, e.g. `conf/layer.conf`.
* For changes that affect the *layer itself* and do not fall into any of
the above cases, please use `meta-raspberrypi` as the component name.
A full example of a suitable commit log message is below:
foobar: Adjusted the foo setting in bar
When using foobar on systems with less than a gigabyte of RAM common
usage patterns often result in an Out-of-memory condition causing
slowdowns and unexpected application termination.
Low-memory systems should continue to function without running into
memory-starvation conditions with minimal cost to systems with more
available memory. High-memory systems will be less able to use the
full extent of the system, a dynamically tunable option may be best,
long-term.
The foo setting in bar was decreased from X to X-50% in order to
ensure we don't exhaust all system memory with foobar threads.
Signed-off-by: Joe Developer <[email protected]>
A common issue during patch reviewing is commit log formatting, please review
the above formatting guidelines carefully before sending your patches.
## Sending patches
The preferred method to contribute to this project is to send pull
requests to the GitHub mirror of the layer:
* <https://github.com/agherzan/meta-raspberrypi>
**In addition**, you may send patches for review to the above specified
mailing list. In this case, when creating patches using `git` please make
sure to use the following formatting for the message subject:
git format-patch -s --subject-prefix='meta-raspberrypi][PATCH' origin
Then, for sending patches to the mailing list, you may use this command:
git send-email --to [email protected] <generated patch>
## GitHub issues
In order to manage and track the layer issues more efficiently, the
GitHub issues facility is used by this project:
* <https://github.com/agherzan/meta-raspberrypi/issues>
If you submit patches that have a GitHub issue associated, please make sure to
use standard GitHub keywords, e.g. `closes`, `resolves` or `fixes`, before the
"Signed-off-by" tag to close the relevant issues automatically:
foobar: Adjusted the foo setting in bar
Fixes: #324
Signed-off-by: Joe Developer <[email protected]>
More information on the available GitHub close keywords can be found here:
* <https://help.github.com/articles/closing-issues-using-keywords>
|
leon-anavi/meta-raspberrypi
|
docs/contributing.md
|
Markdown
|
mit
| 4,232 |
<!doctype html>
<html>
<head>
<title>Network | Hierarchical layout</title>
<style type="text/css">
body {
font: 10pt sans;
}
#mynetwork {
width: 600px;
height: 600px;
border: 1px solid lightgray;
}
</style>
<script type="text/javascript" src="../../../dist/vis.js"></script>
<link href="../../../dist/vis-network.min.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript">
var network = null;
function p(data) {
var container = document.getElementById('mynetwork');
var options = {
layout: {
hierarchical: {},
},
};
console.log("starting layout");
network = new vis.Network(container, data, options);
console.log("layout complete");
}
</script>
</head>
<body>
<h2>Hierarchical Layout</h2>
<div id="mynetwork"></div>
<script type="text/javascript" src="./demo.jsonp"></script>
</body>
</html>
|
jucapoco/baseSiteGanttChart
|
node_modules/vis/examples/network/layout/hierarchicalLayoutBigUserDefined.html
|
HTML
|
mit
| 1,119 |
<?php
namespace WiderFunnel\OptimizelyX\Items;
/**
* Class Experiment
* @package WiderFunnel\Items;
*/
class Experiment extends ItemAbstract
{
//
}
|
WiderFunnel/Optimizely-X-SDK
|
src/OptimizelyX/Items/Experiment.php
|
PHP
|
mit
| 156 |
var jsbin = {
'root': '{{root}}',
'shareRoot': '{{shareRoot}}',
'runner': '{{runner}}',
'static': '{{static}}',
'version': '{{version}}',
user: {{{user}}},
};
(function () {
if (jsbin.user && jsbin.user.name) {
$('.loggedout').hide();
var menu = $('.loggedin').show();
var html = $('#profile-template').text();
var $html = $(html.replace(/({.*?})/g, function (all, match) {
var key = match.slice(1, -1).trim(); // ditch the wrappers
return jsbin.user[key] || '';
}));
if (jsbin.user.pro) {
document.documentElement.className += ' pro';
$html.find('.gopro').remove();
} else {
$html.find('.pro').remove();
}
menu.append($html);
} else {
$('.loggedout').show();
}
})();
|
mingzeke/jsbin
|
views/user.html
|
HTML
|
mit
| 757 |
Hi, this is Mirong Kim.
|
SFPC/ExperimentalMedia
|
people/mirong/about.md
|
Markdown
|
mit
| 25 |
/*------------------------------------*\
# components.profile
\*------------------------------------*/
.profile__login {
position: relative;
display: inline-block;
z-index: 50;
padding-bottom: .5rem;
}
.profile__login__icon {
width: 2.5rem;
margin-bottom: -0.7rem;
}
.profile__login__popup {
opacity: 0;
position: absolute;
right: 3rem;
padding: 1rem;
margin-top: 1rem;
border-radius: .5rem;
white-space: nowrap;
background: var(--color-secondary);
transition: all .2s ease-in-out;
}
.profile__login__popup::before {
content: "";
position: absolute;
top: -0.5rem;
right: 0.8rem;
border-left: 0.625rem solid transparent;
border-right: 0.625rem solid transparent;
border-bottom: 0.625rem solid var(--color-secondary);
transition-duration: 0.2s;
transition-property: transform;
}
.profile__login__link {
font-family: var(--ff-sans);
text-decoration: none;
color: white;
transition: color .2s ease-in-out;
}
.profile__login__link:hover {
color: var(--ultra-dark);
}
.profile__login:hover .profile__login__popup {
opacity: 1;
transform: translate(3rem);
transition: all 0.5s cubic-bezier(0.75, -0.02, 0.2, 0.97);
}
|
Baasic/baasic-starterkit-angularjs-app-webiste
|
src/themes/apptheme/src/components.profilelogin.css
|
CSS
|
mit
| 1,242 |
using System.Text;
namespace GuruComponents.Netrix.Events
{
/// <summary>
/// SaveEventArgs provides information about the current save process.
/// </summary>
public class SaveEventArgs : LoadEventArgs
{
/// <summary>
/// Constructor. It's build by Save event handler and not intendet to being called from user's code.
/// </summary>
/// <param name="encoding"></param>
/// <param name="url"></param>
public SaveEventArgs(Encoding encoding, string url) : base(encoding, url)
{
}
/// <summary>
/// Set another encoding temporarily, if used within the <see cref="IHtmlEditor.Saving">Saving</see> event.
/// </summary>
/// <param name="encoding"></param>
public void SetEncoding(Encoding encoding)
{
_encoding = encoding;
}
}
}
|
joergkrause/netrix
|
NetrixPackage/Core/Events/SaveEventArgs.cs
|
C#
|
mit
| 820 |
YUI.add("yuidoc-meta", function(Y) {
Y.YUIDoc = { meta: {
"classes": [
"Audio"
],
"modules": [
"gallery-audio"
],
"allModules": [
{
"displayName": "gallery-audio",
"name": "gallery-audio"
}
]
} };
});
|
inikoo/fact
|
libs/yui/yui3-gallery/src/gallery-audio/api/api.js
|
JavaScript
|
mit
| 283 |
// angular
import { HttpClient } from '@angular/common/http';
import { Routes } from '@angular/router';
// libs
import * as _ from 'lodash';
import { I18NRouterLoader, I18NRouterSettings } from '@ngx-i18n-router/core';
export class I18NRouterHttpLoader implements I18NRouterLoader {
private _translations: any;
get routes(): Routes {
return _.map(this.providedSettings.routes, _.cloneDeep);
}
get translations(): any {
return this._translations;
}
constructor(private readonly http: HttpClient,
private readonly path: string = '/routes.json',
private readonly providedSettings: I18NRouterSettings = {}) {
}
loadTranslations(): any {
return new Promise((resolve, reject) => {
this.http.get(this.path)
.subscribe(res => {
this._translations = res;
return resolve(res);
}, () => reject('Endpoint unreachable!'));
});
}
}
|
fulls1z3/ngx-i18n-router
|
packages/@ngx-i18n-router/http-loader/src/i18n-router.http-loader.ts
|
TypeScript
|
mit
| 929 |
'use strict';
var fs = require('fs'),
util = require('util'),
Duplexify = require('duplexify'),
_ = require('lodash'),
su = require('bindings')('serialutil.node'),
fsu = require('./fsutil'),
pins = require('./pins'),
Dto = require('./dto'),
dto = new Dto(__dirname + '/../templates/uart.dts');
var DEFAULT_OPTIONS;
function onopen(uart, options) {
if (uart._rxfd !== -1 && uart._txfd !== -1) {
su.setRawMode(uart._rxfd);
uart.baudRate(options.baudRate);
uart.characterSize(options.characterSize);
uart.parity(options.parity);
uart.stopBits(options.stopBits);
setImmediate(function () {
uart.emit('open');
uart.emit('ready');
});
}
}
function onclose(uart) {
if (uart._rxfd === -1 && uart._txfd === -1) {
setImmediate(function () {
uart.emit('close');
});
}
}
function createStreams(uart, options) {
uart._rxfd = -1;
uart._txfd = -1;
uart._rxstream = fs.createReadStream(uart.devPath, {
highWaterMark: options.highWaterMark,
encoding: options.encoding
});
uart._txstream = fs.createWriteStream(uart.devPath, {
highWaterMark: options.highWaterMark,
encoding: options.encoding,
flags: 'r+'
});
uart._rxstream.once('open', function (rxfd) {
uart._rxfd = rxfd;
onopen(uart, options);
});
uart._txstream.once('open', function (txfd) {
uart._txfd = txfd;
onopen(uart, options);
});
uart._rxstream.once('close', function () {
uart._rxfd = -1;
onclose(uart);
});
uart._txstream.once('close', function () {
uart._txfd = -1;
onclose(uart);
});
// TODO - test error handling
uart.setReadable(uart._rxstream);
uart.setWritable(uart._txstream);
}
function waitForUart(uart, options) {
fsu.waitForFile(uart.devPath, function (err, devPath) {
if (err) {
return uart.emit('error', err);
}
createStreams(uart, options);
});
}
function Uart(uartDef, options) {
var badPin,
config;
if (!(this instanceof Uart)) {
return new Uart(uartDef);
}
options = options ? _.defaults(options, DEFAULT_OPTIONS) : DEFAULT_OPTIONS;
// Consider calling Duplexify with the allowHalfOpen option set to false.
// It's super-class (Duplex) will then ensure that this.end is called when
// the read stream fires the 'end' event. (see:
// https://github.com/joyent/node/blob/v0.10.25/lib/_stream_duplex.js)
Duplexify.call(this, null, null);
if (typeof uartDef === 'string') {
this.uartDef = null;
this.devPath = uartDef;
this.name = null;
waitForUart(this, options);
} else {
if (uartDef.txPin.uart === undefined) {
badPin = new Error(uartDef.txPin + ' doesn\'t support uarts');
} else if (uartDef.rxPin.uart === undefined) {
badPin = new Error(uartDef.rxPin + ' doesn\'t support uarts');
}
if (badPin) {
setImmediate(function () {
this.emit('error', badPin);
}.bind(this));
return;
}
this.uartDef = uartDef;
this.devPath = '/dev/ttyO' + uartDef.id;
this.name = 'bot_uart' + uartDef.id;
config = {
txHeader: this.uartDef.txPin.name.toUpperCase().replace('_', '.'),
rxHeader: this.uartDef.rxPin.name.toUpperCase().replace('_', '.'),
hardwareIp: 'uart' + this.uartDef.id,
name: this.name,
rxMuxOffset: '0x' + this.uartDef.rxPin.muxOffset.toString(16),
rxMuxValue: '0x' + this.uartDef.rxPin.uart.muxValue.toString(16),
txMuxOffset: '0x' + this.uartDef.txPin.muxOffset.toString(16),
txMuxValue: '0x' + this.uartDef.txPin.uart.muxValue.toString(16),
targetUart: 'uart' + (this.uartDef.id + 1),
partNumber: this.name
};
dto.install(config, function (err) {
if (err) {
return this.emit('error', err);
}
waitForUart(this, options);
}.bind(this));
}
}
module.exports = Uart;
util.inherits(Uart, Duplexify);
Uart.B0 = su.B0;
Uart.B50 = su.B50;
Uart.B75 = su.B75;
Uart.B110 = su.B110;
Uart.B134 = su.B134;
Uart.B150 = su.B150;
Uart.B200 = su.B200;
Uart.B300 = su.B300;
Uart.B600 = su.B600;
Uart.B1200 = su.B1200;
Uart.B1800 = su.B1800;
Uart.B2400 = su.B2400;
Uart.B4800 = su.B4800;
Uart.B9600 = su.B9600;
Uart.B19200 = su.B19200;
Uart.B38400 = su.B38400;
Uart.B57600 = su.B57600;
Uart.B115200 = su.B115200;
Uart.B230400 = su.B230400;
Uart.B460800 = su.B460800;
Uart.B500000 = su.B500000;
Uart.B576000 = su.B576000;
Uart.B921600 = su.B921600;
Uart.B1000000 = su.B1000000;
Uart.B1152000 = su.B1152000;
Uart.B1500000 = su.B1500000;
Uart.B2000000 = su.B2000000;
Uart.B2500000 = su.B2500000;
Uart.B3000000 = su.B3000000;
Uart.B3500000 = su.B3500000;
Uart.B4000000 = su.B4000000;
Uart.PARITY_NONE = su.PARITY_NONE;
Uart.PARITY_ODD = su.PARITY_ODD;
Uart.PARITY_EVEN = su.PARITY_EVEN;
Uart.UART1 = {
id: 1,
txPin: pins.p9_24,
rxPin: pins.p9_26
};
Uart.UART2 = {
id: 2,
txPin: pins.p9_21,
rxPin: pins.p9_22
};
Uart.UART4 = {
id: 4,
txPin: pins.p9_13,
rxPin: pins.p9_11
};
DEFAULT_OPTIONS = {
baudRate: Uart.B38400,
characterSize: 8,
parity: Uart.PARITY_NONE,
stopBits: 1,
highWaterMark: 512,
encoding: null
};
Object.freeze(DEFAULT_OPTIONS);
Uart.prototype.baudRate = function (rate) {
if (rate === undefined) {
return su.getBaudRate(this._rxfd);
}
su.setBaudRate(this._rxfd, rate);
};
Uart.prototype.characterSize = function (size) {
if (size === undefined) {
return su.getCharacterSize(this._rxfd);
}
su.setCharacterSize(this._rxfd, size);
};
Uart.prototype.parity = function (type) {
if (type === undefined) {
return su.getParity(this._rxfd);
}
su.setParity(this._rxfd, type);
};
Uart.prototype.stopBits = function (count) {
if (count === undefined) {
return su.getStopBits(this._rxfd);
}
su.setStopBits(this._rxfd, count);
};
Uart.prototype.close = function () {
this.removeAllListeners('data'); // Is this a good idea? Should the user be doing this?
// TODO: the following is a bit of a hack.
// Here \n EOF is faked for this._rxfd inorder to close the read stream.
// It's faked three times as the uart may receive a character between
// \n and EOF and the stream will not be closed. Faking three times
// increases the chances of it working!
su.setCanonical(this._rxfd, true);
su.fakeInput(this._rxfd, '\n'.charCodeAt(0));
su.fakeInput(this._rxfd, 4); // fake eof
su.fakeInput(this._rxfd, '\n'.charCodeAt(0));
su.fakeInput(this._rxfd, 4); // fake eof
su.fakeInput(this._rxfd, '\n'.charCodeAt(0));
su.fakeInput(this._rxfd, 4); // fake eof
};
|
fivdi/brkontru
|
lib/uart.js
|
JavaScript
|
mit
| 6,528 |
package de.andreasgiemza.mangadownloader.gui.chapter;
import de.andreasgiemza.mangadownloader.MangaDownloader;
import de.andreasgiemza.mangadownloader.helpers.RegexHelper;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.RowFilter;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import javax.swing.table.TableRowSorter;
/**
*
* @author Andreas Giemza <[email protected]>
*/
public class ChapterListSearchDocumentListener implements DocumentListener {
private final MangaDownloader mangaDownloader;
private final JTextField chapterListSearchTextField;
private final TableRowSorter<ChapterTableModel> chapterTableRowSorter;
@SuppressWarnings("unchecked")
public ChapterListSearchDocumentListener(MangaDownloader mangaDownloader,
JTextField chapterListSearchTextField, JTable chapterListTable) {
this.mangaDownloader = mangaDownloader;
this.chapterListSearchTextField = chapterListSearchTextField;
chapterTableRowSorter = (TableRowSorter<ChapterTableModel>) chapterListTable
.getRowSorter();
}
@Override
public void insertUpdate(DocumentEvent e) {
changed();
}
@Override
public void removeUpdate(DocumentEvent e) {
changed();
}
@Override
public void changedUpdate(DocumentEvent e) {
changed();
}
private void changed() {
mangaDownloader.chapterSearchChanged();
final String searchText = chapterListSearchTextField.getText();
if (searchText.length() == 0) {
chapterTableRowSorter.setRowFilter(null);
} else if (searchText.length() > 0) {
chapterTableRowSorter.setRowFilter(RowFilter
.regexFilter(RegexHelper.build(searchText)));
}
}
}
|
hurik/MangaDownloader
|
src/main/java/de/andreasgiemza/mangadownloader/gui/chapter/ChapterListSearchDocumentListener.java
|
Java
|
mit
| 1,897 |
package nxt.http;
import nxt.Account;
import nxt.Attachment;
import nxt.Constants;
import nxt.NxtException;
import nxt.util.Convert;
import org.json.simple.JSONStreamAware;
import javax.servlet.http.HttpServletRequest;
import static nxt.http.JSONResponses.INCORRECT_ASSET;
import static nxt.http.JSONResponses.INCORRECT_PRICE;
import static nxt.http.JSONResponses.INCORRECT_QUANTITY;
import static nxt.http.JSONResponses.MISSING_ASSET;
import static nxt.http.JSONResponses.MISSING_PRICE;
import static nxt.http.JSONResponses.MISSING_QUANTITY;
import static nxt.http.JSONResponses.NOT_ENOUGH_ASSETS;
import static nxt.http.JSONResponses.UNKNOWN_ACCOUNT;
public final class PlaceAskOrder extends CreateTransaction {
static final PlaceAskOrder instance = new PlaceAskOrder();
private PlaceAskOrder() {
super("asset", "quantity", "price");
}
@Override
JSONStreamAware processRequest(HttpServletRequest req) throws NxtException.ValidationException {
String assetValue = req.getParameter("asset");
String quantityValue = req.getParameter("quantity");
String priceValue = req.getParameter("price");
if (assetValue == null) {
return MISSING_ASSET;
} else if (quantityValue == null) {
return MISSING_QUANTITY;
} else if (priceValue == null) {
return MISSING_PRICE;
}
long price;
try {
price = Long.parseLong(priceValue);
if (price <= 0 || price > Constants.MAX_BALANCE * 100L) {
return INCORRECT_PRICE;
}
} catch (NumberFormatException e) {
return INCORRECT_PRICE;
}
Long asset;
try {
asset = Convert.parseUnsignedLong(assetValue);
} catch (RuntimeException e) {
return INCORRECT_ASSET;
}
int quantity;
try {
quantity = Integer.parseInt(quantityValue);
if (quantity <= 0 || quantity > Constants.MAX_ASSET_QUANTITY) {
return INCORRECT_QUANTITY;
}
} catch (NumberFormatException e) {
return INCORRECT_QUANTITY;
}
Account account = getAccount(req);
if (account == null) {
return UNKNOWN_ACCOUNT;
}
Integer assetBalance = account.getUnconfirmedAssetBalance(asset);
if (assetBalance == null || quantity > assetBalance) {
return NOT_ENOUGH_ASSETS;
}
Attachment attachment = new Attachment.ColoredCoinsAskOrderPlacement(asset, quantity, price);
return createTransaction(req, account, attachment);
}
}
|
aspnmy/NasCoin
|
src/java/nxt/http/PlaceAskOrder.java
|
Java
|
mit
| 2,662 |
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
var _react = require('react');
var _react2 = _interopRequireDefault(_react);
var _reactIconBase = require('react-icon-base');
var _reactIconBase2 = _interopRequireDefault(_reactIconBase);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var FaHouzz = function FaHouzz(props) {
return _react2.default.createElement(
_reactIconBase2.default,
_extends({ viewBox: '0 0 40 40' }, props),
_react2.default.createElement(
'g',
null,
_react2.default.createElement('path', { d: 'm19.9 26.6l11.5-6.6v13.2l-11.5 6.6v-13.2z m-11.4-6.6v13.2l11.4-6.6z m11.4-19.8v13.2l-11.4 6.6v-13.2z m0 13.2l11.5-6.6v13.2z' })
)
);
};
exports.default = FaHouzz;
module.exports = exports['default'];
|
bengimbel/Solstice-React-Contacts-Project
|
node_modules/react-icons/lib/fa/houzz.js
|
JavaScript
|
mit
| 1,139 |
//===--- JumpDiagnostics.cpp - Protected scope jump analysis ------*- C++ -*-=//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file implements the JumpScopeChecker class, which is used to diagnose
// jumps that enter a protected scope in an invalid way.
//
//===----------------------------------------------------------------------===//
#include "clang/Sema/SemaInternal.h"
#include "clang/AST/DeclCXX.h"
#include "clang/AST/Expr.h"
#include "clang/AST/ExprCXX.h"
#include "clang/AST/StmtCXX.h"
#include "clang/AST/StmtObjC.h"
#include "llvm/ADT/BitVector.h"
using namespace clang;
namespace {
/// JumpScopeChecker - This object is used by Sema to diagnose invalid jumps
/// into VLA and other protected scopes. For example, this rejects:
/// goto L;
/// int a[n];
/// L:
///
class JumpScopeChecker {
Sema &S;
/// Permissive - True when recovering from errors, in which case precautions
/// are taken to handle incomplete scope information.
const bool Permissive;
/// GotoScope - This is a record that we use to keep track of all of the
/// scopes that are introduced by VLAs and other things that scope jumps like
/// gotos. This scope tree has nothing to do with the source scope tree,
/// because you can have multiple VLA scopes per compound statement, and most
/// compound statements don't introduce any scopes.
struct GotoScope {
/// ParentScope - The index in ScopeMap of the parent scope. This is 0 for
/// the parent scope is the function body.
unsigned ParentScope;
/// InDiag - The note to emit if there is a jump into this scope.
unsigned InDiag;
/// OutDiag - The note to emit if there is an indirect jump out
/// of this scope. Direct jumps always clean up their current scope
/// in an orderly way.
unsigned OutDiag;
/// Loc - Location to emit the diagnostic.
SourceLocation Loc;
GotoScope(unsigned parentScope, unsigned InDiag, unsigned OutDiag,
SourceLocation L)
: ParentScope(parentScope), InDiag(InDiag), OutDiag(OutDiag), Loc(L) {}
};
SmallVector<GotoScope, 48> Scopes;
llvm::DenseMap<Stmt*, unsigned> LabelAndGotoScopes;
SmallVector<Stmt*, 16> Jumps;
SmallVector<IndirectGotoStmt*, 4> IndirectJumps;
SmallVector<LabelDecl*, 4> IndirectJumpTargets;
public:
JumpScopeChecker(Stmt *Body, Sema &S);
private:
void BuildScopeInformation(Decl *D, unsigned &ParentScope);
void BuildScopeInformation(VarDecl *D, const BlockDecl *BDecl,
unsigned &ParentScope);
void BuildScopeInformation(Stmt *S, unsigned &origParentScope);
void VerifyJumps();
void VerifyIndirectJumps();
void NoteJumpIntoScopes(ArrayRef<unsigned> ToScopes);
void DiagnoseIndirectJump(IndirectGotoStmt *IG, unsigned IGScope,
LabelDecl *Target, unsigned TargetScope);
void CheckJump(Stmt *From, Stmt *To, SourceLocation DiagLoc,
unsigned JumpDiag, unsigned JumpDiagWarning,
unsigned JumpDiagCXX98Compat);
void CheckGotoStmt(GotoStmt *GS);
unsigned GetDeepestCommonScope(unsigned A, unsigned B);
};
} // end anonymous namespace
#define CHECK_PERMISSIVE(x) (assert(Permissive || !(x)), (Permissive && (x)))
JumpScopeChecker::JumpScopeChecker(Stmt *Body, Sema &s)
: S(s), Permissive(s.hasAnyUnrecoverableErrorsInThisFunction()) {
// Add a scope entry for function scope.
Scopes.push_back(GotoScope(~0U, ~0U, ~0U, SourceLocation()));
// Build information for the top level compound statement, so that we have a
// defined scope record for every "goto" and label.
unsigned BodyParentScope = 0;
BuildScopeInformation(Body, BodyParentScope);
// Check that all jumps we saw are kosher.
VerifyJumps();
VerifyIndirectJumps();
}
/// GetDeepestCommonScope - Finds the innermost scope enclosing the
/// two scopes.
unsigned JumpScopeChecker::GetDeepestCommonScope(unsigned A, unsigned B) {
while (A != B) {
// Inner scopes are created after outer scopes and therefore have
// higher indices.
if (A < B) {
assert(Scopes[B].ParentScope < B);
B = Scopes[B].ParentScope;
} else {
assert(Scopes[A].ParentScope < A);
A = Scopes[A].ParentScope;
}
}
return A;
}
typedef std::pair<unsigned,unsigned> ScopePair;
/// GetDiagForGotoScopeDecl - If this decl induces a new goto scope, return a
/// diagnostic that should be emitted if control goes over it. If not, return 0.
static ScopePair GetDiagForGotoScopeDecl(Sema &S, const Decl *D) {
if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
unsigned InDiag = 0;
unsigned OutDiag = 0;
if (VD->getType()->isVariablyModifiedType())
InDiag = diag::note_protected_by_vla;
if (VD->hasAttr<BlocksAttr>())
return ScopePair(diag::note_protected_by___block,
diag::note_exits___block);
if (VD->hasAttr<CleanupAttr>())
return ScopePair(diag::note_protected_by_cleanup,
diag::note_exits_cleanup);
if (VD->hasLocalStorage()) {
switch (VD->getType().isDestructedType()) {
case QualType::DK_objc_strong_lifetime:
return ScopePair(diag::note_protected_by_objc_strong_init,
diag::note_exits_objc_strong);
case QualType::DK_objc_weak_lifetime:
return ScopePair(diag::note_protected_by_objc_weak_init,
diag::note_exits_objc_weak);
case QualType::DK_cxx_destructor:
OutDiag = diag::note_exits_dtor;
break;
case QualType::DK_none:
break;
}
}
const Expr *Init = VD->getInit();
if (S.Context.getLangOpts().CPlusPlus && VD->hasLocalStorage() && Init) {
// C++11 [stmt.dcl]p3:
// A program that jumps from a point where a variable with automatic
// storage duration is not in scope to a point where it is in scope
// is ill-formed unless the variable has scalar type, class type with
// a trivial default constructor and a trivial destructor, a
// cv-qualified version of one of these types, or an array of one of
// the preceding types and is declared without an initializer.
// C++03 [stmt.dcl.p3:
// A program that jumps from a point where a local variable
// with automatic storage duration is not in scope to a point
// where it is in scope is ill-formed unless the variable has
// POD type and is declared without an initializer.
InDiag = diag::note_protected_by_variable_init;
// For a variable of (array of) class type declared without an
// initializer, we will have call-style initialization and the initializer
// will be the CXXConstructExpr with no intervening nodes.
if (const CXXConstructExpr *CCE = dyn_cast<CXXConstructExpr>(Init)) {
const CXXConstructorDecl *Ctor = CCE->getConstructor();
if (Ctor->isTrivial() && Ctor->isDefaultConstructor() &&
VD->getInitStyle() == VarDecl::CallInit) {
if (OutDiag)
InDiag = diag::note_protected_by_variable_nontriv_destructor;
else if (!Ctor->getParent()->isPOD())
InDiag = diag::note_protected_by_variable_non_pod;
else
InDiag = 0;
}
}
}
return ScopePair(InDiag, OutDiag);
}
if (const TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D)) {
if (TD->getUnderlyingType()->isVariablyModifiedType())
return ScopePair(isa<TypedefDecl>(TD)
? diag::note_protected_by_vla_typedef
: diag::note_protected_by_vla_type_alias,
0);
}
return ScopePair(0U, 0U);
}
/// \brief Build scope information for a declaration that is part of a DeclStmt.
void JumpScopeChecker::BuildScopeInformation(Decl *D, unsigned &ParentScope) {
// If this decl causes a new scope, push and switch to it.
std::pair<unsigned,unsigned> Diags = GetDiagForGotoScopeDecl(S, D);
if (Diags.first || Diags.second) {
Scopes.push_back(GotoScope(ParentScope, Diags.first, Diags.second,
D->getLocation()));
ParentScope = Scopes.size()-1;
}
// If the decl has an initializer, walk it with the potentially new
// scope we just installed.
if (VarDecl *VD = dyn_cast<VarDecl>(D))
if (Expr *Init = VD->getInit())
BuildScopeInformation(Init, ParentScope);
}
/// \brief Build scope information for a captured block literal variables.
void JumpScopeChecker::BuildScopeInformation(VarDecl *D,
const BlockDecl *BDecl,
unsigned &ParentScope) {
// exclude captured __block variables; there's no destructor
// associated with the block literal for them.
if (D->hasAttr<BlocksAttr>())
return;
QualType T = D->getType();
QualType::DestructionKind destructKind = T.isDestructedType();
if (destructKind != QualType::DK_none) {
std::pair<unsigned,unsigned> Diags;
switch (destructKind) {
case QualType::DK_cxx_destructor:
Diags = ScopePair(diag::note_enters_block_captures_cxx_obj,
diag::note_exits_block_captures_cxx_obj);
break;
case QualType::DK_objc_strong_lifetime:
Diags = ScopePair(diag::note_enters_block_captures_strong,
diag::note_exits_block_captures_strong);
break;
case QualType::DK_objc_weak_lifetime:
Diags = ScopePair(diag::note_enters_block_captures_weak,
diag::note_exits_block_captures_weak);
break;
case QualType::DK_none:
llvm_unreachable("non-lifetime captured variable");
}
SourceLocation Loc = D->getLocation();
if (Loc.isInvalid())
Loc = BDecl->getLocation();
Scopes.push_back(GotoScope(ParentScope,
Diags.first, Diags.second, Loc));
ParentScope = Scopes.size()-1;
}
}
/// BuildScopeInformation - The statements from CI to CE are known to form a
/// coherent VLA scope with a specified parent node. Walk through the
/// statements, adding any labels or gotos to LabelAndGotoScopes and recursively
/// walking the AST as needed.
void JumpScopeChecker::BuildScopeInformation(Stmt *S,
unsigned &origParentScope) {
// If this is a statement, rather than an expression, scopes within it don't
// propagate out into the enclosing scope. Otherwise we have to worry
// about block literals, which have the lifetime of their enclosing statement.
unsigned independentParentScope = origParentScope;
unsigned &ParentScope = ((isa<Expr>(S) && !isa<StmtExpr>(S))
? origParentScope : independentParentScope);
unsigned StmtsToSkip = 0u;
// If we found a label, remember that it is in ParentScope scope.
switch (S->getStmtClass()) {
case Stmt::AddrLabelExprClass:
IndirectJumpTargets.push_back(cast<AddrLabelExpr>(S)->getLabel());
break;
case Stmt::IndirectGotoStmtClass:
// "goto *&&lbl;" is a special case which we treat as equivalent
// to a normal goto. In addition, we don't calculate scope in the
// operand (to avoid recording the address-of-label use), which
// works only because of the restricted set of expressions which
// we detect as constant targets.
if (cast<IndirectGotoStmt>(S)->getConstantTarget()) {
LabelAndGotoScopes[S] = ParentScope;
Jumps.push_back(S);
return;
}
LabelAndGotoScopes[S] = ParentScope;
IndirectJumps.push_back(cast<IndirectGotoStmt>(S));
break;
case Stmt::SwitchStmtClass:
// Evaluate the C++17 init stmt and condition variable
// before entering the scope of the switch statement.
if (Stmt *Init = cast<SwitchStmt>(S)->getInit()) {
BuildScopeInformation(Init, ParentScope);
++StmtsToSkip;
}
if (VarDecl *Var = cast<SwitchStmt>(S)->getConditionVariable()) {
BuildScopeInformation(Var, ParentScope);
++StmtsToSkip;
}
// Fall through
case Stmt::GotoStmtClass:
// Remember both what scope a goto is in as well as the fact that we have
// it. This makes the second scan not have to walk the AST again.
LabelAndGotoScopes[S] = ParentScope;
Jumps.push_back(S);
break;
case Stmt::IfStmtClass: {
IfStmt *IS = cast<IfStmt>(S);
if (!(IS->isConstexpr() || IS->isObjCAvailabilityCheck()))
break;
unsigned Diag = IS->isConstexpr() ? diag::note_protected_by_constexpr_if
: diag::note_protected_by_if_available;
if (VarDecl *Var = IS->getConditionVariable())
BuildScopeInformation(Var, ParentScope);
// Cannot jump into the middle of the condition.
unsigned NewParentScope = Scopes.size();
Scopes.push_back(GotoScope(ParentScope, Diag, 0, IS->getLocStart()));
BuildScopeInformation(IS->getCond(), NewParentScope);
// Jumps into either arm of an 'if constexpr' are not allowed.
NewParentScope = Scopes.size();
Scopes.push_back(GotoScope(ParentScope, Diag, 0, IS->getLocStart()));
BuildScopeInformation(IS->getThen(), NewParentScope);
if (Stmt *Else = IS->getElse()) {
NewParentScope = Scopes.size();
Scopes.push_back(GotoScope(ParentScope, Diag, 0, IS->getLocStart()));
BuildScopeInformation(Else, NewParentScope);
}
return;
}
case Stmt::CXXTryStmtClass: {
CXXTryStmt *TS = cast<CXXTryStmt>(S);
{
unsigned NewParentScope = Scopes.size();
Scopes.push_back(GotoScope(ParentScope,
diag::note_protected_by_cxx_try,
diag::note_exits_cxx_try,
TS->getSourceRange().getBegin()));
if (Stmt *TryBlock = TS->getTryBlock())
BuildScopeInformation(TryBlock, NewParentScope);
}
// Jump from the catch into the try is not allowed either.
for (unsigned I = 0, E = TS->getNumHandlers(); I != E; ++I) {
CXXCatchStmt *CS = TS->getHandler(I);
unsigned NewParentScope = Scopes.size();
Scopes.push_back(GotoScope(ParentScope,
diag::note_protected_by_cxx_catch,
diag::note_exits_cxx_catch,
CS->getSourceRange().getBegin()));
BuildScopeInformation(CS->getHandlerBlock(), NewParentScope);
}
return;
}
case Stmt::SEHTryStmtClass: {
SEHTryStmt *TS = cast<SEHTryStmt>(S);
{
unsigned NewParentScope = Scopes.size();
Scopes.push_back(GotoScope(ParentScope,
diag::note_protected_by_seh_try,
diag::note_exits_seh_try,
TS->getSourceRange().getBegin()));
if (Stmt *TryBlock = TS->getTryBlock())
BuildScopeInformation(TryBlock, NewParentScope);
}
// Jump from __except or __finally into the __try are not allowed either.
if (SEHExceptStmt *Except = TS->getExceptHandler()) {
unsigned NewParentScope = Scopes.size();
Scopes.push_back(GotoScope(ParentScope,
diag::note_protected_by_seh_except,
diag::note_exits_seh_except,
Except->getSourceRange().getBegin()));
BuildScopeInformation(Except->getBlock(), NewParentScope);
} else if (SEHFinallyStmt *Finally = TS->getFinallyHandler()) {
unsigned NewParentScope = Scopes.size();
Scopes.push_back(GotoScope(ParentScope,
diag::note_protected_by_seh_finally,
diag::note_exits_seh_finally,
Finally->getSourceRange().getBegin()));
BuildScopeInformation(Finally->getBlock(), NewParentScope);
}
return;
}
case Stmt::DeclStmtClass: {
// If this is a declstmt with a VLA definition, it defines a scope from here
// to the end of the containing context.
DeclStmt *DS = cast<DeclStmt>(S);
// The decl statement creates a scope if any of the decls in it are VLAs
// or have the cleanup attribute.
for (auto *I : DS->decls())
BuildScopeInformation(I, origParentScope);
return;
}
case Stmt::ObjCAtTryStmtClass: {
// Disallow jumps into any part of an @try statement by pushing a scope and
// walking all sub-stmts in that scope.
ObjCAtTryStmt *AT = cast<ObjCAtTryStmt>(S);
// Recursively walk the AST for the @try part.
{
unsigned NewParentScope = Scopes.size();
Scopes.push_back(GotoScope(ParentScope,
diag::note_protected_by_objc_try,
diag::note_exits_objc_try,
AT->getAtTryLoc()));
if (Stmt *TryPart = AT->getTryBody())
BuildScopeInformation(TryPart, NewParentScope);
}
// Jump from the catch to the finally or try is not valid.
for (unsigned I = 0, N = AT->getNumCatchStmts(); I != N; ++I) {
ObjCAtCatchStmt *AC = AT->getCatchStmt(I);
unsigned NewParentScope = Scopes.size();
Scopes.push_back(GotoScope(ParentScope,
diag::note_protected_by_objc_catch,
diag::note_exits_objc_catch,
AC->getAtCatchLoc()));
// @catches are nested and it isn't
BuildScopeInformation(AC->getCatchBody(), NewParentScope);
}
// Jump from the finally to the try or catch is not valid.
if (ObjCAtFinallyStmt *AF = AT->getFinallyStmt()) {
unsigned NewParentScope = Scopes.size();
Scopes.push_back(GotoScope(ParentScope,
diag::note_protected_by_objc_finally,
diag::note_exits_objc_finally,
AF->getAtFinallyLoc()));
BuildScopeInformation(AF, NewParentScope);
}
return;
}
case Stmt::ObjCAtSynchronizedStmtClass: {
// Disallow jumps into the protected statement of an @synchronized, but
// allow jumps into the object expression it protects.
ObjCAtSynchronizedStmt *AS = cast<ObjCAtSynchronizedStmt>(S);
// Recursively walk the AST for the @synchronized object expr, it is
// evaluated in the normal scope.
BuildScopeInformation(AS->getSynchExpr(), ParentScope);
// Recursively walk the AST for the @synchronized part, protected by a new
// scope.
unsigned NewParentScope = Scopes.size();
Scopes.push_back(GotoScope(ParentScope,
diag::note_protected_by_objc_synchronized,
diag::note_exits_objc_synchronized,
AS->getAtSynchronizedLoc()));
BuildScopeInformation(AS->getSynchBody(), NewParentScope);
return;
}
case Stmt::ObjCAutoreleasePoolStmtClass: {
// Disallow jumps into the protected statement of an @autoreleasepool.
ObjCAutoreleasePoolStmt *AS = cast<ObjCAutoreleasePoolStmt>(S);
// Recursively walk the AST for the @autoreleasepool part, protected by a
// new scope.
unsigned NewParentScope = Scopes.size();
Scopes.push_back(GotoScope(ParentScope,
diag::note_protected_by_objc_autoreleasepool,
diag::note_exits_objc_autoreleasepool,
AS->getAtLoc()));
BuildScopeInformation(AS->getSubStmt(), NewParentScope);
return;
}
case Stmt::ExprWithCleanupsClass: {
// Disallow jumps past full-expressions that use blocks with
// non-trivial cleanups of their captures. This is theoretically
// implementable but a lot of work which we haven't felt up to doing.
ExprWithCleanups *EWC = cast<ExprWithCleanups>(S);
for (unsigned i = 0, e = EWC->getNumObjects(); i != e; ++i) {
const BlockDecl *BDecl = EWC->getObject(i);
for (const auto &CI : BDecl->captures()) {
VarDecl *variable = CI.getVariable();
BuildScopeInformation(variable, BDecl, origParentScope);
}
}
break;
}
case Stmt::MaterializeTemporaryExprClass: {
// Disallow jumps out of scopes containing temporaries lifetime-extended to
// automatic storage duration.
MaterializeTemporaryExpr *MTE = cast<MaterializeTemporaryExpr>(S);
if (MTE->getStorageDuration() == SD_Automatic) {
SmallVector<const Expr *, 4> CommaLHS;
SmallVector<SubobjectAdjustment, 4> Adjustments;
const Expr *ExtendedObject =
MTE->GetTemporaryExpr()->skipRValueSubobjectAdjustments(
CommaLHS, Adjustments);
if (ExtendedObject->getType().isDestructedType()) {
Scopes.push_back(GotoScope(ParentScope, 0,
diag::note_exits_temporary_dtor,
ExtendedObject->getExprLoc()));
origParentScope = Scopes.size()-1;
}
}
break;
}
case Stmt::CaseStmtClass:
case Stmt::DefaultStmtClass:
case Stmt::LabelStmtClass:
LabelAndGotoScopes[S] = ParentScope;
break;
default:
break;
}
for (Stmt *SubStmt : S->children()) {
if (!SubStmt)
continue;
if (StmtsToSkip) {
--StmtsToSkip;
continue;
}
// Cases, labels, and defaults aren't "scope parents". It's also
// important to handle these iteratively instead of recursively in
// order to avoid blowing out the stack.
while (true) {
Stmt *Next;
if (SwitchCase *SC = dyn_cast<SwitchCase>(SubStmt))
Next = SC->getSubStmt();
else if (LabelStmt *LS = dyn_cast<LabelStmt>(SubStmt))
Next = LS->getSubStmt();
else
break;
LabelAndGotoScopes[SubStmt] = ParentScope;
SubStmt = Next;
}
// Recursively walk the AST.
BuildScopeInformation(SubStmt, ParentScope);
}
}
/// VerifyJumps - Verify each element of the Jumps array to see if they are
/// valid, emitting diagnostics if not.
void JumpScopeChecker::VerifyJumps() {
while (!Jumps.empty()) {
Stmt *Jump = Jumps.pop_back_val();
// With a goto,
if (GotoStmt *GS = dyn_cast<GotoStmt>(Jump)) {
// The label may not have a statement if it's coming from inline MS ASM.
if (GS->getLabel()->getStmt()) {
CheckJump(GS, GS->getLabel()->getStmt(), GS->getGotoLoc(),
diag::err_goto_into_protected_scope,
diag::ext_goto_into_protected_scope,
diag::warn_cxx98_compat_goto_into_protected_scope);
}
CheckGotoStmt(GS);
continue;
}
// We only get indirect gotos here when they have a constant target.
if (IndirectGotoStmt *IGS = dyn_cast<IndirectGotoStmt>(Jump)) {
LabelDecl *Target = IGS->getConstantTarget();
CheckJump(IGS, Target->getStmt(), IGS->getGotoLoc(),
diag::err_goto_into_protected_scope,
diag::ext_goto_into_protected_scope,
diag::warn_cxx98_compat_goto_into_protected_scope);
continue;
}
SwitchStmt *SS = cast<SwitchStmt>(Jump);
for (SwitchCase *SC = SS->getSwitchCaseList(); SC;
SC = SC->getNextSwitchCase()) {
if (CHECK_PERMISSIVE(!LabelAndGotoScopes.count(SC)))
continue;
SourceLocation Loc;
if (CaseStmt *CS = dyn_cast<CaseStmt>(SC))
Loc = CS->getLocStart();
else if (DefaultStmt *DS = dyn_cast<DefaultStmt>(SC))
Loc = DS->getLocStart();
else
Loc = SC->getLocStart();
CheckJump(SS, SC, Loc, diag::err_switch_into_protected_scope, 0,
diag::warn_cxx98_compat_switch_into_protected_scope);
}
}
}
/// VerifyIndirectJumps - Verify whether any possible indirect jump
/// might cross a protection boundary. Unlike direct jumps, indirect
/// jumps count cleanups as protection boundaries: since there's no
/// way to know where the jump is going, we can't implicitly run the
/// right cleanups the way we can with direct jumps.
///
/// Thus, an indirect jump is "trivial" if it bypasses no
/// initializations and no teardowns. More formally, an indirect jump
/// from A to B is trivial if the path out from A to DCA(A,B) is
/// trivial and the path in from DCA(A,B) to B is trivial, where
/// DCA(A,B) is the deepest common ancestor of A and B.
/// Jump-triviality is transitive but asymmetric.
///
/// A path in is trivial if none of the entered scopes have an InDiag.
/// A path out is trivial is none of the exited scopes have an OutDiag.
///
/// Under these definitions, this function checks that the indirect
/// jump between A and B is trivial for every indirect goto statement A
/// and every label B whose address was taken in the function.
void JumpScopeChecker::VerifyIndirectJumps() {
if (IndirectJumps.empty()) return;
// If there aren't any address-of-label expressions in this function,
// complain about the first indirect goto.
if (IndirectJumpTargets.empty()) {
S.Diag(IndirectJumps[0]->getGotoLoc(),
diag::err_indirect_goto_without_addrlabel);
return;
}
// Collect a single representative of every scope containing an
// indirect goto. For most code bases, this substantially cuts
// down on the number of jump sites we'll have to consider later.
typedef std::pair<unsigned, IndirectGotoStmt*> JumpScope;
SmallVector<JumpScope, 32> JumpScopes;
{
llvm::DenseMap<unsigned, IndirectGotoStmt*> JumpScopesMap;
for (SmallVectorImpl<IndirectGotoStmt*>::iterator
I = IndirectJumps.begin(), E = IndirectJumps.end(); I != E; ++I) {
IndirectGotoStmt *IG = *I;
if (CHECK_PERMISSIVE(!LabelAndGotoScopes.count(IG)))
continue;
unsigned IGScope = LabelAndGotoScopes[IG];
IndirectGotoStmt *&Entry = JumpScopesMap[IGScope];
if (!Entry) Entry = IG;
}
JumpScopes.reserve(JumpScopesMap.size());
for (llvm::DenseMap<unsigned, IndirectGotoStmt*>::iterator
I = JumpScopesMap.begin(), E = JumpScopesMap.end(); I != E; ++I)
JumpScopes.push_back(*I);
}
// Collect a single representative of every scope containing a
// label whose address was taken somewhere in the function.
// For most code bases, there will be only one such scope.
llvm::DenseMap<unsigned, LabelDecl*> TargetScopes;
for (SmallVectorImpl<LabelDecl*>::iterator
I = IndirectJumpTargets.begin(), E = IndirectJumpTargets.end();
I != E; ++I) {
LabelDecl *TheLabel = *I;
if (CHECK_PERMISSIVE(!LabelAndGotoScopes.count(TheLabel->getStmt())))
continue;
unsigned LabelScope = LabelAndGotoScopes[TheLabel->getStmt()];
LabelDecl *&Target = TargetScopes[LabelScope];
if (!Target) Target = TheLabel;
}
// For each target scope, make sure it's trivially reachable from
// every scope containing a jump site.
//
// A path between scopes always consists of exitting zero or more
// scopes, then entering zero or more scopes. We build a set of
// of scopes S from which the target scope can be trivially
// entered, then verify that every jump scope can be trivially
// exitted to reach a scope in S.
llvm::BitVector Reachable(Scopes.size(), false);
for (llvm::DenseMap<unsigned,LabelDecl*>::iterator
TI = TargetScopes.begin(), TE = TargetScopes.end(); TI != TE; ++TI) {
unsigned TargetScope = TI->first;
LabelDecl *TargetLabel = TI->second;
Reachable.reset();
// Mark all the enclosing scopes from which you can safely jump
// into the target scope. 'Min' will end up being the index of
// the shallowest such scope.
unsigned Min = TargetScope;
while (true) {
Reachable.set(Min);
// Don't go beyond the outermost scope.
if (Min == 0) break;
// Stop if we can't trivially enter the current scope.
if (Scopes[Min].InDiag) break;
Min = Scopes[Min].ParentScope;
}
// Walk through all the jump sites, checking that they can trivially
// reach this label scope.
for (SmallVectorImpl<JumpScope>::iterator
I = JumpScopes.begin(), E = JumpScopes.end(); I != E; ++I) {
unsigned Scope = I->first;
// Walk out the "scope chain" for this scope, looking for a scope
// we've marked reachable. For well-formed code this amortizes
// to O(JumpScopes.size() / Scopes.size()): we only iterate
// when we see something unmarked, and in well-formed code we
// mark everything we iterate past.
bool IsReachable = false;
while (true) {
if (Reachable.test(Scope)) {
// If we find something reachable, mark all the scopes we just
// walked through as reachable.
for (unsigned S = I->first; S != Scope; S = Scopes[S].ParentScope)
Reachable.set(S);
IsReachable = true;
break;
}
// Don't walk out if we've reached the top-level scope or we've
// gotten shallower than the shallowest reachable scope.
if (Scope == 0 || Scope < Min) break;
// Don't walk out through an out-diagnostic.
if (Scopes[Scope].OutDiag) break;
Scope = Scopes[Scope].ParentScope;
}
// Only diagnose if we didn't find something.
if (IsReachable) continue;
DiagnoseIndirectJump(I->second, I->first, TargetLabel, TargetScope);
}
}
}
/// Return true if a particular error+note combination must be downgraded to a
/// warning in Microsoft mode.
static bool IsMicrosoftJumpWarning(unsigned JumpDiag, unsigned InDiagNote) {
return (JumpDiag == diag::err_goto_into_protected_scope &&
(InDiagNote == diag::note_protected_by_variable_init ||
InDiagNote == diag::note_protected_by_variable_nontriv_destructor));
}
/// Return true if a particular note should be downgraded to a compatibility
/// warning in C++11 mode.
static bool IsCXX98CompatWarning(Sema &S, unsigned InDiagNote) {
return S.getLangOpts().CPlusPlus11 &&
InDiagNote == diag::note_protected_by_variable_non_pod;
}
/// Produce primary diagnostic for an indirect jump statement.
static void DiagnoseIndirectJumpStmt(Sema &S, IndirectGotoStmt *Jump,
LabelDecl *Target, bool &Diagnosed) {
if (Diagnosed)
return;
S.Diag(Jump->getGotoLoc(), diag::err_indirect_goto_in_protected_scope);
S.Diag(Target->getStmt()->getIdentLoc(), diag::note_indirect_goto_target);
Diagnosed = true;
}
/// Produce note diagnostics for a jump into a protected scope.
void JumpScopeChecker::NoteJumpIntoScopes(ArrayRef<unsigned> ToScopes) {
if (CHECK_PERMISSIVE(ToScopes.empty()))
return;
for (unsigned I = 0, E = ToScopes.size(); I != E; ++I)
if (Scopes[ToScopes[I]].InDiag)
S.Diag(Scopes[ToScopes[I]].Loc, Scopes[ToScopes[I]].InDiag);
}
/// Diagnose an indirect jump which is known to cross scopes.
void JumpScopeChecker::DiagnoseIndirectJump(IndirectGotoStmt *Jump,
unsigned JumpScope,
LabelDecl *Target,
unsigned TargetScope) {
if (CHECK_PERMISSIVE(JumpScope == TargetScope))
return;
unsigned Common = GetDeepestCommonScope(JumpScope, TargetScope);
bool Diagnosed = false;
// Walk out the scope chain until we reach the common ancestor.
for (unsigned I = JumpScope; I != Common; I = Scopes[I].ParentScope)
if (Scopes[I].OutDiag) {
DiagnoseIndirectJumpStmt(S, Jump, Target, Diagnosed);
S.Diag(Scopes[I].Loc, Scopes[I].OutDiag);
}
SmallVector<unsigned, 10> ToScopesCXX98Compat;
// Now walk into the scopes containing the label whose address was taken.
for (unsigned I = TargetScope; I != Common; I = Scopes[I].ParentScope)
if (IsCXX98CompatWarning(S, Scopes[I].InDiag))
ToScopesCXX98Compat.push_back(I);
else if (Scopes[I].InDiag) {
DiagnoseIndirectJumpStmt(S, Jump, Target, Diagnosed);
S.Diag(Scopes[I].Loc, Scopes[I].InDiag);
}
// Diagnose this jump if it would be ill-formed in C++98.
if (!Diagnosed && !ToScopesCXX98Compat.empty()) {
S.Diag(Jump->getGotoLoc(),
diag::warn_cxx98_compat_indirect_goto_in_protected_scope);
S.Diag(Target->getStmt()->getIdentLoc(), diag::note_indirect_goto_target);
NoteJumpIntoScopes(ToScopesCXX98Compat);
}
}
/// CheckJump - Validate that the specified jump statement is valid: that it is
/// jumping within or out of its current scope, not into a deeper one.
void JumpScopeChecker::CheckJump(Stmt *From, Stmt *To, SourceLocation DiagLoc,
unsigned JumpDiagError, unsigned JumpDiagWarning,
unsigned JumpDiagCXX98Compat) {
if (CHECK_PERMISSIVE(!LabelAndGotoScopes.count(From)))
return;
if (CHECK_PERMISSIVE(!LabelAndGotoScopes.count(To)))
return;
unsigned FromScope = LabelAndGotoScopes[From];
unsigned ToScope = LabelAndGotoScopes[To];
// Common case: exactly the same scope, which is fine.
if (FromScope == ToScope) return;
// Warn on gotos out of __finally blocks.
if (isa<GotoStmt>(From) || isa<IndirectGotoStmt>(From)) {
// If FromScope > ToScope, FromScope is more nested and the jump goes to a
// less nested scope. Check if it crosses a __finally along the way.
for (unsigned I = FromScope; I > ToScope; I = Scopes[I].ParentScope) {
if (Scopes[I].InDiag == diag::note_protected_by_seh_finally) {
S.Diag(From->getLocStart(), diag::warn_jump_out_of_seh_finally);
break;
}
}
}
unsigned CommonScope = GetDeepestCommonScope(FromScope, ToScope);
// It's okay to jump out from a nested scope.
if (CommonScope == ToScope) return;
// Pull out (and reverse) any scopes we might need to diagnose skipping.
SmallVector<unsigned, 10> ToScopesCXX98Compat;
SmallVector<unsigned, 10> ToScopesError;
SmallVector<unsigned, 10> ToScopesWarning;
for (unsigned I = ToScope; I != CommonScope; I = Scopes[I].ParentScope) {
if (S.getLangOpts().MSVCCompat && JumpDiagWarning != 0 &&
IsMicrosoftJumpWarning(JumpDiagError, Scopes[I].InDiag))
ToScopesWarning.push_back(I);
else if (IsCXX98CompatWarning(S, Scopes[I].InDiag))
ToScopesCXX98Compat.push_back(I);
else if (Scopes[I].InDiag)
ToScopesError.push_back(I);
}
// Handle warnings.
if (!ToScopesWarning.empty()) {
S.Diag(DiagLoc, JumpDiagWarning);
NoteJumpIntoScopes(ToScopesWarning);
}
// Handle errors.
if (!ToScopesError.empty()) {
S.Diag(DiagLoc, JumpDiagError);
NoteJumpIntoScopes(ToScopesError);
}
// Handle -Wc++98-compat warnings if the jump is well-formed.
if (ToScopesError.empty() && !ToScopesCXX98Compat.empty()) {
S.Diag(DiagLoc, JumpDiagCXX98Compat);
NoteJumpIntoScopes(ToScopesCXX98Compat);
}
}
void JumpScopeChecker::CheckGotoStmt(GotoStmt *GS) {
if (GS->getLabel()->isMSAsmLabel()) {
S.Diag(GS->getGotoLoc(), diag::err_goto_ms_asm_label)
<< GS->getLabel()->getIdentifier();
S.Diag(GS->getLabel()->getLocation(), diag::note_goto_ms_asm_label)
<< GS->getLabel()->getIdentifier();
}
}
void Sema::DiagnoseInvalidJumps(Stmt *Body) {
(void)JumpScopeChecker(Body, *this);
}
|
ensemblr/llvm-project-boilerplate
|
include/llvm/tools/clang/lib/Sema/JumpDiagnostics.cpp
|
C++
|
mit
| 35,368 |
// Copyright 2009-2020 Intel Corporation
// SPDX-License-Identifier: Apache-2.0
#pragma once
#include "trianglei.h"
#include "triangle_intersector_moeller.h"
#include "triangle_intersector_pluecker.h"
namespace embree
{
namespace isa
{
/*! Intersects M triangles with 1 ray */
template<int M, int Mx, bool filter>
struct TriangleMiIntersector1Moeller
{
typedef TriangleMi<M> Primitive;
typedef MoellerTrumboreIntersector1<Mx> Precalculations;
static __forceinline void intersect(const Precalculations& pre, RayHit& ray, IntersectContext* context, const Primitive& tri)
{
STAT3(normal.trav_prims,1,1,1);
Vec3vf<M> v0, v1, v2; tri.gather(v0,v1,v2,context->scene);
pre.intersect(ray,v0,v1,v2,/*UVIdentity<Mx>(),*/Intersect1EpilogM<M,Mx,filter>(ray,context,tri.geomID(),tri.primID()));
}
static __forceinline bool occluded(const Precalculations& pre, Ray& ray, IntersectContext* context, const Primitive& tri)
{
STAT3(shadow.trav_prims,1,1,1);
Vec3vf<M> v0, v1, v2; tri.gather(v0,v1,v2,context->scene);
return pre.intersect(ray,v0,v1,v2,/*UVIdentity<Mx>(),*/Occluded1EpilogM<M,Mx,filter>(ray,context,tri.geomID(),tri.primID()));
}
static __forceinline bool pointQuery(PointQuery* query, PointQueryContext* context, const Primitive& tri)
{
return PrimitivePointQuery1<Primitive>::pointQuery(query, context, tri);
}
};
/*! Intersects M triangles with K rays */
template<int M, int Mx, int K, bool filter>
struct TriangleMiIntersectorKMoeller
{
typedef TriangleMi<M> Primitive;
typedef MoellerTrumboreIntersectorK<Mx,K> Precalculations;
static __forceinline void intersect(const vbool<K>& valid_i, Precalculations& pre, RayHitK<K>& ray, IntersectContext* context, const Primitive& tri)
{
const Scene* scene = context->scene;
for (size_t i=0; i<Primitive::max_size(); i++)
{
if (!tri.valid(i)) break;
STAT3(normal.trav_prims,1,popcnt(valid_i),RayHitK<K>::size());
const Vec3vf<K> v0 = tri.template getVertex<0>(i,scene);
const Vec3vf<K> v1 = tri.template getVertex<1>(i,scene);
const Vec3vf<K> v2 = tri.template getVertex<2>(i,scene);
pre.intersectK(valid_i,ray,v0,v1,v2,/*UVIdentity<K>(),*/IntersectKEpilogM<M,K,filter>(ray,context,tri.geomID(),tri.primID(),i));
}
}
static __forceinline vbool<K> occluded(const vbool<K>& valid_i, Precalculations& pre, RayK<K>& ray, IntersectContext* context, const Primitive& tri)
{
vbool<K> valid0 = valid_i;
const Scene* scene = context->scene;
for (size_t i=0; i<Primitive::max_size(); i++)
{
if (!tri.valid(i)) break;
STAT3(shadow.trav_prims,1,popcnt(valid_i),RayHitK<K>::size());
const Vec3vf<K> v0 = tri.template getVertex<0>(i,scene);
const Vec3vf<K> v1 = tri.template getVertex<1>(i,scene);
const Vec3vf<K> v2 = tri.template getVertex<2>(i,scene);
pre.intersectK(valid0,ray,v0,v1,v2,/*UVIdentity<K>(),*/OccludedKEpilogM<M,K,filter>(valid0,ray,context,tri.geomID(),tri.primID(),i));
if (none(valid0)) break;
}
return !valid0;
}
static __forceinline void intersect(Precalculations& pre, RayHitK<K>& ray, size_t k, IntersectContext* context, const Primitive& tri)
{
STAT3(normal.trav_prims,1,1,1);
Vec3vf<M> v0, v1, v2; tri.gather(v0,v1,v2,context->scene);
pre.intersect(ray,k,v0,v1,v2,/*UVIdentity<Mx>(),*/Intersect1KEpilogM<M,Mx,K,filter>(ray,k,context,tri.geomID(),tri.primID()));
}
static __forceinline bool occluded(Precalculations& pre, RayK<K>& ray, size_t k, IntersectContext* context, const Primitive& tri)
{
STAT3(shadow.trav_prims,1,1,1);
Vec3vf<M> v0, v1, v2; tri.gather(v0,v1,v2,context->scene);
return pre.intersect(ray,k,v0,v1,v2,/*UVIdentity<Mx>(),*/Occluded1KEpilogM<M,Mx,K,filter>(ray,k,context,tri.geomID(),tri.primID()));
}
};
/*! Intersects M triangles with 1 ray */
template<int M, int Mx, bool filter>
struct TriangleMiIntersector1Pluecker
{
typedef TriangleMi<M> Primitive;
typedef PlueckerIntersector1<Mx> Precalculations;
static __forceinline void intersect(const Precalculations& pre, RayHit& ray, IntersectContext* context, const Primitive& tri)
{
STAT3(normal.trav_prims,1,1,1);
Vec3vf<M> v0, v1, v2; tri.gather(v0,v1,v2,context->scene);
pre.intersect(ray,v0,v1,v2,UVIdentity<Mx>(),Intersect1EpilogM<M,Mx,filter>(ray,context,tri.geomID(),tri.primID()));
}
static __forceinline bool occluded(const Precalculations& pre, Ray& ray, IntersectContext* context, const Primitive& tri)
{
STAT3(shadow.trav_prims,1,1,1);
Vec3vf<M> v0, v1, v2; tri.gather(v0,v1,v2,context->scene);
return pre.intersect(ray,v0,v1,v2,UVIdentity<Mx>(),Occluded1EpilogM<M,Mx,filter>(ray,context,tri.geomID(),tri.primID()));
}
static __forceinline bool pointQuery(PointQuery* query, PointQueryContext* context, const Primitive& tri)
{
return PrimitivePointQuery1<Primitive>::pointQuery(query, context, tri);
}
};
/*! Intersects M triangles with K rays */
template<int M, int Mx, int K, bool filter>
struct TriangleMiIntersectorKPluecker
{
typedef TriangleMi<M> Primitive;
typedef PlueckerIntersectorK<Mx,K> Precalculations;
static __forceinline void intersect(const vbool<K>& valid_i, Precalculations& pre, RayHitK<K>& ray, IntersectContext* context, const Primitive& tri)
{
const Scene* scene = context->scene;
for (size_t i=0; i<Primitive::max_size(); i++)
{
if (!tri.valid(i)) break;
STAT3(normal.trav_prims,1,popcnt(valid_i),RayHitK<K>::size());
const Vec3vf<K> v0 = tri.template getVertex<0>(i,scene);
const Vec3vf<K> v1 = tri.template getVertex<1>(i,scene);
const Vec3vf<K> v2 = tri.template getVertex<2>(i,scene);
pre.intersectK(valid_i,ray,v0,v1,v2,UVIdentity<K>(),IntersectKEpilogM<M,K,filter>(ray,context,tri.geomID(),tri.primID(),i));
}
}
static __forceinline vbool<K> occluded(const vbool<K>& valid_i, Precalculations& pre, RayK<K>& ray, IntersectContext* context, const Primitive& tri)
{
vbool<K> valid0 = valid_i;
const Scene* scene = context->scene;
for (size_t i=0; i<Primitive::max_size(); i++)
{
if (!tri.valid(i)) break;
STAT3(shadow.trav_prims,1,popcnt(valid_i),RayHitK<K>::size());
const Vec3vf<K> v0 = tri.template getVertex<0>(i,scene);
const Vec3vf<K> v1 = tri.template getVertex<1>(i,scene);
const Vec3vf<K> v2 = tri.template getVertex<2>(i,scene);
pre.intersectK(valid0,ray,v0,v1,v2,UVIdentity<K>(),OccludedKEpilogM<M,K,filter>(valid0,ray,context,tri.geomID(),tri.primID(),i));
if (none(valid0)) break;
}
return !valid0;
}
static __forceinline void intersect(Precalculations& pre, RayHitK<K>& ray, size_t k, IntersectContext* context, const Primitive& tri)
{
STAT3(normal.trav_prims,1,1,1);
Vec3vf<M> v0, v1, v2; tri.gather(v0,v1,v2,context->scene);
pre.intersect(ray,k,v0,v1,v2,UVIdentity<Mx>(),Intersect1KEpilogM<M,Mx,K,filter>(ray,k,context,tri.geomID(),tri.primID()));
}
static __forceinline bool occluded(Precalculations& pre, RayK<K>& ray, size_t k, IntersectContext* context, const Primitive& tri)
{
STAT3(shadow.trav_prims,1,1,1);
Vec3vf<M> v0, v1, v2; tri.gather(v0,v1,v2,context->scene);
return pre.intersect(ray,k,v0,v1,v2,UVIdentity<Mx>(),Occluded1KEpilogM<M,Mx,K,filter>(ray,k,context,tri.geomID(),tri.primID()));
}
};
/*! Intersects M motion blur triangles with 1 ray */
template<int M, int Mx, bool filter>
struct TriangleMiMBIntersector1Moeller
{
typedef TriangleMi<M> Primitive;
typedef MoellerTrumboreIntersector1<Mx> Precalculations;
/*! Intersect a ray with the M triangles and updates the hit. */
static __forceinline void intersect(const Precalculations& pre, RayHit& ray, IntersectContext* context, const Primitive& tri)
{
STAT3(normal.trav_prims,1,1,1);
Vec3vf<M> v0,v1,v2; tri.gather(v0,v1,v2,context->scene,ray.time());
pre.intersect(ray,v0,v1,v2,/*UVIdentity<Mx>(),*/Intersect1EpilogM<M,Mx,filter>(ray,context,tri.geomID(),tri.primID()));
}
/*! Test if the ray is occluded by one of M triangles. */
static __forceinline bool occluded(const Precalculations& pre, Ray& ray, IntersectContext* context, const Primitive& tri)
{
STAT3(shadow.trav_prims,1,1,1);
Vec3vf<M> v0,v1,v2; tri.gather(v0,v1,v2,context->scene,ray.time());
return pre.intersect(ray,v0,v1,v2,/*UVIdentity<Mx>(),*/Occluded1EpilogM<M,Mx,filter>(ray,context,tri.geomID(),tri.primID()));
}
static __forceinline bool pointQuery(PointQuery* query, PointQueryContext* context, const Primitive& tri)
{
return PrimitivePointQuery1<Primitive>::pointQuery(query, context, tri);
}
};
/*! Intersects M motion blur triangles with K rays. */
template<int M, int Mx, int K, bool filter>
struct TriangleMiMBIntersectorKMoeller
{
typedef TriangleMi<M> Primitive;
typedef MoellerTrumboreIntersectorK<Mx,K> Precalculations;
/*! Intersects K rays with M triangles. */
static __forceinline void intersect(const vbool<K>& valid_i, Precalculations& pre, RayHitK<K>& ray, IntersectContext* context, const TriangleMi<M>& tri)
{
for (size_t i=0; i<TriangleMi<M>::max_size(); i++)
{
if (!tri.valid(i)) break;
STAT3(normal.trav_prims,1,popcnt(valid_i),K);
Vec3vf<K> v0,v1,v2; tri.gather(valid_i,v0,v1,v2,i,context->scene,ray.time());
pre.intersectK(valid_i,ray,v0,v1,v2,/*UVIdentity<K>(),*/IntersectKEpilogM<M,K,filter>(ray,context,tri.geomID(),tri.primID(),i));
}
}
/*! Test for K rays if they are occluded by any of the M triangles. */
static __forceinline vbool<K> occluded(const vbool<K>& valid_i, Precalculations& pre, RayK<K>& ray, IntersectContext* context, const TriangleMi<M>& tri)
{
vbool<K> valid0 = valid_i;
for (size_t i=0; i<TriangleMi<M>::max_size(); i++)
{
if (!tri.valid(i)) break;
STAT3(shadow.trav_prims,1,popcnt(valid0),K);
Vec3vf<K> v0,v1,v2; tri.gather(valid_i,v0,v1,v2,i,context->scene,ray.time());
pre.intersectK(valid0,ray,v0,v1,v2,/*UVIdentity<K>(),*/OccludedKEpilogM<M,K,filter>(valid0,ray,context,tri.geomID(),tri.primID(),i));
if (none(valid0)) break;
}
return !valid0;
}
/*! Intersect a ray with M triangles and updates the hit. */
static __forceinline void intersect(Precalculations& pre, RayHitK<K>& ray, size_t k, IntersectContext* context, const TriangleMi<M>& tri)
{
STAT3(normal.trav_prims,1,1,1);
Vec3vf<M> v0,v1,v2; tri.gather(v0,v1,v2,context->scene,ray.time()[k]);
pre.intersect(ray,k,v0,v1,v2,/*UVIdentity<Mx>(),*/Intersect1KEpilogM<M,Mx,K,filter>(ray,k,context,tri.geomID(),tri.primID()));
}
/*! Test if the ray is occluded by one of the M triangles. */
static __forceinline bool occluded(Precalculations& pre, RayK<K>& ray, size_t k, IntersectContext* context, const TriangleMi<M>& tri)
{
STAT3(shadow.trav_prims,1,1,1);
Vec3vf<M> v0,v1,v2; tri.gather(v0,v1,v2,context->scene,ray.time()[k]);
return pre.intersect(ray,k,v0,v1,v2,/*UVIdentity<Mx>(),*/Occluded1KEpilogM<M,Mx,K,filter>(ray,k,context,tri.geomID(),tri.primID()));
}
};
/*! Intersects M motion blur triangles with 1 ray */
template<int M, int Mx, bool filter>
struct TriangleMiMBIntersector1Pluecker
{
typedef TriangleMi<M> Primitive;
typedef PlueckerIntersector1<Mx> Precalculations;
/*! Intersect a ray with the M triangles and updates the hit. */
static __forceinline void intersect(const Precalculations& pre, RayHit& ray, IntersectContext* context, const Primitive& tri)
{
STAT3(normal.trav_prims,1,1,1);
Vec3vf<M> v0,v1,v2; tri.gather(v0,v1,v2,context->scene,ray.time());
pre.intersect(ray,v0,v1,v2,UVIdentity<Mx>(),Intersect1EpilogM<M,Mx,filter>(ray,context,tri.geomID(),tri.primID()));
}
/*! Test if the ray is occluded by one of M triangles. */
static __forceinline bool occluded(const Precalculations& pre, Ray& ray, IntersectContext* context, const Primitive& tri)
{
STAT3(shadow.trav_prims,1,1,1);
Vec3vf<M> v0,v1,v2; tri.gather(v0,v1,v2,context->scene,ray.time());
return pre.intersect(ray,v0,v1,v2,UVIdentity<Mx>(),Occluded1EpilogM<M,Mx,filter>(ray,context,tri.geomID(),tri.primID()));
}
static __forceinline bool pointQuery(PointQuery* query, PointQueryContext* context, const Primitive& tri)
{
return PrimitivePointQuery1<Primitive>::pointQuery(query, context, tri);
}
};
/*! Intersects M motion blur triangles with K rays. */
template<int M, int Mx, int K, bool filter>
struct TriangleMiMBIntersectorKPluecker
{
typedef TriangleMi<M> Primitive;
typedef PlueckerIntersectorK<Mx,K> Precalculations;
/*! Intersects K rays with M triangles. */
static __forceinline void intersect(const vbool<K>& valid_i, Precalculations& pre, RayHitK<K>& ray, IntersectContext* context, const TriangleMi<M>& tri)
{
for (size_t i=0; i<TriangleMi<M>::max_size(); i++)
{
if (!tri.valid(i)) break;
STAT3(normal.trav_prims,1,popcnt(valid_i),K);
Vec3vf<K> v0,v1,v2; tri.gather(valid_i,v0,v1,v2,i,context->scene,ray.time());
pre.intersectK(valid_i,ray,v0,v1,v2,UVIdentity<K>(),IntersectKEpilogM<M,K,filter>(ray,context,tri.geomID(),tri.primID(),i));
}
}
/*! Test for K rays if they are occluded by any of the M triangles. */
static __forceinline vbool<K> occluded(const vbool<K>& valid_i, Precalculations& pre, RayK<K>& ray, IntersectContext* context, const TriangleMi<M>& tri)
{
vbool<K> valid0 = valid_i;
for (size_t i=0; i<TriangleMi<M>::max_size(); i++)
{
if (!tri.valid(i)) break;
STAT3(shadow.trav_prims,1,popcnt(valid0),K);
Vec3vf<K> v0,v1,v2; tri.gather(valid_i,v0,v1,v2,i,context->scene,ray.time());
pre.intersectK(valid0,ray,v0,v1,v2,UVIdentity<K>(),OccludedKEpilogM<M,K,filter>(valid0,ray,context,tri.geomID(),tri.primID(),i));
if (none(valid0)) break;
}
return !valid0;
}
/*! Intersect a ray with M triangles and updates the hit. */
static __forceinline void intersect(Precalculations& pre, RayHitK<K>& ray, size_t k, IntersectContext* context, const TriangleMi<M>& tri)
{
STAT3(normal.trav_prims,1,1,1);
Vec3vf<M> v0,v1,v2; tri.gather(v0,v1,v2,context->scene,ray.time()[k]);
pre.intersect(ray,k,v0,v1,v2,UVIdentity<Mx>(),Intersect1KEpilogM<M,Mx,K,filter>(ray,k,context,tri.geomID(),tri.primID()));
}
/*! Test if the ray is occluded by one of the M triangles. */
static __forceinline bool occluded(Precalculations& pre, RayK<K>& ray, size_t k, IntersectContext* context, const TriangleMi<M>& tri)
{
STAT3(shadow.trav_prims,1,1,1);
Vec3vf<M> v0,v1,v2; tri.gather(v0,v1,v2,context->scene,ray.time()[k]);
return pre.intersect(ray,k,v0,v1,v2,UVIdentity<Mx>(),Occluded1KEpilogM<M,Mx,K,filter>(ray,k,context,tri.geomID(),tri.primID()));
}
};
}
}
|
rokups/Urho3D
|
Source/ThirdParty/embree/kernels/geometry/trianglei_intersector.h
|
C
|
mit
| 15,922 |
<div class="container-fluid landing">
<div id="almari">
<center>
<h1 id="alm">Almari</h1>
<h2 id="sub">Elegant clothing. Delivered.</h2>
</center>
</div>
<div class="sec1">
<div class="row" id="toprow">
<div class="col-md-6" id="borrow">
<center>
<img src="clothing285.png" class="icon">
<p> Prom, party or wedding, but nothing to wear? <br> Your virtual wardrobe has some exotic clothing...</p>
<div class="col-md-4 col-centered btn" type="button">
<h3 class = "box" ng-click="borrow()">BORROW</h3>
</div>
</center>
</div>
<div class="col-md-6">
<center>
<img src="pricetag.png" class="icon">
<p> Bought an expensive dress, but wore it only once? <br> Monetize your wardrobe </p>
<div class="col-md-4 col-centered btn" type="button">
<h3 class="box" ng-click="lend()">LEND</h3>
</div>
</center>
</div>
</div>
<br><br>
</div>
<div id="sec2">
<br>
<br>
</div>
</div>
|
rishabhaggarwal2/Almari
|
app/landing/landing.html
|
HTML
|
mit
| 1,175 |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
// ==++==
//
//
// ==--==
// ****************************************************************************
// File: controller.cpp
//
//
// controller.cpp: Debugger execution control routines
//
// ****************************************************************************
// Putting code & #includes, #defines, etc, before the stdafx.h will
// cause the code,etc, to be silently ignored
#include "stdafx.h"
#include "openum.h"
#include "../inc/common.h"
#include "eeconfig.h"
#include "../../vm/methoditer.h"
const char *GetTType( TraceType tt);
#define IsSingleStep(exception) (exception == EXCEPTION_SINGLE_STEP)
// -------------------------------------------------------------------------
// DebuggerController routines
// -------------------------------------------------------------------------
SPTR_IMPL_INIT(DebuggerPatchTable, DebuggerController, g_patches, NULL);
SVAL_IMPL_INIT(BOOL, DebuggerController, g_patchTableValid, FALSE);
#if !defined(DACCESS_COMPILE)
DebuggerController *DebuggerController::g_controllers = NULL;
DebuggerControllerPage *DebuggerController::g_protections = NULL;
CrstStatic DebuggerController::g_criticalSection;
int DebuggerController::g_cTotalMethodEnter = 0;
// Is this patch at a position at which it's safe to take a stack?
bool DebuggerControllerPatch::IsSafeForStackTrace()
{
LIMITED_METHOD_CONTRACT;
TraceType tt = this->trace.GetTraceType();
Module *module = this->key.module;
BOOL managed = this->IsManagedPatch();
// Patches placed by MgrPush can come at lots of illegal spots. Can't take a stack trace here.
if ((module == NULL) && managed && (tt == TRACE_MGR_PUSH))
{
return false;
}
// Consider everything else legal.
// This is a little shady for TRACE_FRAME_PUSH. But TraceFrame() needs a stackInfo
// to get a RegDisplay (though almost nobody uses it, so perhaps it could be removed).
return true;
}
#ifndef _TARGET_ARM_
// returns a pointer to the shared buffer. each call will AddRef() the object
// before returning it so callers only need to Release() when they're finished with it.
SharedPatchBypassBuffer* DebuggerControllerPatch::GetOrCreateSharedPatchBypassBuffer()
{
CONTRACTL
{
THROWS;
GC_NOTRIGGER;
}
CONTRACTL_END;
if (m_pSharedPatchBypassBuffer == NULL)
{
m_pSharedPatchBypassBuffer = new (interopsafeEXEC) SharedPatchBypassBuffer();
_ASSERTE(m_pSharedPatchBypassBuffer);
TRACE_ALLOC(m_pSharedPatchBypassBuffer);
}
m_pSharedPatchBypassBuffer->AddRef();
return m_pSharedPatchBypassBuffer;
}
#endif // _TARGET_ARM_
// @todo - remove all this splicing trash
// This Sort/Splice stuff just reorders the patches within a particular chain such
// that when we iterate through by calling GetPatch() and GetNextPatch(DebuggerControllerPatch),
// we'll get patches in increasing order of DebuggerControllerTypes.
// Practically, this means that calling GetPatch() will return EnC patches before stepping patches.
//
#if 1
void DebuggerPatchTable::SortPatchIntoPatchList(DebuggerControllerPatch **ppPatch)
{
LOG((LF_CORDB, LL_EVERYTHING, "DPT::SPIPL called.\n"));
#ifdef _DEBUG
DebuggerControllerPatch *patchFirst
= (DebuggerControllerPatch *) Find(Hash((*ppPatch)), Key((*ppPatch)));
_ASSERTE(patchFirst == (*ppPatch));
_ASSERTE((*ppPatch)->controller->GetDCType() != DEBUGGER_CONTROLLER_STATIC);
#endif //_DEBUG
DebuggerControllerPatch *patchNext = GetNextPatch((*ppPatch));
LOG((LF_CORDB, LL_EVERYTHING, "DPT::SPIPL GetNextPatch passed\n"));
//List contains one, (sorted) element
if (patchNext == NULL)
{
LOG((LF_CORDB, LL_INFO10000,
"DPT::SPIPL: Patch 0x%x is a sorted singleton\n", (*ppPatch)));
return;
}
// If we decide to reorder the list, we'll need to keep the element
// indexed by the hash function as the (sorted)first item. Everything else
// chains off this element, can can thus stay put.
// Thus, either the element we just added is already sorted, or else we'll
// have to move it elsewhere in the list, meaning that we'll have to swap
// the second item & the new item, so that the index points to the proper
// first item in the list.
//use Cur ptr for case where patch gets appended to list
DebuggerControllerPatch *patchCur = patchNext;
while (patchNext != NULL &&
((*ppPatch)->controller->GetDCType() >
patchNext->controller->GetDCType()) )
{
patchCur = patchNext;
patchNext = GetNextPatch(patchNext);
}
if (patchNext == GetNextPatch((*ppPatch)))
{
LOG((LF_CORDB, LL_INFO10000,
"DPT::SPIPL: Patch 0x%x is already sorted\n", (*ppPatch)));
return; //already sorted
}
LOG((LF_CORDB, LL_INFO10000,
"DPT::SPIPL: Patch 0x%x will be moved \n", (*ppPatch)));
//remove it from the list
SpliceOutOfList((*ppPatch));
// the kinda neat thing is: since we put it originally at the front of the list,
// and it's not in order, then it must be behind another element of this list,
// so we don't have to write any 'SpliceInFrontOf' code.
_ASSERTE(patchCur != NULL);
SpliceInBackOf((*ppPatch), patchCur);
LOG((LF_CORDB, LL_INFO10000,
"DPT::SPIPL: Patch 0x%x is now sorted\n", (*ppPatch)));
}
// This can leave the list empty, so don't do this unless you put
// the patch back somewhere else.
void DebuggerPatchTable::SpliceOutOfList(DebuggerControllerPatch *patch)
{
// We need to get iHash, the index of the ptr within
// m_piBuckets, ie it's entry in the hashtable.
ULONG iHash = Hash(patch) % m_iBuckets;
ULONG iElement = m_piBuckets[iHash];
DebuggerControllerPatch *patchFirst
= (DebuggerControllerPatch *) EntryPtr(iElement);
// Fix up pointers to chain
if (patchFirst == patch)
{
// The first patch shouldn't have anything behind it.
_ASSERTE(patch->entry.iPrev == DPT_INVALID_SLOT);
if (patch->entry.iNext != DPT_INVALID_SLOT)
{
m_piBuckets[iHash] = patch->entry.iNext;
}
else
{
m_piBuckets[iHash] = DPT_INVALID_SLOT;
}
}
if (patch->entry.iNext != DPT_INVALID_SLOT)
{
EntryPtr(patch->entry.iNext)->iPrev = patch->entry.iPrev;
}
if (patch->entry.iPrev != DPT_INVALID_SLOT)
{
EntryPtr(patch->entry.iNext)->iNext = patch->entry.iNext;
}
patch->entry.iNext = DPT_INVALID_SLOT;
patch->entry.iPrev = DPT_INVALID_SLOT;
}
void DebuggerPatchTable::SpliceInBackOf(DebuggerControllerPatch *patchAppend,
DebuggerControllerPatch *patchEnd)
{
ULONG iAppend = ItemIndex((HASHENTRY*)patchAppend);
ULONG iEnd = ItemIndex((HASHENTRY*)patchEnd);
patchAppend->entry.iPrev = iEnd;
patchAppend->entry.iNext = patchEnd->entry.iNext;
if (patchAppend->entry.iNext != DPT_INVALID_SLOT)
EntryPtr(patchAppend->entry.iNext)->iPrev = iAppend;
patchEnd->entry.iNext = iAppend;
}
#endif
//-----------------------------------------------------------------------------
// Stack safety rules.
// In general, we're safe to crawl whenever we're in preemptive mode.
// We're also must be safe at any spot the thread could get synchronized,
// because that means that the thread will be stopped to let the debugger shell
// inspect it and that can definitely take stack traces.
// Basically the only unsafe spot is in the middle of goofy stub with some
// partially constructed frame while in coop mode.
//-----------------------------------------------------------------------------
// Safe if we're at certain types of patches.
// See Patch::IsSafeForStackTrace for details.
StackTraceTicket::StackTraceTicket(DebuggerControllerPatch * patch)
{
_ASSERTE(patch != NULL);
_ASSERTE(patch->IsSafeForStackTrace());
}
// Safe if there was already another stack trace at this spot. (Grandfather clause)
// This is commonly used for StepOut, which takes runs stacktraces to crawl up
// the stack to find a place to patch.
StackTraceTicket::StackTraceTicket(ControllerStackInfo * info)
{
_ASSERTE(info != NULL);
// Ensure that the other stack info object actually executed (and thus was
// actually valid).
_ASSERTE(info->m_dbgExecuted);
}
// Safe b/c the context shows we're in native managed code.
// This must be safe because we could always set a managed breakpoint by native
// offset and thus synchronize the shell at this spot. So this is
// a specific example of the Synchronized case. The fact that we don't actually
// synchronize doesn't make us any less safe.
StackTraceTicket::StackTraceTicket(const BYTE * ip)
{
_ASSERTE(g_pEEInterface->IsManagedNativeCode(ip));
}
// Safe it we're at a Synchronized point point.
StackTraceTicket::StackTraceTicket(Thread * pThread)
{
_ASSERTE(pThread != NULL);
// If we're synchronized, the debugger should be stopped.
// That means all threads are synced and must be safe to take a stacktrace.
// Thus we don't even need to do a thread-specific check.
_ASSERTE(g_pDebugger->IsStopped());
}
// DebuggerUserBreakpoint has a special case of safety. See that ctor for details.
StackTraceTicket::StackTraceTicket(DebuggerUserBreakpoint * p)
{
_ASSERTE(p != NULL);
}
//void ControllerStackInfo::GetStackInfo(): GetStackInfo
// is invoked by the user to trigger the stack walk. This will
// cause the stack walk detailed in the class description to happen.
// Thread* thread: The thread to do the stack walk on.
// void* targetFP: Can be either NULL (meaning that the bottommost
// frame is the target), or an frame pointer, meaning that the
// caller wants information about a specific frame.
// CONTEXT* pContext: A pointer to a CONTEXT structure. Can be null,
// we use our temp context.
// bool suppressUMChainFromComPlusMethodFrameGeneric - A ridiculous flag that is trying to narrowly
// target a fix for issue 650903.
// StackTraceTicket - ticket to ensure that we actually have permission for this stacktrace
void ControllerStackInfo::GetStackInfo(
StackTraceTicket ticket,
Thread *thread,
FramePointer targetFP,
CONTEXT *pContext,
bool suppressUMChainFromComPlusMethodFrameGeneric
)
{
_ASSERTE(thread != NULL);
BOOL contextValid = (pContext != NULL);
if (!contextValid)
{
// We're assuming the thread is protected w/ a frame (which includes the redirection
// case). The stackwalker will use that protection to prime the context.
pContext = &this->m_tempContext;
}
else
{
// If we provided an explicit context for this thread, it better not be redirected.
_ASSERTE(!ISREDIRECTEDTHREAD(thread));
}
// Mark this stackwalk as valid so that it can in turn be used to grandfather
// in other stackwalks.
INDEBUG(m_dbgExecuted = true);
m_activeFound = false;
m_returnFound = false;
m_bottomFP = LEAF_MOST_FRAME;
m_targetFP = targetFP;
m_targetFrameFound = (m_targetFP == LEAF_MOST_FRAME);
m_specialChainReason = CHAIN_NONE;
m_suppressUMChainFromComPlusMethodFrameGeneric = suppressUMChainFromComPlusMethodFrameGeneric;
int result = DebuggerWalkStack(thread,
LEAF_MOST_FRAME,
pContext,
contextValid,
WalkStack,
(void *) this,
FALSE);
_ASSERTE(m_activeFound); // All threads have at least one unmanaged frame
if (result == SWA_DONE)
{
_ASSERTE(!m_returnFound);
m_returnFrame = m_activeFrame;
}
}
//---------------------------------------------------------------------------------------
//
// This function "undoes" an unwind, i.e. it takes the active frame (the current frame)
// and sets it to be the return frame (the caller frame). Currently it is only used by
// the stepper to step out of an LCG method. See DebuggerStepper::DetectHandleLCGMethods()
// for more information.
//
// Assumptions:
// The current frame is valid on entry.
//
// Notes:
// After this function returns, the active frame on this instance of ControllerStackInfo will no longer be valid.
//
// This function is specifically for DebuggerStepper::DetectHandleLCGMethods(). Using it in other scencarios may
// require additional changes.
//
void ControllerStackInfo::SetReturnFrameWithActiveFrame()
{
// Copy the active frame into the return frame.
m_returnFound = true;
m_returnFrame = m_activeFrame;
// Invalidate the active frame.
m_activeFound = false;
memset(&(m_activeFrame), 0, sizeof(m_activeFrame));
m_activeFrame.fp = LEAF_MOST_FRAME;
}
// Fill in a controller-stack info.
StackWalkAction ControllerStackInfo::WalkStack(FrameInfo *pInfo, void *data)
{
LIMITED_METHOD_CONTRACT;
_ASSERTE(!pInfo->HasStubFrame()); // we didn't ask for stub frames.
ControllerStackInfo *i = (ControllerStackInfo *) data;
//save this info away for later use
if (i->m_bottomFP == LEAF_MOST_FRAME)
i->m_bottomFP = pInfo->fp;
// This is part of the targetted fix for issue 650903. (See the other
// parts in in code:TrackUMChain and code:DebuggerStepper::TrapStepOut.)
// pInfo->fIgnoreThisFrameIfSuppressingUMChainFromComPlusMethodFrameGeneric has been
// set by TrackUMChain to help us remember that the current frame we're looking at is
// ComPlusMethodFrameGeneric (we can't rely on looking at pInfo->frame to check
// this), and i->m_suppressUMChainFromComPlusMethodFrameGeneric has been set by the
// dude initiating this walk to remind us that our goal in life is to do a Step Out
// during managed-only debugging. These two things together tell us we should ignore
// this frame, rather than erroneously identifying it as the target frame.
#ifdef FEATURE_COMINTEROP
if(i->m_suppressUMChainFromComPlusMethodFrameGeneric &&
(pInfo->chainReason == CHAIN_ENTER_UNMANAGED) &&
(pInfo->fIgnoreThisFrameIfSuppressingUMChainFromComPlusMethodFrameGeneric))
{
return SWA_CONTINUE;
}
#endif // FEATURE_COMINTEROP
//have we reached the correct frame yet?
if (!i->m_targetFrameFound &&
IsEqualOrCloserToLeaf(i->m_targetFP, pInfo->fp))
{
i->m_targetFrameFound = true;
}
if (i->m_targetFrameFound )
{
// Ignore Enter-managed chains.
if (pInfo->chainReason == CHAIN_ENTER_MANAGED)
{
return SWA_CONTINUE;
}
if (i->m_activeFound )
{
// We care if the current frame is unmanaged (in case a managed stepper is initiated
// on a thread currently in unmanaged code). But since we can't step-out to UM frames,
// we can just skip them in the stack walk.
if (!pInfo->managed)
{
return SWA_CONTINUE;
}
if (pInfo->chainReason == CHAIN_CLASS_INIT)
i->m_specialChainReason = pInfo->chainReason;
if (pInfo->fp != i->m_activeFrame.fp) // avoid dups
{
i->m_returnFrame = *pInfo;
#if defined(WIN64EXCEPTIONS)
CopyREGDISPLAY(&(i->m_returnFrame.registers), &(pInfo->registers));
#endif // WIN64EXCEPTIONS
i->m_returnFound = true;
return SWA_ABORT;
}
}
else
{
i->m_activeFrame = *pInfo;
#if defined(WIN64EXCEPTIONS)
CopyREGDISPLAY(&(i->m_activeFrame.registers), &(pInfo->registers));
#endif // WIN64EXCEPTIONS
i->m_activeFound = true;
return SWA_CONTINUE;
}
}
return SWA_CONTINUE;
}
//
// Note that patches may be reallocated - do not keep a pointer to a patch.
//
DebuggerControllerPatch *DebuggerPatchTable::AddPatchForMethodDef(DebuggerController *controller,
Module *module,
mdMethodDef md,
size_t offset,
DebuggerPatchKind kind,
FramePointer fp,
AppDomain *pAppDomain,
SIZE_T masterEnCVersion,
DebuggerJitInfo *dji)
{
CONTRACTL
{
THROWS;
MODE_ANY;
GC_NOTRIGGER;
}
CONTRACTL_END;
LOG( (LF_CORDB,LL_INFO10000,"DCP:AddPatchForMethodDef unbound "
"relative in methodDef 0x%x with dji 0x%x "
"controller:0x%x AD:0x%x\n", md,
dji, controller, pAppDomain));
DebuggerFunctionKey key;
key.module = module;
key.md = md;
// Get a new uninitialized patch object
DebuggerControllerPatch *patch =
(DebuggerControllerPatch *) Add(HashKey(&key));
if (patch == NULL)
{
ThrowOutOfMemory();
}
#ifndef _TARGET_ARM_
patch->Initialize();
#endif
//initialize the patch data structure.
InitializePRD(&(patch->opcode));
patch->controller = controller;
patch->key.module = module;
patch->key.md = md;
patch->offset = offset;
patch->offsetIsIL = (kind == PATCH_KIND_IL_MASTER);
patch->address = NULL;
patch->fp = fp;
patch->trace.Bad_SetTraceType(DPT_DEFAULT_TRACE_TYPE); // TRACE_OTHER
patch->refCount = 1; // AddRef()
patch->fSaveOpcode = false;
patch->pAppDomain = pAppDomain;
patch->pid = m_pid++;
if (kind == PATCH_KIND_IL_MASTER)
{
_ASSERTE(dji == NULL);
patch->encVersion = masterEnCVersion;
}
else
{
patch->dji = dji;
}
patch->kind = kind;
if (dji)
LOG((LF_CORDB,LL_INFO10000,"AddPatchForMethodDef w/ version 0x%04x, "
"pid:0x%x\n", dji->m_encVersion, patch->pid));
else if (kind == PATCH_KIND_IL_MASTER)
LOG((LF_CORDB,LL_INFO10000,"AddPatchForMethodDef w/ version 0x%04x, "
"pid:0x%x\n", masterEnCVersion,patch->pid));
else
LOG((LF_CORDB,LL_INFO10000,"AddPatchForMethodDef w/ no dji or dmi, pid:0x%x\n",patch->pid));
// This patch is not yet bound or activated
_ASSERTE( !patch->IsBound() );
_ASSERTE( !patch->IsActivated() );
// The only kind of patch with IL offset is the IL master patch.
_ASSERTE(patch->IsILMasterPatch() || patch->offsetIsIL == FALSE);
return patch;
}
// Create and bind a patch to the specified address
// The caller should immediately activate the patch since we typically expect bound patches
// will always be activated.
DebuggerControllerPatch *DebuggerPatchTable::AddPatchForAddress(DebuggerController *controller,
MethodDesc *fd,
size_t offset,
DebuggerPatchKind kind,
CORDB_ADDRESS_TYPE *address,
FramePointer fp,
AppDomain *pAppDomain,
DebuggerJitInfo *dji,
SIZE_T pid,
TraceType traceType)
{
CONTRACTL
{
THROWS;
MODE_ANY;
GC_NOTRIGGER;
}
CONTRACTL_END;
_ASSERTE(kind == PATCH_KIND_NATIVE_MANAGED || kind == PATCH_KIND_NATIVE_UNMANAGED);
LOG((LF_CORDB,LL_INFO10000,"DCP:AddPatchForAddress bound "
"absolute to 0x%x with dji 0x%x (mdDef:0x%x) "
"controller:0x%x AD:0x%x\n",
address, dji, (fd!=NULL?fd->GetMemberDef():0), controller,
pAppDomain));
// get new uninitialized patch object
DebuggerControllerPatch *patch =
(DebuggerControllerPatch *) Add(HashAddress(address));
if (patch == NULL)
{
ThrowOutOfMemory();
}
#ifndef _TARGET_ARM_
patch->Initialize();
#endif
// initialize the patch data structure
InitializePRD(&(patch->opcode));
patch->controller = controller;
if (fd == NULL)
{
patch->key.module = NULL;
patch->key.md = mdTokenNil;
}
else
{
patch->key.module = g_pEEInterface->MethodDescGetModule(fd);
patch->key.md = fd->GetMemberDef();
}
patch->offset = offset;
patch->offsetIsIL = FALSE;
patch->address = address;
patch->fp = fp;
patch->trace.Bad_SetTraceType(traceType);
patch->refCount = 1; // AddRef()
patch->fSaveOpcode = false;
patch->pAppDomain = pAppDomain;
if (pid == DCP_PID_INVALID)
patch->pid = m_pid++;
else
patch->pid = pid;
patch->dji = dji;
patch->kind = kind;
if (dji == NULL)
LOG((LF_CORDB,LL_INFO10000,"AddPatchForAddress w/ version with no dji, pid:0x%x\n", patch->pid));
else
{
LOG((LF_CORDB,LL_INFO10000,"AddPatchForAddress w/ version 0x%04x, "
"pid:0x%x\n", dji->m_methodInfo->GetCurrentEnCVersion(), patch->pid));
_ASSERTE( fd==NULL || fd == dji->m_fd );
}
SortPatchIntoPatchList(&patch);
// This patch is bound but not yet activated
_ASSERTE( patch->IsBound() );
_ASSERTE( !patch->IsActivated() );
// The only kind of patch with IL offset is the IL master patch.
_ASSERTE(patch->IsILMasterPatch() || patch->offsetIsIL == FALSE);
return patch;
}
// Set the native address for this patch.
void DebuggerPatchTable::BindPatch(DebuggerControllerPatch *patch, CORDB_ADDRESS_TYPE *address)
{
_ASSERTE(patch != NULL);
_ASSERTE(address != NULL);
_ASSERTE( !patch->IsILMasterPatch() );
_ASSERTE(!patch->IsBound() );
//Since the actual patch doesn't move, we don't have to worry about
//zeroing out the opcode field (see lenghty comment above)
// Since the patch is double-hashed based off Address, if we change the address,
// we must remove and reinsert the patch.
CHashTable::Delete(HashKey(&patch->key), ItemIndex((HASHENTRY*)patch));
patch->address = address;
CHashTable::Add(HashAddress(address), ItemIndex((HASHENTRY*)patch));
SortPatchIntoPatchList(&patch);
_ASSERTE(patch->IsBound() );
_ASSERTE(!patch->IsActivated() );
}
// Disassociate a patch from a specific code address.
void DebuggerPatchTable::UnbindPatch(DebuggerControllerPatch *patch)
{
_ASSERTE(patch != NULL);
_ASSERTE(patch->kind != PATCH_KIND_IL_MASTER);
_ASSERTE(patch->IsBound() );
_ASSERTE(!patch->IsActivated() );
//<REVISIT_TODO>@todo We're hosed if the patch hasn't been primed with
// this info & we can't get it...</REVISIT_TODO>
if (patch->key.module == NULL ||
patch->key.md == mdTokenNil)
{
MethodDesc *fd = g_pEEInterface->GetNativeCodeMethodDesc(
dac_cast<PCODE>(patch->address));
_ASSERTE( fd != NULL );
patch->key.module = g_pEEInterface->MethodDescGetModule(fd);
patch->key.md = fd->GetMemberDef();
}
// Update it's index entry in the table to use it's unbound key
// Since the patch is double-hashed based off Address, if we change the address,
// we must remove and reinsert the patch.
CHashTable::Delete( HashAddress(patch->address),
ItemIndex((HASHENTRY*)patch));
patch->address = NULL; // we're no longer bound to this address
CHashTable::Add( HashKey(&patch->key),
ItemIndex((HASHENTRY*)patch));
_ASSERTE(!patch->IsBound() );
}
void DebuggerPatchTable::RemovePatch(DebuggerControllerPatch *patch)
{
// Since we're deleting this patch, it must not be activated (i.e. it must not have a stored opcode)
_ASSERTE( !patch->IsActivated() );
#ifndef _TARGET_ARM_
patch->DoCleanup();
#endif
//
// Because of the implementation of CHashTable, we can safely
// delete elements while iterating through the table. This
// behavior is relied upon - do not change to a different
// implementation without considering this fact.
//
Delete(Hash(patch), (HASHENTRY *) patch);
}
DebuggerControllerPatch *DebuggerPatchTable::GetNextPatch(DebuggerControllerPatch *prev)
{
ULONG iNext;
HASHENTRY *psEntry;
// Start at the next entry in the chain.
// @todo - note that: EntryPtr(ItemIndex(x)) == x
iNext = EntryPtr(ItemIndex((HASHENTRY*)prev))->iNext;
// Search until we hit the end.
while (iNext != UINT32_MAX)
{
// Compare the keys.
psEntry = EntryPtr(iNext);
// Careful here... we can hash the entries in this table
// by two types of keys. In this type of search, the type
// of the second key (psEntry) does not necessarily
// indicate the type of the first key (prev), so we have
// to check for sure.
DebuggerControllerPatch *pc2 = (DebuggerControllerPatch*)psEntry;
if (((pc2->address == NULL) && (prev->address == NULL)) ||
((pc2->address != NULL) && (prev->address != NULL)))
if (!Cmp(Key(prev), psEntry))
return pc2;
// Advance to the next item in the chain.
iNext = psEntry->iNext;
}
return NULL;
}
#ifdef _DEBUG_PATCH_TABLE
// DEBUG An internal debugging routine, it iterates
// through the hashtable, stopping at every
// single entry, no matter what it's state. For this to
// compile, you're going to have to add friend status
// of this class to CHashTableAndData in
// to $\Com99\Src\inc\UtilCode.h
void DebuggerPatchTable::CheckPatchTable()
{
if (NULL != m_pcEntries)
{
DebuggerControllerPatch *dcp;
int i = 0;
while (i++ <m_iEntries)
{
dcp = (DebuggerControllerPatch*)&(((DebuggerControllerPatch *)m_pcEntries)[i]);
if (dcp->opcode != 0 )
{
LOG((LF_CORDB,LL_INFO1000, "dcp->addr:0x%8x "
"mdMD:0x%8x, offset:0x%x, native:%d\n",
dcp->address, dcp->key.md, dcp->offset,
dcp->IsNativePatch()));
}
}
}
}
#endif // _DEBUG_PATCH_TABLE
// Count how many patches are in the table.
// Use for asserts
int DebuggerPatchTable::GetNumberOfPatches()
{
int total = 0;
if (NULL != m_pcEntries)
{
DebuggerControllerPatch *dcp;
ULONG i = 0;
while (i++ <m_iEntries)
{
dcp = (DebuggerControllerPatch*)&(((DebuggerControllerPatch *)m_pcEntries)[i]);
if (dcp->IsActivated() || !dcp->IsFree())
total++;
}
}
return total;
}
#if defined(_DEBUG)
//-----------------------------------------------------------------------------
// Debug check that we only have 1 thread-starter per thread.
// pNew - the new DTS. We'll make sure there's not already a DTS on this thread.
//-----------------------------------------------------------------------------
void DebuggerController::EnsureUniqueThreadStarter(DebuggerThreadStarter * pNew)
{
// This lock should be safe to take since our base class ctor takes it.
ControllerLockHolder lockController;
DebuggerController * pExisting = g_controllers;
while(pExisting != NULL)
{
if (pExisting->GetDCType() == DEBUGGER_CONTROLLER_THREAD_STARTER)
{
if (pExisting != pNew)
{
// If we have 2 thread starters, they'd better be on different threads.
_ASSERTE((pExisting->GetThread() != pNew->GetThread()));
}
}
pExisting = pExisting->m_next;
}
}
#endif
//-----------------------------------------------------------------------------
// If we have a thread-starter on the given EE thread, make sure it's cancel.
// Thread-Starters normally delete themselves when they fire. But if the EE
// destroys the thread before it fires, then we'd still have an active DTS.
//-----------------------------------------------------------------------------
void DebuggerController::CancelOutstandingThreadStarter(Thread * pThread)
{
_ASSERTE(pThread != NULL);
LOG((LF_CORDB, LL_EVERYTHING, "DC:CancelOutstandingThreadStarter - checking on thread =0x%p\n", pThread));
ControllerLockHolder lockController;
DebuggerController * p = g_controllers;
while(p != NULL)
{
if (p->GetDCType() == DEBUGGER_CONTROLLER_THREAD_STARTER)
{
if (p->GetThread() == pThread)
{
LOG((LF_CORDB, LL_EVERYTHING, "DC:CancelOutstandingThreadStarter, pThread=0x%p, Found=0x%p\n", p));
// There's only 1 DTS per thread, so once we find it, we can quit.
p->Delete();
p = NULL;
break;
}
}
p = p->m_next;
}
// The common case is that our DTS hit its patch and did a SendEvent (and
// deleted itself). So usually we'll get through the whole list w/o deleting anything.
}
//void DebuggerController::Initialize() Sets up the static
// variables for the static DebuggerController class.
// How: Sets g_runningOnWin95, initializes the critical section
HRESULT DebuggerController::Initialize()
{
CONTRACT(HRESULT)
{
THROWS;
GC_NOTRIGGER;
// This can be called in an "early attach" case, so DebuggerIsInvolved()
// will be b/c we don't realize the debugger's attaching to us.
//PRECONDITION(DebuggerIsInvolved());
POSTCONDITION(CheckPointer(g_patches));
POSTCONDITION(RETVAL == S_OK);
}
CONTRACT_END;
if (g_patches == NULL)
{
ZeroMemory(&g_criticalSection, sizeof(g_criticalSection)); // Init() expects zero-init memory.
// NOTE: CRST_UNSAFE_ANYMODE prevents a GC mode switch when entering this crst.
// If you remove this flag, we will switch to preemptive mode when entering
// g_criticalSection, which means all functions that enter it will become
// GC_TRIGGERS. (This includes all uses of ControllerLockHolder.) So be sure
// to update the contracts if you remove this flag.
g_criticalSection.Init(CrstDebuggerController,
(CrstFlags)(CRST_UNSAFE_ANYMODE | CRST_REENTRANCY | CRST_DEBUGGER_THREAD));
g_patches = new (interopsafe) DebuggerPatchTable();
_ASSERTE(g_patches != NULL); // throws on oom
HRESULT hr = g_patches->Init();
if (FAILED(hr))
{
DeleteInteropSafe(g_patches);
ThrowHR(hr);
}
g_patchTableValid = TRUE;
TRACE_ALLOC(g_patches);
}
_ASSERTE(g_patches != NULL);
RETURN (S_OK);
}
//---------------------------------------------------------------------------------------
//
// Constructor for a controller
//
// Arguments:
// pThread - thread that controller has affinity to. NULL if no thread - affinity.
// pAppdomain - appdomain that controller has affinity to. NULL if no AD affinity.
//
//
// Notes:
// "Affinity" is per-controller specific. Affinity is generally passed on to
// any patches the controller creates. So if a controller has affinity to Thread X,
// then any patches it creates will only fire on Thread-X.
//
//---------------------------------------------------------------------------------------
DebuggerController::DebuggerController(Thread * pThread, AppDomain * pAppDomain)
: m_pAppDomain(pAppDomain),
m_thread(pThread),
m_singleStep(false),
m_exceptionHook(false),
m_traceCall(0),
m_traceCallFP(ROOT_MOST_FRAME),
m_unwindFP(LEAF_MOST_FRAME),
m_eventQueuedCount(0),
m_deleted(false),
m_fEnableMethodEnter(false)
{
CONTRACTL
{
SO_NOT_MAINLINE;
NOTHROW;
GC_NOTRIGGER;
CONSTRUCTOR_CHECK;
}
CONTRACTL_END;
LOG((LF_CORDB, LL_INFO10000, "DC: 0x%x m_eventQueuedCount to 0 - DC::DC\n", this));
ControllerLockHolder lockController;
{
m_next = g_controllers;
g_controllers = this;
}
}
//---------------------------------------------------------------------------------------
//
// Debugger::Controller::DeleteAllControlers - deletes all debugger contollers
//
// Arguments:
// None
//
// Return Value:
// None
//
// Notes:
// This is used at detach time to remove all DebuggerControllers. This will remove all
// patches and do whatever other cleanup individual DebuggerControllers consider
// necessary to allow the debugger to detach and the process to run normally.
//
void DebuggerController::DeleteAllControllers()
{
CONTRACTL
{
SO_NOT_MAINLINE;
NOTHROW;
GC_NOTRIGGER;
}
CONTRACTL_END;
ControllerLockHolder lockController;
DebuggerController * pDebuggerController = g_controllers;
DebuggerController * pNextDebuggerController = NULL;
while (pDebuggerController != NULL)
{
pNextDebuggerController = pDebuggerController->m_next;
pDebuggerController->DebuggerDetachClean();
pDebuggerController->Delete();
pDebuggerController = pNextDebuggerController;
}
}
DebuggerController::~DebuggerController()
{
CONTRACTL
{
SO_NOT_MAINLINE;
NOTHROW;
GC_NOTRIGGER;
DESTRUCTOR_CHECK;
}
CONTRACTL_END;
ControllerLockHolder lockController;
_ASSERTE(m_eventQueuedCount == 0);
DisableAll();
//
// Remove controller from list
//
DebuggerController **c;
c = &g_controllers;
while (*c != this)
c = &(*c)->m_next;
*c = m_next;
}
// void DebuggerController::Delete()
// What: Marks an instance as deletable. If it's ref count
// (see Enqueue, Dequeue) is currently zero, it actually gets deleted
// How: Set m_deleted to true. If m_eventQueuedCount==0, delete this
void DebuggerController::Delete()
{
CONTRACTL
{
SO_NOT_MAINLINE;
NOTHROW;
GC_NOTRIGGER;
}
CONTRACTL_END;
if (m_eventQueuedCount == 0)
{
LOG((LF_CORDB|LF_ENC, LL_INFO100000, "DC::Delete: actual delete of this:0x%x!\n", this));
TRACE_FREE(this);
DeleteInteropSafe(this);
}
else
{
LOG((LF_CORDB|LF_ENC, LL_INFO100000, "DC::Delete: marked for "
"future delete of this:0x%x!\n", this));
LOG((LF_CORDB|LF_ENC, LL_INFO10000, "DC:0x%x m_eventQueuedCount at 0x%x\n",
this, m_eventQueuedCount));
m_deleted = true;
}
}
void DebuggerController::DebuggerDetachClean()
{
//do nothing here
}
//static
void DebuggerController::AddRef(DebuggerControllerPatch *patch)
{
patch->refCount++;
}
//static
void DebuggerController::Release(DebuggerControllerPatch *patch)
{
patch->refCount--;
if (patch->refCount == 0)
{
LOG((LF_CORDB, LL_INFO10000, "DCP::R: patch deleted, deactivating\n"));
DeactivatePatch(patch);
GetPatchTable()->RemovePatch(patch);
}
}
// void DebuggerController::DisableAll() DisableAll removes
// all control from the controller. This includes all patches & page
// protection. This will invoke Disable* for unwind,singlestep,
// exceptionHook, and tracecall. It will also go through the patch table &
// attempt to remove any and all patches that belong to this controller.
// If the patch is currently triggering, then a Dispatch* method expects the
// patch to be there after we return, so we instead simply mark the patch
// itself as deleted.
void DebuggerController::DisableAll()
{
CONTRACTL
{
SO_NOT_MAINLINE;
NOTHROW;
GC_NOTRIGGER;
MODE_ANY;
}
CONTRACTL_END;
LOG((LF_CORDB,LL_INFO1000, "DC::DisableAll\n"));
_ASSERTE(g_patches != NULL);
ControllerLockHolder ch;
{
//
// Remove controller's patches from list.
// Don't do this on shutdown because the shutdown thread may have killed another thread asynchronously
// thus leaving the patchtable in an inconsistent state such that we may fail trying to walk it.
// Since we're exiting anyways, leaving int3 in the code can't harm anybody.
//
if (!g_fProcessDetach)
{
HASHFIND f;
for (DebuggerControllerPatch *patch = g_patches->GetFirstPatch(&f);
patch != NULL;
patch = g_patches->GetNextPatch(&f))
{
if (patch->controller == this)
{
Release(patch);
}
}
}
if (m_singleStep)
DisableSingleStep();
if (m_exceptionHook)
DisableExceptionHook();
if (m_unwindFP != LEAF_MOST_FRAME)
DisableUnwind();
if (m_traceCall)
DisableTraceCall();
if (m_fEnableMethodEnter)
DisableMethodEnter();
}
}
// void DebuggerController::Enqueue() What: Does
// reference counting so we don't toast a
// DebuggerController while it's in a Dispatch queue.
// Why: In DispatchPatchOrSingleStep, we can't hold locks when going
// into PreEmptiveGC mode b/c we'll create a deadlock.
// So we have to UnLock() prior to
// EnablePreEmptiveGC(). But somebody else can show up and delete the
// DebuggerControllers since we no longer have the lock. So we have to
// do this reference counting thing to make sure that the controllers
// don't get toasted as we're trying to invoke SendEvent on them. We have to
// reaquire the lock before invoking Dequeue because Dequeue may
// result in the controller being deleted, which would change the global
// controller list.
// How: InterlockIncrement( m_eventQueuedCount )
void DebuggerController::Enqueue()
{
LIMITED_METHOD_CONTRACT;
m_eventQueuedCount++;
LOG((LF_CORDB, LL_INFO10000, "DC::Enq DC:0x%x m_eventQueuedCount at 0x%x\n",
this, m_eventQueuedCount));
}
// void DebuggerController::Dequeue() What: Does
// reference counting so we don't toast a
// DebuggerController while it's in a Dispatch queue.
// How: InterlockDecrement( m_eventQueuedCount ), delete this if
// m_eventQueuedCount == 0 AND m_deleted has been set to true
void DebuggerController::Dequeue()
{
CONTRACTL
{
SO_NOT_MAINLINE;
NOTHROW;
GC_NOTRIGGER;
}
CONTRACTL_END;
LOG((LF_CORDB, LL_INFO10000, "DC::Deq DC:0x%x m_eventQueuedCount at 0x%x\n",
this, m_eventQueuedCount));
if (--m_eventQueuedCount == 0)
{
if (m_deleted)
{
TRACE_FREE(this);
DeleteInteropSafe(this);
}
}
}
// bool DebuggerController::BindPatch() If the method has
// been JITted and isn't hashed by address already, then hash
// it into the hashtable by address and not DebuggerFunctionKey.
// If the patch->address field is nonzero, we're done.
// Otherwise ask g_pEEInterface to FindLoadedMethodRefOrDef, then
// GetFunctionAddress of the method, if the method is in IL,
// MapILOffsetToNative. If everything else went Ok, we can now invoke
// g_patches->BindPatch.
// Returns: false if we know that we can't bind the patch immediately.
// true if we either can bind the patch right now, or can't right now,
// but might be able to in the future (eg, the method hasn't been JITted)
// Have following outcomes:
// 1) Succeeded in binding the patch to a raw address. patch->address is set.
// (Note we still must apply the patch to put the int 3 in.)
// returns true, *pFail = false
//
// 2) Fails to bind, but a future attempt may succeed. Obvious ex, for an IL-only
// patch on an unjitted method.
// returns false, *pFail = false
//
// 3) Fails to bind because something's wrong. Ex: bad IL offset, no DJI to do a
// mapping with. Future calls will fail too.
// returns false, *pFail = true
bool DebuggerController::BindPatch(DebuggerControllerPatch *patch,
MethodDesc *fd,
CORDB_ADDRESS_TYPE *startAddr)
{
CONTRACTL
{
SO_NOT_MAINLINE;
THROWS; // from GetJitInfo
GC_NOTRIGGER;
MODE_ANY; // don't really care what mode we're in.
PRECONDITION(ThisMaybeHelperThread());
}
CONTRACTL_END;
_ASSERTE(patch != NULL);
_ASSERTE(!patch->IsILMasterPatch());
_ASSERTE(fd != NULL);
//
// Translate patch to address, if it hasn't been already.
//
if (patch->address != NULL)
{
return true;
}
if (startAddr == NULL)
{
if (patch->HasDJI() && patch->GetDJI()->m_jitComplete)
{
startAddr = (CORDB_ADDRESS_TYPE *) CORDB_ADDRESS_TO_PTR(patch->GetDJI()->m_addrOfCode);
_ASSERTE(startAddr != NULL);
}
if (startAddr == NULL)
{
// Should not be trying to place patches on MethodDecs's for stubs.
// These stubs will never get jitted.
CONSISTENCY_CHECK_MSGF(!fd->IsWrapperStub(), ("Can't place patch at stub md %p, %s::%s",
fd, fd->m_pszDebugClassName, fd->m_pszDebugMethodName));
startAddr = (CORDB_ADDRESS_TYPE *)g_pEEInterface->GetFunctionAddress(fd);
//
// Code is not available yet to patch. The prestub should
// notify us when it is executed.
//
if (startAddr == NULL)
{
LOG((LF_CORDB, LL_INFO10000,
"DC::BP:Patch at 0x%x not bindable yet.\n", patch->offset));
return false;
}
}
}
_ASSERTE(!g_pEEInterface->IsStub((const BYTE *)startAddr));
// If we've jitted, map to a native offset.
DebuggerJitInfo *info = g_pDebugger->GetJitInfo(fd, (const BYTE *)startAddr);
#ifdef LOGGING
if (info == NULL)
{
LOG((LF_CORDB,LL_INFO10000, "DC::BindPa: For startAddr 0x%x, didn't find a DJI\n", startAddr));
}
#endif //LOGGING
if (info != NULL)
{
// There is a strange case with prejitted code and unjitted trace patches. We can enter this function
// with no DebuggerJitInfo created, then have the call just above this actually create the
// DebuggerJitInfo, which causes JitComplete to be called, which causes all patches to be bound! If this
// happens, then we don't need to continue here (its already been done recursivley) and we don't need to
// re-active the patch, so we return false from right here. We can check this by seeing if we suddently
// have the address in the patch set.
if (patch->address != NULL)
{
LOG((LF_CORDB,LL_INFO10000, "DC::BindPa: patch bound recursivley by GetJitInfo, bailing...\n"));
return false;
}
LOG((LF_CORDB,LL_INFO10000, "DC::BindPa: For startAddr 0x%x, got DJI "
"0x%x, from 0x%x size: 0x%x\n", startAddr, info, info->m_addrOfCode, info->m_sizeOfCode));
}
LOG((LF_CORDB, LL_INFO10000, "DC::BP:Trying to bind patch in %s::%s version %d\n",
fd->m_pszDebugClassName, fd->m_pszDebugMethodName, info ? info->m_encVersion : (SIZE_T)-1));
_ASSERTE(g_patches != NULL);
CORDB_ADDRESS_TYPE *addr = (CORDB_ADDRESS_TYPE *)
CodeRegionInfo::GetCodeRegionInfo(NULL, NULL, startAddr).OffsetToAddress(patch->offset);
g_patches->BindPatch(patch, addr);
LOG((LF_CORDB, LL_INFO10000, "DC::BP:Binding patch at 0x%x(off:%x)\n", addr, patch->offset));
return true;
}
// bool DebuggerController::ApplyPatch() applies
// the patch described to the code, and
// remembers the replaced opcode. Note that the same address
// cannot be patched twice at the same time.
// Grabs the opcode & stores in patch, then sets a break
// instruction for either native or IL.
// VirtualProtect & some macros. Returns false if anything
// went bad.
// DebuggerControllerPatch *patch: The patch, indicates where
// to set the INT3 instruction
// Returns: true if the user break instruction was successfully
// placed into the code-stream, false otherwise
bool DebuggerController::ApplyPatch(DebuggerControllerPatch *patch)
{
LOG((LF_CORDB, LL_INFO10000, "DC::ApplyPatch at addr 0x%p\n",
patch->address));
// If we try to apply an already applied patch, we'll overide our saved opcode
// with the break opcode and end up getting a break in out patch bypass buffer.
_ASSERTE(!patch->IsActivated() );
_ASSERTE(patch->IsBound());
// Note we may be patching at certain "blessed" points in mscorwks.
// This is very dangerous b/c we can't be sure patch->Address is blessed or not.
//
// Apply the patch.
//
_ASSERTE(!(g_pConfig->GetGCStressLevel() & (EEConfig::GCSTRESS_INSTR_JIT|EEConfig::GCSTRESS_INSTR_NGEN))
&& "Debugger does not work with GCSTRESS 4");
if (patch->IsNativePatch())
{
if (patch->fSaveOpcode)
{
// We only used SaveOpcode for when we've moved code, so
// the patch should already be there.
patch->opcode = patch->opcodeSaved;
_ASSERTE( AddressIsBreakpoint(patch->address) );
return true;
}
#if _DEBUG
VerifyExecutableAddress((BYTE*)patch->address);
#endif
LPVOID baseAddress = (LPVOID)(patch->address);
DWORD oldProt;
if (!VirtualProtect(baseAddress,
CORDbg_BREAK_INSTRUCTION_SIZE,
PAGE_EXECUTE_READWRITE, &oldProt))
{
_ASSERTE(!"VirtualProtect of code page failed");
return false;
}
patch->opcode = CORDbgGetInstruction(patch->address);
CORDbgInsertBreakpoint((CORDB_ADDRESS_TYPE *)patch->address);
LOG((LF_CORDB, LL_EVERYTHING, "Breakpoint was inserted at %p for opcode %x\n", patch->address, patch->opcode));
if (!VirtualProtect(baseAddress,
CORDbg_BREAK_INSTRUCTION_SIZE,
oldProt, &oldProt))
{
_ASSERTE(!"VirtualProtect of code page failed");
return false;
}
}
// TODO: : determine if this is needed for AMD64
#if defined(_TARGET_X86_) //REVISIT_TODO what is this?!
else
{
DWORD oldProt;
//
// !!! IL patch logic assumes reference insruction encoding
//
if (!VirtualProtect((void *) patch->address, 2,
PAGE_EXECUTE_READWRITE, &oldProt))
{
_ASSERTE(!"VirtualProtect of code page failed");
return false;
}
patch->opcode =
(unsigned int) *(unsigned short*)(patch->address+1);
_ASSERTE(patch->opcode != CEE_BREAK);
*(unsigned short *) (patch->address+1) = CEE_BREAK;
if (!VirtualProtect((void *) patch->address, 2, oldProt, &oldProt))
{
_ASSERTE(!"VirtualProtect of code page failed");
return false;
}
}
#endif //_TARGET_X86_
return true;
}
// bool DebuggerController::UnapplyPatch()
// UnapplyPatch removes the patch described by the patch.
// (CopyOpcodeFromAddrToPatch, in reverse.)
// Looks a lot like CopyOpcodeFromAddrToPatch, except that we use a macro to
// copy the instruction back to the code-stream & immediately set the
// opcode field to 0 so ReadMemory,WriteMemory will work right.
// Note that it's very important to zero out the opcode field, as it
// is used by the right side to determine if a patch is
// valid or not.
// NO LOCKING
// DebuggerControllerPatch * patch: Patch to remove
// Returns: true if the patch was unapplied, false otherwise
bool DebuggerController::UnapplyPatch(DebuggerControllerPatch *patch)
{
_ASSERTE(patch->address != NULL);
_ASSERTE(patch->IsActivated() );
LOG((LF_CORDB,LL_INFO1000, "DC::UP unapply patch at addr 0x%p\n",
patch->address));
if (patch->IsNativePatch())
{
if (patch->fSaveOpcode)
{
// We're doing this for MoveCode, and we don't want to
// overwrite something if we don't get moved far enough.
patch->opcodeSaved = patch->opcode;
InitializePRD(&(patch->opcode));
_ASSERTE( !patch->IsActivated() );
return true;
}
LPVOID baseAddress = (LPVOID)(patch->address);
DWORD oldProt;
if (!VirtualProtect(baseAddress,
CORDbg_BREAK_INSTRUCTION_SIZE,
PAGE_EXECUTE_READWRITE, &oldProt))
{
//
// We may be trying to remove a patch from memory
// which has been unmapped. We can ignore the
// error in this case.
//
InitializePRD(&(patch->opcode));
return false;
}
CORDbgSetInstruction((CORDB_ADDRESS_TYPE *)patch->address, patch->opcode);
//VERY IMPORTANT to zero out opcode, else we might mistake
//this patch for an active on on ReadMem/WriteMem (see
//header file comment)
InitializePRD(&(patch->opcode));
if (!VirtualProtect(baseAddress,
CORDbg_BREAK_INSTRUCTION_SIZE,
oldProt, &oldProt))
{
_ASSERTE(!"VirtualProtect of code page failed");
return false;
}
}
else
{
DWORD oldProt;
if (!VirtualProtect((void *) patch->address, 2,
PAGE_EXECUTE_READWRITE, &oldProt))
{
//
// We may be trying to remove a patch from memory
// which has been unmapped. We can ignore the
// error in this case.
//
InitializePRD(&(patch->opcode));
return false;
}
//
// !!! IL patch logic assumes reference encoding
//
// TODO: : determine if this is needed for AMD64
#if defined(_TARGET_X86_)
_ASSERTE(*(unsigned short*)(patch->address+1) == CEE_BREAK);
*(unsigned short *) (patch->address+1)
= (unsigned short) patch->opcode;
#endif //this makes no sense on anything but X86
//VERY IMPORTANT to zero out opcode, else we might mistake
//this patch for an active on on ReadMem/WriteMem (see
//header file comment
InitializePRD(&(patch->opcode));
if (!VirtualProtect((void *) patch->address, 2, oldProt, &oldProt))
{
_ASSERTE(!"VirtualProtect of code page failed");
return false;
}
}
_ASSERTE( !patch->IsActivated() );
_ASSERTE( patch->IsBound() );
return true;
}
// void DebuggerController::UnapplyPatchAt()
// NO LOCKING
// UnapplyPatchAt removes the patch from a copy of the patched code.
// Like UnapplyPatch, except that we don't bother checking
// memory permissions, but instead replace the breakpoint instruction
// with the opcode at an arbitrary memory address.
void DebuggerController::UnapplyPatchAt(DebuggerControllerPatch *patch,
CORDB_ADDRESS_TYPE *address)
{
_ASSERTE(patch->IsBound() );
if (patch->IsNativePatch())
{
CORDbgSetInstruction((CORDB_ADDRESS_TYPE *)address, patch->opcode);
//note that we don't have to zero out opcode field
//since we're unapplying at something other than
//the original spot. We assert this is true:
_ASSERTE( patch->address != address );
}
else
{
//
// !!! IL patch logic assumes reference encoding
//
// TODO: : determine if this is needed for AMD64
#ifdef _TARGET_X86_
_ASSERTE(*(unsigned short*)(address+1) == CEE_BREAK);
*(unsigned short *) (address+1)
= (unsigned short) patch->opcode;
_ASSERTE( patch->address != address );
#endif // this makes no sense on anything but X86
}
}
// bool DebuggerController::IsPatched() Is there a patch at addr?
// How: if fNative && the instruction at addr is the break
// instruction for this platform.
bool DebuggerController::IsPatched(CORDB_ADDRESS_TYPE *address, BOOL native)
{
LIMITED_METHOD_CONTRACT;
if (native)
{
return AddressIsBreakpoint(address);
}
else
return false;
}
// DWORD DebuggerController::GetPatchedOpcode() Gets the opcode
// at addr, 'looking underneath' any patches if needed.
// GetPatchedInstruction is a function for the EE to call to "see through"
// a patch to the opcodes which was patched.
// How: Lock() grab opcode directly unless there's a patch, in
// which case grab it out of the patch table.
// BYTE * address: The address that we want to 'see through'
// Returns: DWORD value, that is the opcode that should really be there,
// if we hadn't placed a patch there. If we haven't placed a patch
// there, then we'll see the actual opcode at that address.
PRD_TYPE DebuggerController::GetPatchedOpcode(CORDB_ADDRESS_TYPE *address)
{
_ASSERTE(g_patches != NULL);
PRD_TYPE opcode;
ZeroMemory(&opcode, sizeof(opcode));
ControllerLockHolder lockController;
//
// Look for a patch at the address
//
DebuggerControllerPatch *patch = g_patches->GetPatch((CORDB_ADDRESS_TYPE *)address);
if (patch != NULL)
{
// Since we got the patch at this address, is must by definition be bound to that address
_ASSERTE( patch->IsBound() );
_ASSERTE( patch->address == address );
// If we're going to be returning it's opcode, then the patch must also be activated
_ASSERTE( patch->IsActivated() );
opcode = patch->opcode;
}
else
{
//
// Patch was not found - it either is not our patch, or it has
// just been removed. In either case, just return the current
// opcode.
//
if (g_pEEInterface->IsManagedNativeCode((const BYTE *)address))
{
opcode = CORDbgGetInstruction((CORDB_ADDRESS_TYPE *)address);
}
// <REVISIT_TODO>
// TODO: : determine if this is needed for AMD64
// </REVISIT_TODO>
#ifdef _TARGET_X86_ //what is this?!
else
{
//
// !!! IL patch logic assumes reference encoding
//
opcode = *(unsigned short*)(address+1);
}
#endif //_TARGET_X86_
}
return opcode;
}
// Holding the controller lock, this will check if an address is patched,
// and if so will then set the PRT_TYPE out parameter to the unpatched value.
BOOL DebuggerController::CheckGetPatchedOpcode(CORDB_ADDRESS_TYPE *address,
/*OUT*/ PRD_TYPE *pOpcode)
{
CONTRACTL
{
SO_NOT_MAINLINE; // take Controller lock.
NOTHROW;
GC_NOTRIGGER;
}
CONTRACTL_END;
_ASSERTE(g_patches != NULL);
BOOL res;
ControllerLockHolder lockController;
//
// Look for a patch at the address
//
if (IsAddressPatched(address))
{
*pOpcode = GetPatchedOpcode(address);
res = TRUE;
}
else
{
InitializePRD(pOpcode);
res = FALSE;
}
return res;
}
// void DebuggerController::ActivatePatch() Place a breakpoint
// so that threads will trip over this patch.
// If there any patches at the address already, then copy
// their opcode into this one & return. Otherwise,
// call ApplyPatch(patch). There is an implicit list of patches at this
// address by virtue of the fact that we can iterate through all the
// patches in the patch with the same address.
// DebuggerControllerPatch *patch: The patch to activate
/* static */ void DebuggerController::ActivatePatch(DebuggerControllerPatch *patch)
{
_ASSERTE(g_patches != NULL);
_ASSERTE(patch != NULL);
_ASSERTE(patch->IsBound() );
_ASSERTE(!patch->IsActivated() );
bool fApply = true;
//
// See if we already have an active patch at this address.
//
for (DebuggerControllerPatch *p = g_patches->GetPatch(patch->address);
p != NULL;
p = g_patches->GetNextPatch(p))
{
if (p != patch)
{
// If we're going to skip activating 'patch' because 'p' already exists at the same address
// then 'p' must be activated. We expect that all bound patches are activated.
_ASSERTE( p->IsActivated() );
patch->opcode = p->opcode;
fApply = false;
break;
}
}
//
// This is the only patch at this address - apply the patch
// to the code.
//
if (fApply)
{
ApplyPatch(patch);
}
_ASSERTE(patch->IsActivated() );
}
// void DebuggerController::DeactivatePatch() Make sure that a
// patch won't be hit.
// How: If this patch is the last one at this address, then
// UnapplyPatch. The caller should then invoke RemovePatch to remove the
// patch from the patch table.
// DebuggerControllerPatch *patch: Patch to deactivate
void DebuggerController::DeactivatePatch(DebuggerControllerPatch *patch)
{
_ASSERTE(g_patches != NULL);
if( !patch->IsBound() ) {
// patch is not bound, nothing to do
return;
}
// We expect that all bound patches are also activated.
// One exception to this is if the shutdown thread killed another thread right after
// if deactivated a patch but before it got to remove it.
_ASSERTE(patch->IsActivated() );
bool fUnapply = true;
//
// See if we already have an active patch at this address.
//
for (DebuggerControllerPatch *p = g_patches->GetPatch(patch->address);
p != NULL;
p = g_patches->GetNextPatch(p))
{
if (p != patch)
{
// There is another patch at this address, so don't remove it
// However, clear the patch data so that we no longer consider this particular patch activated
fUnapply = false;
InitializePRD(&(patch->opcode));
break;
}
}
if (fUnapply)
{
UnapplyPatch(patch);
}
_ASSERTE(!patch->IsActivated() );
//
// Patch must now be removed from the table.
//
}
// AddILMasterPatch: record a patch on IL code but do not bind it or activate it. The master b.p.
// is associated with a module/token pair. It is used later
// (e.g. in MapAndBindFunctionPatches) to create one or more "slave"
// breakpoints which are associated with particular MethodDescs/JitInfos.
//
// Rationale: For generic code a single IL patch (e.g a breakpoint)
// may give rise to several patches, one for each JITting of
// the IL (i.e. generic code may be JITted multiple times for
// different instantiations).
//
// So we keep one patch which describes
// the breakpoint but which is never actually bound or activated.
// This is then used to apply new "slave" patches to all copies of
// JITted code associated with the method.
//
// <REVISIT_TODO>In theory we could bind and apply the master patch when the
// code is known not to be generic (as used to happen to all breakpoint
// patches in V1). However this seems like a premature
// optimization.</REVISIT_TODO>
DebuggerControllerPatch *DebuggerController::AddILMasterPatch(Module *module,
mdMethodDef md,
SIZE_T offset,
SIZE_T encVersion)
{
CONTRACTL
{
THROWS;
MODE_ANY;
GC_NOTRIGGER;
}
CONTRACTL_END;
_ASSERTE(g_patches != NULL);
ControllerLockHolder ch;
DebuggerControllerPatch *patch = g_patches->AddPatchForMethodDef(this,
module,
md,
offset,
PATCH_KIND_IL_MASTER,
LEAF_MOST_FRAME,
NULL,
encVersion,
NULL);
LOG((LF_CORDB, LL_INFO10000,
"DC::AP: Added IL master patch 0x%x for md 0x%x at offset %d encVersion %d\n", patch, md, offset, encVersion));
return patch;
}
// See notes above on AddILMasterPatch
BOOL DebuggerController::AddBindAndActivateILSlavePatch(DebuggerControllerPatch *master,
DebuggerJitInfo *dji)
{
_ASSERTE(g_patches != NULL);
_ASSERTE(master->IsILMasterPatch());
_ASSERTE(dji != NULL);
// Do not dereference the "master" pointer in the loop! The loop may add more patches,
// causing the patch table to grow and move.
BOOL result = FALSE;
SIZE_T masterILOffset = master->offset;
// Loop through all the native offsets mapped to the given IL offset. On x86 the mapping
// should be 1:1. On WIN64, because there are funclets, we have have an 1:N mapping.
DebuggerJitInfo::ILToNativeOffsetIterator it;
for (dji->InitILToNativeOffsetIterator(it, masterILOffset); !it.IsAtEnd(); it.Next())
{
BOOL fExact;
SIZE_T offsetNative = it.Current(&fExact);
// We special case offset 0, which is when a breakpoint is set
// at the beginning of a method that hasn't been jitted yet. In
// that case it's possible that offset 0 has been optimized out,
// but we still want to set the closest breakpoint to that.
if (!fExact && (masterILOffset != 0))
{
LOG((LF_CORDB, LL_INFO10000, "DC::BP:Failed to bind patch at IL offset 0x%p in %s::%s\n",
masterILOffset, dji->m_fd->m_pszDebugClassName, dji->m_fd->m_pszDebugMethodName));
continue;
}
else
{
result = TRUE;
}
INDEBUG(BOOL fOk = )
AddBindAndActivatePatchForMethodDesc(dji->m_fd, dji,
offsetNative, PATCH_KIND_IL_SLAVE,
LEAF_MOST_FRAME, m_pAppDomain);
_ASSERTE(fOk);
}
// As long as we have successfully bound at least one patch, we consider the operation successful.
return result;
}
// This routine places a patch that is conceptually a patch on the IL code.
// The IL code may be jitted multiple times, e.g. due to generics.
// This routine ensures that both present and subsequent JITtings of code will
// also be patched.
//
// This routine will return FALSE only if we will _never_ be able to
// place the patch in any native code corresponding to the given offset.
// Otherwise it will:
// (a) record a "master" patch
// (b) apply as many slave patches as it can to existing copies of code
// that have debugging information
BOOL DebuggerController::AddILPatch(AppDomain * pAppDomain, Module *module,
mdMethodDef md,
SIZE_T encVersion, // what encVersion does this apply to?
SIZE_T offset)
{
_ASSERTE(g_patches != NULL);
_ASSERTE(md != NULL);
_ASSERTE(module != NULL);
BOOL fOk = FALSE;
DebuggerMethodInfo *dmi = g_pDebugger->GetOrCreateMethodInfo(module, md); // throws
if (dmi == NULL)
{
return false;
}
EX_TRY
{
// OK, we either have (a) no code at all or (b) we have both JIT information and code
//.
// Either way, lay down the MasterPatch.
//
// MapAndBindFunctionPatches will take care of any instantiations that haven't
// finished JITting, by making a copy of the master breakpoint.
DebuggerControllerPatch *master = AddILMasterPatch(module, md, offset, encVersion);
// We have to keep the index here instead of the pointer. The loop below adds more patches,
// which may cause the patch table to grow and move.
ULONG masterIndex = g_patches->GetItemIndex((HASHENTRY*)master);
// Iterate through every existing NativeCodeBlob (with the same EnC version).
// This includes generics + prejitted code.
DebuggerMethodInfo::DJIIterator it;
dmi->IterateAllDJIs(pAppDomain, NULL /* module filter */, &it);
if (it.IsAtEnd())
{
// It is okay if we don't have any DJIs yet. It just means that the method hasn't been jitted.
fOk = TRUE;
}
else
{
// On the other hand, if the method has been jitted, then we expect to be able to bind at least
// one breakpoint. The exception is when we have multiple EnC versions of the method, in which
// case it is ok if we don't bind any breakpoint. One scenario is when a method has been updated
// via EnC but it's not yet jitted. We need to allow a debugger to put a breakpoint on the new
// version of the method, but the new version won't have a DJI yet.
BOOL fVersionMatch = FALSE;
while(!it.IsAtEnd())
{
DebuggerJitInfo *dji = it.Current();
_ASSERTE(dji->m_jitComplete);
if (dji->m_encVersion == encVersion)
{
fVersionMatch = TRUE;
master = (DebuggerControllerPatch *)g_patches->GetEntryPtr(masterIndex);
// <REVISIT_TODO> If we're missing JIT info for any then
// we won't have applied the bp to every instantiation. That should probably be reported
// as a new kind of condition to the debugger, i.e. report "bp only partially applied". It would be
// a shame to completely fail just because on instantiation is missing debug info: e.g. just because
// one component hasn't been prejitted with debugging information.</REVISIT_TODO>
fOk = (AddBindAndActivateILSlavePatch(master, dji) || fOk);
}
it.Next();
}
// This is the exceptional case referred to in the comment above. If we fail to put a breakpoint
// because we don't have a matching version of the method, we need to return TRUE.
if (fVersionMatch == FALSE)
{
fOk = TRUE;
}
}
}
EX_CATCH
{
fOk = FALSE;
}
EX_END_CATCH(SwallowAllExceptions)
return fOk;
}
// Add a patch at native-offset 0 in the latest version of the method.
// This is used by step-in.
// Calls to new methods always go to the latest version, so EnC is not an issue here.
// The method may be not yet jitted. Or it may be prejitted.
void DebuggerController::AddPatchToStartOfLatestMethod(MethodDesc * fd)
{
CONTRACTL
{
SO_NOT_MAINLINE;
THROWS; // from GetJitInfo
GC_NOTRIGGER;
MODE_ANY; // don't really care what mode we're in.
PRECONDITION(ThisMaybeHelperThread());
PRECONDITION(CheckPointer(fd));
}
CONTRACTL_END;
_ASSERTE(g_patches != NULL);
DebuggerController::AddBindAndActivatePatchForMethodDesc(fd, NULL, 0, PATCH_KIND_NATIVE_MANAGED, LEAF_MOST_FRAME, NULL);
return;
}
// Place patch in method at native offset.
BOOL DebuggerController::AddBindAndActivateNativeManagedPatch(MethodDesc * fd,
DebuggerJitInfo *dji,
SIZE_T offsetNative,
FramePointer fp,
AppDomain *pAppDomain)
{
CONTRACTL
{
SO_NOT_MAINLINE;
THROWS; // from GetJitInfo
GC_NOTRIGGER;
MODE_ANY; // don't really care what mode we're in.
PRECONDITION(ThisMaybeHelperThread());
PRECONDITION(CheckPointer(fd));
PRECONDITION(fd->IsDynamicMethod() || (dji != NULL));
}
CONTRACTL_END;
// For non-dynamic methods, we always expect to have a DJI, but just in case, we don't want the assert to AV.
_ASSERTE((dji == NULL) || (fd == dji->m_fd));
_ASSERTE(g_patches != NULL);
return DebuggerController::AddBindAndActivatePatchForMethodDesc(fd, dji, offsetNative, PATCH_KIND_NATIVE_MANAGED, fp, pAppDomain);
}
BOOL DebuggerController::AddBindAndActivatePatchForMethodDesc(MethodDesc *fd,
DebuggerJitInfo *dji,
SIZE_T offset,
DebuggerPatchKind kind,
FramePointer fp,
AppDomain *pAppDomain)
{
CONTRACTL
{
SO_NOT_MAINLINE;
THROWS;
GC_NOTRIGGER;
MODE_ANY; // don't really care what mode we're in.
PRECONDITION(ThisMaybeHelperThread());
}
CONTRACTL_END;
BOOL ok = FALSE;
ControllerLockHolder ch;
LOG((LF_CORDB|LF_ENC,LL_INFO10000,"DC::AP: Add to %s::%s, at offs 0x%x "
"fp:0x%x AD:0x%x\n", fd->m_pszDebugClassName,
fd->m_pszDebugMethodName,
offset, fp.GetSPValue(), pAppDomain));
DebuggerControllerPatch *patch = g_patches->AddPatchForMethodDef(
this,
g_pEEInterface->MethodDescGetModule(fd),
fd->GetMemberDef(),
offset,
kind,
fp,
pAppDomain,
NULL,
dji);
if (DebuggerController::BindPatch(patch, fd, NULL))
{
LOG((LF_CORDB|LF_ENC,LL_INFO1000,"BindPatch went fine, doing ActivatePatch\n"));
DebuggerController::ActivatePatch(patch);
ok = TRUE;
}
return ok;
}
// This version is particularly useful b/c it doesn't assume that the
// patch is inside a managed method.
DebuggerControllerPatch *DebuggerController::AddAndActivateNativePatchForAddress(CORDB_ADDRESS_TYPE *address,
FramePointer fp,
bool managed,
TraceType traceType)
{
CONTRACTL
{
THROWS;
MODE_ANY;
GC_NOTRIGGER;
PRECONDITION(g_patches != NULL);
}
CONTRACTL_END;
ControllerLockHolder ch;
DebuggerControllerPatch *patch
= g_patches->AddPatchForAddress(this,
NULL,
0,
(managed? PATCH_KIND_NATIVE_MANAGED : PATCH_KIND_NATIVE_UNMANAGED),
address,
fp,
NULL,
NULL,
DebuggerPatchTable::DCP_PID_INVALID,
traceType);
ActivatePatch(patch);
return patch;
}
void DebuggerController::RemovePatchesFromModule(Module *pModule, AppDomain *pAppDomain )
{
CONTRACTL
{
SO_NOT_MAINLINE;
NOTHROW;
GC_NOTRIGGER;
}
CONTRACTL_END;
LOG((LF_CORDB, LL_INFO100000, "DPT::CPFM mod:0x%p (%S)\n",
pModule, pModule->GetDebugName()));
// First find all patches of interest
DebuggerController::ControllerLockHolder ch;
HASHFIND f;
for (DebuggerControllerPatch *patch = g_patches->GetFirstPatch(&f);
patch != NULL;
patch = g_patches->GetNextPatch(&f))
{
// Skip patches not in the specified domain
if ((pAppDomain != NULL) && (patch->pAppDomain != pAppDomain))
continue;
BOOL fRemovePatch = FALSE;
// Remove both native and IL patches the belong to this module
if (patch->HasDJI())
{
DebuggerJitInfo * dji = patch->GetDJI();
_ASSERTE(patch->key.module == dji->m_fd->GetModule());
// It is not necessary to check for m_fd->GetModule() here. It will
// be covered by other module unload notifications issued for the appdomain.
if ( dji->m_pLoaderModule == pModule )
fRemovePatch = TRUE;
}
else
if (patch->key.module == pModule)
{
fRemovePatch = TRUE;
}
if (fRemovePatch)
{
LOG((LF_CORDB, LL_EVERYTHING, "Removing patch 0x%p\n",
patch));
// we shouldn't be both hitting this patch AND
// unloading the module it belongs to.
_ASSERTE(!patch->IsTriggering());
Release( patch );
}
}
}
#ifdef _DEBUG
bool DebuggerController::ModuleHasPatches( Module* pModule )
{
CONTRACTL
{
SO_NOT_MAINLINE;
NOTHROW;
GC_NOTRIGGER;
}
CONTRACTL_END;
if( g_patches == NULL )
{
// Patch table hasn't been initialized
return false;
}
// First find all patches of interest
HASHFIND f;
for (DebuggerControllerPatch *patch = g_patches->GetFirstPatch(&f);
patch != NULL;
patch = g_patches->GetNextPatch(&f))
{
//
// This mirrors logic in code:DebuggerController::RemovePatchesFromModule
//
if (patch->HasDJI())
{
DebuggerJitInfo * dji = patch->GetDJI();
_ASSERTE(patch->key.module == dji->m_fd->GetModule());
// It may be sufficient to just check m_pLoaderModule here. Since this is used for debug-only
// check, we will check for m_fd->GetModule() as well to catch more potential problems.
if ( (dji->m_pLoaderModule == pModule) || (dji->m_fd->GetModule() == pModule) )
{
return true;
}
}
if (patch->key.module == pModule)
{
return true;
}
}
return false;
}
#endif // _DEBUG
//
// Returns true if the given address is in an internal helper
// function, false if its not.
//
// This is a temporary workaround function to avoid having us stop in
// unmanaged code belonging to the Runtime during a StepIn operation.
//
static bool _AddrIsJITHelper(PCODE addr)
{
#if !defined(_WIN64) && !defined(FEATURE_PAL)
// Is the address in the runtime dll (clr.dll or coreclr.dll) at all? (All helpers are in
// that dll)
if (g_runtimeLoadedBaseAddress <= addr &&
addr < g_runtimeLoadedBaseAddress + g_runtimeVirtualSize)
{
for (int i = 0; i < CORINFO_HELP_COUNT; i++)
{
if (hlpFuncTable[i].pfnHelper == (void*)addr)
{
LOG((LF_CORDB, LL_INFO10000,
"_ANIM: address of helper function found: 0x%08x\n",
addr));
return true;
}
}
for (unsigned d = 0; d < DYNAMIC_CORINFO_HELP_COUNT; d++)
{
if (hlpDynamicFuncTable[d].pfnHelper == (void*)addr)
{
LOG((LF_CORDB, LL_INFO10000,
"_ANIM: address of helper function found: 0x%08x\n",
addr));
return true;
}
}
LOG((LF_CORDB, LL_INFO10000,
"_ANIM: address within runtime dll, but not a helper function "
"0x%08x\n", addr));
}
#else // !defined(_WIN64) && !defined(FEATURE_PAL)
// TODO: Figure out what we want to do here
#endif // !defined(_WIN64) && !defined(FEATURE_PAL)
return false;
}
// bool DebuggerController::PatchTrace() What: Invoke
// AddPatch depending on the type of the given TraceDestination.
// How: Invokes AddPatch based on the trace type: TRACE_OTHER will
// return false, the others will obtain args for a call to an AddPatch
// method & return true.
//
// Return true if we set a patch, else false
bool DebuggerController::PatchTrace(TraceDestination *trace,
FramePointer fp,
bool fStopInUnmanaged)
{
CONTRACTL
{
THROWS; // Because AddPatch may throw on oom. We may want to convert this to nothrow and return false.
MODE_ANY;
DISABLED(GC_TRIGGERS); // @todo - what should this be?
PRECONDITION(ThisMaybeHelperThread());
}
CONTRACTL_END;
DebuggerControllerPatch *dcp = NULL;
switch (trace->GetTraceType())
{
case TRACE_ENTRY_STUB: // fall through
case TRACE_UNMANAGED:
LOG((LF_CORDB, LL_INFO10000,
"DC::PT: Setting unmanaged trace patch at 0x%p(%p)\n",
trace->GetAddress(), fp.GetSPValue()));
if (fStopInUnmanaged && !_AddrIsJITHelper(trace->GetAddress()))
{
AddAndActivateNativePatchForAddress((CORDB_ADDRESS_TYPE *)trace->GetAddress(),
fp,
FALSE,
trace->GetTraceType());
return true;
}
else
{
LOG((LF_CORDB, LL_INFO10000, "DC::PT: decided to NOT "
"place a patch in unmanaged code\n"));
return false;
}
case TRACE_MANAGED:
LOG((LF_CORDB, LL_INFO10000,
"Setting managed trace patch at 0x%p(%p)\n", trace->GetAddress(), fp.GetSPValue()));
MethodDesc *fd;
fd = g_pEEInterface->GetNativeCodeMethodDesc(trace->GetAddress());
_ASSERTE(fd);
DebuggerJitInfo *dji;
dji = g_pDebugger->GetJitInfoFromAddr(trace->GetAddress());
//_ASSERTE(dji); //we'd like to assert this, but attach won't work
AddBindAndActivateNativeManagedPatch(fd,
dji,
CodeRegionInfo::GetCodeRegionInfo(dji, fd).AddressToOffset((const BYTE *)trace->GetAddress()),
fp,
NULL);
return true;
case TRACE_UNJITTED_METHOD:
// trace->address is actually a MethodDesc* of the method that we'll
// soon JIT, so put a relative bp at offset zero in.
LOG((LF_CORDB, LL_INFO10000,
"Setting unjitted method patch in MethodDesc 0x%p %s\n", trace->GetMethodDesc(), trace->GetMethodDesc() ? trace->GetMethodDesc()->m_pszDebugMethodName : ""));
// Note: we have to make sure to bind here. If this function is prejitted, this may be our only chance to get a
// DebuggerJITInfo and thereby cause a JITComplete callback.
AddPatchToStartOfLatestMethod(trace->GetMethodDesc());
return true;
case TRACE_FRAME_PUSH:
LOG((LF_CORDB, LL_INFO10000,
"Setting frame patch at 0x%p(%p)\n", trace->GetAddress(), fp.GetSPValue()));
AddAndActivateNativePatchForAddress((CORDB_ADDRESS_TYPE *)trace->GetAddress(),
fp,
TRUE,
TRACE_FRAME_PUSH);
return true;
case TRACE_MGR_PUSH:
LOG((LF_CORDB, LL_INFO10000,
"Setting frame patch (TRACE_MGR_PUSH) at 0x%p(%p)\n",
trace->GetAddress(), fp.GetSPValue()));
dcp = AddAndActivateNativePatchForAddress((CORDB_ADDRESS_TYPE *)trace->GetAddress(),
LEAF_MOST_FRAME, // But Mgr_push can't have fp affinity!
TRUE,
DPT_DEFAULT_TRACE_TYPE); // TRACE_OTHER
// Now copy over the trace field since TriggerPatch will expect this
// to be set for this case.
if (dcp != NULL)
{
dcp->trace = *trace;
}
return true;
case TRACE_OTHER:
LOG((LF_CORDB, LL_INFO10000,
"Can't set a trace patch for TRACE_OTHER...\n"));
return false;
default:
_ASSERTE(0);
return false;
}
}
//-----------------------------------------------------------------------------
// Checks if the patch matches the context + thread.
// Multiple patches can exist at a single address, so given a patch at the
// Context's current address, this does additional patch-affinity checks like
// thread, AppDomain, and frame-pointer.
// thread - thread executing the given context that hit the patch
// context - context of the thread that hit the patch
// patch - candidate patch that we're looking for a match.
// Returns:
// True if the patch matches.
// False
//-----------------------------------------------------------------------------
bool DebuggerController::MatchPatch(Thread *thread,
CONTEXT *context,
DebuggerControllerPatch *patch)
{
LOG((LF_CORDB, LL_INFO100000, "DC::MP: EIP:0x%p\n", GetIP(context)));
// Caller should have already matched our addresses.
if (patch->address != dac_cast<PTR_CORDB_ADDRESS_TYPE>(GetIP(context)))
{
return false;
}
// <BUGNUM>RAID 67173 -</BUGNUM> we'll make sure that intermediate patches have NULL
// pAppDomain so that we don't end up running to completion when
// the appdomain switches halfway through a step.
if (patch->pAppDomain != NULL)
{
AppDomain *pAppDomainCur = thread->GetDomain();
if (pAppDomainCur != patch->pAppDomain)
{
LOG((LF_CORDB, LL_INFO10000, "DC::MP: patches didn't match b/c of "
"appdomains!\n"));
return false;
}
}
if (patch->controller->m_thread != NULL && patch->controller->m_thread != thread)
{
LOG((LF_CORDB, LL_INFO10000, "DC::MP: patches didn't match b/c threads\n"));
return false;
}
if (patch->fp != LEAF_MOST_FRAME)
{
// If we specified a Frame-pointer, than it should have been safe to take a stack trace.
ControllerStackInfo info;
StackTraceTicket ticket(patch);
info.GetStackInfo(ticket, thread, LEAF_MOST_FRAME, context);
// !!! This check should really be != , but there is some ambiguity about which frame is the parent frame
// in the destination returned from Frame::TraceFrame, so this allows some slop there.
if (info.HasReturnFrame() && IsCloserToLeaf(info.m_returnFrame.fp, patch->fp))
{
LOG((LF_CORDB, LL_INFO10000, "Patch hit but frame not matched at %p (current=%p, patch=%p)\n",
patch->address, info.m_returnFrame.fp.GetSPValue(), patch->fp.GetSPValue()));
return false;
}
}
LOG((LF_CORDB, LL_INFO100000, "DC::MP: Returning true"));
return true;
}
DebuggerPatchSkip *DebuggerController::ActivatePatchSkip(Thread *thread,
const BYTE *PC,
BOOL fForEnC)
{
#ifdef _DEBUG
BOOL shouldBreak = CLRConfig::GetConfigValue(CLRConfig::INTERNAL_ActivatePatchSkip);
if (shouldBreak > 0) {
_ASSERTE(!"ActivatePatchSkip");
}
#endif
LOG((LF_CORDB,LL_INFO10000, "DC::APS thread=0x%p pc=0x%p fForEnc=%d\n",
thread, PC, fForEnC));
_ASSERTE(g_patches != NULL);
// Previously, we assumed that if we got to this point & the patch
// was still there that we'd have to skip the patch. SetIP changes
// this like so:
// A breakpoint is set, and hit (but not removed), and all the
// EE threads come to a skreeching halt. The Debugger RC thread
// continues along, and is told to SetIP of the thread that hit
// the BP to whatever. Eventually the RC thread is told to continue,
// and at that point the EE thread is released, finishes DispatchPatchOrSingleStep,
// and shows up here.
// At that point, if the thread's current PC is
// different from the patch PC, then SetIP must have moved it elsewhere
// & we shouldn't do this patch skip (which will put us back to where
// we were, which is clearly wrong). If the PC _is_ the same, then
// the thread hasn't been moved, the patch is still in the code stream,
// and we want to do the patch skip thing in order to execute this
// instruction w/o removing it from the code stream.
DebuggerControllerPatch *patch = g_patches->GetPatch((CORDB_ADDRESS_TYPE *)PC);
DebuggerPatchSkip *skip = NULL;
if (patch != NULL && patch->IsNativePatch())
{
//
// We adjust the thread's PC to someplace where we write
// the next instruction, then
// we single step over that, then we set the PC back here so
// we don't let other threads race past here while we're stepping
// this one.
//
// !!! check result
LOG((LF_CORDB,LL_INFO10000, "DC::APS: About to skip from PC=0x%p\n", PC));
skip = new (interopsafe) DebuggerPatchSkip(thread, patch, thread->GetDomain());
TRACE_ALLOC(skip);
}
return skip;
}
DPOSS_ACTION DebuggerController::ScanForTriggers(CORDB_ADDRESS_TYPE *address,
Thread *thread,
CONTEXT *context,
DebuggerControllerQueue *pDcq,
SCAN_TRIGGER stWhat,
TP_RESULT *pTpr)
{
CONTRACTL
{
SO_NOT_MAINLINE;
// @todo - should this throw or not?
NOTHROW;
// call Triggers which may invoke GC stuff... See comment in DispatchNativeException for why it's disabled.
DISABLED(GC_TRIGGERS);
PRECONDITION(!ThisIsHelperThreadWorker());
PRECONDITION(CheckPointer(address));
PRECONDITION(CheckPointer(thread));
PRECONDITION(CheckPointer(context));
PRECONDITION(CheckPointer(pDcq));
PRECONDITION(CheckPointer(pTpr));
}
CONTRACTL_END;
_ASSERTE(HasLock());
CONTRACT_VIOLATION(ThrowsViolation);
LOG((LF_CORDB, LL_INFO10000, "DC::SFT: starting scan for addr:0x%p"
" thread:0x%x\n", address, thread));
_ASSERTE( pTpr != NULL );
DebuggerControllerPatch *patch = NULL;
if (g_patches != NULL)
patch = g_patches->GetPatch(address);
ULONG iEvent = UINT32_MAX;
ULONG iEventNext = UINT32_MAX;
BOOL fDone = FALSE;
// This is a debugger exception if there's a patch here, or
// we're here for something like a single step.
DPOSS_ACTION used = DPOSS_INVALID;
if ((patch != NULL) || !IsPatched(address, TRUE))
{
// we are sure that we care for this exception but not sure
// if we will send event to the RS
used = DPOSS_USED_WITH_NO_EVENT;
}
else
{
// initialize it to don't care for now
used = DPOSS_DONT_CARE;
}
TP_RESULT tpr = TPR_IGNORE;
while (stWhat & ST_PATCH &&
patch != NULL &&
!fDone)
{
_ASSERTE(IsInUsedAction(used) == true);
DebuggerControllerPatch *patchNext
= g_patches->GetNextPatch(patch);
LOG((LF_CORDB, LL_INFO10000, "DC::SFT: patch 0x%x, patchNext 0x%x\n", patch, patchNext));
// Annoyingly, TriggerPatch may add patches, which may cause
// the patch table to move, which may, in turn, invalidate
// the patch (and patchNext) pointers. Store indeces, instead.
iEvent = g_patches->GetItemIndex( (HASHENTRY *)patch );
if (patchNext != NULL)
{
iEventNext = g_patches->GetItemIndex((HASHENTRY *)patchNext);
}
if (MatchPatch(thread, context, patch))
{
LOG((LF_CORDB, LL_INFO10000, "DC::SFT: patch matched\n"));
AddRef(patch);
// We are hitting a patch at a virtual trace call target, so let's trigger trace call here.
if (patch->trace.GetTraceType() == TRACE_ENTRY_STUB)
{
patch->controller->TriggerTraceCall(thread, dac_cast<PTR_CBYTE>(::GetIP(context)));
tpr = TPR_IGNORE;
}
else
{
// Mark if we're at an unsafe place.
AtSafePlaceHolder unsafePlaceHolder(thread);
tpr = patch->controller->TriggerPatch(patch,
thread,
TY_NORMAL);
}
// Any patch may potentially send an event.
// (Whereas some single-steps are "internal-only" and can
// never send an event- such as a single step over an exception that
// lands us in la-la land.)
used = DPOSS_USED_WITH_EVENT;
if (tpr == TPR_TRIGGER ||
tpr == TPR_TRIGGER_ONLY_THIS ||
tpr == TPR_TRIGGER_ONLY_THIS_AND_LOOP)
{
// Make sure we've still got a valid pointer.
patch = (DebuggerControllerPatch *)
DebuggerController::g_patches->GetEntryPtr( iEvent );
pDcq->dcqEnqueue(patch->controller, TRUE); // <REVISIT_TODO>@todo Return value</REVISIT_TODO>
}
// Make sure we've got a valid pointer in case TriggerPatch
// returned false but still caused the table to move.
patch = (DebuggerControllerPatch *)
g_patches->GetEntryPtr( iEvent );
// A patch can be deleted as a result of it's being triggered.
// The actual deletion of the patch is delayed until after the
// the end of the trigger.
// Moreover, "patchNext" could have been deleted as a result of DisableAll()
// being called in TriggerPatch(). Thus, we should update our patchNext
// pointer now. We were just lucky before, because the now-deprecated
// "deleted" flag didn't get set when we iterate the patches in DisableAll().
patchNext = g_patches->GetNextPatch(patch);
if (patchNext != NULL)
iEventNext = g_patches->GetItemIndex((HASHENTRY *)patchNext);
// Note that Release() actually removes the patch if its ref count
// reaches 0 after the release.
Release(patch);
}
if (tpr == TPR_IGNORE_AND_STOP ||
tpr == TPR_TRIGGER_ONLY_THIS ||
tpr == TPR_TRIGGER_ONLY_THIS_AND_LOOP)
{
#ifdef _DEBUG
if (tpr == TPR_TRIGGER_ONLY_THIS ||
tpr == TPR_TRIGGER_ONLY_THIS_AND_LOOP)
_ASSERTE(pDcq->dcqGetCount() == 1);
#endif //_DEBUG
fDone = TRUE;
}
else if (patchNext != NULL)
{
patch = (DebuggerControllerPatch *)
g_patches->GetEntryPtr(iEventNext);
}
else
{
patch = NULL;
}
}
if (stWhat & ST_SINGLE_STEP &&
tpr != TPR_TRIGGER_ONLY_THIS)
{
LOG((LF_CORDB, LL_INFO10000, "DC::SFT: Trigger controllers with single step\n"));
//
// Now, go ahead & trigger all controllers with
// single step events
//
DebuggerController *p;
p = g_controllers;
while (p != NULL)
{
DebuggerController *pNext = p->m_next;
if (p->m_thread == thread && p->m_singleStep)
{
if (used == DPOSS_DONT_CARE)
{
// Debugger does care for this exception.
used = DPOSS_USED_WITH_NO_EVENT;
}
if (p->TriggerSingleStep(thread, (const BYTE *)address))
{
// by now, we should already know that we care for this exception.
_ASSERTE(IsInUsedAction(used) == true);
// now we are sure that we will send event to the RS
used = DPOSS_USED_WITH_EVENT;
pDcq->dcqEnqueue(p, FALSE); // <REVISIT_TODO>@todo Return value</REVISIT_TODO>
}
}
p = pNext;
}
UnapplyTraceFlag(thread);
//
// See if we have any steppers still active for this thread, if so
// re-apply the trace flag.
//
p = g_controllers;
while (p != NULL)
{
if (p->m_thread == thread && p->m_singleStep)
{
ApplyTraceFlag(thread);
break;
}
p = p->m_next;
}
}
// Significant speed increase from single dereference, I bet :)
(*pTpr) = tpr;
LOG((LF_CORDB, LL_INFO10000, "DC::SFT returning 0x%x as used\n",used));
return used;
}
#ifdef EnC_SUPPORTED
DebuggerControllerPatch *DebuggerController::IsXXXPatched(const BYTE *PC,
DEBUGGER_CONTROLLER_TYPE dct)
{
_ASSERTE(g_patches != NULL);
DebuggerControllerPatch *patch = g_patches->GetPatch((CORDB_ADDRESS_TYPE *)PC);
while(patch != NULL &&
(int)patch->controller->GetDCType() <= (int)dct)
{
if (patch->IsNativePatch() &&
patch->controller->GetDCType()==dct)
{
return patch;
}
patch = g_patches->GetNextPatch(patch);
}
return NULL;
}
// This function will check for an EnC patch at the given address and return
// it if one is there, otherwise it will return NULL.
DebuggerControllerPatch *DebuggerController::GetEnCPatch(const BYTE *address)
{
_ASSERTE(address);
if( g_pEEInterface->IsManagedNativeCode(address) )
{
DebuggerJitInfo *dji = g_pDebugger->GetJitInfoFromAddr((TADDR) address);
if (dji == NULL)
return NULL;
// we can have two types of patches - one in code where the IL has been updated to trigger
// the switch and the other in the code we've switched to in order to trigger FunctionRemapComplete
// callback. If version == default then can't be the latter, but otherwise if haven't handled the
// remap for this function yet is certainly the latter.
if (! dji->m_encBreakpointsApplied &&
(dji->m_encVersion == CorDB_DEFAULT_ENC_FUNCTION_VERSION))
{
return NULL;
}
}
return IsXXXPatched(address, DEBUGGER_CONTROLLER_ENC);
}
#endif //EnC_SUPPORTED
// DebuggerController::DispatchPatchOrSingleStep - Ask any patches that are active at a given
// address if they want to do anything about the exception that's occurred there. How: For the given
// address, go through the list of patches & see if any of them are interested (by invoking their
// DebuggerController's TriggerPatch). Put any DCs that are interested into a queue and then calls
// SendEvent on each.
// Note that control will not return from this function in the case of EnC remap
DPOSS_ACTION DebuggerController::DispatchPatchOrSingleStep(Thread *thread, CONTEXT *context, CORDB_ADDRESS_TYPE *address, SCAN_TRIGGER which)
{
CONTRACT(DPOSS_ACTION)
{
// @todo - should this throw or not?
NOTHROW;
DISABLED(GC_TRIGGERS); // Only GC triggers if we send an event. See Comment in DispatchNativeException
PRECONDITION(!ThisIsHelperThreadWorker());
PRECONDITION(CheckPointer(thread));
PRECONDITION(CheckPointer(context));
PRECONDITION(CheckPointer(address));
PRECONDITION(!HasLock());
POSTCONDITION(!HasLock()); // make sure we're not leaking the controller lock
}
CONTRACT_END;
CONTRACT_VIOLATION(ThrowsViolation);
LOG((LF_CORDB|LF_ENC,LL_INFO1000,"DC:DPOSS at 0x%x trigger:0x%x\n", address, which));
// We should only have an exception if some managed thread was running.
// Thus we should never be here when we're stopped.
// @todo - this assert fires! Is that an issue, or is it invalid?
//_ASSERTE(!g_pDebugger->IsStopped());
DPOSS_ACTION used = DPOSS_DONT_CARE;
DebuggerControllerQueue dcq;
if (!g_patchTableValid)
{
LOG((LF_CORDB|LF_ENC, LL_INFO1000, "DC::DPOSS returning, no patch table.\n"));
RETURN (used);
}
_ASSERTE(g_patches != NULL);
CrstHolderWithState lockController(&g_criticalSection);
TADDR originalAddress = 0;
#ifdef EnC_SUPPORTED
DebuggerControllerPatch *dcpEnCOriginal = NULL;
// If this sequence point has an EnC patch, we want to process it ahead of any others. If the
// debugger wants to remap the function at this point, then we'll call ResumeInUpdatedFunction and
// not return, otherwise we will just continue with regular patch-handling logic
dcpEnCOriginal = GetEnCPatch(dac_cast<PTR_CBYTE>(GetIP(context)));
if (dcpEnCOriginal)
{
LOG((LF_CORDB|LF_ENC,LL_INFO10000, "DC::DPOSS EnC short-circuit\n"));
TP_RESULT tpres =
dcpEnCOriginal->controller->TriggerPatch(dcpEnCOriginal,
thread,
TY_SHORT_CIRCUIT);
// We will only come back here on a RemapOppporunity that wasn't taken, or on a RemapComplete.
// If we processed a RemapComplete (which returns TPR_IGNORE_AND_STOP), then don't want to handle
// additional breakpoints on the current line because we've already effectively executed to that point
// and would have hit them already. If they are new, we also don't want to hit them because eg. if are
// sitting on line 10 and add a breakpoint at line 10 and step,
// don't expect to stop at line 10, expect to go to line 11.
//
// Special case is if an EnC remap breakpoint exists in the function. This could only happen if the function was
// updated between the RemapOpportunity and the RemapComplete. In that case we want to not skip the patches
// and fall through to handle the remap breakpoint.
if (tpres == TPR_IGNORE_AND_STOP)
{
// It was a RemapComplete, so fall through. Set dcpEnCOriginal to NULL to indicate that any
// EnC patch still there should be treated as a new patch. Any RemapComplete patch will have been
// already removed by patch processing.
dcpEnCOriginal = NULL;
LOG((LF_CORDB|LF_ENC,LL_INFO10000, "DC::DPOSS done EnC short-circuit, exiting\n"));
used = DPOSS_USED_WITH_EVENT; // indicate that we handled a patch
goto Exit;
}
_ASSERTE(tpres==TPR_IGNORE);
LOG((LF_CORDB|LF_ENC,LL_INFO10000, "DC::DPOSS done EnC short-circuit, ignoring\n"));
// if we got here, then the EnC remap opportunity was not taken, so just continue on.
}
#endif // EnC_SUPPORTED
TP_RESULT tpr;
used = ScanForTriggers((CORDB_ADDRESS_TYPE *)address, thread, context, &dcq, which, &tpr);
LOG((LF_CORDB|LF_ENC, LL_EVERYTHING, "DC::DPOSS ScanForTriggers called and returned.\n"));
// If we setip, then that will change the address in the context.
// Remeber the old address so that we can compare it to the context's ip and see if it changed.
// If it did change, then don't dispatch our current event.
originalAddress = (TADDR) address;
#ifdef _DEBUG
// If we do a SetIP after this point, the value of address will be garbage. Set it to a distictive pattern now, so
// we don't accidentally use what will (98% of the time) appear to be a valid value.
address = (CORDB_ADDRESS_TYPE *)(UINT_PTR)0xAABBCCFF;
#endif //_DEBUG
if (dcq.dcqGetCount()> 0)
{
lockController.Release();
// Mark if we're at an unsafe place.
bool atSafePlace = g_pDebugger->IsThreadAtSafePlace(thread);
if (!atSafePlace)
g_pDebugger->IncThreadsAtUnsafePlaces();
DWORD dwEvent = 0xFFFFFFFF;
DWORD dwNumberEvents = 0;
BOOL reabort = FALSE;
SENDIPCEVENT_BEGIN(g_pDebugger, thread);
// Now that we've resumed from blocking, check if somebody did a SetIp on us.
bool fIpChanged = (originalAddress != GetIP(context));
// Send the events outside of the controller lock
bool anyEventsSent = false;
dwNumberEvents = dcq.dcqGetCount();
dwEvent = 0;
while (dwEvent < dwNumberEvents)
{
DebuggerController *event = dcq.dcqGetElement(dwEvent);
if (!event->m_deleted)
{
#ifdef DEBUGGING_SUPPORTED
if (thread->GetDomain()->IsDebuggerAttached())
{
if (event->SendEvent(thread, fIpChanged))
{
anyEventsSent = true;
}
}
#endif //DEBUGGING_SUPPORTED
}
dwEvent++;
}
// Trap all threads if necessary, but only if we actually sent a event up (i.e., all the queued events weren't
// deleted before we got a chance to get the EventSending lock.)
if (anyEventsSent)
{
LOG((LF_CORDB|LF_ENC, LL_EVERYTHING, "DC::DPOSS We sent an event\n"));
g_pDebugger->SyncAllThreads(SENDIPCEVENT_PtrDbgLockHolder);
LOG((LF_CORDB,LL_INFO1000, "SAT called!\n"));
}
// If we need to to a re-abort (see below), then save the current IP in the thread's context before we block and
// possibly let another func eval get setup.
reabort = thread->m_StateNC & Thread::TSNC_DebuggerReAbort;
SENDIPCEVENT_END;
if (!atSafePlace)
g_pDebugger->DecThreadsAtUnsafePlaces();
lockController.Acquire();
// Dequeue the events while we have the controller lock.
dwEvent = 0;
while (dwEvent < dwNumberEvents)
{
dcq.dcqDequeue();
dwEvent++;
}
// If a func eval completed with a ThreadAbortException, go ahead and setup the thread to re-abort itself now
// that we're continuing the thread. Note: we make sure that the thread's IP hasn't changed between now and when
// we blocked above. While blocked above, the debugger has a chance to setup another func eval on this
// thread. If that happens, we don't want to setup the reabort just yet.
if (reabort)
{
if ((UINT_PTR)GetEEFuncEntryPoint(::FuncEvalHijack) != (UINT_PTR)GetIP(context))
{
HRESULT hr;
hr = g_pDebugger->FuncEvalSetupReAbort(thread, Thread::TAR_Thread);
_ASSERTE(SUCCEEDED(hr));
}
}
}
#if defined EnC_SUPPORTED
Exit:
#endif
// Note: if the thread filter context is NULL, then SetIP would have failed & thus we should do the
// patch skip thing.
// @todo - do we need to get the context again here?
CONTEXT *pCtx = GetManagedLiveCtx(thread);
#ifdef EnC_SUPPORTED
DebuggerControllerPatch *dcpEnCCurrent = GetEnCPatch(dac_cast<PTR_CBYTE>((GetIP(context))));
// we have a new patch if the original was null and the current is non-null. Otherwise we have an old
// patch. We want to skip old patches, but handle new patches.
if (dcpEnCOriginal == NULL && dcpEnCCurrent != NULL)
{
LOG((LF_CORDB|LF_ENC,LL_INFO10000, "DC::DPOSS EnC post-processing\n"));
dcpEnCCurrent->controller->TriggerPatch( dcpEnCCurrent,
thread,
TY_SHORT_CIRCUIT);
used = DPOSS_USED_WITH_EVENT; // indicate that we handled a patch
}
#endif
ActivatePatchSkip(thread, dac_cast<PTR_CBYTE>(GetIP(pCtx)), FALSE);
lockController.Release();
// We pulse the GC mode here too cooperate w/ a thread trying to suspend the runtime. If we didn't pulse
// the GC, the odds of catching this thread in interuptable code may be very small (since this filter
// could be very large compared to the managed code this thread is running).
// Only do this if the exception was actually for the debugger. (We don't want to toggle the GC mode on every
// random exception). We can't do this while holding any debugger locks.
if (used == DPOSS_USED_WITH_EVENT)
{
bool atSafePlace = g_pDebugger->IsThreadAtSafePlace(thread);
if (!atSafePlace)
{
g_pDebugger->IncThreadsAtUnsafePlaces();
}
// Always pulse the GC mode. This will allow an async break to complete even if we have a patch
// at an unsafe place.
// If we are at an unsafe place, then we can't do a GC.
thread->PulseGCMode();
if (!atSafePlace)
{
g_pDebugger->DecThreadsAtUnsafePlaces();
}
}
RETURN used;
}
bool DebuggerController::IsSingleStepEnabled()
{
LIMITED_METHOD_CONTRACT;
return m_singleStep;
}
void DebuggerController::EnableSingleStep()
{
CONTRACTL
{
SO_NOT_MAINLINE;
NOTHROW;
GC_NOTRIGGER;
}
CONTRACTL_END;
#ifdef _DEBUG
// Some controllers don't need to set the SS to do their job, and if they are setting it, it's likely an issue.
// So we assert here to catch them red-handed. This assert can always be updated to accomodate changes
// in a controller's behavior.
switch(GetDCType())
{
case DEBUGGER_CONTROLLER_THREAD_STARTER:
case DEBUGGER_CONTROLLER_BREAKPOINT:
case DEBUGGER_CONTROLLER_USER_BREAKPOINT:
case DEBUGGER_CONTROLLER_FUNC_EVAL_COMPLETE:
CONSISTENCY_CHECK_MSGF(false, ("Controller pThis=%p shouldn't be setting ss flag.", this));
break;
default: // MingW compilers require all enum cases to be handled in switch statement.
break;
}
#endif
EnableSingleStep(m_thread);
m_singleStep = true;
}
#ifdef EnC_SUPPORTED
// Note that this doesn't tell us if Single Stepping is currently enabled
// at the hardware level (ie, for x86, if (context->EFlags & 0x100), but
// rather, if we WANT single stepping enabled (pThread->m_State &Thread::TS_DebuggerIsStepping)
// This gets called from exactly one place - ActivatePatchSkipForEnC
BOOL DebuggerController::IsSingleStepEnabled(Thread *pThread)
{
CONTRACTL
{
SO_NOT_MAINLINE;
NOTHROW;
GC_NOTRIGGER;
}
CONTRACTL_END;
// This should be an atomic operation, do we
// don't need to lock it.
if(pThread->m_StateNC & Thread::TSNC_DebuggerIsStepping)
{
_ASSERTE(pThread->m_StateNC & Thread::TSNC_DebuggerIsStepping);
return TRUE;
}
else
return FALSE;
}
#endif //EnC_SUPPORTED
void DebuggerController::EnableSingleStep(Thread *pThread)
{
CONTRACTL
{
SO_NOT_MAINLINE;
NOTHROW;
GC_NOTRIGGER;
}
CONTRACTL_END;
LOG((LF_CORDB,LL_INFO1000, "DC::EnableSingleStep\n"));
_ASSERTE(pThread != NULL);
ControllerLockHolder lockController;
ApplyTraceFlag(pThread);
}
// Disable Single stepping for this controller.
// If none of the controllers on this thread want single-stepping, then also
// ensure that it's disabled on the hardware level.
void DebuggerController::DisableSingleStep()
{
CONTRACTL
{
SO_NOT_MAINLINE;
NOTHROW;
GC_NOTRIGGER;
}
CONTRACTL_END;
_ASSERTE(m_thread != NULL);
LOG((LF_CORDB,LL_INFO1000, "DC::DisableSingleStep\n"));
ControllerLockHolder lockController;
{
DebuggerController *p = g_controllers;
m_singleStep = false;
while (p != NULL)
{
if (p->m_thread == m_thread
&& p->m_singleStep)
break;
p = p->m_next;
}
if (p == NULL)
{
UnapplyTraceFlag(m_thread);
}
}
}
//
// ApplyTraceFlag sets the trace flag (i.e., turns on single-stepping)
// for a thread.
//
void DebuggerController::ApplyTraceFlag(Thread *thread)
{
LOG((LF_CORDB,LL_INFO1000, "DC::ApplyTraceFlag thread:0x%x [0x%0x]\n", thread, Debugger::GetThreadIdHelper(thread)));
CONTEXT *context;
if(thread->GetInteropDebuggingHijacked())
{
context = GetManagedLiveCtx(thread);
}
else
{
context = GetManagedStoppedCtx(thread);
}
CONSISTENCY_CHECK_MSGF(context != NULL, ("Can't apply ss flag to thread 0x%p b/c it's not in a safe place.\n", thread));
PREFIX_ASSUME(context != NULL);
g_pEEInterface->MarkThreadForDebugStepping(thread, true);
LOG((LF_CORDB,LL_INFO1000, "DC::ApplyTraceFlag marked thread for debug stepping\n"));
SetSSFlag(reinterpret_cast<DT_CONTEXT *>(context) ARM_ARG(thread));
LOG((LF_CORDB,LL_INFO1000, "DC::ApplyTraceFlag Leaving, baby!\n"));
}
//
// UnapplyTraceFlag sets the trace flag for a thread.
// Removes the hardware trace flag on this thread.
//
void DebuggerController::UnapplyTraceFlag(Thread *thread)
{
LOG((LF_CORDB,LL_INFO1000, "DC::UnapplyTraceFlag thread:0x%x\n", thread));
// Either this is the helper thread, or we're manipulating our own context.
_ASSERTE(
ThisIsHelperThreadWorker() ||
(thread == ::GetThread())
);
CONTEXT *context = GetManagedStoppedCtx(thread);
// If there's no context available, then the thread shouldn't have the single-step flag
// enabled and there's nothing for us to do.
if (context == NULL)
{
// In theory, I wouldn't expect us to ever get here.
// Even if we are here, our single-step flag should already be deactivated,
// so there should be nothing to do. However, we still assert b/c we want to know how
// we'd actually hit this.
// @todo - is there a path if TriggerUnwind() calls DisableAll(). But why would
CONSISTENCY_CHECK_MSGF(false, ("How did we get here?. thread=%p\n", thread));
LOG((LF_CORDB,LL_INFO1000, "DC::UnapplyTraceFlag couldn't get context.\n"));
return;
}
// Always need to unmark for stepping
g_pEEInterface->MarkThreadForDebugStepping(thread, false);
UnsetSSFlag(reinterpret_cast<DT_CONTEXT *>(context) ARM_ARG(thread));
}
void DebuggerController::EnableExceptionHook()
{
CONTRACTL
{
SO_NOT_MAINLINE;
NOTHROW;
GC_NOTRIGGER;
}
CONTRACTL_END;
_ASSERTE(m_thread != NULL);
ControllerLockHolder lockController;
m_exceptionHook = true;
}
void DebuggerController::DisableExceptionHook()
{
CONTRACTL
{
SO_NOT_MAINLINE;
NOTHROW;
GC_NOTRIGGER;
}
CONTRACTL_END;
_ASSERTE(m_thread != NULL);
ControllerLockHolder lockController;
m_exceptionHook = false;
}
// void DebuggerController::DispatchExceptionHook() Called before
// the switch statement in DispatchNativeException (therefore
// when any exception occurs), this allows patches to do something before the
// regular DispatchX methods.
// How: Iterate through list of controllers. If m_exceptionHook
// is set & m_thread is either thread or NULL, then invoke TriggerExceptionHook()
BOOL DebuggerController::DispatchExceptionHook(Thread *thread,
CONTEXT *context,
EXCEPTION_RECORD *pException)
{
// ExceptionHook has restrictive contract b/c it could come from anywhere.
// This can only modify controller's internal state. Can't send managed debug events.
CONTRACTL
{
SO_NOT_MAINLINE;
GC_NOTRIGGER;
NOTHROW;
MODE_ANY;
// Filter context not set yet b/c we can only set it in COOP, and this may be in preemptive.
PRECONDITION(thread == ::GetThread());
PRECONDITION((g_pEEInterface->GetThreadFilterContext(thread) == NULL));
PRECONDITION(CheckPointer(pException));
}
CONTRACTL_END;
LOG((LF_CORDB, LL_INFO1000, "DC:: DispatchExceptionHook\n"));
if (!g_patchTableValid)
{
LOG((LF_CORDB, LL_INFO1000, "DC::DEH returning, no patch table.\n"));
return (TRUE);
}
_ASSERTE(g_patches != NULL);
ControllerLockHolder lockController;
TP_RESULT tpr = TPR_IGNORE;
DebuggerController *p;
p = g_controllers;
while (p != NULL)
{
DebuggerController *pNext = p->m_next;
if (p->m_exceptionHook
&& (p->m_thread == NULL || p->m_thread == thread) &&
tpr != TPR_IGNORE_AND_STOP)
{
LOG((LF_CORDB, LL_INFO1000, "DC::DEH calling TEH...\n"));
tpr = p->TriggerExceptionHook(thread, context , pException);
LOG((LF_CORDB, LL_INFO1000, "DC::DEH ... returned.\n"));
if (tpr == TPR_IGNORE_AND_STOP)
{
LOG((LF_CORDB, LL_INFO1000, "DC:: DEH: leaving early!\n"));
break;
}
}
p = pNext;
}
LOG((LF_CORDB, LL_INFO1000, "DC:: DEH: returning 0x%x!\n", tpr));
return (tpr != TPR_IGNORE_AND_STOP);
}
//
// EnableUnwind enables an unwind event to be called when the stack is unwound
// (via an exception) to or past the given pointer.
//
void DebuggerController::EnableUnwind(FramePointer fp)
{
CONTRACTL
{
SO_NOT_MAINLINE;
NOTHROW;
GC_NOTRIGGER;
}
CONTRACTL_END;
ASSERT(m_thread != NULL);
LOG((LF_CORDB,LL_EVERYTHING,"DC:EU EnableUnwind at 0x%x\n", fp.GetSPValue()));
ControllerLockHolder lockController;
m_unwindFP = fp;
}
FramePointer DebuggerController::GetUnwind()
{
LIMITED_METHOD_CONTRACT;
return m_unwindFP;
}
//
// DisableUnwind disables the unwind event for the controller.
//
void DebuggerController::DisableUnwind()
{
CONTRACTL
{
NOTHROW;
GC_NOTRIGGER;
MODE_ANY;
CAN_TAKE_LOCK;
}
CONTRACTL_END;
ASSERT(m_thread != NULL);
LOG((LF_CORDB,LL_INFO1000, "DC::DU\n"));
ControllerLockHolder lockController;
m_unwindFP = LEAF_MOST_FRAME;
}
//
// DispatchUnwind is called when an unwind happens.
// the event to the appropriate controllers.
// - handlerFP is the frame pointer that the handler will be invoked at.
// - DJI is EnC-aware method that the handler is in.
// - newOffset is the
//
bool DebuggerController::DispatchUnwind(Thread *thread,
MethodDesc *fd, DebuggerJitInfo * pDJI,
SIZE_T newOffset,
FramePointer handlerFP,
CorDebugStepReason unwindReason)
{
CONTRACTL
{
SO_NOT_MAINLINE;
NOTHROW;
GC_NOTRIGGER; // don't send IPC events
MODE_COOPERATIVE; // TriggerUnwind always is coop
PRECONDITION(!IsDbgHelperSpecialThread());
}
CONTRACTL_END;
CONTRACT_VIOLATION(ThrowsViolation); // trigger unwind throws
_ASSERTE(unwindReason == STEP_EXCEPTION_FILTER || unwindReason == STEP_EXCEPTION_HANDLER);
bool used = false;
LOG((LF_CORDB, LL_INFO10000, "DC: Dispatch Unwind\n"));
ControllerLockHolder lockController;
{
DebuggerController *p;
p = g_controllers;
while (p != NULL)
{
DebuggerController *pNext = p->m_next;
if (p->m_thread == thread && p->m_unwindFP != LEAF_MOST_FRAME)
{
LOG((LF_CORDB, LL_INFO10000, "Dispatch Unwind: Found candidate\n"));
// Assumptions here:
// Function with handlers are -ALWAYS- EBP-frame based (JIT assumption)
//
// newFrame is the EBP for the handler
// p->m_unwindFP points to the stack slot with the return address of the function.
//
// For the interesting case: stepover, we want to know if the handler is in the same function
// as the stepper, if its above it (caller) o under it (callee) in order to know if we want
// to patch the handler or not.
//
// 3 cases:
//
// a) Handler is in a function under the function where the step happened. It therefore is
// a stepover. We don't want to patch this handler. The handler will have an EBP frame.
// So it will be at least be 2 DWORDs away from the m_unwindFP of the controller (
// 1 DWORD from the pushed return address and 1 DWORD for the push EBP).
//
// b) Handler is in the same function as the stepper. We want to patch the handler. In this
// case handlerFP will be the same as p->m_unwindFP-sizeof(void*). Why? p->m_unwindFP
// stores a pointer to the return address of the function. As a function with a handler
// is always EBP frame based it will have the following code in the prolog:
//
// push ebp <- ( sub esp, 4 ; mov [esp], ebp )
// mov esp, ebp
//
// Therefore EBP will be equal to &CallerReturnAddress-4.
//
// c) Handler is above the function where the stepper is. We want to patch the handler. handlerFP
// will be always greater than the pointer to the return address of the function where the
// stepper is.
//
//
//
if (IsEqualOrCloserToRoot(handlerFP, p->m_unwindFP))
{
used = true;
//
// Assume that this isn't going to block us at all --
// other threads may be waiting to patch or unpatch something,
// or to dispatch.
//
LOG((LF_CORDB, LL_INFO10000,
"Unwind trigger at offset 0x%p; handlerFP: 0x%p unwindReason: 0x%x.\n",
newOffset, handlerFP.GetSPValue(), unwindReason));
p->TriggerUnwind(thread,
fd, pDJI,
newOffset,
handlerFP,
unwindReason);
}
else
{
LOG((LF_CORDB, LL_INFO10000,
"Unwind trigger at offset 0x%p; handlerFP: 0x%p unwindReason: 0x%x.\n",
newOffset, handlerFP.GetSPValue(), unwindReason));
}
}
p = pNext;
}
}
return used;
}
//
// EnableTraceCall enables a call event on the controller
// maxFrame is the leaf-most frame that we want notifications for.
// For step-in stuff, this will always be LEAF_MOST_FRAME.
// for step-out, this will be the current frame because we don't
// care if the current frame calls back into managed code when we're
// only interested in our parent frames.
//
void DebuggerController::EnableTraceCall(FramePointer maxFrame)
{
CONTRACTL
{
SO_NOT_MAINLINE;
NOTHROW;
GC_NOTRIGGER;
}
CONTRACTL_END;
ASSERT(m_thread != NULL);
LOG((LF_CORDB,LL_INFO1000, "DC::ETC maxFrame=0x%x, thread=0x%x\n",
maxFrame.GetSPValue(), Debugger::GetThreadIdHelper(m_thread)));
// JMC stepper should never enabled this. (They should enable ME instead).
_ASSERTE((DEBUGGER_CONTROLLER_JMC_STEPPER != this->GetDCType()) || !"JMC stepper shouldn't enable trace-call");
ControllerLockHolder lockController;
{
if (!m_traceCall)
{
m_traceCall = true;
g_pEEInterface->EnableTraceCall(m_thread);
}
if (IsCloserToLeaf(maxFrame, m_traceCallFP))
m_traceCallFP = maxFrame;
}
}
struct PatchTargetVisitorData
{
DebuggerController* controller;
FramePointer maxFrame;
};
VOID DebuggerController::PatchTargetVisitor(TADDR pVirtualTraceCallTarget, VOID* pUserData)
{
CONTRACTL
{
SO_NOT_MAINLINE;
NOTHROW;
GC_NOTRIGGER;
}
CONTRACTL_END;
DebuggerController* controller = ((PatchTargetVisitorData*) pUserData)->controller;
FramePointer maxFrame = ((PatchTargetVisitorData*) pUserData)->maxFrame;
EX_TRY
{
CONTRACT_VIOLATION(GCViolation); // PatchTrace throws, which implies GC-triggers
TraceDestination trace;
trace.InitForUnmanagedStub(pVirtualTraceCallTarget);
controller->PatchTrace(&trace, maxFrame, true);
}
EX_CATCH
{
// not much we can do here
}
EX_END_CATCH(SwallowAllExceptions)
}
//
// DisableTraceCall disables call events on the controller
//
void DebuggerController::DisableTraceCall()
{
CONTRACTL
{
SO_NOT_MAINLINE;
NOTHROW;
GC_NOTRIGGER;
}
CONTRACTL_END;
ASSERT(m_thread != NULL);
ControllerLockHolder lockController;
{
if (m_traceCall)
{
LOG((LF_CORDB,LL_INFO1000, "DC::DTC thread=0x%x\n",
Debugger::GetThreadIdHelper(m_thread)));
g_pEEInterface->DisableTraceCall(m_thread);
m_traceCall = false;
m_traceCallFP = ROOT_MOST_FRAME;
}
}
}
// Get a FramePointer for the leafmost frame on this thread's stacktrace.
// It's tempting to create this off the head of the Frame chain, but that may
// include internal EE Frames (like GCRoot frames) which a FrameInfo-stackwalk may skip over.
// Thus using the Frame chain would err on the side of returning a FramePointer that
// closer to the leaf.
FramePointer GetCurrentFramePointerFromStackTraceForTraceCall(Thread * thread)
{
_ASSERTE(thread != NULL);
// Ensure this is really the same as CSI.
ControllerStackInfo info;
// It's possible this stackwalk may be done at an unsafe time.
// this method may trigger a GC, for example, in
// FramedMethodFrame::AskStubForUnmanagedCallSite
// which will trash the incoming argument array
// which is not gc-protected.
// We could probably imagine a more specialized stackwalk that
// avoids these calls and is thus GC_NOTRIGGER.
CONTRACT_VIOLATION(GCViolation);
// This is being run live, so there's no filter available.
CONTEXT *context;
context = g_pEEInterface->GetThreadFilterContext(thread);
_ASSERTE(context == NULL);
_ASSERTE(!ISREDIRECTEDTHREAD(thread));
// This is actually safe because we're coming from a TraceCall, which
// means we're not in the middle of a stub. We don't have some partially
// constructed frame, so we can safely traverse the stack.
// However, we may still have a problem w/ the GC-violation.
StackTraceTicket ticket(StackTraceTicket::SPECIAL_CASE_TICKET);
info.GetStackInfo(ticket, thread, LEAF_MOST_FRAME, NULL);
FramePointer fp = info.m_activeFrame.fp;
return fp;
}
//
// DispatchTraceCall is called when a call is traced in the EE
// It dispatches the event to the appropriate controllers.
//
bool DebuggerController::DispatchTraceCall(Thread *thread,
const BYTE *ip)
{
CONTRACTL
{
GC_NOTRIGGER;
THROWS;
}
CONTRACTL_END;
bool used = false;
LOG((LF_CORDB, LL_INFO10000,
"DC::DTC: TraceCall at 0x%x\n", ip));
ControllerLockHolder lockController;
{
DebuggerController *p;
p = g_controllers;
while (p != NULL)
{
DebuggerController *pNext = p->m_next;
if (p->m_thread == thread && p->m_traceCall)
{
bool trigger;
if (p->m_traceCallFP == LEAF_MOST_FRAME)
trigger = true;
else
{
// We know we don't have a filter context, so get a frame pointer from our frame chain.
FramePointer fpToCheck = GetCurrentFramePointerFromStackTraceForTraceCall(thread);
// <REVISIT_TODO>
//
// Currently, we never ever put a patch in an IL stub, and as such, if the IL stub
// throws an exception after returning from unmanaged code, we would not trigger
// a trace call when we call the constructor of the exception. The following is
// kind of a workaround to make that working. If we ever make the change to stop in
// IL stubs (for example, if we start to share security IL stub), then this can be
// removed.
//
// </REVISIT_TODO>
// It's possible this stackwalk may be done at an unsafe time.
// this method may trigger a GC, for example, in
// FramedMethodFrame::AskStubForUnmanagedCallSite
// which will trash the incoming argument array
// which is not gc-protected.
ControllerStackInfo info;
{
CONTRACT_VIOLATION(GCViolation);
#ifdef _DEBUG
CONTEXT *context = g_pEEInterface->GetThreadFilterContext(thread);
#endif // _DEBUG
_ASSERTE(context == NULL);
_ASSERTE(!ISREDIRECTEDTHREAD(thread));
// See explanation in GetCurrentFramePointerFromStackTraceForTraceCall.
StackTraceTicket ticket(StackTraceTicket::SPECIAL_CASE_TICKET);
info.GetStackInfo(ticket, thread, LEAF_MOST_FRAME, NULL);
}
if (info.m_activeFrame.chainReason == CHAIN_ENTER_UNMANAGED)
{
_ASSERTE(info.HasReturnFrame());
// This check makes sure that we don't do this logic for inlined frames.
if (info.m_returnFrame.md->IsILStub())
{
// Make sure that the frame pointer of the active frame is actually
// the address of an exit frame.
_ASSERTE( (static_cast<Frame*>(info.m_activeFrame.fp.GetSPValue()))->GetFrameType()
== Frame::TYPE_EXIT );
_ASSERTE(!info.m_returnFrame.HasChainMarker());
fpToCheck = info.m_returnFrame.fp;
}
}
// @todo - This comparison seems somewhat nonsensical. We don't have a filter context
// in place, so what frame pointer is fpToCheck actually for?
trigger = IsEqualOrCloserToRoot(fpToCheck, p->m_traceCallFP);
}
if (trigger)
{
used = true;
// This can only update controller's state, can't actually send IPC events.
p->TriggerTraceCall(thread, ip);
}
}
p = pNext;
}
}
return used;
}
bool DebuggerController::IsMethodEnterEnabled()
{
LIMITED_METHOD_CONTRACT;
return m_fEnableMethodEnter;
}
// Notify dispatching logic that this controller wants to get TriggerMethodEnter
// We keep a count of total controllers waiting for MethodEnter (in g_cTotalMethodEnter).
// That way we know if any controllers want MethodEnter callbacks. If none do,
// then we can set the JMC probe flag to false for all modules.
void DebuggerController::EnableMethodEnter()
{
CONTRACTL
{
SO_NOT_MAINLINE;
NOTHROW;
GC_NOTRIGGER;
}
CONTRACTL_END;
ControllerLockHolder chController;
Debugger::DebuggerDataLockHolder chInfo(g_pDebugger);
// Both JMC + Traditional steppers may use MethodEnter.
// For JMC, it's a core part of functionality. For Traditional steppers, we use it as a backstop
// in case the stub-managers fail.
_ASSERTE(g_cTotalMethodEnter >= 0);
if (!m_fEnableMethodEnter)
{
LOG((LF_CORDB, LL_INFO1000000, "DC::EnableME, this=%p, previously disabled\n", this));
m_fEnableMethodEnter = true;
g_cTotalMethodEnter++;
}
else
{
LOG((LF_CORDB, LL_INFO1000000, "DC::EnableME, this=%p, already set\n", this));
}
g_pDebugger->UpdateAllModuleJMCFlag(g_cTotalMethodEnter != 0); // Needs JitInfo lock
}
// Notify dispatching logic that this controller doesn't want to get
// TriggerMethodEnter
void DebuggerController::DisableMethodEnter()
{
CONTRACTL
{
SO_NOT_MAINLINE;
NOTHROW;
GC_NOTRIGGER;
}
CONTRACTL_END;
ControllerLockHolder chController;
Debugger::DebuggerDataLockHolder chInfo(g_pDebugger);
if (m_fEnableMethodEnter)
{
LOG((LF_CORDB, LL_INFO1000000, "DC::DisableME, this=%p, previously set\n", this));
m_fEnableMethodEnter = false;
g_cTotalMethodEnter--;
_ASSERTE(g_cTotalMethodEnter >= 0);
}
else
{
LOG((LF_CORDB, LL_INFO1000000, "DC::DisableME, this=%p, already disabled\n", this));
}
g_pDebugger->UpdateAllModuleJMCFlag(g_cTotalMethodEnter != 0); // Needs JitInfo lock
}
// Loop through controllers and dispatch TriggerMethodEnter
void DebuggerController::DispatchMethodEnter(void * pIP, FramePointer fp)
{
_ASSERTE(pIP != NULL);
Thread * pThread = g_pEEInterface->GetThread();
_ASSERTE(pThread != NULL);
// Lookup the DJI for this method & ip.
// Since we create DJIs when we jit the code, and this code has been jitted
// (that's where the probe's coming from!), we will have a DJI.
DebuggerJitInfo * dji = g_pDebugger->GetJitInfoFromAddr((TADDR) pIP);
// This includes the case where we have a LightWeight codegen method.
if (dji == NULL)
{
return;
}
LOG((LF_CORDB, LL_INFO100000, "DC::DispatchMethodEnter for '%s::%s'\n",
dji->m_fd->m_pszDebugClassName,
dji->m_fd->m_pszDebugMethodName));
ControllerLockHolder lockController;
// For debug check, keep a count to make sure that g_cTotalMethodEnter
// is actually the number of controllers w/ MethodEnter enabled.
int count = 0;
DebuggerController *p = g_controllers;
while (p != NULL)
{
if (p->m_fEnableMethodEnter)
{
if ((p->GetThread() == NULL) || (p->GetThread() == pThread))
{
++count;
p->TriggerMethodEnter(pThread, dji, (const BYTE *) pIP, fp);
}
}
p = p->m_next;
}
_ASSERTE(g_cTotalMethodEnter == count);
}
//
// AddProtection adds page protection to (at least) the given range of
// addresses
//
void DebuggerController::AddProtection(const BYTE *start, const BYTE *end,
bool readable)
{
// !!!
_ASSERTE(!"Not implemented yet");
}
//
// RemoveProtection removes page protection from the given
// addresses. The parameters should match an earlier call to
// AddProtection
//
void DebuggerController::RemoveProtection(const BYTE *start, const BYTE *end,
bool readable)
{
// !!!
_ASSERTE(!"Not implemented yet");
}
// Default implementations for FuncEvalEnter & Exit notifications.
void DebuggerController::TriggerFuncEvalEnter(Thread * thread)
{
LOG((LF_CORDB, LL_INFO100000, "DC::TFEEnter, thead=%p, this=%p\n", thread, this));
}
void DebuggerController::TriggerFuncEvalExit(Thread * thread)
{
LOG((LF_CORDB, LL_INFO100000, "DC::TFEExit, thead=%p, this=%p\n", thread, this));
}
// bool DebuggerController::TriggerPatch() What: Tells the
// static DC whether this patch should be activated now.
// Returns true if it should be, false otherwise.
// How: Base class implementation returns false. Others may
// return true.
TP_RESULT DebuggerController::TriggerPatch(DebuggerControllerPatch *patch,
Thread *thread,
TRIGGER_WHY tyWhy)
{
LOG((LF_CORDB, LL_INFO10000, "DC::TP: in default TriggerPatch\n"));
return TPR_IGNORE;
}
bool DebuggerController::TriggerSingleStep(Thread *thread,
const BYTE *ip)
{
LOG((LF_CORDB, LL_INFO10000, "DC::TP: in default TriggerSingleStep\n"));
return false;
}
void DebuggerController::TriggerUnwind(Thread *thread,
MethodDesc *fd, DebuggerJitInfo * pDJI, SIZE_T offset,
FramePointer fp,
CorDebugStepReason unwindReason)
{
LOG((LF_CORDB, LL_INFO10000, "DC::TP: in default TriggerUnwind\n"));
}
void DebuggerController::TriggerTraceCall(Thread *thread,
const BYTE *ip)
{
LOG((LF_CORDB, LL_INFO10000, "DC::TP: in default TriggerTraceCall\n"));
}
TP_RESULT DebuggerController::TriggerExceptionHook(Thread *thread, CONTEXT * pContext,
EXCEPTION_RECORD *exception)
{
LOG((LF_CORDB, LL_INFO10000, "DC::TP: in default TriggerExceptionHook\n"));
return TPR_IGNORE;
}
void DebuggerController::TriggerMethodEnter(Thread * thread,
DebuggerJitInfo * dji,
const BYTE * ip,
FramePointer fp)
{
LOG((LF_CORDB, LL_INFO10000, "DC::TME in default impl. dji=%p, addr=%p, fp=%p\n",
dji, ip, fp.GetSPValue()));
}
bool DebuggerController::SendEvent(Thread *thread, bool fIpChanged)
{
CONTRACTL
{
SO_NOT_MAINLINE;
NOTHROW;
SENDEVENT_CONTRACT_ITEMS;
}
CONTRACTL_END;
LOG((LF_CORDB, LL_INFO10000, "DC::TP: in default SendEvent\n"));
// If any derived class trigger SendEvent, it should also implement SendEvent.
_ASSERTE(false || !"Base DebuggerController sending an event?");
return false;
}
// Dispacth Func-Eval Enter & Exit notifications.
void DebuggerController::DispatchFuncEvalEnter(Thread * thread)
{
LOG((LF_CORDB, LL_INFO100000, "DC::DispatchFuncEvalEnter for thread 0x%p\n", thread));
ControllerLockHolder lockController;
DebuggerController *p = g_controllers;
while (p != NULL)
{
if ((p->GetThread() == NULL) || (p->GetThread() == thread))
{
p->TriggerFuncEvalEnter(thread);
}
p = p->m_next;
}
}
void DebuggerController::DispatchFuncEvalExit(Thread * thread)
{
LOG((LF_CORDB, LL_INFO100000, "DC::DispatchFuncEvalExit for thread 0x%p\n", thread));
ControllerLockHolder lockController;
DebuggerController *p = g_controllers;
while (p != NULL)
{
if ((p->GetThread() == NULL) || (p->GetThread() == thread))
{
p->TriggerFuncEvalExit(thread);
}
p = p->m_next;
}
}
#ifdef _DEBUG
// See comment in DispatchNativeException
void ThisFunctionMayHaveTriggerAGC()
{
CONTRACTL
{
SO_NOT_MAINLINE;
GC_TRIGGERS;
NOTHROW;
}
CONTRACTL_END;
}
#endif
// bool DebuggerController::DispatchNativeException() Figures out
// if any debugger controllers will handle the exception.
// DispatchNativeException should be called by the EE when a native exception
// occurs. If it returns true, the exception was generated by a Controller and
// should be ignored.
// How: Calls DispatchExceptionHook to see if anything is
// interested in ExceptionHook, then does a switch on dwCode:
// EXCEPTION_BREAKPOINT means invoke DispatchPatchOrSingleStep(ST_PATCH).
// EXCEPTION_SINGLE_STEP means DispatchPatchOrSingleStep(ST_SINGLE_STEP).
// EXCEPTION_ACCESS_VIOLATION means invoke DispatchAccessViolation.
// Returns true if the exception was actually meant for the debugger,
// returns false otherwise.
bool DebuggerController::DispatchNativeException(EXCEPTION_RECORD *pException,
CONTEXT *pContext,
DWORD dwCode,
Thread *pCurThread)
{
CONTRACTL
{
SO_INTOLERANT;
NOTHROW;
// If this exception is for the debugger, then we may trigger a GC.
// But we'll be called on _any_ exception, including ones in a GC-no-triggers region.
// Our current contract system doesn't let us specify such conditions on GC_TRIGGERS.
// So we disable it now, and if we find out the exception is meant for the debugger,
// we'll call ThisFunctionMayHaveTriggerAGC() to ping that we're really a GC_TRIGGERS.
DISABLED(GC_TRIGGERS); // Only GC triggers if we send an event,
PRECONDITION(!IsDbgHelperSpecialThread());
// If we're called from preemptive mode, than our caller has protected the stack.
// If we're in cooperative mode, then we need to protect the stack before toggling GC modes
// (by setting the filter-context)
MODE_ANY;
PRECONDITION(CheckPointer(pException));
PRECONDITION(CheckPointer(pContext));
PRECONDITION(CheckPointer(pCurThread));
}
CONTRACTL_END;
LOG((LF_CORDB, LL_EVERYTHING, "DispatchNativeException was called\n"));
LOG((LF_CORDB, LL_INFO10000, "Native exception at 0x%p, code=0x%8x, context=0x%p, er=0x%p\n",
pException->ExceptionAddress, dwCode, pContext, pException));
bool fDebuggers;
BOOL fDispatch;
DPOSS_ACTION result = DPOSS_DONT_CARE;
// We have a potentially ugly locking problem here. This notification is called on any exception,
// but we have no idea what our locking context is at the time. Thus we may hold locks smaller
// than the controller lock.
// The debugger logic really only cares about exceptions directly in managed code (eg, hardware exceptions)
// or in patch-skippers (since that's a copy of managed code running in a look-aside buffer).
// That should exclude all C++ exceptions, which are the common case if Runtime code throws an internal ex.
// So we ignore those to avoid the lock violation.
if (pException->ExceptionCode == EXCEPTION_MSVC)
{
LOG((LF_CORDB, LL_INFO1000, "Debugger skipping for C++ exception.\n"));
return FALSE;
}
// The debugger really only cares about exceptions in managed code. Any exception that occurs
// while the thread is redirected (such as EXCEPTION_HIJACK) is not of interest to the debugger.
// Allowing this would be problematic because when an exception occurs while the thread is
// redirected, we don't know which context (saved redirection context or filter context)
// we should be operating on (see code:GetManagedStoppedCtx).
if( ISREDIRECTEDTHREAD(pCurThread) )
{
LOG((LF_CORDB, LL_INFO1000, "Debugger ignoring exception 0x%x on redirected thread.\n", dwCode));
// We shouldn't be seeing debugging exceptions on a redirected thread. While a thread is
// redirected we only call a few internal things (see code:Thread.RedirectedHandledJITCase),
// and may call into the host. We can't call normal managed code or anything we'd want to debug.
_ASSERTE(dwCode != EXCEPTION_BREAKPOINT);
_ASSERTE(dwCode != EXCEPTION_SINGLE_STEP);
return FALSE;
}
// It's possible we're here without a debugger (since we have to call the
// patch skippers). The Debugger may detach anytime,
// so remember the attach state now.
#ifdef _DEBUG
bool fWasAttached = false;
#ifdef DEBUGGING_SUPPORTED
fWasAttached = (CORDebuggerAttached() != 0);
#endif //DEBUGGING_SUPPORTED
#endif //_DEBUG
{
// If we're in cooperative mode, it's unsafe to do a GC until we've put a filter context in place.
GCX_NOTRIGGER();
// If we know the debugger doesn't care about this exception, bail now.
// Usually this is just if there's a debugger attached.
// However, if a debugger detached but left outstanding controllers (like patch-skippers),
// we still may care.
// The only way a controller would get created outside of the helper thread is from
// a patch skipper, so we always handle breakpoints.
if (!CORDebuggerAttached() && (g_controllers == NULL) && (dwCode != EXCEPTION_BREAKPOINT))
{
return false;
}
FireEtwDebugExceptionProcessingStart();
// We should never be here if the debugger was never involved.
CONTEXT * pOldContext;
pOldContext = pCurThread->GetFilterContext();
// In most cases it is an error to nest, however in the patch-skipping logic we must
// copy an unknown amount of code into another buffer and it occasionally triggers
// an AV. This heuristic should filter that case out. See DDB 198093.
// Ensure we perform this exception nesting filtering even before the call to
// DebuggerController::DispatchExceptionHook, otherwise the nesting will continue when
// a contract check is triggered in DispatchExceptionHook and another BP exception is
// raised. See Dev11 66058.
if ((pOldContext != NULL) && pCurThread->AVInRuntimeImplOkay() &&
pException->ExceptionCode == STATUS_ACCESS_VIOLATION)
{
STRESS_LOG1(LF_CORDB, LL_INFO100, "DC::DNE Nested Access Violation at 0x%p is being ignored\n",
pException->ExceptionAddress);
return false;
}
// Otherwise it is an error to nest at all
_ASSERTE(pOldContext == NULL);
fDispatch = DebuggerController::DispatchExceptionHook(pCurThread,
pContext,
pException);
{
// Must be in cooperative mode to set the filter context. We know there are times we'll be in preemptive mode,
// (such as M2U handoff, or potentially patches in the middle of a stub, or various random exceptions)
// @todo - We need to worry about GC-protecting our stack. If we're in preemptive mode, the caller did it for us.
// If we're in cooperative, then we need to set the FilterContext *before* we toggle GC mode (since
// the FC protects the stack).
// If we're in preemptive, then we need to set the FilterContext *after* we toggle ourselves to Cooperative.
// Also note it may not be possible to toggle GC mode at these times (such as in the middle of the stub).
//
// Part of the problem is that the Filter Context is serving 2 purposes here:
// - GC protect the stack. (essential if we're in coop mode).
// - provide info to controllers (such as current IP, and a place to set the Single-Step flag).
//
// This contract violation is mitigated in that we must have had the debugger involved to get to this point.
CONTRACT_VIOLATION(ModeViolation);
g_pEEInterface->SetThreadFilterContext(pCurThread, pContext);
}
// Now that we've set the filter context, we can let the GCX_NOTRIGGER expire.
// It's still possible that we may be called from a No-trigger region.
}
if (fDispatch)
{
// Disable SingleStep for all controllers on this thread. This requires the filter context set.
// This is what would disable the ss-flag when single-stepping over an AV.
if (g_patchTableValid && (dwCode != EXCEPTION_SINGLE_STEP))
{
LOG((LF_CORDB, LL_INFO1000, "DC::DNE non-single-step exception; check if any controller has ss turned on\n"));
ControllerLockHolder lockController;
for (DebuggerController* p = g_controllers; p != NULL; p = p->m_next)
{
if (p->m_singleStep && (p->m_thread == pCurThread))
{
LOG((LF_CORDB, LL_INFO1000, "DC::DNE turn off ss for controller 0x%p\n", p));
p->DisableSingleStep();
}
}
// implicit controller lock release
}
CORDB_ADDRESS_TYPE * ip = dac_cast<PTR_CORDB_ADDRESS_TYPE>(GetIP(pContext));
switch (dwCode)
{
case EXCEPTION_BREAKPOINT:
// EIP should be properly set up at this point.
result = DebuggerController::DispatchPatchOrSingleStep(pCurThread,
pContext,
ip,
ST_PATCH);
LOG((LF_CORDB, LL_EVERYTHING, "DC::DNE DispatchPatch call returned\n"));
// If we detached, we should remove all our breakpoints. So if we try
// to handle this breakpoint, make sure that we're attached.
if (IsInUsedAction(result) == true)
{
_ASSERTE(fWasAttached);
}
break;
case EXCEPTION_SINGLE_STEP:
LOG((LF_CORDB, LL_EVERYTHING, "DC::DNE SINGLE_STEP Exception\n"));
result = DebuggerController::DispatchPatchOrSingleStep(pCurThread,
pContext,
ip,
(SCAN_TRIGGER)(ST_PATCH|ST_SINGLE_STEP));
// We pass patch | single step since single steps actually
// do both (eg, you SS onto a breakpoint).
break;
default:
break;
} // end switch
}
#ifdef _DEBUG
else
{
LOG((LF_CORDB, LL_INFO1000, "DC:: DNE step-around fDispatch:0x%x!\n", fDispatch));
}
#endif //_DEBUG
fDebuggers = (fDispatch?(IsInUsedAction(result)?true:false):true);
LOG((LF_CORDB, LL_INFO10000, "DC::DNE, returning 0x%x.\n", fDebuggers));
#ifdef _DEBUG
if (fDebuggers && (result == DPOSS_USED_WITH_EVENT))
{
// If the exception belongs to the debugger, then we may have sent an event,
// and thus we may have triggered a GC.
ThisFunctionMayHaveTriggerAGC();
}
#endif
// Must restore the filter context. After the filter context is gone, we're
// unprotected again and unsafe for a GC.
{
CONTRACT_VIOLATION(ModeViolation);
g_pEEInterface->SetThreadFilterContext(pCurThread, NULL);
}
#ifdef _TARGET_ARM_
if (pCurThread->IsSingleStepEnabled())
pCurThread->ApplySingleStep(pContext);
#endif
FireEtwDebugExceptionProcessingEnd();
return fDebuggers;
}
// * -------------------------------------------------------------------------
// * DebuggerPatchSkip routines
// * -------------------------------------------------------------------------
DebuggerPatchSkip::DebuggerPatchSkip(Thread *thread,
DebuggerControllerPatch *patch,
AppDomain *pAppDomain)
: DebuggerController(thread, pAppDomain),
m_address(patch->address)
{
LOG((LF_CORDB, LL_INFO10000,
"DPS::DPS: Patch skip 0x%p\n", patch->address));
// On ARM the single-step emulation already utilizes a per-thread execution buffer similar to the scheme
// below. As a result we can skip most of the instruction parsing logic that's instead internalized into
// the single-step emulation itself.
#ifndef _TARGET_ARM_
// NOTE: in order to correctly single-step RIP-relative writes on multiple threads we need to set up
// a shared buffer with the instruction and a buffer for the RIP-relative value so that all threads
// are working on the same copy. as the single-steps complete the modified data in the buffer is
// copied back to the real address to ensure proper execution of the program.
//
// Create the shared instruction block. this will also create the shared RIP-relative buffer
//
m_pSharedPatchBypassBuffer = patch->GetOrCreateSharedPatchBypassBuffer();
BYTE* patchBypass = m_pSharedPatchBypassBuffer->PatchBypass;
// Copy the instruction block over to the patch skip
// WARNING: there used to be an issue here because CopyInstructionBlock copied the breakpoint from the
// jitted code stream into the patch buffer. Further below CORDbgSetInstruction would correct the
// first instruction. This buffer is shared by all threads so if another thread executed the buffer
// between this thread's execution of CopyInstructionBlock and CORDbgSetInstruction the wrong
// code would be executed. The bug has been fixed by changing CopyInstructionBlock to only copy
// the code bytes after the breakpoint.
// You might be tempted to stop copying the code at all, however that wouldn't work well with rejit.
// If we skip a breakpoint that is sitting at the beginning of a method, then the profiler rejits that
// method causing a jump-stamp to be placed, then we skip the breakpoint again, we need to make sure
// the 2nd skip executes the new jump-stamp code and not the original method prologue code. Copying
// the code every time ensures that we have the most up-to-date version of the code in the buffer.
_ASSERTE( patch->IsBound() );
CopyInstructionBlock(patchBypass, (const BYTE *)patch->address);
// Technically, we could create a patch skipper for an inactive patch, but we rely on the opcode being
// set here.
_ASSERTE( patch->IsActivated() );
CORDbgSetInstruction((CORDB_ADDRESS_TYPE *)patchBypass, patch->opcode);
LOG((LF_CORDB, LL_EVERYTHING, "SetInstruction was called\n"));
//
// Look at instruction to get some attributes
//
NativeWalker::DecodeInstructionForPatchSkip(patchBypass, &(m_instrAttrib));
#if defined(_TARGET_AMD64_)
// The code below handles RIP-relative addressing on AMD64. the original implementation made the assumption that
// we are only using RIP-relative addressing to access read-only data (see VSW 246145 for more information). this
// has since been expanded to handle RIP-relative writes as well.
if (m_instrAttrib.m_dwOffsetToDisp != 0)
{
_ASSERTE(m_instrAttrib.m_cbInstr != 0);
//
// Populate the RIP-relative buffer with the current value if needed
//
BYTE* bufferBypass = m_pSharedPatchBypassBuffer->BypassBuffer;
// Overwrite the *signed* displacement.
int dwOldDisp = *(int*)(&patchBypass[m_instrAttrib.m_dwOffsetToDisp]);
int dwNewDisp = offsetof(SharedPatchBypassBuffer, BypassBuffer) -
(offsetof(SharedPatchBypassBuffer, PatchBypass) + m_instrAttrib.m_cbInstr);
*(int*)(&patchBypass[m_instrAttrib.m_dwOffsetToDisp]) = dwNewDisp;
// This could be an LEA, which we'll just have to change into a MOV
// and copy the original address
if (((patchBypass[0] == 0x4C) || (patchBypass[0] == 0x48)) && (patchBypass[1] == 0x8d))
{
patchBypass[1] = 0x8b; // MOV reg, mem
_ASSERTE((int)sizeof(void*) <= SharedPatchBypassBuffer::cbBufferBypass);
*(void**)bufferBypass = (void*)(patch->address + m_instrAttrib.m_cbInstr + dwOldDisp);
}
else
{
// Copy the data into our buffer.
memcpy(bufferBypass, patch->address + m_instrAttrib.m_cbInstr + dwOldDisp, SharedPatchBypassBuffer::cbBufferBypass);
if (m_instrAttrib.m_fIsWrite)
{
// save the actual destination address and size so when we TriggerSingleStep() we can update the value
m_pSharedPatchBypassBuffer->RipTargetFixup = (UINT_PTR)(patch->address + m_instrAttrib.m_cbInstr + dwOldDisp);
m_pSharedPatchBypassBuffer->RipTargetFixupSize = m_instrAttrib.m_cOperandSize;
}
}
}
#endif // _TARGET_AMD64_
#endif // !_TARGET_ARM_
// Signals our thread that the debugger will be manipulating the context
// during the patch skip operation. This effectively prevents other threads
// from suspending us until we have completed skiping the patch and restored
// a good context (See DDB 188816)
thread->BeginDebuggerPatchSkip(this);
//
// Set IP of context to point to patch bypass buffer
//
T_CONTEXT *context = g_pEEInterface->GetThreadFilterContext(thread);
_ASSERTE(!ISREDIRECTEDTHREAD(thread));
CONTEXT c;
if (context == NULL)
{
// We can't play with our own context!
#if _DEBUG
if (g_pEEInterface->GetThread())
{
// current thread is mamaged thread
_ASSERTE(Debugger::GetThreadIdHelper(thread) != Debugger::GetThreadIdHelper(g_pEEInterface->GetThread()));
}
#endif // _DEBUG
c.ContextFlags = CONTEXT_CONTROL;
thread->GetThreadContext(&c);
context =(T_CONTEXT *) &c;
ARM_ONLY(_ASSERTE(!"We should always have a filter context in DebuggerPatchSkip."));
}
#ifdef _TARGET_ARM_
// Since we emulate all single-stepping on ARM using an instruction buffer and a breakpoint all we have to
// do here is initiate a normal single-step except that we pass the instruction to be stepped explicitly
// (calling EnableSingleStep() would infer this by looking at the PC in the context, which would pick up
// the patch we're trying to skip).
//
// Ideally we'd refactor the EnableSingleStep to support this alternative calling sequence but since this
// involves three levels of methods and is only applicable to ARM we've chosen to replicate the relevant
// implementation here instead.
{
ControllerLockHolder lockController;
g_pEEInterface->MarkThreadForDebugStepping(thread, true);
WORD opcode2 = 0;
if (Is32BitInstruction(patch->opcode))
{
opcode2 = CORDbgGetInstruction((CORDB_ADDRESS_TYPE *)(((DWORD)patch->address) + 2));
}
thread->BypassWithSingleStep((DWORD)patch->address, patch->opcode, opcode2);
m_singleStep = true;
}
#else // _TARGET_ARM_
#ifdef _TARGET_ARM64_
patchBypass = NativeWalker::SetupOrSimulateInstructionForPatchSkip(context, m_pSharedPatchBypassBuffer, (const BYTE *)patch->address, patch->opcode);
#endif //_TARGET_ARM64_
//set eip to point to buffer...
SetIP(context, (PCODE)patchBypass);
if (context ==(T_CONTEXT*) &c)
thread->SetThreadContext(&c);
LOG((LF_CORDB, LL_INFO10000, "DPS::DPS Bypass at 0x%p for opcode %p \n", patchBypass, patch->opcode));
//
// Turn on single step (if the platform supports it) so we can
// fix up state after the instruction is executed.
// Also turn on exception hook so we can adjust IP in exceptions
//
EnableSingleStep();
#endif // _TARGET_ARM_
EnableExceptionHook();
}
DebuggerPatchSkip::~DebuggerPatchSkip()
{
#ifndef _TARGET_ARM_
_ASSERTE(m_pSharedPatchBypassBuffer);
m_pSharedPatchBypassBuffer->Release();
#endif
}
void DebuggerPatchSkip::DebuggerDetachClean()
{
// Since for ARM SharedPatchBypassBuffer isn't existed, we don't have to anything here.
#ifndef _TARGET_ARM_
// Fix for Bug 1176448
// When a debugger is detaching from the debuggee, we need to move the IP if it is pointing
// somewhere in PatchBypassBuffer.All managed threads are suspended during detach, so changing
// the context without notifications is safe.
// Notice:
// THIS FIX IS INCOMPLETE!It attempts to update the IP in the cases we can easily detect.However,
// if a thread is in pre - emptive mode, and its filter context has been propagated to a VEH
// context, then the filter context we get will be NULL and this fix will not work.Our belief is
// that this scenario is rare enough that it doesnt justify the cost and risk associated with a
// complete fix, in which we would have to either :
// 1. Change the reference counting for DebuggerController and then change the exception handling
// logic in the debuggee so that we can handle the debugger event after detach.
// 2. Create a "stack walking" implementation for native code and use it to get the current IP and
// set the IP to the right place.
Thread *thread = GetThread();
if (thread != NULL)
{
BYTE *patchBypass = m_pSharedPatchBypassBuffer->PatchBypass;
CONTEXT *context = thread->GetFilterContext();
if (patchBypass != NULL &&
context != NULL &&
(size_t)GetIP(context) >= (size_t)patchBypass &&
(size_t)GetIP(context) <= (size_t)(patchBypass + MAX_INSTRUCTION_LENGTH + 1))
{
SetIP(context, (PCODE)((BYTE *)GetIP(context) - (patchBypass - (BYTE *)m_address)));
}
}
#endif
}
//
// We have to have a whole seperate function for this because you
// can't use __try in a function that requires object unwinding...
//
LONG FilterAccessViolation2(LPEXCEPTION_POINTERS ep, PVOID pv)
{
LIMITED_METHOD_CONTRACT;
return (ep->ExceptionRecord->ExceptionCode == EXCEPTION_ACCESS_VIOLATION)
? EXCEPTION_EXECUTE_HANDLER : EXCEPTION_CONTINUE_SEARCH;
}
// This helper is required because the AVInRuntimeImplOkayHolder can not
// be directly placed inside the scope of a PAL_TRY
void _CopyInstructionBlockHelper(BYTE* to, const BYTE* from)
{
AVInRuntimeImplOkayHolder AVOkay;
// This function only copies the portion of the instruction that follows the
// breakpoint opcode, not the breakpoint itself
to += CORDbg_BREAK_INSTRUCTION_SIZE;
from += CORDbg_BREAK_INSTRUCTION_SIZE;
// If an AV occurs because we walked off a valid page then we need
// to be certain that all bytes on the previous page were copied.
// We are certain that we copied enough bytes to contain the instruction
// because it must have fit within the valid page.
for (int i = 0; i < MAX_INSTRUCTION_LENGTH - CORDbg_BREAK_INSTRUCTION_SIZE; i++)
{
*to++ = *from++;
}
}
// WARNING: this function skips copying the first CORDbg_BREAK_INSTRUCTION_SIZE bytes by design
// See the comment at the callsite in DebuggerPatchSkip::DebuggerPatchSkip for more details on
// this
void DebuggerPatchSkip::CopyInstructionBlock(BYTE *to, const BYTE* from)
{
// We wrap the memcpy in an exception handler to handle the
// extremely rare case where we're copying an instruction off the
// end of a method that is also at the end of a page, and the next
// page is unmapped.
struct Param
{
BYTE *to;
const BYTE* from;
} param;
param.to = to;
param.from = from;
PAL_TRY(Param *, pParam, ¶m)
{
_CopyInstructionBlockHelper(pParam->to, pParam->from);
}
PAL_EXCEPT_FILTER(FilterAccessViolation2)
{
// The whole point is that if we copy up the the AV, then
// that's enough to execute, otherwise we would not have been
// able to execute the code anyway. So we just ignore the
// exception.
LOG((LF_CORDB, LL_INFO10000,
"DPS::DPS: AV copying instruction block ignored.\n"));
}
PAL_ENDTRY
// We just created a new buffer of code, but the CPU caches code and may
// not be aware of our changes. This should force the CPU to dump any cached
// instructions it has in this region and load the new ones from memory
FlushInstructionCache(GetCurrentProcess(), to + CORDbg_BREAK_INSTRUCTION_SIZE,
MAX_INSTRUCTION_LENGTH - CORDbg_BREAK_INSTRUCTION_SIZE);
}
TP_RESULT DebuggerPatchSkip::TriggerPatch(DebuggerControllerPatch *patch,
Thread *thread,
TRIGGER_WHY tyWhy)
{
ARM_ONLY(_ASSERTE(!"Should not have called DebuggerPatchSkip::TriggerPatch."));
LOG((LF_CORDB, LL_EVERYTHING, "DPS::TP called\n"));
#if defined(_DEBUG) && !defined(_TARGET_ARM_)
CONTEXT *context = GetManagedLiveCtx(thread);
LOG((LF_CORDB, LL_INFO1000, "DPS::TP: We've patched 0x%x (byPass:0x%x) "
"for a skip after an EnC update!\n", GetIP(context),
GetBypassAddress()));
_ASSERTE(g_patches != NULL);
// We shouldn't have mucked with EIP, yet.
_ASSERTE(dac_cast<PTR_CORDB_ADDRESS_TYPE>(GetIP(context)) == GetBypassAddress());
//We should be the _only_ patch here
MethodDesc *md2 = dac_cast<PTR_MethodDesc>(GetIP(context));
DebuggerControllerPatch *patchCheck = g_patches->GetPatch(g_pEEInterface->MethodDescGetModule(md2),md2->GetMemberDef());
_ASSERTE(patchCheck == patch);
_ASSERTE(patchCheck->controller == patch->controller);
patchCheck = g_patches->GetNextPatch(patchCheck);
_ASSERTE(patchCheck == NULL);
#endif // _DEBUG
DisableAll();
EnableExceptionHook();
EnableSingleStep(); //gets us back to where we want.
return TPR_IGNORE; // don't actually want to stop here....
}
TP_RESULT DebuggerPatchSkip::TriggerExceptionHook(Thread *thread, CONTEXT * context,
EXCEPTION_RECORD *exception)
{
CONTRACTL
{
SO_NOT_MAINLINE;
NOTHROW;
GC_NOTRIGGER;
// Patch skippers only operate on patches set in managed code. But the infrastructure may have
// toggled the GC mode underneath us.
MODE_ANY;
PRECONDITION(GetThread() == thread);
PRECONDITION(thread != NULL);
PRECONDITION(CheckPointer(context));
}
CONTRACTL_END;
if (m_pAppDomain != NULL)
{
AppDomain *pAppDomainCur = thread->GetDomain();
if (pAppDomainCur != m_pAppDomain)
{
LOG((LF_CORDB,LL_INFO10000, "DPS::TEH: Appdomain mismatch - not skiiping!\n"));
return TPR_IGNORE;
}
}
LOG((LF_CORDB,LL_INFO10000, "DPS::TEH: doing the patch-skip thing\n"));
#if defined(_TARGET_ARM64_)
if (!IsSingleStep(exception->ExceptionCode))
{
LOG((LF_CORDB, LL_INFO10000, "Exception in patched Bypass instruction .\n"));
return (TPR_IGNORE_AND_STOP);
}
_ASSERTE(m_pSharedPatchBypassBuffer);
BYTE* patchBypass = m_pSharedPatchBypassBuffer->PatchBypass;
PCODE targetIp;
if (m_pSharedPatchBypassBuffer->RipTargetFixup)
{
targetIp = m_pSharedPatchBypassBuffer->RipTargetFixup;
}
else
{
targetIp = (PCODE)((BYTE *)GetIP(context) - (patchBypass - (BYTE *)m_address));
}
SetIP(context, targetIp);
LOG((LF_CORDB, LL_ALWAYS, "Redirecting after Patch to 0x%p\n", GetIP(context)));
#elif defined (_TARGET_ARM_)
//Do nothing
#else
_ASSERTE(m_pSharedPatchBypassBuffer);
BYTE* patchBypass = m_pSharedPatchBypassBuffer->PatchBypass;
if (m_instrAttrib.m_fIsCall && IsSingleStep(exception->ExceptionCode))
{
// Fixup return address on stack
#if defined(_TARGET_X86_) || defined(_TARGET_AMD64_)
SIZE_T *sp = (SIZE_T *) GetSP(context);
LOG((LF_CORDB, LL_INFO10000,
"Bypass call return address redirected from 0x%p\n", *sp));
*sp -= patchBypass - (BYTE*)m_address;
LOG((LF_CORDB, LL_INFO10000, "to 0x%p\n", *sp));
#else
PORTABILITY_ASSERT("DebuggerPatchSkip::TriggerExceptionHook -- return address fixup NYI");
#endif
}
if (!m_instrAttrib.m_fIsAbsBranch || !IsSingleStep(exception->ExceptionCode))
{
// Fixup IP
LOG((LF_CORDB, LL_INFO10000, "Bypass instruction redirected from 0x%p\n", GetIP(context)));
if (IsSingleStep(exception->ExceptionCode))
{
#ifndef FEATURE_PAL
// Check if the current IP is anywhere near the exception dispatcher logic.
// If it is, ignore the exception, as the real exception is coming next.
static FARPROC pExcepDispProc = NULL;
if (!pExcepDispProc)
{
HMODULE hNtDll = WszGetModuleHandle(W("ntdll.dll"));
if (hNtDll != NULL)
{
pExcepDispProc = GetProcAddress(hNtDll, "KiUserExceptionDispatcher");
if (!pExcepDispProc)
pExcepDispProc = (FARPROC)(size_t)(-1);
}
else
pExcepDispProc = (FARPROC)(size_t)(-1);
}
_ASSERTE(pExcepDispProc != NULL);
if ((size_t)pExcepDispProc != (size_t)(-1))
{
LPVOID pExcepDispEntryPoint = pExcepDispProc;
if ((size_t)GetIP(context) > (size_t)pExcepDispEntryPoint &&
(size_t)GetIP(context) <= ((size_t)pExcepDispEntryPoint + MAX_INSTRUCTION_LENGTH * 2 + 1))
{
LOG((LF_CORDB, LL_INFO10000,
"Bypass instruction not redirected. Landed in exception dispatcher.\n"));
return (TPR_IGNORE_AND_STOP);
}
}
#endif // FEATURE_PAL
// If the IP is close to the skip patch start, or if we were skipping over a call, then assume the IP needs
// adjusting.
if (m_instrAttrib.m_fIsCall ||
((size_t)GetIP(context) > (size_t)patchBypass &&
(size_t)GetIP(context) <= (size_t)(patchBypass + MAX_INSTRUCTION_LENGTH + 1)))
{
LOG((LF_CORDB, LL_INFO10000, "Bypass instruction redirected because still in skip area.\n"));
LOG((LF_CORDB, LL_INFO10000, "m_fIsCall = %d, patchBypass = 0x%x, m_address = 0x%x\n",
m_instrAttrib.m_fIsCall, patchBypass, m_address));
SetIP(context, (PCODE)((BYTE *)GetIP(context) - (patchBypass - (BYTE *)m_address)));
}
else
{
// Otherwise, need to see if the IP is something we recognize (either managed code
// or stub code) - if not, we ignore the exception
PCODE newIP = GetIP(context);
newIP -= PCODE(patchBypass - (BYTE *)m_address);
TraceDestination trace;
if (g_pEEInterface->IsManagedNativeCode(dac_cast<PTR_CBYTE>(newIP)) ||
(g_pEEInterface->TraceStub(LPBYTE(newIP), &trace)))
{
LOG((LF_CORDB, LL_INFO10000, "Bypass instruction redirected because we landed in managed or stub code\n"));
SetIP(context, newIP);
}
// If we have no idea where things have gone, then we assume that the IP needs no adjusting (which
// could happen if the instruction we were trying to patch skip caused an AV). In this case we want
// to claim it as ours but ignore it and continue execution.
else
{
LOG((LF_CORDB, LL_INFO10000, "Bypass instruction not redirected because we're not in managed or stub code.\n"));
return (TPR_IGNORE_AND_STOP);
}
}
}
else
{
LOG((LF_CORDB, LL_INFO10000, "Bypass instruction redirected because it wasn't a single step exception.\n"));
SetIP(context, (PCODE)((BYTE *)GetIP(context) - (patchBypass - (BYTE *)m_address)));
}
LOG((LF_CORDB, LL_ALWAYS, "to 0x%x\n", GetIP(context)));
}
#endif
// Signals our thread that the debugger is done manipulating the context
// during the patch skip operation. This effectively prevented other threads
// from suspending us until we completed skiping the patch and restored
// a good context (See DDB 188816)
m_thread->EndDebuggerPatchSkip();
// Don't delete the controller yet if this is a single step exception, as the code will still want to dispatch to
// our single step method, and if it doesn't find something to dispatch to we won't continue from the exception.
//
// (This is kind of broken behavior but is easily worked around here
// by this test)
if (!IsSingleStep(exception->ExceptionCode))
{
Delete();
}
DisableExceptionHook();
return TPR_TRIGGER;
}
bool DebuggerPatchSkip::TriggerSingleStep(Thread *thread, const BYTE *ip)
{
LOG((LF_CORDB,LL_INFO10000, "DPS::TSS: basically a no-op\n"));
if (m_pAppDomain != NULL)
{
AppDomain *pAppDomainCur = thread->GetDomain();
if (pAppDomainCur != m_pAppDomain)
{
LOG((LF_CORDB,LL_INFO10000, "DPS::TSS: Appdomain mismatch - "
"not SingSteping!!\n"));
return false;
}
}
#if defined(_TARGET_AMD64_)
// Dev11 91932: for RIP-relative writes we need to copy the value that was written in our buffer to the actual address
_ASSERTE(m_pSharedPatchBypassBuffer);
if (m_pSharedPatchBypassBuffer->RipTargetFixup)
{
_ASSERTE(m_pSharedPatchBypassBuffer->RipTargetFixupSize);
BYTE* bufferBypass = m_pSharedPatchBypassBuffer->BypassBuffer;
BYTE fixupSize = m_pSharedPatchBypassBuffer->RipTargetFixupSize;
UINT_PTR targetFixup = m_pSharedPatchBypassBuffer->RipTargetFixup;
switch (fixupSize)
{
case 1:
*(reinterpret_cast<BYTE*>(targetFixup)) = *(reinterpret_cast<BYTE*>(bufferBypass));
break;
case 2:
*(reinterpret_cast<WORD*>(targetFixup)) = *(reinterpret_cast<WORD*>(bufferBypass));
break;
case 4:
*(reinterpret_cast<DWORD*>(targetFixup)) = *(reinterpret_cast<DWORD*>(bufferBypass));
break;
case 8:
*(reinterpret_cast<ULONGLONG*>(targetFixup)) = *(reinterpret_cast<ULONGLONG*>(bufferBypass));
break;
case 16:
memcpy(reinterpret_cast<void*>(targetFixup), bufferBypass, 16);
break;
default:
_ASSERTE(!"bad operand size");
}
}
#endif
LOG((LF_CORDB,LL_INFO10000, "DPS::TSS: triggered, about to delete\n"));
TRACE_FREE(this);
Delete();
return false;
}
// * -------------------------------------------------------------------------
// * DebuggerBreakpoint routines
// * -------------------------------------------------------------------------
// DebuggerBreakpoint::DebuggerBreakpoint() The constructor
// invokes AddBindAndActivatePatch to set the breakpoint
DebuggerBreakpoint::DebuggerBreakpoint(Module *module,
mdMethodDef md,
AppDomain *pAppDomain,
SIZE_T offset,
bool native,
SIZE_T ilEnCVersion, // must give the EnC version for non-native bps
MethodDesc *nativeMethodDesc, // use only when m_native
DebuggerJitInfo *nativeJITInfo, // optional when m_native, null otherwise
BOOL *pSucceed
)
: DebuggerController(NULL, pAppDomain)
{
_ASSERTE(pSucceed != NULL);
_ASSERTE(native == (nativeMethodDesc != NULL));
_ASSERTE(native || nativeJITInfo == NULL);
_ASSERTE(!nativeJITInfo || nativeJITInfo->m_jitComplete); // this is sent by the left-side, and it couldn't have got the code if the JIT wasn't complete
if (native)
{
(*pSucceed) = AddBindAndActivateNativeManagedPatch(nativeMethodDesc, nativeJITInfo, offset, LEAF_MOST_FRAME, pAppDomain);
return;
}
else
{
(*pSucceed) = AddILPatch(pAppDomain, module, md, ilEnCVersion, offset);
}
}
// TP_RESULT DebuggerBreakpoint::TriggerPatch()
// What: This patch will always be activated.
// How: return true.
TP_RESULT DebuggerBreakpoint::TriggerPatch(DebuggerControllerPatch *patch,
Thread *thread,
TRIGGER_WHY tyWhy)
{
LOG((LF_CORDB, LL_INFO10000, "DB::TP\n"));
return TPR_TRIGGER;
}
// void DebuggerBreakpoint::SendEvent() What: Inform
// the right side that the breakpoint was reached.
// How: g_pDebugger->SendBreakpoint()
bool DebuggerBreakpoint::SendEvent(Thread *thread, bool fIpChanged)
{
CONTRACTL
{
SO_NOT_MAINLINE;
NOTHROW;
SENDEVENT_CONTRACT_ITEMS;
}
CONTRACTL_END;
LOG((LF_CORDB, LL_INFO10000, "DB::SE: in DebuggerBreakpoint's SendEvent\n"));
CONTEXT *context = g_pEEInterface->GetThreadFilterContext(thread);
// If we got interupted by SetIp, we just don't send the IPC event. Our triggers are still
// active so no harm done.
if (!fIpChanged)
{
g_pDebugger->SendBreakpoint(thread, context, this);
return true;
}
// Controller is still alive, will fire if we hit the breakpoint again.
return false;
}
//* -------------------------------------------------------------------------
// * DebuggerStepper routines
// * -------------------------------------------------------------------------
DebuggerStepper::DebuggerStepper(Thread *thread,
CorDebugUnmappedStop rgfMappingStop,
CorDebugIntercept interceptStop,
AppDomain *appDomain)
: DebuggerController(thread, appDomain),
m_stepIn(false),
m_reason(STEP_NORMAL),
m_fpStepInto(LEAF_MOST_FRAME),
m_rgfInterceptStop(interceptStop),
m_rgfMappingStop(rgfMappingStop),
m_range(NULL),
m_rangeCount(0),
m_realRangeCount(0),
m_fp(LEAF_MOST_FRAME),
#if defined(WIN64EXCEPTIONS)
m_fpParentMethod(LEAF_MOST_FRAME),
#endif // WIN64EXCEPTIONS
m_fpException(LEAF_MOST_FRAME),
m_fdException(0),
m_cFuncEvalNesting(0)
{
#ifdef _DEBUG
m_fReadyToSend = false;
#endif
}
DebuggerStepper::~DebuggerStepper()
{
if (m_range != NULL)
{
TRACE_FREE(m_range);
DeleteInteropSafe(m_range);
}
}
// bool DebuggerStepper::ShouldContinueStep() Return true if
// the stepper should not stop at this address. The stepper should not
// stop here if: here is in the {prolog,epilog,etc};
// and the stepper is not interested in stopping here.
// We assume that this is being called in the frame which the stepper steps
// through. Unless, of course, we're returning from a call, in which
// case we want to stop in the epilog even if the user didn't say so,
// to prevent stepping out of multiple frames at once.
// <REVISIT_TODO>Possible optimization: GetJitInfo, then AddPatch @ end of prolog?</REVISIT_TODO>
bool DebuggerStepper::ShouldContinueStep( ControllerStackInfo *info,
SIZE_T nativeOffset)
{
LOG((LF_CORDB,LL_INFO10000, "DeSt::ShContSt: nativeOffset:0x%p \n", nativeOffset));
if (m_rgfMappingStop != STOP_ALL && (m_reason != STEP_EXIT) )
{
DebuggerJitInfo *ji = info->m_activeFrame.GetJitInfoFromFrame();
if ( ji != NULL )
{
LOG((LF_CORDB,LL_INFO10000,"DeSt::ShContSt: For code 0x%p, got "
"DJI 0x%p, from 0x%p to 0x%p\n",
(const BYTE*)GetControlPC(&(info->m_activeFrame.registers)),
ji, ji->m_addrOfCode, ji->m_addrOfCode+ji->m_sizeOfCode));
}
else
{
LOG((LF_CORDB,LL_INFO10000,"DeSt::ShCoSt: For code 0x%p, didn't "
"get DJI\n",(const BYTE*)GetControlPC(&(info->m_activeFrame.registers))));
return false; // Haven't a clue if we should continue, so
// don't
}
CorDebugMappingResult map = MAPPING_UNMAPPED_ADDRESS;
DWORD whichIDontCare;
ji->MapNativeOffsetToIL( nativeOffset, &map, &whichIDontCare);
unsigned int interestingMappings =
(map & ~(MAPPING_APPROXIMATE | MAPPING_EXACT));
LOG((LF_CORDB,LL_INFO10000,
"DeSt::ShContSt: interestingMappings:0x%x m_rgfMappingStop:%x\n",
interestingMappings,m_rgfMappingStop));
// If we're in a prolog,epilog, then we may want to skip
// over it or stop
if ( interestingMappings )
{
if ( interestingMappings & m_rgfMappingStop )
return false;
else
return true;
}
}
return false;
}
bool DebuggerStepper::IsRangeAppropriate(ControllerStackInfo *info)
{
LOG((LF_CORDB,LL_INFO10000, "DS::IRA: info:0x%x \n", info));
if (m_range == NULL)
{
LOG((LF_CORDB,LL_INFO10000, "DS::IRA: m_range == NULL, returning FALSE\n"));
return false;
}
FrameInfo *realFrame;
#if defined(WIN64EXCEPTIONS)
bool fActiveFrameIsFunclet = info->m_activeFrame.IsNonFilterFuncletFrame();
if (fActiveFrameIsFunclet)
{
realFrame = &(info->m_returnFrame);
}
else
#endif // WIN64EXCEPTIONS
{
realFrame = &(info->m_activeFrame);
}
LOG((LF_CORDB,LL_INFO10000, "DS::IRA: info->m_activeFrame.fp:0x%x m_fp:0x%x\n", info->m_activeFrame.fp, m_fp));
LOG((LF_CORDB,LL_INFO10000, "DS::IRA: m_fdException:0x%x realFrame->md:0x%x realFrame->fp:0x%x m_fpException:0x%x\n",
m_fdException, realFrame->md, realFrame->fp, m_fpException));
if ( (info->m_activeFrame.fp == m_fp) ||
( (m_fdException != NULL) && (realFrame->md == m_fdException) &&
IsEqualOrCloserToRoot(realFrame->fp, m_fpException) ) )
{
LOG((LF_CORDB,LL_INFO10000, "DS::IRA: returning TRUE\n"));
return true;
}
#if defined(WIN64EXCEPTIONS)
// There are two scenarios which make this function more complicated on WIN64.
// 1) We initiate a step in the parent method or a funclet but end up stepping into another funclet closer to the leaf.
// a) start in the parent method
// b) start in a funclet
// 2) We initiate a step in a funclet but end up stepping out to the parent method or a funclet closer to the root.
// a) end up in the parent method
// b) end up in a funclet
// In both cases the range of the stepper should still be appropriate.
bool fValidParentMethodFP = (m_fpParentMethod != LEAF_MOST_FRAME);
if (fActiveFrameIsFunclet)
{
// Scenario 1a
if (m_fp == info->m_returnFrame.fp)
{
LOG((LF_CORDB,LL_INFO10000, "DS::IRA: returning TRUE\n"));
return true;
}
// Scenario 1b & 2b have the same condition
else if (fValidParentMethodFP && (m_fpParentMethod == info->m_returnFrame.fp))
{
LOG((LF_CORDB,LL_INFO10000, "DS::IRA: returning TRUE\n"));
return true;
}
}
else
{
// Scenario 2a
if (fValidParentMethodFP && (m_fpParentMethod == info->m_activeFrame.fp))
{
LOG((LF_CORDB,LL_INFO10000, "DS::IRA: returning TRUE\n"));
return true;
}
}
#endif // WIN64EXCEPTIONS
LOG((LF_CORDB,LL_INFO10000, "DS::IRA: returning FALSE\n"));
return false;
}
// bool DebuggerStepper::IsInRange() Given the native offset ip,
// returns true if ip falls within any of the native offset ranges specified
// by the array of COR_DEBUG_STEP_RANGEs.
// Returns true if ip falls within any of the ranges. Returns false
// if ip doesn't, or if there are no ranges (rangeCount==0). Note that a
// COR_DEBUG_STEP_RANGE with an endOffset of zero is interpreted as extending
// from startOffset to the end of the method.
// SIZE_T ip: Native offset, relative to the beginning of the method.
// COR_DEBUG_STEP_RANGE *range: An array of ranges, which are themselves
// native offsets, to compare against ip.
// SIZE_T rangeCount: Number of elements in range
bool DebuggerStepper::IsInRange(SIZE_T ip, COR_DEBUG_STEP_RANGE *range, SIZE_T rangeCount,
ControllerStackInfo *pInfo)
{
LOG((LF_CORDB,LL_INFO10000,"DS::IIR: off=0x%x\n", ip));
if (range == NULL)
{
LOG((LF_CORDB,LL_INFO10000,"DS::IIR: range == NULL -> not in range\n"));
return false;
}
if (pInfo && !IsRangeAppropriate(pInfo))
{
LOG((LF_CORDB,LL_INFO10000,"DS::IIR: no pInfo or range not appropriate -> not in range\n"));
return false;
}
COR_DEBUG_STEP_RANGE *r = range;
COR_DEBUG_STEP_RANGE *rEnd = r + rangeCount;
while (r < rEnd)
{
SIZE_T endOffset = r->endOffset ? r->endOffset : ~0;
LOG((LF_CORDB,LL_INFO100000,"DS::IIR: so=0x%x, eo=0x%x\n",
r->startOffset, endOffset));
if (ip >= r->startOffset && ip < endOffset)
{
LOG((LF_CORDB,LL_INFO1000,"DS::IIR:this:0x%x Found native offset "
"0x%x to be in the range"
"[0x%x, 0x%x), index 0x%x\n\n", this, ip, r->startOffset,
endOffset, ((r-range)/sizeof(COR_DEBUG_STEP_RANGE *)) ));
return true;
}
r++;
}
LOG((LF_CORDB,LL_INFO10000,"DS::IIR: not in range\n"));
return false;
}
// bool DebuggerStepper::DetectHandleInterceptors() Return true if
// the current execution takes place within an interceptor (that is, either
// the current frame, or the parent frame is a framed frame whose
// GetInterception method returns something other than INTERCEPTION_NONE),
// and this stepper doesn't want to stop in an interceptor, and we successfully
// set a breakpoint after the top-most interceptor in the stack.
bool DebuggerStepper::DetectHandleInterceptors(ControllerStackInfo *info)
{
LOG((LF_CORDB,LL_INFO10000,"DS::DHI: Start DetectHandleInterceptors\n"));
LOG((LF_CORDB,LL_INFO10000,"DS::DHI: active frame=0x%08x, has return frame=%d, return frame=0x%08x m_reason:%d\n",
info->m_activeFrame.frame, info->HasReturnFrame(), info->m_returnFrame.frame, m_reason));
// If this is a normal step, then we want to continue stepping, even if we
// are in an interceptor.
if (m_reason == STEP_NORMAL || m_reason == STEP_RETURN || m_reason == STEP_EXCEPTION_HANDLER)
{
LOG((LF_CORDB,LL_INFO1000,"DS::DHI: Returning false while stepping within function, finally!\n"));
return false;
}
bool fAttemptStepOut = false;
if (m_rgfInterceptStop != INTERCEPT_ALL) // we may have to skip out of one
{
if (info->m_activeFrame.frame != NULL &&
info->m_activeFrame.frame != FRAME_TOP &&
info->m_activeFrame.frame->GetInterception() != Frame::INTERCEPTION_NONE)
{
if (!((CorDebugIntercept)info->m_activeFrame.frame->GetInterception() & Frame::Interception(m_rgfInterceptStop)))
{
LOG((LF_CORDB,LL_INFO10000,"DS::DHI: Stepping out b/c of excluded frame type:0x%x\n",
info->m_returnFrame. frame->GetInterception()));
fAttemptStepOut = true;
}
else
{
LOG((LF_CORDB,LL_INFO10000,"DS::DHI: 0x%x set to STEP_INTERCEPT\n", this));
m_reason = STEP_INTERCEPT; //remember why we've stopped
}
}
if ((m_reason == STEP_EXCEPTION_FILTER) ||
(info->HasReturnFrame() &&
info->m_returnFrame.frame != NULL &&
info->m_returnFrame.frame != FRAME_TOP &&
info->m_returnFrame.frame->GetInterception() != Frame::INTERCEPTION_NONE))
{
if (m_reason == STEP_EXCEPTION_FILTER)
{
// Exceptions raised inside of the EE by COMPlusThrow, FCThrow, etc will not
// insert an ExceptionFrame, and hence info->m_returnFrame.frame->GetInterception()
// will not be accurate. Hence we use m_reason instead
if (!(Frame::INTERCEPTION_EXCEPTION & Frame::Interception(m_rgfInterceptStop)))
{
LOG((LF_CORDB,LL_INFO10000,"DS::DHI: Stepping out b/c of excluded INTERCEPTION_EXCEPTION\n"));
fAttemptStepOut = true;
}
}
else if (!(info->m_returnFrame.frame->GetInterception() & Frame::Interception(m_rgfInterceptStop)))
{
LOG((LF_CORDB,LL_INFO10000,"DS::DHI: Stepping out b/c of excluded return frame type:0x%x\n",
info->m_returnFrame.frame->GetInterception()));
fAttemptStepOut = true;
}
if (!fAttemptStepOut)
{
LOG((LF_CORDB,LL_INFO10000,"DS::DHI 0x%x set to STEP_INTERCEPT\n", this));
m_reason = STEP_INTERCEPT; //remember why we've stopped
}
}
else if (info->m_specialChainReason != CHAIN_NONE)
{
if(!(info->m_specialChainReason & CorDebugChainReason(m_rgfInterceptStop)) )
{
LOG((LF_CORDB,LL_INFO10000, "DS::DHI: (special) Stepping out b/c of excluded return frame type:0x%x\n",
info->m_specialChainReason));
fAttemptStepOut = true;
}
else
{
LOG((LF_CORDB,LL_INFO10000,"DS::DHI 0x%x set to STEP_INTERCEPT\n", this));
m_reason = STEP_INTERCEPT; //remember why we've stopped
}
}
else if (info->m_activeFrame.frame == NULL)
{
// Make sure we are not dealing with a chain here.
if (info->m_activeFrame.HasMethodFrame())
{
// Check whether we are executing in a class constructor.
_ASSERTE(info->m_activeFrame.md != NULL);
if (info->m_activeFrame.md->IsClassConstructor())
{
// We are in a class constructor. Check whether we want to stop in it.
if (!(CHAIN_CLASS_INIT & CorDebugChainReason(m_rgfInterceptStop)))
{
LOG((LF_CORDB, LL_INFO10000, "DS::DHI: Stepping out b/c of excluded cctor:0x%x\n",
CHAIN_CLASS_INIT));
fAttemptStepOut = true;
}
else
{
LOG((LF_CORDB, LL_INFO10000,"DS::DHI 0x%x set to STEP_INTERCEPT\n", this));
m_reason = STEP_INTERCEPT; //remember why we've stopped
}
}
}
}
}
if (fAttemptStepOut)
{
LOG((LF_CORDB,LL_INFO1000,"DS::DHI: Doing TSO!\n"));
// TrapStepOut could alter the step reason if we're stepping out of an inteceptor and it looks like we're
// running off the top of the program. So hold onto it here, and if our step reason becomes STEP_EXIT, then
// reset it to what it was.
CorDebugStepReason holdReason = m_reason;
// @todo - should this be TrapStepNext??? But that may stop in a child...
TrapStepOut(info);
EnableUnwind(m_fp);
if (m_reason == STEP_EXIT)
{
m_reason = holdReason;
}
return true;
}
// We're not in a special area of code, so we don't want to continue unless some other part of the code decides that
// we should.
LOG((LF_CORDB,LL_INFO1000,"DS::DHI: Returning false, finally!\n"));
return false;
}
//---------------------------------------------------------------------------------------
//
// This function checks whether the given IP is in an LCG method. If so, it enables
// JMC and does a step out. This effectively makes sure that we never stop in an LCG method.
//
// There are two common scnearios here:
// 1) We single-step into an LCG method from a managed method.
// 2) We single-step off the end of a method called by an LCG method and end up in the calling LCG method.
//
// In both cases, we don't want to stop in the LCG method. If the LCG method directly or indirectly calls
// another user method, we want to stop there. Otherwise, we just want to step out back to the caller of
// LCG method. In other words, what we want is exactly the JMC behaviour.
//
// Arguments:
// ip - the current IP where the thread is stopped at
// pMD - This is the MethodDesc for the specified ip. This can be NULL, but if it's not,
// then it has to match the specified IP.
// pInfo - the ControllerStackInfo taken at the specified IP (see Notes below)
//
// Return Value:
// Returns TRUE if the specified IP is indeed in an LCG method, in which case this function has already
// enabled all the traps to catch the thread, including turning on JMC, enabling unwind callback, and
// putting a patch in the caller.
//
// Notes:
// LCG methods don't show up in stackwalks done by the ControllerStackInfo. So even if the specified IP
// is in an LCG method, the LCG method won't show up in the call strack. That's why we need to call
// ControllerStackInfo::SetReturnFrameWithActiveFrame() in this function before calling TrapStepOut().
// Otherwise TrapStepOut() will put a patch in the caller's caller (if there is one).
//
BOOL DebuggerStepper::DetectHandleLCGMethods(const PCODE ip, MethodDesc * pMD, ControllerStackInfo * pInfo)
{
// Look up the MethodDesc for the given IP.
if (pMD == NULL)
{
if (g_pEEInterface->IsManagedNativeCode((const BYTE *)ip))
{
pMD = g_pEEInterface->GetNativeCodeMethodDesc(ip);
_ASSERTE(pMD != NULL);
}
}
#if defined(_DEBUG)
else
{
// If a MethodDesc is specified, it has to match the given IP.
_ASSERTE(pMD == g_pEEInterface->GetNativeCodeMethodDesc(ip));
}
#endif // _DEBUG
// If the given IP is in unmanaged code, then we won't have a MethodDesc by this point.
if (pMD != NULL)
{
if (pMD->IsLCGMethod())
{
// Enable all the traps to catch the thread.
EnableUnwind(m_fp);
EnableJMCBackStop(pMD);
pInfo->SetReturnFrameWithActiveFrame();
TrapStepOut(pInfo);
return TRUE;
}
}
return FALSE;
}
// Steppers override these so that they can skip func-evals. Note that steppers can
// be created & used inside of func-evals (nested-break states).
// On enter, we check for freezing the stepper.
void DebuggerStepper::TriggerFuncEvalEnter(Thread * thread)
{
LOG((LF_CORDB, LL_INFO10000, "DS::TFEEnter, this=0x%p, old nest=%d\n", this, m_cFuncEvalNesting));
// Since this is always called on the hijacking thread, we should be thread-safe
_ASSERTE(thread == this->GetThread());
if (IsDead())
return;
m_cFuncEvalNesting++;
if (m_cFuncEvalNesting == 1)
{
// We're entering our 1st funceval, so freeze us.
LOG((LF_CORDB, LL_INFO100000, "DS::TFEEnter - freezing stepper\n"));
// Freeze the stepper by disabling all triggers
m_bvFrozenTriggers = 0;
//
// We dont explicitly disable single-stepping because the OS
// gives us a new thread context during an exception. Since
// all func-evals are done inside exceptions, we should never
// have this problem.
//
// Note: however, that if func-evals were no longer done in
// exceptions, this would have to change.
//
if (IsMethodEnterEnabled())
{
m_bvFrozenTriggers |= kMethodEnter;
DisableMethodEnter();
}
}
else
{
LOG((LF_CORDB, LL_INFO100000, "DS::TFEEnter - new nest=%d\n", m_cFuncEvalNesting));
}
}
// On Func-EvalExit, we check if the stepper is trying to step-out of a func-eval
// (in which case we kill it)
// or if we previously entered this func-eval and should thaw it now.
void DebuggerStepper::TriggerFuncEvalExit(Thread * thread)
{
LOG((LF_CORDB, LL_INFO10000, "DS::TFEExit, this=0x%p, old nest=%d\n", this, m_cFuncEvalNesting));
// Since this is always called on the hijacking thread, we should be thread-safe
_ASSERTE(thread == this->GetThread());
if (IsDead())
return;
m_cFuncEvalNesting--;
if (m_cFuncEvalNesting == -1)
{
LOG((LF_CORDB, LL_INFO100000, "DS::TFEExit - disabling stepper\n"));
// we're exiting the func-eval session we were created in. So we just completely
// disable ourselves so that we don't fire anything anymore.
// The RS still has to free the stepper though.
// This prevents us from stepping-out of a func-eval. For traditional steppers,
// this is overkill since it won't have any outstanding triggers. (trap-step-out
// won't patch if it crosses a func-eval frame).
// But JMC-steppers have Method-Enter; and so this is the only place we have to
// disable that.
DisableAll();
}
else if (m_cFuncEvalNesting == 0)
{
// We're back to our starting Func-eval session, we should have been frozen,
// so now we thaw.
LOG((LF_CORDB, LL_INFO100000, "DS::TFEExit - thawing stepper\n"));
// Thaw the stepper (reenable triggers)
if ((m_bvFrozenTriggers & kMethodEnter) != 0)
{
EnableMethodEnter();
}
m_bvFrozenTriggers = 0;
}
else
{
LOG((LF_CORDB, LL_INFO100000, "DS::TFEExit - new nest=%d\n", m_cFuncEvalNesting));
}
}
// Return true iff we set a patch (which implies to caller that we should
// let controller run free and hit that patch)
bool DebuggerStepper::TrapStepInto(ControllerStackInfo *info,
const BYTE *ip,
TraceDestination *pTD)
{
_ASSERTE( pTD != NULL );
_ASSERTE(this->GetDCType() == DEBUGGER_CONTROLLER_STEPPER);
EnableTraceCall(LEAF_MOST_FRAME);
if (IsCloserToRoot(info->m_activeFrame.fp, m_fpStepInto))
m_fpStepInto = info->m_activeFrame.fp;
LOG((LF_CORDB, LL_INFO1000, "Ds::TSI this:0x%x m_fpStepInto:0x%x\n",
this, m_fpStepInto.GetSPValue()));
TraceDestination trace;
// Trace through the stubs.
// If we're calling from managed code, this should either succeed
// or become an ecall into mscorwks.
// @Todo - what about stubs in mscorwks.
// @todo - if this fails, we want to provde as much info as possible.
if (!g_pEEInterface->TraceStub(ip, &trace)
|| !g_pEEInterface->FollowTrace(&trace))
{
return false;
}
(*pTD) = trace; //bitwise copy
// Step-in always operates at the leaf-most frame. Thus the frame pointer for any
// patch for step-in should be LEAF_MOST_FRAME, regardless of whatever our current fp
// is before the step-in.
// Note that step-in may skip 'internal' frames (FrameInfo w/ internal=true) since
// such frames may really just be a marker for an internal EE Frame on the stack.
// However, step-out uses these frames b/c it may call frame->TraceFrame() on them.
return PatchTrace(&trace,
LEAF_MOST_FRAME, // step-in is always leaf-most frame.
(m_rgfMappingStop&STOP_UNMANAGED)?(true):(false));
}
// Enable the JMC backstop for stepping on Step-In.
// This activate the JMC probes, which will provide a safety net
// to stop a stepper if the StubManagers don't predict the call properly.
// Ideally, this should never be necessary (because the SMs would do their job).
void DebuggerStepper::EnableJMCBackStop(MethodDesc * pStartMethod)
{
// JMC steppers should not need the JMC backstop unless a thread inadvertently stops in an LCG method.
//_ASSERTE(DEBUGGER_CONTROLLER_JMC_STEPPER != this->GetDCType());
// Since we should never hit the JMC backstop (since it's really a SM issue), we'll assert if we actually do.
// However, there's 1 corner case here. If we trace calls at the start of the method before the JMC-probe,
// then we'll still hit the JMC backstop in our own method.
// Record that starting method. That way, if we end up hitting our JMC backstop in our own method,
// we don't over aggressively fire the assert. (This won't work for recursive cases, but since this is just
// changing an assert, we don't care).
#ifdef _DEBUG
// May be NULL if we didn't start in a method.
m_StepInStartMethod = pStartMethod;
#endif
// We don't want traditional steppers to rely on MethodEnter (b/c it's not guaranteed to be correct),
// but it may be a useful last resort.
this->EnableMethodEnter();
}
// Return true if the stepper can run free.
bool DebuggerStepper::TrapStepInHelper(
ControllerStackInfo * pInfo,
const BYTE * ipCallTarget,
const BYTE * ipNext,
bool fCallingIntoFunclet)
{
TraceDestination td;
#ifdef _DEBUG
// Begin logging the step-in activity in debug builds.
StubManager::DbgBeginLog((TADDR) ipNext, (TADDR) ipCallTarget);
#endif
if (TrapStepInto(pInfo, ipCallTarget, &td))
{
// If we placed a patch, see if we need to update our step-reason
if (td.GetTraceType() == TRACE_MANAGED )
{
// Possible optimization: Roll all of g_pEEInterface calls into
// one function so we don't repeatedly get the CodeMan,etc
MethodDesc *md = NULL;
_ASSERTE( g_pEEInterface->IsManagedNativeCode((const BYTE *)td.GetAddress()) );
md = g_pEEInterface->GetNativeCodeMethodDesc(td.GetAddress());
DebuggerJitInfo* pDJI = g_pDebugger->GetJitInfoFromAddr(td.GetAddress());
CodeRegionInfo code = CodeRegionInfo::GetCodeRegionInfo(pDJI, md);
if (code.AddressToOffset((const BYTE *)td.GetAddress()) == 0)
{
LOG((LF_CORDB,LL_INFO1000,"\tDS::TS 0x%x m_reason = STEP_CALL"
"@ip0x%x\n", this, (BYTE*)GetControlPC(&(pInfo->m_activeFrame.registers))));
m_reason = STEP_CALL;
}
else
{
LOG((LF_CORDB, LL_INFO1000, "Didn't step: md:0x%x"
"td.type:%s td.address:0x%x, gfa:0x%x\n",
md, GetTType(td.GetTraceType()), td.GetAddress(),
g_pEEInterface->GetFunctionAddress(md)));
}
}
else
{
LOG((LF_CORDB,LL_INFO10000,"DS::TS else 0x%x m_reason = STEP_CALL\n",
this));
m_reason = STEP_CALL;
}
return true;
} // end TrapStepIn
else
{
// If we can't figure out where the stepper should call into (likely because we can't find a stub-manager),
// then enable the JMC backstop.
EnableJMCBackStop(pInfo->m_activeFrame.md);
}
// We ignore ipNext here. Instead we'll return false and let the caller (TrapStep)
// set the patch for us.
return false;
}
FORCEINLINE bool IsTailCall(const BYTE * pTargetIP)
{
return TailCallStubManager::IsTailCallStubHelper(reinterpret_cast<PCODE>(pTargetIP));
}
// bool DebuggerStepper::TrapStep() TrapStep attepts to set a
// patch at the next IL instruction to be executed. If we're stepping in &
// the next IL instruction is a call, then this'll set a breakpoint inside
// the code that will be called.
// How: There are a number of cases, depending on where the IP
// currently is:
// Unmanaged code: EnableTraceCall() & return false - try and get
// it when it returns.
// In a frame: if the <p in> param is true, then do an
// EnableTraceCall(). If the frame isn't the top frame, also do
// g_pEEInterface->TraceFrame(), g_pEEInterface->FollowTrace, and
// PatchTrace.
// Normal managed frame: create a Walker and walk the instructions until either
// leave the provided range (AddPatch there, return true), or we don't know what the
// next instruction is (say, after a call, or return, or branch - return false).
// Returns a boolean indicating if we were able to set a patch successfully
// in either this method, or (if in == true & the next instruction is a call)
// inside a callee method.
// true: Patch successfully placed either in this method or a callee,
// so the stepping is taken care of.
// false: Unable to place patch in either this method or any
// applicable callee methods, so the only option the caller has to put
// patch to control flow is to call TrapStepOut & try and place a patch
// on the method that called the current frame's method.
bool DebuggerStepper::TrapStep(ControllerStackInfo *info, bool in)
{
LOG((LF_CORDB,LL_INFO10000,"DS::TS: this:0x%x\n", this));
if (!info->m_activeFrame.managed)
{
//
// We're not in managed code. Patch up all paths back in.
//
LOG((LF_CORDB,LL_INFO10000, "DS::TS: not in managed code\n"));
if (in)
{
EnablePolyTraceCall();
}
return false;
}
if (info->m_activeFrame.frame != NULL)
{
//
// We're in some kind of weird frame. Patch further entry to the frame.
// or if we can't, patch return from the frame
//
LOG((LF_CORDB,LL_INFO10000, "DS::TS: in a weird frame\n"));
if (in)
{
EnablePolyTraceCall();
// Only traditional steppers should patch a frame. JMC steppers will
// just rely on TriggerMethodEnter.
if (DEBUGGER_CONTROLLER_STEPPER == this->GetDCType())
{
if (info->m_activeFrame.frame != FRAME_TOP)
{
TraceDestination trace;
CONTRACT_VIOLATION(GCViolation); // TraceFrame GC-triggers
// This could be anywhere, especially b/c step could be on non-leaf frame.
if (g_pEEInterface->TraceFrame(this->GetThread(),
info->m_activeFrame.frame,
FALSE, &trace,
&(info->m_activeFrame.registers))
&& g_pEEInterface->FollowTrace(&trace)
&& PatchTrace(&trace, info->m_activeFrame.fp,
(m_rgfMappingStop&STOP_UNMANAGED)?
(true):(false)))
{
return true;
}
}
}
}
return false;
}
#ifdef _TARGET_X86_
LOG((LF_CORDB,LL_INFO1000, "GetJitInfo for pc = 0x%x (addr of "
"that value:0x%x)\n", (const BYTE*)(GetControlPC(&info->m_activeFrame.registers)),
info->m_activeFrame.registers.PCTAddr));
#endif
// Note: we used to pass in the IP from the active frame to GetJitInfo, but there seems to be no value in that, and
// it was causing problems creating a stepper while sitting in ndirect stubs after we'd returned from the unmanaged
// function that had been called.
DebuggerJitInfo *ji = info->m_activeFrame.GetJitInfoFromFrame();
if( ji != NULL )
{
LOG((LF_CORDB,LL_INFO10000,"DS::TS: For code 0x%p, got DJI 0x%p, "
"from 0x%p to 0x%p\n",
(const BYTE*)(GetControlPC(&info->m_activeFrame.registers)),
ji, ji->m_addrOfCode, ji->m_addrOfCode+ji->m_sizeOfCode));
}
else
{
LOG((LF_CORDB,LL_INFO10000,"DS::TS: For code 0x%p, "
"didn't get a DJI \n",
(const BYTE*)(GetControlPC(&info->m_activeFrame.registers))));
}
//
// We're in a normal managed frame - walk the code
//
NativeWalker walker;
LOG((LF_CORDB,LL_INFO1000, "DS::TS: &info->m_activeFrame.registers 0x%p\n", &info->m_activeFrame.registers));
// !!! Eventually when using the fjit, we'll want
// to walk the IL to get the next location, & then map
// it back to native.
walker.Init((BYTE*)GetControlPC(&(info->m_activeFrame.registers)), &info->m_activeFrame.registers);
// Is the active frame really the active frame?
// What if the thread is stopped at a managed debug event outside of a filter ctx? Eg, stopped
// somewhere directly in mscorwks (like sending a LogMsg or ClsLoad event) or even at WaitForSingleObject.
// ActiveFrame is either the stepper's initial frame or the frame of a filterctx.
bool fIsActivFrameLive = (info->m_activeFrame.fp == info->m_bottomFP);
// If this thread isn't stopped in managed code, it can't be at the active frame.
if (GetManagedStoppedCtx(this->GetThread()) == NULL)
{
fIsActivFrameLive = false;
}
bool fIsJump = false;
bool fCallingIntoFunclet = false;
// If m_activeFrame is not the actual active frame,
// we should skip this first switch - never single step, and
// assume our context is bogus.
if (fIsActivFrameLive)
{
LOG((LF_CORDB,LL_INFO10000, "DC::TS: immediate?\n"));
// Note that by definition our walker must always be able to step
// through a single instruction, so any return
// of NULL IP's from those cases on the first step
// means that an exception is going to be generated.
//
// (On future steps, it can also mean that the destination
// simply can't be computed.)
WALK_TYPE wt = walker.GetOpcodeWalkType();
{
switch (wt)
{
case WALK_RETURN:
{
LOG((LF_CORDB,LL_INFO10000, "DC::TS:Imm:WALK_RETURN\n"));
// Normally a 'ret' opcode means we're at the end of a function and doing a step-out.
// But the jit is free to use a 'ret' opcode to implement various goofy constructs like
// managed filters, in which case we may ret to the same function or we may ret to some
// internal CLR stub code.
// So we'll just ignore this and tell the Stepper to enable every notification it has
// and let the thread run free. This will include TrapStepOut() and EnableUnwind()
// to catch any potential filters.
// Go ahead and enable the single-step flag too. We know it's safe.
// If this lands in random code, then TriggerSingleStep will just ignore it.
EnableSingleStep();
// Don't set step-reason yet. If another trigger gets hit, it will set the reason.
return false;
}
case WALK_BRANCH:
LOG((LF_CORDB,LL_INFO10000, "DC::TS:Imm:WALK_BRANCH\n"));
// A branch can be handled just like a call. If the branch is within the current method, then we just
// down to WALK_UNKNOWN, otherwise we handle it just like a call. Note: we need to force in=true
// because for a jmp, in or over is the same thing, we're still going there, and the in==true case is
// the case we want to use...
fIsJump = true;
// fall through...
case WALK_CALL:
LOG((LF_CORDB,LL_INFO10000, "DC::TS:Imm:WALK_CALL ip=%p nextip=%p\n", walker.GetIP(), walker.GetNextIP()));
// If we're doing some sort of intra-method jump (usually, to get EIP in a clever way, via the CALL
// instruction), then put the bp where we're going, NOT at the instruction following the call
if (IsAddrWithinFrame(ji, info->m_activeFrame.md, walker.GetIP(), walker.GetNextIP()))
{
LOG((LF_CORDB, LL_INFO1000, "Walk call within method!" ));
goto LWALK_UNKNOWN;
}
if (walker.GetNextIP() != NULL)
{
#ifdef WIN64EXCEPTIONS
// There are 4 places we could be jumping:
// 1) to the beginning of the same method (recursive call)
// 2) somewhere in the same funclet, that isn't the method start
// 3) somewhere in the same method but different funclet
// 4) somewhere in a different method
//
// IsAddrWithinFrame ruled out option 2, IsAddrWithinMethodIncludingFunclet rules out option 4,
// and checking the IP against the start address rules out option 1. That leaves option only what we
// wanted, option #3
fCallingIntoFunclet = IsAddrWithinMethodIncludingFunclet(ji, info->m_activeFrame.md, walker.GetNextIP()) &&
((CORDB_ADDRESS)(SIZE_T)walker.GetNextIP() != ji->m_addrOfCode);
#endif
// At this point, we know that the call/branch target is not in the current method.
// So if the current instruction is a jump, this must be a tail call or possibly a jump to the finally.
// So, check if the call/branch target is the JIT helper for handling tail calls if we are not calling
// into the funclet.
if ((fIsJump && !fCallingIntoFunclet) || IsTailCall(walker.GetNextIP()))
{
// A step-over becomes a step-out for a tail call.
if (!in)
{
TrapStepOut(info);
return true;
}
}
// To preserve the old behaviour, if this is not a tail call, then we assume we want to
// follow the call/jump.
if (fIsJump)
{
in = true;
}
// There are two cases where we need to perform a step-in. One, if the step operation is
// a step-in. Two, if the target address of the call is in a funclet of the current method.
// In this case, we want to step into the funclet even if the step operation is a step-over.
if (in || fCallingIntoFunclet)
{
if (TrapStepInHelper(info, walker.GetNextIP(), walker.GetSkipIP(), fCallingIntoFunclet))
{
return true;
}
}
}
if (walker.GetSkipIP() == NULL)
{
LOG((LF_CORDB,LL_INFO10000,"DS::TS 0x%x m_reason = STEP_CALL (skip)\n",
this));
m_reason = STEP_CALL;
return true;
}
LOG((LF_CORDB,LL_INFO100000, "DC::TS:Imm:WALK_CALL Skip instruction\n"));
walker.Skip();
break;
case WALK_UNKNOWN:
LWALK_UNKNOWN:
LOG((LF_CORDB,LL_INFO10000,"DS::TS:WALK_UNKNOWN - curIP:0x%x "
"nextIP:0x%x skipIP:0x%x 1st byte of opcode:0x%x\n", (BYTE*)GetControlPC(&(info->m_activeFrame.
registers)), walker.GetNextIP(),walker.GetSkipIP(),
*(BYTE*)GetControlPC(&(info->m_activeFrame.registers))));
EnableSingleStep();
return true;
default:
if (walker.GetNextIP() == NULL)
{
return true;
}
walker.Next();
}
}
} // if (fIsActivFrameLive)
//
// Use our range, if we're in the original
// frame.
//
COR_DEBUG_STEP_RANGE *range;
SIZE_T rangeCount;
if (info->m_activeFrame.fp == m_fp)
{
range = m_range;
rangeCount = m_rangeCount;
}
else
{
range = NULL;
rangeCount = 0;
}
//
// Keep walking until either we're out of range, or
// else we can't predict ahead any more.
//
while (TRUE)
{
const BYTE *ip = walker.GetIP();
SIZE_T offset = CodeRegionInfo::GetCodeRegionInfo(ji, info->m_activeFrame.md).AddressToOffset(ip);
LOG((LF_CORDB, LL_INFO1000, "Walking to ip 0x%p (natOff:0x%x)\n",ip,offset));
if (!IsInRange(offset, range, rangeCount)
&& !ShouldContinueStep( info, offset ))
{
AddBindAndActivateNativeManagedPatch(info->m_activeFrame.md,
ji,
offset,
info->m_returnFrame.fp,
NULL);
return true;
}
switch (walker.GetOpcodeWalkType())
{
case WALK_RETURN:
LOG((LF_CORDB, LL_INFO10000, "DS::TS: WALK_RETURN Adding Patch.\n"));
// In the loop above, if we're at the return address, we'll check & see
// if we're returning to elsewhere within the same method, and if so,
// we'll single step rather than TrapStepOut. If we see a return in the
// code stream, then we'll set a breakpoint there, so that we can
// examine the return address, and decide whether to SS or TSO then
AddBindAndActivateNativeManagedPatch(info->m_activeFrame.md,
ji,
offset,
info->m_returnFrame.fp,
NULL);
return true;
case WALK_CALL:
LOG((LF_CORDB, LL_INFO10000, "DS::TS: WALK_CALL.\n"));
// If we're doing some sort of intra-method jump (usually, to get EIP in a clever way, via the CALL
// instruction), then put the bp where we're going, NOT at the instruction following the call
if (IsAddrWithinFrame(ji, info->m_activeFrame.md, walker.GetIP(), walker.GetNextIP()))
{
LOG((LF_CORDB, LL_INFO10000, "DS::TS: WALK_CALL IsAddrWithinFrame, Adding Patch.\n"));
// How else to detect this?
AddBindAndActivateNativeManagedPatch(info->m_activeFrame.md,
ji,
CodeRegionInfo::GetCodeRegionInfo(ji, info->m_activeFrame.md).AddressToOffset(walker.GetNextIP()),
info->m_returnFrame.fp,
NULL);
return true;
}
if (IsTailCall(walker.GetNextIP()))
{
if (!in)
{
AddBindAndActivateNativeManagedPatch(info->m_activeFrame.md,
ji,
offset,
info->m_returnFrame.fp,
NULL);
return true;
}
}
#ifdef WIN64EXCEPTIONS
fCallingIntoFunclet = IsAddrWithinMethodIncludingFunclet(ji, info->m_activeFrame.md, walker.GetNextIP());
#endif
if (in || fCallingIntoFunclet)
{
LOG((LF_CORDB, LL_INFO10000, "DS::TS: WALK_CALL step in is true\n"));
if (walker.GetNextIP() == NULL)
{
LOG((LF_CORDB, LL_INFO10000, "DS::TS: WALK_CALL NextIP == NULL\n"));
AddBindAndActivateNativeManagedPatch(info->m_activeFrame.md,
ji,
offset,
info->m_returnFrame.fp,
NULL);
LOG((LF_CORDB,LL_INFO10000,"DS0x%x m_reason=STEP_CALL 2\n",
this));
m_reason = STEP_CALL;
return true;
}
if (TrapStepInHelper(info, walker.GetNextIP(), walker.GetSkipIP(), fCallingIntoFunclet))
{
return true;
}
}
LOG((LF_CORDB, LL_INFO10000, "DS::TS: WALK_CALL Calling GetSkipIP\n"));
if (walker.GetSkipIP() == NULL)
{
AddBindAndActivateNativeManagedPatch(info->m_activeFrame.md,
ji,
offset,
info->m_returnFrame.fp,
NULL);
LOG((LF_CORDB,LL_INFO10000,"DS 0x%x m_reason=STEP_CALL4\n",this));
m_reason = STEP_CALL;
return true;
}
walker.Skip();
LOG((LF_CORDB, LL_INFO10000, "DS::TS: skipping over call.\n"));
break;
default:
if (walker.GetNextIP() == NULL)
{
AddBindAndActivateNativeManagedPatch(info->m_activeFrame.md,
ji,
offset,
info->m_returnFrame.fp,
NULL);
return true;
}
walker.Next();
break;
}
}
LOG((LF_CORDB,LL_INFO1000,"Ending TrapStep\n"));
}
bool DebuggerStepper::IsAddrWithinFrame(DebuggerJitInfo *dji,
MethodDesc* pMD,
const BYTE* currentAddr,
const BYTE* targetAddr)
{
_ASSERTE(dji != NULL);
bool result = IsAddrWithinMethodIncludingFunclet(dji, pMD, targetAddr);
// We need to check if this is a recursive call. In RTM we should see if this method is really necessary,
// since it looks like the X86 JIT doesn't emit intra-method jumps anymore.
if (result)
{
if ((CORDB_ADDRESS)(SIZE_T)targetAddr == dji->m_addrOfCode)
{
result = false;
}
}
#if defined(WIN64EXCEPTIONS)
// On WIN64, we also check whether the targetAddr and the currentAddr is in the same funclet.
_ASSERTE(currentAddr != NULL);
if (result)
{
int currentFuncletIndex = dji->GetFuncletIndex((CORDB_ADDRESS)currentAddr, DebuggerJitInfo::GFIM_BYADDRESS);
int targetFuncletIndex = dji->GetFuncletIndex((CORDB_ADDRESS)targetAddr, DebuggerJitInfo::GFIM_BYADDRESS);
result = (currentFuncletIndex == targetFuncletIndex);
}
#endif // WIN64EXCEPTIONS
return result;
}
// x86 shouldn't need to call this method directly. We should call IsAddrWithinFrame() on x86 instead.
// That's why I use a name with the word "funclet" in it to scare people off.
bool DebuggerStepper::IsAddrWithinMethodIncludingFunclet(DebuggerJitInfo *dji,
MethodDesc* pMD,
const BYTE* targetAddr)
{
_ASSERTE(dji != NULL);
return CodeRegionInfo::GetCodeRegionInfo(dji, pMD).IsMethodAddress(targetAddr);
}
void DebuggerStepper::TrapStepNext(ControllerStackInfo *info)
{
LOG((LF_CORDB, LL_INFO10000, "DS::TrapStepNext, this=%p\n", this));
// StepNext for a Normal stepper is just a step-out
TrapStepOut(info);
// @todo -should we also EnableTraceCall??
}
// Is this frame interesting?
// For a traditional stepper, all frames are interesting.
bool DebuggerStepper::IsInterestingFrame(FrameInfo * pFrame)
{
LIMITED_METHOD_CONTRACT;
return true;
}
// Place a single patch somewhere up the stack to do a step-out
void DebuggerStepper::TrapStepOut(ControllerStackInfo *info, bool fForceTraditional)
{
ControllerStackInfo returnInfo;
DebuggerJitInfo *dji;
LOG((LF_CORDB, LL_INFO10000, "DS::TSO this:0x%p\n", this));
bool fReturningFromFinallyFunclet = false;
#if defined(WIN64EXCEPTIONS)
// When we step out of a funclet, we should do one of two things, depending
// on the original stepping intention:
// 1) If we originally want to step out, then we should skip the parent method.
// 2) If we originally want to step in/over but we step off the end of the funclet,
// then we should resume in the parent, if possible.
if (info->m_activeFrame.IsNonFilterFuncletFrame())
{
// There should always be a frame for the parent method.
_ASSERTE(info->HasReturnFrame());
#ifdef _TARGET_ARM_
while (info->HasReturnFrame() && info->m_activeFrame.md != info->m_returnFrame.md)
{
StackTraceTicket ticket(info);
returnInfo.GetStackInfo(ticket, GetThread(), info->m_returnFrame.fp, NULL);
info = &returnInfo;
}
_ASSERTE(info->HasReturnFrame());
#endif
_ASSERTE(info->m_activeFrame.md == info->m_returnFrame.md);
if (m_eMode == cStepOut)
{
StackTraceTicket ticket(info);
returnInfo.GetStackInfo(ticket, GetThread(), info->m_returnFrame.fp, NULL);
info = &returnInfo;
}
else
{
_ASSERTE(info->m_returnFrame.managed);
_ASSERTE(info->m_returnFrame.frame == NULL);
MethodDesc *md = info->m_returnFrame.md;
dji = info->m_returnFrame.GetJitInfoFromFrame();
// The return value of a catch funclet is the control PC to resume to.
// The return value of a finally funclet has no meaning, so we need to check
// if the return value is in the main method.
LPVOID resumePC = GetRegdisplayReturnValue(&(info->m_activeFrame.registers));
// For finally funclet, there are two possible situations. Either the finally is
// called normally (i.e. no exception), in which case we simply fall through and
// let the normal loop do its work below, or the finally is called by the EH
// routines, in which case we need the unwind notification.
if (IsAddrWithinMethodIncludingFunclet(dji, md, (const BYTE *)resumePC))
{
SIZE_T reloffset = dji->m_codeRegionInfo.AddressToOffset((BYTE*)resumePC);
AddBindAndActivateNativeManagedPatch(info->m_returnFrame.md,
dji,
reloffset,
info->m_returnFrame.fp,
NULL);
LOG((LF_CORDB, LL_INFO10000,
"DS::TSO:normally managed code AddPatch"
" in %s::%s, offset 0x%x, m_reason=%d\n",
info->m_returnFrame.md->m_pszDebugClassName,
info->m_returnFrame.md->m_pszDebugMethodName,
reloffset, m_reason));
// Do not set m_reason to STEP_RETURN here. Logically, the funclet and the parent method are the
// same method, so we should not "return" to the parent method.
LOG((LF_CORDB, LL_INFO10000,"DS::TSO: done\n"));
return;
}
else
{
// This is the case where we step off the end of a finally funclet.
fReturningFromFinallyFunclet = true;
}
}
}
#endif // WIN64EXCEPTIONS
#ifdef _DEBUG
FramePointer dbgLastFP; // for debug, make sure we're making progress through the stack.
#endif
while (info->HasReturnFrame())
{
#ifdef _DEBUG
dbgLastFP = info->m_activeFrame.fp;
#endif
// Continue walking up the stack & set a patch upon the next
// frame up. We will eventually either hit managed code
// (which we can set a definite patch in), or the top of the
// stack.
StackTraceTicket ticket(info);
// The last parameter here is part of a really targetted (*cough* dirty) fix to
// disable getting an unwanted UMChain to fix issue 650903 (See
// code:ControllerStackInfo::WalkStack and code:TrackUMChain for the other
// parts.) In the case of managed step out we know that we aren't interested in
// unmanaged frames, and generating that unmanaged frame causes the stackwalker
// not to report the managed frame that was at the same SP. However the unmanaged
// frame might be used in the mixed-mode step out case so I don't suppress it
// there.
returnInfo.GetStackInfo(ticket, GetThread(), info->m_returnFrame.fp, NULL, !(m_rgfMappingStop & STOP_UNMANAGED));
info = &returnInfo;
#ifdef _DEBUG
// If this assert fires, then it means that we're not making progress while
// tracing up the towards the root of the stack. Likely an issue in the Left-Side's
// stackwalker.
_ASSERTE(IsCloserToLeaf(dbgLastFP, info->m_activeFrame.fp));
#endif
#ifdef FEATURE_STUBS_AS_IL
if (info->m_activeFrame.md->IsILStub() && info->m_activeFrame.md->AsDynamicMethodDesc()->IsMulticastStub())
{
LOG((LF_CORDB, LL_INFO10000,
"DS::TSO: multicast frame.\n"));
// User break should always be called from managed code, so it should never actually hit this codepath.
_ASSERTE(GetDCType() != DEBUGGER_CONTROLLER_USER_BREAKPOINT);
// JMC steppers shouldn't be patching stubs.
if (DEBUGGER_CONTROLLER_JMC_STEPPER == this->GetDCType())
{
LOG((LF_CORDB, LL_INFO10000, "DS::TSO: JMC stepper skipping frame.\n"));
continue;
}
TraceDestination trace;
EnableTraceCall(info->m_activeFrame.fp);
PCODE ip = GetControlPC(&(info->m_activeFrame.registers));
if (g_pEEInterface->TraceStub((BYTE*)ip, &trace)
&& g_pEEInterface->FollowTrace(&trace)
&& PatchTrace(&trace, info->m_activeFrame.fp,
true))
break;
}
else
#endif // FEATURE_STUBS_AS_IL
if (info->m_activeFrame.managed)
{
LOG((LF_CORDB, LL_INFO10000,
"DS::TSO: return frame is managed.\n"));
if (info->m_activeFrame.frame == NULL)
{
// Returning normally to managed code.
_ASSERTE(info->m_activeFrame.md != NULL);
// Polymorphic check to skip over non-interesting frames.
if (!fForceTraditional && !this->IsInterestingFrame(&info->m_activeFrame))
continue;
dji = info->m_activeFrame.GetJitInfoFromFrame();
_ASSERTE(dji != NULL);
// Note: we used to pass in the IP from the active frame to GetJitInfo, but there seems to be no value
// in that, and it was causing problems creating a stepper while sitting in ndirect stubs after we'd
// returned from the unmanaged function that had been called.
ULONG reloffset = info->m_activeFrame.relOffset;
AddBindAndActivateNativeManagedPatch(info->m_activeFrame.md,
dji,
reloffset,
info->m_returnFrame.fp,
NULL);
LOG((LF_CORDB, LL_INFO10000,
"DS::TSO:normally managed code AddPatch"
" in %s::%s, offset 0x%x, m_reason=%d\n",
info->m_activeFrame.md->m_pszDebugClassName,
info->m_activeFrame.md->m_pszDebugMethodName,
reloffset, m_reason));
// Do not set m_reason to STEP_RETURN here. Logically, the funclet and the parent method are the
// same method, so we should not "return" to the parent method.
if (!fReturningFromFinallyFunclet)
{
m_reason = STEP_RETURN;
}
break;
}
else if (info->m_activeFrame.frame == FRAME_TOP)
{
// Trad-stepper's step-out is actually like a step-next when we go off the top.
// JMC-steppers do a true-step out. So for JMC-steppers, don't enable trace-call.
if (DEBUGGER_CONTROLLER_JMC_STEPPER == this->GetDCType())
{
LOG((LF_CORDB, LL_EVERYTHING, "DS::TSO: JMC stepper skipping exit-frame case.\n"));
break;
}
// User break should always be called from managed code, so it should never actually hit this codepath.
_ASSERTE(GetDCType() != DEBUGGER_CONTROLLER_USER_BREAKPOINT);
// We're walking off the top of the stack. Note that if we call managed code again,
// this trace-call will cause us our stepper-to fire. So we'll actually do a
// step-next; not a true-step out.
EnableTraceCall(info->m_activeFrame.fp);
LOG((LF_CORDB, LL_INFO1000, "DS::TSO: Off top of frame!\n"));
m_reason = STEP_EXIT; //we're on the way out..
// <REVISIT_TODO>@todo not that it matters since we don't send a
// stepComplete message to the right side.</REVISIT_TODO>
break;
}
else if (info->m_activeFrame.frame->GetFrameType() == Frame::TYPE_FUNC_EVAL)
{
// Note: we treat walking off the top of the stack and
// walking off the top of a func eval the same way,
// except that we don't enable trace call since we
// know exactly where were going.
LOG((LF_CORDB, LL_INFO1000,
"DS::TSO: Off top of func eval!\n"));
m_reason = STEP_EXIT;
break;
}
else if (info->m_activeFrame.frame->GetFrameType() == Frame::TYPE_SECURITY &&
info->m_activeFrame.frame->GetInterception() == Frame::INTERCEPTION_NONE)
{
// If we're stepping out of something that was protected by (declarative) security,
// the security subsystem may leave a frame on the stack to cache it's computation.
// HOWEVER, this isn't a real frame, and so we don't want to stop here. On the other
// hand, if we're in the security goop (sec. executes managed code to do stuff), then
// we'll want to use the "returning to stub case", below. GetInterception()==NONE
// indicates that the frame is just a cache frame:
// Skip it and keep on going
LOG((LF_CORDB, LL_INFO10000,
"DS::TSO: returning to a non-intercepting frame. Keep unwinding\n"));
continue;
}
else
{
LOG((LF_CORDB, LL_INFO10000,
"DS::TSO: returning to a stub frame.\n"));
// User break should always be called from managed code, so it should never actually hit this codepath.
_ASSERTE(GetDCType() != DEBUGGER_CONTROLLER_USER_BREAKPOINT);
// JMC steppers shouldn't be patching stubs.
if (DEBUGGER_CONTROLLER_JMC_STEPPER == this->GetDCType())
{
LOG((LF_CORDB, LL_INFO10000, "DS::TSO: JMC stepper skipping frame.\n"));
continue;
}
// We're returning to some funky frame.
// (E.g. a security frame has called a native method.)
// Patch the frame from entering other methods. This effectively gives the Step-out
// a step-next behavior. For eg, this can be useful for step-out going between multicast delegates.
// This step-next could actually land us leaf-more on the callstack than we currently are!
// If we were a true-step out, we'd skip this and keep crawling.
// up the callstack.
//
// !!! For now, we assume that the TraceFrame entry
// point is smart enough to tell where it is in the
// calling sequence. We'll see how this holds up.
TraceDestination trace;
// We don't want notifications of trace-calls leaf-more than our current frame.
// For eg, if our current frame calls out to unmanaged code and then back in,
// we'll get a TraceCall notification. But since it's leaf-more than our current frame,
// we don't care because we just want to step out of our current frame (and everything
// our current frame may call).
EnableTraceCall(info->m_activeFrame.fp);
CONTRACT_VIOLATION(GCViolation); // TraceFrame GC-triggers
if (g_pEEInterface->TraceFrame(GetThread(),
info->m_activeFrame.frame, FALSE,
&trace, &(info->m_activeFrame.registers))
&& g_pEEInterface->FollowTrace(&trace)
&& PatchTrace(&trace, info->m_activeFrame.fp,
true))
break;
// !!! Problem: we don't know which return frame to use -
// the TraceFrame patch may be in a frame below the return
// frame, or in a frame parallel with it
// (e.g. prestub popping itself & then calling.)
//
// For now, I've tweaked the FP comparison in the
// patch dispatching code to allow either case.
}
}
else
{
LOG((LF_CORDB, LL_INFO10000,
"DS::TSO: return frame is not managed.\n"));
// Only step out to unmanaged code if we're actually
// marked to stop in unamanged code. Otherwise, just loop
// to get us past the unmanaged frames.
if (m_rgfMappingStop & STOP_UNMANAGED)
{
LOG((LF_CORDB, LL_INFO10000,
"DS::TSO: return to unmanaged code "
"m_reason=STEP_RETURN\n"));
// Do not set m_reason to STEP_RETURN here. Logically, the funclet and the parent method are the
// same method, so we should not "return" to the parent method.
if (!fReturningFromFinallyFunclet)
{
m_reason = STEP_RETURN;
}
// We're stepping out into unmanaged code
LOG((LF_CORDB, LL_INFO10000,
"DS::TSO: Setting unmanaged trace patch at 0x%x(%x)\n",
GetControlPC(&(info->m_activeFrame.registers)),
info->m_returnFrame.fp.GetSPValue()));
AddAndActivateNativePatchForAddress((CORDB_ADDRESS_TYPE *)GetControlPC(&(info->m_activeFrame.registers)),
info->m_returnFrame.fp,
FALSE,
TRACE_UNMANAGED);
break;
}
}
}
// <REVISIT_TODO>If we get here, we may be stepping out of the last frame. Our thread
// exit logic should catch this case. (@todo)</REVISIT_TODO>
LOG((LF_CORDB, LL_INFO10000,"DS::TSO: done\n"));
}
// void DebuggerStepper::StepOut()
// Called by Debugger::HandleIPCEvent to setup
// everything so that the process will step over the range of IL
// correctly.
// How: Converts the provided array of ranges from IL ranges to
// native ranges (if they're not native already), and then calls
// TrapStep or TrapStepOut, like so:
// Get the appropriate MethodDesc & JitInfo
// Iterate through array of IL ranges, use
// JitInfo::MapILRangeToMapEntryRange to translate IL to native
// ranges.
// Set member variables to remember that the DebuggerStepper now uses
// the ranges: m_range, m_rangeCount, m_stepIn, m_fp
// If (!TrapStep()) then {m_stepIn = true; TrapStepOut()}
// EnableUnwind( m_fp );
void DebuggerStepper::StepOut(FramePointer fp, StackTraceTicket ticket)
{
LOG((LF_CORDB, LL_INFO10000, "Attempting to step out, fp:0x%x this:0x%x"
"\n", fp.GetSPValue(), this ));
Thread *thread = GetThread();
CONTEXT *context = g_pEEInterface->GetThreadFilterContext(thread);
ControllerStackInfo info;
// We pass in the ticket b/c this is called both when we're live (via
// DebuggerUserBreakpoint) and when we're stopped (via normal StepOut)
info.GetStackInfo(ticket, thread, fp, context);
ResetRange();
m_stepIn = FALSE;
m_fp = info.m_activeFrame.fp;
#if defined(WIN64EXCEPTIONS)
// We need to remember the parent method frame pointer here so that we will recognize
// the range of the stepper as being valid when we return to the parent method.
if (info.m_activeFrame.IsNonFilterFuncletFrame())
{
m_fpParentMethod = info.m_returnFrame.fp;
}
#endif // WIN64EXCEPTIONS
m_eMode = cStepOut;
_ASSERTE((fp == LEAF_MOST_FRAME) || (info.m_activeFrame.md != NULL) || (info.m_returnFrame.md != NULL));
TrapStepOut(&info);
EnableUnwind(m_fp);
}
#define GROW_RANGES_IF_NECESSARY() \
if (rTo == rToEnd) \
{ \
ULONG NewSize, OldSize; \
if (!ClrSafeInt<ULONG>::multiply(sizeof(COR_DEBUG_STEP_RANGE), (ULONG)(realRangeCount*2), NewSize) || \
!ClrSafeInt<ULONG>::multiply(sizeof(COR_DEBUG_STEP_RANGE), (ULONG)realRangeCount, OldSize) || \
NewSize < OldSize) \
{ \
DeleteInteropSafe(m_range); \
m_range = NULL; \
return false; \
} \
COR_DEBUG_STEP_RANGE *_pTmp = (COR_DEBUG_STEP_RANGE*) \
g_pDebugger->GetInteropSafeHeap()->Realloc(m_range, \
NewSize, \
OldSize); \
\
if (_pTmp == NULL) \
{ \
DeleteInteropSafe(m_range); \
m_range = NULL; \
return false; \
} \
\
m_range = _pTmp; \
rTo = m_range + realRangeCount; \
rToEnd = m_range + (realRangeCount*2); \
realRangeCount *= 2; \
}
//-----------------------------------------------------------------------------
// Given a set of IL ranges, convert them to native and cache them.
// Return true on success, false on error.
//-----------------------------------------------------------------------------
bool DebuggerStepper::SetRangesFromIL(DebuggerJitInfo *dji, COR_DEBUG_STEP_RANGE *ranges, SIZE_T rangeCount)
{
CONTRACTL
{
SO_NOT_MAINLINE;
WRAPPER(THROWS);
GC_NOTRIGGER;
PRECONDITION(ThisIsHelperThreadWorker()); // Only help initializes a stepper.
PRECONDITION(m_range == NULL); // shouldn't be set already.
PRECONDITION(CheckPointer(ranges));
PRECONDITION(CheckPointer(dji));
}
CONTRACTL_END;
// Note: we used to pass in the IP from the active frame to GetJitInfo, but there seems to be no value in that, and
// it was causing problems creating a stepper while sitting in ndirect stubs after we'd returned from the unmanaged
// function that had been called.
MethodDesc *fd = dji->m_fd;
// The "+1" is for internal use, when we need to
// set an intermediate patch in pitched code. Isn't
// used unless the method is pitched & a patch is set
// inside it. Thus we still pass cRanges as the
// range count.
m_range = new (interopsafe) COR_DEBUG_STEP_RANGE[rangeCount+1];
if (m_range == NULL)
return false;
TRACE_ALLOC(m_range);
SIZE_T realRangeCount = rangeCount;
if (dji != NULL)
{
LOG((LF_CORDB,LL_INFO10000,"DeSt::St: For code md=0x%x, got DJI 0x%x, from 0x%x to 0x%x\n",
fd,
dji, dji->m_addrOfCode, (ULONG)dji->m_addrOfCode
+ (ULONG)dji->m_sizeOfCode));
//
// Map ranges to native offsets for jitted code
//
COR_DEBUG_STEP_RANGE *r, *rEnd, *rTo, *rToEnd;
r = ranges;
rEnd = r + rangeCount;
rTo = m_range;
rToEnd = rTo + realRangeCount;
// <NOTE>
// rTo may also be incremented in the middle of the loop on WIN64 platforms.
// </NOTE>
for (/**/; r < rEnd; r++, rTo++)
{
// If we are already at the end of our allocated array, but there are still
// more ranges to copy over, then grow the array.
GROW_RANGES_IF_NECESSARY();
if (r->startOffset == 0 && r->endOffset == (ULONG) ~0)
{
// {0...-1} means use the entire method as the range
// Code dup'd from below case.
LOG((LF_CORDB, LL_INFO10000, "DS:Step: Have DJI, special (0,-1) entry\n"));
rTo->startOffset = 0;
rTo->endOffset = (ULONG32)g_pEEInterface->GetFunctionSize(fd);
}
else
{
//
// One IL range may consist of multiple
// native ranges.
//
DebuggerILToNativeMap *mStart, *mEnd;
dji->MapILRangeToMapEntryRange(r->startOffset,
r->endOffset,
&mStart,
&mEnd);
// Either mStart and mEnd are both NULL (we don't have any sequence point),
// or they are both non-NULL.
_ASSERTE( ((mStart == NULL) && (mEnd == NULL)) ||
((mStart != NULL) && (mEnd != NULL)) );
if (mStart == NULL)
{
// <REVISIT_TODO>@todo Won't this result in us stepping across
// the entire method?</REVISIT_TODO>
rTo->startOffset = 0;
rTo->endOffset = 0;
}
else if (mStart == mEnd)
{
rTo->startOffset = mStart->nativeStartOffset;
rTo->endOffset = mStart->nativeEndOffset;
}
else
{
// Account for more than one continuous range here.
// Move the pointer back to work with the loop increment below.
// Don't dereference this pointer now!
rTo--;
for (DebuggerILToNativeMap* pMap = mStart;
pMap <= mEnd;
pMap = pMap + 1)
{
if ((pMap == mStart) ||
(pMap->nativeStartOffset != (pMap-1)->nativeEndOffset))
{
rTo++;
GROW_RANGES_IF_NECESSARY();
rTo->startOffset = pMap->nativeStartOffset;
rTo->endOffset = pMap->nativeEndOffset;
}
else
{
// If we have continuous ranges, then lump them together.
_ASSERTE(rTo->endOffset == pMap->nativeStartOffset);
rTo->endOffset = pMap->nativeEndOffset;
}
}
LOG((LF_CORDB, LL_INFO10000, "DS:Step: nat off:0x%x to 0x%x\n", rTo->startOffset, rTo->endOffset));
}
}
}
rangeCount = (int)((BYTE*)rTo - (BYTE*)m_range) / sizeof(COR_DEBUG_STEP_RANGE);
}
else
{
// Even if we don't have debug info, we'll be able to
// step through the method
SIZE_T functionSize = g_pEEInterface->GetFunctionSize(fd);
COR_DEBUG_STEP_RANGE *r = ranges;
COR_DEBUG_STEP_RANGE *rEnd = r + rangeCount;
COR_DEBUG_STEP_RANGE *rTo = m_range;
for(/**/; r < rEnd; r++, rTo++)
{
if (r->startOffset == 0 && r->endOffset == (ULONG) ~0)
{
LOG((LF_CORDB, LL_INFO10000, "DS:Step:No DJI, (0,-1) special entry\n"));
// Code dup'd from above case.
// {0...-1} means use the entire method as the range
rTo->startOffset = 0;
rTo->endOffset = (ULONG32)functionSize;
}
else
{
LOG((LF_CORDB, LL_INFO10000, "DS:Step:No DJI, regular entry\n"));
// We can't just leave ths IL entry - we have to
// get rid of it.
// This will just be ignored
rTo->startOffset = rTo->endOffset = (ULONG32)functionSize;
}
}
}
m_rangeCount = rangeCount;
m_realRangeCount = rangeCount;
return true;
}
// void DebuggerStepper::Step() Tells the stepper to step over
// the provided ranges.
// void *fp: frame pointer.
// bool in: true if we want to step into a function within the range,
// false if we want to step over functions within the range.
// COR_DEBUG_STEP_RANGE *ranges: Assumed to be nonNULL, it will
// always hold at least one element.
// SIZE_T rangeCount: One less than the true number of elements in
// the ranges argument.
// bool rangeIL: true if the ranges are provided in IL (they'll be
// converted to native before the DebuggerStepper uses them,
// false if they already are native.
bool DebuggerStepper::Step(FramePointer fp, bool in,
COR_DEBUG_STEP_RANGE *ranges, SIZE_T rangeCount,
bool rangeIL)
{
LOG((LF_CORDB, LL_INFO1000, "DeSt:Step this:0x%x ", this));
if (rangeCount>0)
LOG((LF_CORDB,LL_INFO10000," start,end[0]:(0x%x,0x%x)\n",
ranges[0].startOffset, ranges[0].endOffset));
else
LOG((LF_CORDB,LL_INFO10000," single step\n"));
Thread *thread = GetThread();
CONTEXT *context = g_pEEInterface->GetThreadFilterContext(thread);
// ControllerStackInfo doesn't report IL stubs, so if we are in an IL stub, we need
// to handle the single-step specially. There are probably other problems when we stop
// in an IL stub. We need to revisit this later.
bool fIsILStub = false;
if ((context != NULL) &&
g_pEEInterface->IsManagedNativeCode(reinterpret_cast<const BYTE *>(GetIP(context))))
{
MethodDesc * pMD = g_pEEInterface->GetNativeCodeMethodDesc(GetIP(context));
if (pMD != NULL)
{
fIsILStub = pMD->IsILStub();
}
}
LOG((LF_CORDB, LL_INFO10000, "DS::S - fIsILStub = %d\n", fIsILStub));
ControllerStackInfo info;
StackTraceTicket ticket(thread);
info.GetStackInfo(ticket, thread, fp, context);
_ASSERTE((fp == LEAF_MOST_FRAME) || (info.m_activeFrame.md != NULL) ||
(info.m_returnFrame.md != NULL));
m_stepIn = in;
DebuggerJitInfo *dji = info.m_activeFrame.GetJitInfoFromFrame();
if (dji == NULL)
{
// !!! ERROR range step in frame with no code
ranges = NULL;
rangeCount = 0;
}
if (m_range != NULL)
{
TRACE_FREE(m_range);
DeleteInteropSafe(m_range);
m_range = NULL;
m_rangeCount = 0;
m_realRangeCount = 0;
}
if (rangeCount > 0)
{
if (rangeIL)
{
// IL ranges supplied, we need to convert them to native ranges.
bool fOk = SetRangesFromIL(dji, ranges, rangeCount);
if (!fOk)
{
return false;
}
}
else
{
// Native ranges, already supplied. Just copy them over.
m_range = new (interopsafe) COR_DEBUG_STEP_RANGE[rangeCount];
if (m_range == NULL)
{
return false;
}
memcpy(m_range, ranges, sizeof(COR_DEBUG_STEP_RANGE) * rangeCount);
m_realRangeCount = m_rangeCount = rangeCount;
}
_ASSERTE(m_range != NULL);
_ASSERTE(m_rangeCount > 0);
_ASSERTE(m_realRangeCount > 0);
}
else
{
// !!! ERROR cannot map IL ranges
ranges = NULL;
rangeCount = 0;
}
if (fIsILStub)
{
// Don't use the ControllerStackInfo if we are in an IL stub.
m_fp = fp;
}
else
{
m_fp = info.m_activeFrame.fp;
#if defined(WIN64EXCEPTIONS)
// We need to remember the parent method frame pointer here so that we will recognize
// the range of the stepper as being valid when we return to the parent method.
if (info.m_activeFrame.IsNonFilterFuncletFrame())
{
m_fpParentMethod = info.m_returnFrame.fp;
}
#endif // WIN64EXCEPTIONS
}
m_eMode = m_stepIn ? cStepIn : cStepOver;
LOG((LF_CORDB,LL_INFO10000,"DS 0x%x STep: STEP_NORMAL\n",this));
m_reason = STEP_NORMAL; //assume it'll be a normal step & set it to
//something else if we walk over it
if (fIsILStub)
{
LOG((LF_CORDB, LL_INFO10000, "DS:Step: stepping in an IL stub\n"));
// Enable the right triggers if the user wants to step in.
if (in)
{
if (this->GetDCType() == DEBUGGER_CONTROLLER_STEPPER)
{
EnableTraceCall(info.m_activeFrame.fp);
}
else if (this->GetDCType() == DEBUGGER_CONTROLLER_JMC_STEPPER)
{
EnableMethodEnter();
}
}
// Also perform a step-out in case this IL stub is returning to managed code.
// However, we must fix up the ControllerStackInfo first, since it doesn't
// report IL stubs. The active frame reported by the ControllerStackInfo is
// actually the return frame in this case.
info.SetReturnFrameWithActiveFrame();
TrapStepOut(&info);
}
else if (!TrapStep(&info, in))
{
LOG((LF_CORDB,LL_INFO10000,"DS:Step: Did TS\n"));
m_stepIn = true;
TrapStepNext(&info);
}
LOG((LF_CORDB,LL_INFO10000,"DS:Step: Did TS,TSO\n"));
EnableUnwind(m_fp);
return true;
}
// TP_RESULT DebuggerStepper::TriggerPatch()
// What: Triggers patch if we're not in a stub, and we're
// outside of the stepping range. Otherwise sets another patch so as to
// step out of the stub, or in the next instruction within the range.
// How: If module==NULL & managed==> we're in a stub:
// TrapStepOut() and return false. Module==NULL&!managed==> return
// true. If m_range != NULL & execution is currently in the range,
// attempt a TrapStep (TrapStepOut otherwise) & return false. Otherwise,
// return true.
TP_RESULT DebuggerStepper::TriggerPatch(DebuggerControllerPatch *patch,
Thread *thread,
TRIGGER_WHY tyWhy)
{
LOG((LF_CORDB, LL_INFO10000, "DeSt::TP\n"));
// If we're frozen, we may hit a patch but we just ignore it
if (IsFrozen())
{
LOG((LF_CORDB, LL_INFO1000000, "DS::TP, ignoring patch at %p during frozen state\n", patch->address));
return TPR_IGNORE;
}
Module *module = patch->key.module;
BOOL managed = patch->IsManagedPatch();
mdMethodDef md = patch->key.md;
SIZE_T offset = patch->offset;
_ASSERTE((this->GetThread() == thread) || !"Stepper should only get patches on its thread");
// Note we can only run a stack trace if:
// - the context is in managed code (eg, not a stub)
// - OR we have a frame in place to prime the stackwalk.
ControllerStackInfo info;
CONTEXT *context = g_pEEInterface->GetThreadFilterContext(thread);
_ASSERTE(!ISREDIRECTEDTHREAD(thread));
// Context should always be from patch.
_ASSERTE(context != NULL);
bool fSafeToDoStackTrace = true;
// If we're in a stub (module == NULL and still in managed code), then our context is off in lala-land
// Then, it's only safe to do a stackwalk if the top frame is protecting us. That's only true for a
// frame_push. If we're here on a manager_push, then we don't have any such protection, so don't do the
// stackwalk.
fSafeToDoStackTrace = patch->IsSafeForStackTrace();
if (fSafeToDoStackTrace)
{
StackTraceTicket ticket(patch);
info.GetStackInfo(ticket, thread, LEAF_MOST_FRAME, context);
LOG((LF_CORDB, LL_INFO10000, "DS::TP: this:0x%p in %s::%s (fp:0x%p, "
"off:0x%p md:0x%p), \n\texception source:%s::%s (fp:0x%p)\n",
this,
info.m_activeFrame.md!=NULL?info.m_activeFrame.md->m_pszDebugClassName:"Unknown",
info.m_activeFrame.md!=NULL?info.m_activeFrame.md->m_pszDebugMethodName:"Unknown",
info.m_activeFrame.fp.GetSPValue(), patch->offset, patch->key.md,
m_fdException!=NULL?m_fdException->m_pszDebugClassName:"None",
m_fdException!=NULL?m_fdException->m_pszDebugMethodName:"None",
m_fpException.GetSPValue()));
}
DisableAll();
if (DetectHandleLCGMethods(dac_cast<PCODE>(patch->address), NULL, &info))
{
return TPR_IGNORE;
}
if (module == NULL)
{
// JMC steppers should not be patching here...
_ASSERTE(DEBUGGER_CONTROLLER_JMC_STEPPER != this->GetDCType());
if (managed)
{
LOG((LF_CORDB, LL_INFO10000,
"Frame (stub) patch hit at offset 0x%x\n", offset));
// This is a stub patch. If it was a TRACE_FRAME_PUSH that
// got us here, then the stub's frame is pushed now, so we
// tell the frame to apply the real patch. If we got here
// via a TRACE_MGR_PUSH, however, then there is no frame
// and we tell the stub manager that generated the
// TRACE_MGR_PUSH to apply the real patch.
TraceDestination trace;
bool traceOk;
FramePointer frameFP;
PTR_BYTE traceManagerRetAddr = NULL;
if (patch->trace.GetTraceType() == TRACE_MGR_PUSH)
{
_ASSERTE(context != NULL);
CONTRACT_VIOLATION(GCViolation);
traceOk = g_pEEInterface->TraceManager(
thread,
patch->trace.GetStubManager(),
&trace,
context,
&traceManagerRetAddr);
// We don't hae an active frame here, so patch with a
// FP of NULL so anything will match.
//
// <REVISIT_TODO>@todo: should we take Esp out of the context?</REVISIT_TODO>
frameFP = LEAF_MOST_FRAME;
}
else
{
_ASSERTE(fSafeToDoStackTrace);
CONTRACT_VIOLATION(GCViolation); // TraceFrame GC-triggers
traceOk = g_pEEInterface->TraceFrame(thread,
thread->GetFrame(),
TRUE,
&trace,
&(info.m_activeFrame.registers));
frameFP = info.m_activeFrame.fp;
}
// Enable the JMC backstop for traditional steppers to catch us in case
// we didn't predict the call target properly.
EnableJMCBackStop(NULL);
if (!traceOk
|| !g_pEEInterface->FollowTrace(&trace)
|| !PatchTrace(&trace, frameFP,
(m_rgfMappingStop&STOP_UNMANAGED)?
(true):(false)))
{
//
// We can't set a patch in the frame -- we need
// to trap returning from this frame instead.
//
// Note: if we're in the TRACE_MGR_PUSH case from
// above, then we must place a patch where the
// TraceManager function told us to, since we can't
// actually unwind from here.
//
if (patch->trace.GetTraceType() != TRACE_MGR_PUSH)
{
_ASSERTE(fSafeToDoStackTrace);
LOG((LF_CORDB,LL_INFO10000,"TSO for non TRACE_MGR_PUSH case\n"));
TrapStepOut(&info);
}
else
{
LOG((LF_CORDB, LL_INFO10000,
"TSO for TRACE_MGR_PUSH case."));
// We'd better have a valid return address.
_ASSERTE(traceManagerRetAddr != NULL);
if (g_pEEInterface->IsManagedNativeCode(traceManagerRetAddr))
{
// Grab the jit info for the method.
DebuggerJitInfo *dji;
dji = g_pDebugger->GetJitInfoFromAddr((TADDR) traceManagerRetAddr);
MethodDesc * mdNative = (dji == NULL) ?
g_pEEInterface->GetNativeCodeMethodDesc(dac_cast<PCODE>(traceManagerRetAddr)) : dji->m_fd;
_ASSERTE(mdNative != NULL);
// Find the method that the return is to.
_ASSERTE(g_pEEInterface->GetFunctionAddress(mdNative) != NULL);
SIZE_T offsetRet = dac_cast<TADDR>(traceManagerRetAddr -
g_pEEInterface->GetFunctionAddress(mdNative));
// Place the patch.
AddBindAndActivateNativeManagedPatch(mdNative,
dji,
offsetRet,
LEAF_MOST_FRAME,
NULL);
LOG((LF_CORDB, LL_INFO10000,
"DS::TP: normally managed code AddPatch"
" in %s::%s, offset 0x%x\n",
mdNative->m_pszDebugClassName,
mdNative->m_pszDebugMethodName,
offsetRet));
}
else
{
// We're hitting this code path with MC++ assemblies
// that have an unmanaged entry point so the stub returns to CallDescrWorker.
_ASSERTE(g_pEEInterface->GetNativeCodeMethodDesc(dac_cast<PCODE>(patch->address))->IsILStub());
}
}
m_reason = STEP_NORMAL; //we tried to do a STEP_CALL, but since it didn't
//work, we're doing what amounts to a normal step.
LOG((LF_CORDB,LL_INFO10000,"DS 0x%x m_reason = STEP_NORMAL"
"(attempted call thru stub manager, SM didn't know where"
" we're going, so did a step out to original call\n",this));
}
else
{
m_reason = STEP_CALL;
}
EnableTraceCall(LEAF_MOST_FRAME);
EnableUnwind(m_fp);
return TPR_IGNORE;
}
else
{
// @todo - when would we hit this codepath?
// If we're not in managed, then we should have pushed a frame onto the Thread's frame chain,
// and thus we should still safely be able to do a stackwalk here.
_ASSERTE(fSafeToDoStackTrace);
if (DetectHandleInterceptors(&info) )
{
return TPR_IGNORE; //don't actually want to stop
}
LOG((LF_CORDB, LL_INFO10000,
"Unmanaged step patch hit at 0x%x\n", offset));
StackTraceTicket ticket(patch);
PrepareForSendEvent(ticket);
return TPR_TRIGGER;
}
} // end (module == NULL)
// If we're inside an interceptor but don't want to be,then we'll set a
// patch outside the current function.
_ASSERTE(fSafeToDoStackTrace);
if (DetectHandleInterceptors(&info) )
{
return TPR_IGNORE; //don't actually want to stop
}
LOG((LF_CORDB,LL_INFO10000, "DS: m_fp:0x%p, activeFP:0x%p fpExc:0x%p\n",
m_fp.GetSPValue(), info.m_activeFrame.fp.GetSPValue(), m_fpException.GetSPValue()));
if (IsInRange(offset, m_range, m_rangeCount, &info) ||
ShouldContinueStep( &info, offset))
{
LOG((LF_CORDB, LL_INFO10000,
"Intermediate step patch hit at 0x%x\n", offset));
if (!TrapStep(&info, m_stepIn))
TrapStepNext(&info);
EnableUnwind(m_fp);
return TPR_IGNORE;
}
else
{
LOG((LF_CORDB, LL_INFO10000, "Step patch hit at 0x%x\n", offset));
// For a JMC stepper, we have an additional constraint:
// skip non-user code. So if we're still in non-user code, then
// we've got to keep going
DebuggerMethodInfo * dmi = g_pDebugger->GetOrCreateMethodInfo(module, md);
if ((dmi != NULL) && DetectHandleNonUserCode(&info, dmi))
{
return TPR_IGNORE;
}
StackTraceTicket ticket(patch);
PrepareForSendEvent(ticket);
return TPR_TRIGGER;
}
}
// Return true if this should be skipped.
// For a non-jmc stepper, we don't care about non-user code, so we
// don't skip it and so we always return false.
bool DebuggerStepper::DetectHandleNonUserCode(ControllerStackInfo *info, DebuggerMethodInfo * pInfo)
{
LIMITED_METHOD_CONTRACT;
return false;
}
// For regular steppers, trace-call is just a trace-call.
void DebuggerStepper::EnablePolyTraceCall()
{
this->EnableTraceCall(LEAF_MOST_FRAME);
}
// Traditional steppers enable MethodEnter as a back-stop for step-in.
// We hope that the stub-managers will predict the step-in for us,
// but in case they don't the Method-Enter should catch us.
// MethodEnter is not fully correct for traditional steppers for a few reasons:
// - doesn't handle step-in to native
// - stops us *after* the prolog (a traditional stepper can stop us before the prolog).
// - only works for methods that have the JMC probe. That can exclude all optimized code.
void DebuggerStepper::TriggerMethodEnter(Thread * thread,
DebuggerJitInfo *dji,
const BYTE * ip,
FramePointer fp)
{
_ASSERTE(dji != NULL);
_ASSERTE(thread != NULL);
_ASSERTE(ip != NULL);
_ASSERTE(this->GetDCType() == DEBUGGER_CONTROLLER_STEPPER);
_ASSERTE(!IsFrozen());
MethodDesc * pDesc = dji->m_fd;
LOG((LF_CORDB, LL_INFO10000, "DJMCStepper::TME, desc=%p, addr=%p\n",
pDesc, ip));
// JMC steppers won't stop in Lightweight delegates. Just return & keep executing.
if (pDesc->IsNoMetadata())
{
LOG((LF_CORDB, LL_INFO100000, "DJMCStepper::TME, skipping b/c it's lw-codegen\n"));
return;
}
// This is really just a heuristic. We don't want to trigger a JMC probe when we are
// executing in an IL stub, or in one of the marshaling methods called by the IL stub.
// The problem is that the IL stub can call into arbitrary code, including custom marshalers.
// In that case the user has to put a breakpoint to stop in the code.
if (g_pEEInterface->DetectHandleILStubs(thread))
{
return;
}
#ifdef _DEBUG
// To help trace down if a problem is related to a stubmanager,
// we add a knob that lets us skip the MethodEnter checks. This lets tests directly
// go against the Stub-managers w/o the MethodEnter check backstops.
int fSkip = CLRConfig::GetConfigValue(CLRConfig::INTERNAL_DbgSkipMEOnStep);
if (fSkip)
{
return;
}
// See EnableJMCBackStop() for details here. This check just makes sure that we don't fire
// the assert if we end up in the method we started in (which could happen if we trace call
// instructions before the JMC probe).
// m_StepInStartMethod may be null (if this step-in didn't start from managed code).
if ((m_StepInStartMethod != pDesc) &&
(!m_StepInStartMethod->IsLCGMethod()))
{
// Since normal step-in should stop us at the prolog, and TME is after the prolog,
// if a stub-manager did successfully find the address, we should get a TriggerPatch first
// at native offset 0 (before the prolog) and before we get the TME. That means if
// we do get the TME, then there was no stub-manager to find us.
SString sLog;
StubManager::DbgGetLog(&sLog);
// Assert b/c the Stub-manager should have caught us first.
// We don't want people relying on TriggerMethodEnter as the real implementation for Traditional Step-in
// (see above for reasons why). However, using TME will provide a bandage for the final retail product
// in cases where we are missing a stub-manager.
CONSISTENCY_CHECK_MSGF(false, (
"\nThe Stubmanagers failed to identify and trace a stub on step-in. The stub-managers for this code-path path need to be fixed.\n"
"See http://team/sites/clrdev/Devdocs/StubManagers.rtf for more information on StubManagers.\n"
"Stepper this=0x%p, startMethod='%s::%s'\n"
"---------------------------------\n"
"Stub manager log:\n%S"
"\n"
"The thread is now in managed method '%s::%s'.\n"
"---------------------------------\n",
this,
((m_StepInStartMethod == NULL) ? "unknown" : m_StepInStartMethod->m_pszDebugClassName),
((m_StepInStartMethod == NULL) ? "unknown" : m_StepInStartMethod->m_pszDebugMethodName),
sLog.GetUnicode(),
pDesc->m_pszDebugClassName, pDesc->m_pszDebugMethodName
));
}
#endif
// Place a patch to stopus.
// Don't bind to a particular AppDomain so that we can do a Cross-Appdomain step.
AddBindAndActivateNativeManagedPatch(pDesc,
dji,
CodeRegionInfo::GetCodeRegionInfo(dji, pDesc).AddressToOffset(ip),
fp,
NULL // AppDomain
);
LOG((LF_CORDB, LL_INFO10000, "DJMCStepper::TME, after setting patch to stop\n"));
// Once we resume, we'll go hit that patch (duh, we patched our return address)
// Furthermore, we know the step will complete with reason = call, so set that now.
m_reason = STEP_CALL;
}
// We may have single-stepped over a return statement to land us up a frame.
// Or we may have single-stepped through a method.
// We never single-step into calls (we place a patch at the call destination).
bool DebuggerStepper::TriggerSingleStep(Thread *thread, const BYTE *ip)
{
LOG((LF_CORDB,LL_INFO10000,"DS:TSS this:0x%x, @ ip:0x%x\n", this, ip));
_ASSERTE(!IsFrozen());
// User break should only do a step-out and never actually need a singlestep flag.
_ASSERTE(GetDCType() != DEBUGGER_CONTROLLER_USER_BREAKPOINT);
//
// there's one weird case here - if the last instruction generated
// a hardware exception, we may be in lala land. If so, rely on the unwind
// handler to figure out what happened.
//
// <REVISIT_TODO>@todo this could be wrong when we have the incremental collector going</REVISIT_TODO>
//
if (!g_pEEInterface->IsManagedNativeCode(ip))
{
LOG((LF_CORDB,LL_INFO10000, "DS::TSS: not in managed code, Returning false (case 0)!\n"));
DisableSingleStep();
return false;
}
// If we EnC the method, we'll blast the function address,
// and so have to get it from teh DJI that we'll have. If
// we haven't gotten debugger info about a regular function, then
// we'll have to get the info from the EE, which will be valid
// since we're standing in the function at this point, and
// EnC couldn't have happened yet.
MethodDesc *fd = g_pEEInterface->GetNativeCodeMethodDesc((PCODE)ip);
SIZE_T offset;
DebuggerJitInfo *dji = g_pDebugger->GetJitInfoFromAddr((TADDR) ip);
offset = CodeRegionInfo::GetCodeRegionInfo(dji, fd).AddressToOffset(ip);
ControllerStackInfo info;
// Safe to stackwalk b/c we've already checked that our IP is in crawlable code.
StackTraceTicket ticket(ip);
info.GetStackInfo(ticket, GetThread(), LEAF_MOST_FRAME, NULL);
// This is a special case where we return from a managed method back to an IL stub. This can
// only happen if there's no more managed method frames closer to the root and we want to perform
// a step out, or if we step-next off the end of a method called by an IL stub. In either case,
// we'll get a single step in an IL stub, which we want to ignore. We also want to enable trace
// call here, just in case this IL stub is about to call the managed target (in the reverse interop case).
if (fd->IsILStub())
{
LOG((LF_CORDB,LL_INFO10000, "DS::TSS: not in managed code, Returning false (case 0)!\n"));
if (this->GetDCType() == DEBUGGER_CONTROLLER_STEPPER)
{
EnableTraceCall(info.m_activeFrame.fp);
}
else if (this->GetDCType() == DEBUGGER_CONTROLLER_JMC_STEPPER)
{
EnableMethodEnter();
}
DisableSingleStep();
return false;
}
DisableAll();
LOG((LF_CORDB,LL_INFO10000, "DS::TSS m_fp:0x%x, activeFP:0x%x fpExc:0x%x\n",
m_fp.GetSPValue(), info.m_activeFrame.fp.GetSPValue(), m_fpException.GetSPValue()));
if (DetectHandleLCGMethods((PCODE)ip, fd, &info))
{
return false;
}
if (IsInRange(offset, m_range, m_rangeCount, &info) ||
ShouldContinueStep( &info, offset))
{
if (!TrapStep(&info, m_stepIn))
TrapStepNext(&info);
EnableUnwind(m_fp);
LOG((LF_CORDB,LL_INFO10000, "DS::TSS: Returning false Case 1!\n"));
return false;
}
else
{
LOG((LF_CORDB,LL_INFO10000, "DS::TSS: Returning true Case 2 for reason STEP_%02x!\n", m_reason));
// @todo - when would a single-step (not a patch) land us in user-code?
// For a JMC stepper, we have an additional constraint:
// skip non-user code. So if we're still in non-user code, then
// we've got to keep going
DebuggerMethodInfo * dmi = g_pDebugger->GetOrCreateMethodInfo(fd->GetModule(), fd->GetMemberDef());
if ((dmi != NULL) && DetectHandleNonUserCode(&info, dmi))
return false;
PrepareForSendEvent(ticket);
return true;
}
}
void DebuggerStepper::TriggerTraceCall(Thread *thread, const BYTE *ip)
{
LOG((LF_CORDB,LL_INFO10000,"DS:TTC this:0x%x, @ ip:0x%x\n",this,ip));
TraceDestination trace;
if (IsFrozen())
{
LOG((LF_CORDB,LL_INFO10000,"DS:TTC exit b/c of Frozen\n"));
return;
}
// This is really just a heuristic. We don't want to trigger a JMC probe when we are
// executing in an IL stub, or in one of the marshaling methods called by the IL stub.
// The problem is that the IL stub can call into arbitrary code, including custom marshalers.
// In that case the user has to put a breakpoint to stop in the code.
if (g_pEEInterface->DetectHandleILStubs(thread))
{
return;
}
if (g_pEEInterface->TraceStub(ip, &trace)
&& g_pEEInterface->FollowTrace(&trace)
&& PatchTrace(&trace, LEAF_MOST_FRAME,
(m_rgfMappingStop&STOP_UNMANAGED)?(true):(false)))
{
// !!! We really want to know ahead of time if PatchTrace will succeed.
DisableAll();
PatchTrace(&trace, LEAF_MOST_FRAME, (m_rgfMappingStop&STOP_UNMANAGED)?
(true):(false));
// If we're triggering a trace call, and we're following a trace into either managed code or unjitted managed
// code, then we need to update our stepper's reason to STEP_CALL to reflect the fact that we're going to land
// into a new function because of a call.
if ((trace.GetTraceType() == TRACE_UNJITTED_METHOD) || (trace.GetTraceType() == TRACE_MANAGED))
{
m_reason = STEP_CALL;
}
EnableUnwind(m_fp);
LOG((LF_CORDB, LL_INFO10000, "DS::TTC potentially a step call!\n"));
}
}
void DebuggerStepper::TriggerUnwind(Thread *thread,
MethodDesc *fd, DebuggerJitInfo * pDJI, SIZE_T offset,
FramePointer fp,
CorDebugStepReason unwindReason)
{
CONTRACTL
{
SO_NOT_MAINLINE;
THROWS; // from GetJitInfo
GC_NOTRIGGER; // don't send IPC events
MODE_COOPERATIVE; // TriggerUnwind always is coop
PRECONDITION(!IsDbgHelperSpecialThread());
PRECONDITION(fd->IsDynamicMethod() || (pDJI != NULL));
}
CONTRACTL_END;
LOG((LF_CORDB,LL_INFO10000,"DS::TU this:0x%p, in %s::%s, offset 0x%p "
"frame:0x%p unwindReason:0x%x\n", this, fd->m_pszDebugClassName,
fd->m_pszDebugMethodName, offset, fp.GetSPValue(), unwindReason));
_ASSERTE(unwindReason == STEP_EXCEPTION_FILTER || unwindReason == STEP_EXCEPTION_HANDLER);
if (IsFrozen())
{
LOG((LF_CORDB,LL_INFO10000,"DS:TTC exit b/c of Frozen\n"));
return;
}
if (IsCloserToRoot(fp, GetUnwind()))
{
// Handler is in a parent frame . For all steps (in,out,over)
// we want to stop in the handler.
// This will be like a Step Out, so we don't need any range.
ResetRange();
}
else
{
// Handler/Filter is in the same frame as the stepper
// For a step-in/over, we want to patch the handler/filter.
// But for a step-out, we want to just continue executing (and don't change
// the step-reason either).
if (m_eMode == cStepOut)
{
LOG((LF_CORDB, LL_INFO10000, "DS::TU Step-out, returning for same-frame case.\n"));
return;
}
}
// Remember the origin of the exception, so that if the step looks like
// it's going to complete in a different frame, but the code comes from the
// same frame as the one we're in, we won't stop twice in the "same" range
m_fpException = fp;
m_fdException = fd;
//
// An exception is exiting the step region. Set a patch on
// the filter/handler.
//
DisableAll();
BOOL fOk;
fOk = AddBindAndActivateNativeManagedPatch(fd, pDJI, offset, LEAF_MOST_FRAME, NULL);
// Since we're unwinding to an already executed method, the method should already
// be jitted and placing the patch should work.
CONSISTENCY_CHECK_MSGF(fOk, ("Failed to place patch at TriggerUnwind.\npThis=0x%p md=0x%p, native offset=0x%x\n", this, fd, offset));
LOG((LF_CORDB,LL_INFO100000,"Step reason:%s\n", unwindReason==STEP_EXCEPTION_FILTER
? "STEP_EXCEPTION_FILTER":"STEP_EXCEPTION_HANDLER"));
m_reason = unwindReason;
}
// Prepare for sending an event.
// This is called 1:1 w/ SendEvent, but this guy can be called in a GC_TRIGGERABLE context
// whereas SendEvent is pretty strict.
// Caller ensures that it's safe to run a stack trace.
void DebuggerStepper::PrepareForSendEvent(StackTraceTicket ticket)
{
#ifdef _DEBUG
_ASSERTE(!m_fReadyToSend);
m_fReadyToSend = true;
#endif
LOG((LF_CORDB, LL_INFO10000, "DS::SE m_fpStepInto:0x%x\n", m_fpStepInto.GetSPValue()));
if (m_fpStepInto != LEAF_MOST_FRAME)
{
ControllerStackInfo csi;
csi.GetStackInfo(ticket, GetThread(), LEAF_MOST_FRAME, NULL);
if (csi.m_targetFrameFound &&
#if !defined(WIN64EXCEPTIONS)
IsCloserToRoot(m_fpStepInto, csi.m_activeFrame.fp)
#else
IsCloserToRoot(m_fpStepInto, (csi.m_activeFrame.IsNonFilterFuncletFrame() ? csi.m_returnFrame.fp : csi.m_activeFrame.fp))
#endif // WIN64EXCEPTIONS
)
{
m_reason = STEP_CALL;
LOG((LF_CORDB, LL_INFO10000, "DS::SE this:0x%x STEP_CALL!\n", this));
}
#ifdef _DEBUG
else
{
LOG((LF_CORDB, LL_INFO10000, "DS::SE this:0x%x not a step call!\n", this));
}
#endif
}
#ifdef _DEBUG
// Steppers should only stop in interesting code.
if (this->GetDCType() == DEBUGGER_CONTROLLER_JMC_STEPPER)
{
// If we're at either a patch or SS, we'll have a context.
CONTEXT *context = g_pEEInterface->GetThreadFilterContext(GetThread());
if (context == NULL)
{
void * pIP = CORDbgGetIP(reinterpret_cast<DT_CONTEXT *>(context));
DebuggerJitInfo * dji = g_pDebugger->GetJitInfoFromAddr((TADDR) pIP);
DebuggerMethodInfo * dmi = NULL;
if (dji != NULL)
{
dmi = dji->m_methodInfo;
CONSISTENCY_CHECK_MSGF(dmi->IsJMCFunction(), ("JMC stepper %p stopping in non-jmc method, MD=%p, '%s::%s'",
this, dji->m_fd, dji->m_fd->m_pszDebugClassName, dji->m_fd->m_pszDebugMethodName));
}
}
}
#endif
}
bool DebuggerStepper::SendEvent(Thread *thread, bool fIpChanged)
{
CONTRACTL
{
SO_NOT_MAINLINE;
NOTHROW;
SENDEVENT_CONTRACT_ITEMS;
}
CONTRACTL_END;
// We practically should never have a step interupted by SetIp.
// We'll still go ahead and send the Step-complete event because we've already
// deactivated our triggers by now and we haven't placed any new patches to catch us.
// We assert here because we don't believe we'll ever be able to hit this scenario.
// This is technically an issue, but we consider it benign enough to leave in.
_ASSERTE(!fIpChanged || !"Stepper interupted by SetIp");
LOG((LF_CORDB, LL_INFO10000, "DS::SE m_fpStepInto:0x%x\n", m_fpStepInto.GetSPValue()));
_ASSERTE(m_fReadyToSend);
_ASSERTE(GetThread() == thread);
CONTEXT *context = g_pEEInterface->GetThreadFilterContext(thread);
_ASSERTE(!ISREDIRECTEDTHREAD(thread));
// We need to send the stepper and delete the controller because our stepper
// no longer has any patches or other triggers that will let it send the step-complete event.
g_pDebugger->SendStep(thread, context, this, m_reason);
this->Delete();
#ifdef _DEBUG
// Now that we've sent the event, we can stop recording information.
StubManager::DbgFinishLog();
#endif
return true;
}
void DebuggerStepper::ResetRange()
{
if (m_range)
{
TRACE_FREE(m_range);
DeleteInteropSafe(m_range);
m_range = NULL;
}
}
//-----------------------------------------------------------------------------
// Return true if this stepper is alive, but frozen. (we freeze when the stepper
// enters a nested func-eval).
//-----------------------------------------------------------------------------
bool DebuggerStepper::IsFrozen()
{
return (m_cFuncEvalNesting > 0);
}
//-----------------------------------------------------------------------------
// Returns true if this stepper is 'dead' - which happens if a non-frozen stepper
// gets a func-eval exit.
//-----------------------------------------------------------------------------
bool DebuggerStepper::IsDead()
{
return (m_cFuncEvalNesting < 0);
}
// * ------------------------------------------------------------------------
// * DebuggerJMCStepper routines
// * ------------------------------------------------------------------------
DebuggerJMCStepper::DebuggerJMCStepper(Thread *thread,
CorDebugUnmappedStop rgfMappingStop,
CorDebugIntercept interceptStop,
AppDomain *appDomain) :
DebuggerStepper(thread, rgfMappingStop, interceptStop, appDomain)
{
LOG((LF_CORDB, LL_INFO10000, "DJMCStepper ctor, this=%p\n", this));
}
DebuggerJMCStepper::~DebuggerJMCStepper()
{
LOG((LF_CORDB, LL_INFO10000, "DJMCStepper dtor, this=%p\n", this));
}
// If we're a JMC stepper, then don't stop in non-user code.
bool DebuggerJMCStepper::IsInterestingFrame(FrameInfo * pFrame)
{
CONTRACTL
{
THROWS;
MODE_ANY;
GC_NOTRIGGER;
}
CONTRACTL_END;
DebuggerMethodInfo *pInfo = pFrame->GetMethodInfoFromFrameOrThrow();
_ASSERTE(pInfo != NULL); // throws on failure
bool fIsUserCode = pInfo->IsJMCFunction();
LOG((LF_CORDB, LL_INFO1000000, "DS::TSO, frame '%s::%s' is '%s' code\n",
pFrame->DbgGetClassName(), pFrame->DbgGetMethodName(),
fIsUserCode ? "user" : "non-user"));
return fIsUserCode;
}
// A JMC stepper's step-next stops at the next thing of code run.
// This may be a Step-Out, or any User code called before that.
// A1 -> B1 -> { A2, B2 -> B3 -> A3}
// So TrapStepNex at end of A2 should land us in A3.
void DebuggerJMCStepper::TrapStepNext(ControllerStackInfo *info)
{
LOG((LF_CORDB, LL_INFO10000, "DJMCStepper::TrapStepNext, this=%p\n", this));
EnableMethodEnter();
// This will place a patch up the stack and set m_reason = STEP_RETURN.
// If we end up hitting JMC before that patch, we'll hit TriggerMethodEnter
// and that will set our reason to STEP_CALL.
TrapStepOut(info);
}
// ip - target address for call instruction
bool DebuggerJMCStepper::TrapStepInHelper(
ControllerStackInfo * pInfo,
const BYTE * ipCallTarget,
const BYTE * ipNext,
bool fCallingIntoFunclet)
{
#ifndef WIN64EXCEPTIONS
// There are no funclets on x86.
_ASSERTE(!fCallingIntoFunclet);
#endif
// If we are calling into a funclet, then we can't rely on the JMC probe to stop us because there are no
// JMC probes in funclets. Instead, we have to perform a traditional step-in here.
if (fCallingIntoFunclet)
{
TraceDestination td;
td.InitForManaged(reinterpret_cast<PCODE>(ipCallTarget));
PatchTrace(&td, LEAF_MOST_FRAME, false);
// If this succeeds, then we still need to put a patch at the return address. This is done below.
// If this fails, then we definitely need to put a patch at the return address to trap the thread.
// So in either case, we have to execute the rest of this function.
}
MethodDesc * pDesc = pInfo->m_activeFrame.md;
DebuggerJitInfo *dji = NULL;
// We may not have a DJI if we're in an attach case. We should still be able to do a JMC-step in though.
// So NULL is ok here.
dji = g_pDebugger->GetJitInfo(pDesc, (const BYTE*) ipNext);
// Place patch after call, which is at ipNext. Note we don't need an IL->Native map here
// since we disassembled native code to find the ip after the call.
SIZE_T offset = CodeRegionInfo::GetCodeRegionInfo(dji, pDesc).AddressToOffset(ipNext);
LOG((LF_CORDB, LL_INFO100000, "DJMCStepper::TSIH, at '%s::%s', calling=0x%p, next=0x%p, offset=%d\n",
pDesc->m_pszDebugClassName,
pDesc->m_pszDebugMethodName,
ipCallTarget, ipNext,
offset));
// Place a patch at the native address (inside the managed method).
AddBindAndActivateNativeManagedPatch(pInfo->m_activeFrame.md,
dji,
offset,
pInfo->m_returnFrame.fp,
NULL);
EnableMethodEnter();
// Return true means that we want to let the stepper run free. It will either
// hit the patch after the call instruction or it will hit a TriggerMethodEnter.
return true;
}
// For JMC-steppers, we don't enable trace-call; we enable Method-Enter.
void DebuggerJMCStepper::EnablePolyTraceCall()
{
_ASSERTE(!IsFrozen());
this->EnableMethodEnter();
}
// Return true if this is non-user code. This means we've setup the proper patches &
// triggers, etc and so we expect the controller to just run free.
// This is called when all other stepping criteria are met and we're about to
// send a step-complete. For JMC, this is when we see if we're in non-user code
// and if so, continue stepping instead of send the step complete.
// Return false if this is user-code.
bool DebuggerJMCStepper::DetectHandleNonUserCode(ControllerStackInfo *pInfo, DebuggerMethodInfo * dmi)
{
_ASSERTE(dmi != NULL);
bool fIsUserCode = dmi->IsJMCFunction();
if (!fIsUserCode)
{
LOG((LF_CORDB, LL_INFO10000, "JMC stepper stopped in non-user code, continuing.\n"));
// Not-user code, we want to skip through this.
// We may be here while trying to step-out.
// Step-out just means stop at the first interesting frame above us.
// So JMC TrapStepOut won't patch a non-user frame.
// But if we're skipping over other stuff (prolog, epilog, interceptors,
// trace calls), then we may still be in the middle of non-user
//_ASSERTE(m_eMode != cStepOut);
if (m_eMode == cStepOut)
{
TrapStepOut(pInfo);
}
else if (m_stepIn)
{
EnableMethodEnter();
TrapStepOut(pInfo);
// Run until we hit the next thing of managed code.
} else {
// Do a traditional step-out since we just want to go up 1 frame.
TrapStepOut(pInfo, true); // force trad step out.
// If we're not in the original frame anymore, then
// If we did a Step-over at the end of a method, and that did a single-step over the return
// then we may already be in our parent frame. In that case, we also want to behave
// like a step-in and TriggerMethodEnter.
if (this->m_fp != pInfo->m_activeFrame.fp)
{
// If we're a step-over, then we should only be stopped in a parent frame.
_ASSERTE(m_stepIn || IsCloserToLeaf(this->m_fp, pInfo->m_activeFrame.fp));
EnableMethodEnter();
}
// Step-over shouldn't stop in a frame below us in the same callstack.
// So we do a tradional step-out of our current frame, which guarantees
// that. After that, we act just like a step-in.
m_stepIn = true;
}
EnableUnwind(m_fp);
// Must keep going...
return true;
}
return false;
}
// Dispatched right after the prolog of a JMC function.
// We may be blocking the GC here, so let's be fast!
void DebuggerJMCStepper::TriggerMethodEnter(Thread * thread,
DebuggerJitInfo *dji,
const BYTE * ip,
FramePointer fp)
{
_ASSERTE(dji != NULL);
_ASSERTE(thread != NULL);
_ASSERTE(ip != NULL);
_ASSERTE(!IsFrozen());
MethodDesc * pDesc = dji->m_fd;
LOG((LF_CORDB, LL_INFO10000, "DJMCStepper::TME, desc=%p, addr=%p\n",
pDesc, ip));
// JMC steppers won't stop in Lightweight delegates. Just return & keep executing.
if (pDesc->IsNoMetadata())
{
LOG((LF_CORDB, LL_INFO100000, "DJMCStepper::TME, skipping b/c it's lw-codegen\n"));
return;
}
// Is this user code?
DebuggerMethodInfo * dmi = dji->m_methodInfo;
bool fIsUserCode = dmi->IsJMCFunction();
LOG((LF_CORDB, LL_INFO100000, "DJMCStepper::TME, '%s::%s' is '%s' code\n",
pDesc->m_pszDebugClassName,
pDesc->m_pszDebugMethodName,
fIsUserCode ? "user" : "non-user"
));
// If this isn't user code, then just return and continue executing.
if (!fIsUserCode)
return;
// MethodEnter is only enabled when we want to stop in a JMC function.
// And that's where we are now. So patch the ip and resume.
// The stepper will hit the patch, and stop.
// It's a good thing we have the fp passed in, because we have no other
// way of getting it. We can't do a stack trace here (the stack trace
// would start at the last pushed Frame, which miss a lot of managed
// frames).
// Don't bind to a particular AppDomain so that we can do a Cross-Appdomain step.
AddBindAndActivateNativeManagedPatch(pDesc,
dji,
CodeRegionInfo::GetCodeRegionInfo(dji, pDesc).AddressToOffset(ip),
fp,
NULL // AppDomain
);
LOG((LF_CORDB, LL_INFO10000, "DJMCStepper::TME, after setting patch to stop\n"));
// Once we resume, we'll go hit that patch (duh, we patched our return address)
// Furthermore, we know the step will complete with reason = call, so set that now.
m_reason = STEP_CALL;
}
//-----------------------------------------------------------------------------
// Helper to convert form an EE Frame's interception enum to a CorDebugIntercept
// bitfield.
// The intercept value in EE Frame's is a 0-based enumeration (not a bitfield).
// The intercept value for ICorDebug is a bitfied.
//-----------------------------------------------------------------------------
CorDebugIntercept ConvertFrameBitsToDbg(Frame::Interception i)
{
_ASSERTE(i >= 0 && i < Frame::INTERCEPTION_COUNT);
// Since the ee frame is a 0-based enum, we can just use a map.
const CorDebugIntercept map[Frame::INTERCEPTION_COUNT] =
{
// ICorDebug EE Frame
INTERCEPT_NONE, // INTERCEPTION_NONE,
INTERCEPT_CLASS_INIT, // INTERCEPTION_CLASS_INIT
INTERCEPT_EXCEPTION_FILTER, // INTERCEPTION_EXCEPTION
INTERCEPT_CONTEXT_POLICY, // INTERCEPTION_CONTEXT
INTERCEPT_SECURITY, // INTERCEPTION_SECURITY
INTERCEPT_INTERCEPTION, // INTERCEPTION_OTHER
};
return map[i];
}
//-----------------------------------------------------------------------------
// This is a helper class to do a stack walk over a certain range and find all the interceptors.
// This allows a JMC stepper to see if there are any interceptors it wants to skip over (though
// there's nothing JMC-specific about this).
// Note that we only want to walk the stack range that the stepper is operating in.
// That's because we don't care about interceptors that happened _before_ the
// stepper was created.
//-----------------------------------------------------------------------------
class InterceptorStackInfo
{
public:
#ifdef _DEBUG
InterceptorStackInfo()
{
// since this ctor just nulls out fpTop (which is already done in Init), we
// only need it in debug.
m_fpTop = LEAF_MOST_FRAME;
}
#endif
// Get a CorDebugIntercept bitfield that contains a bit for each type of interceptor
// if that interceptor is present within our stack-range.
// Stack range is from leaf-most up to and including fp
CorDebugIntercept GetInterceptorsInRange()
{
_ASSERTE(m_fpTop != LEAF_MOST_FRAME || !"Must call Init first");
return (CorDebugIntercept) m_bits;
}
// Prime the stackwalk.
void Init(FramePointer fpTop, Thread *thread, CONTEXT *pContext, BOOL contextValid)
{
_ASSERTE(fpTop != LEAF_MOST_FRAME);
_ASSERTE(thread != NULL);
m_bits = 0;
m_fpTop = fpTop;
LOG((LF_CORDB,LL_EVERYTHING, "ISI::Init - fpTop=%p, thread=%p, pContext=%p, contextValid=%d\n",
fpTop.GetSPValue(), thread, pContext, contextValid));
int result;
result = DebuggerWalkStack(
thread,
LEAF_MOST_FRAME,
pContext,
contextValid,
WalkStack,
(void *) this,
FALSE
);
}
protected:
// This is a bitfield of all the interceptors we encounter in our stack-range
int m_bits;
// This is the top of our stack range.
FramePointer m_fpTop;
static StackWalkAction WalkStack(FrameInfo *pInfo, void *data)
{
_ASSERTE(pInfo != NULL);
_ASSERTE(data != NULL);
InterceptorStackInfo * pThis = (InterceptorStackInfo*) data;
// If there's an interceptor frame here, then set those
// bits in our bitfield.
Frame::Interception i = Frame::INTERCEPTION_NONE;
Frame * pFrame = pInfo->frame;
if ((pFrame != NULL) && (pFrame != FRAME_TOP))
{
i = pFrame->GetInterception();
if (i != Frame::INTERCEPTION_NONE)
{
pThis->m_bits |= (int) ConvertFrameBitsToDbg(i);
}
}
else if (pInfo->HasMethodFrame())
{
// Check whether we are executing in a class constructor.
_ASSERTE(pInfo->md != NULL);
// Need to be careful about an off-by-one error here! Imagine your stack looks like:
// Foo.DoSomething()
// Foo..cctor <--- step starts/ends in here
// Bar.Bar();
//
// and your code looks like this:
// Foo..cctor()
// {
// Foo.DoSomething(); <-- JMC step started here
// int x = 1; <-- step ends here
// }
// This stackwalk covers the inclusive range [Foo..cctor, Foo.DoSomething()] so we will see
// the static cctor in this walk. However executing inside a static class constructor does not
// count as an interceptor. You must start the step outside the static constructor and then call
// into it to have an interceptor. Therefore only static constructors that aren't the outermost
// frame should be treated as interceptors.
if (pInfo->md->IsClassConstructor() && (pInfo->fp != pThis->m_fpTop))
{
// We called a class constructor, add the appropriate flag
pThis->m_bits |= (int) INTERCEPT_CLASS_INIT;
}
}
LOG((LF_CORDB,LL_EVERYTHING,"ISI::WS- Frame=%p, fp=%p, Frame bits=%x, Cor bits=0x%x\n", pInfo->frame, pInfo->fp.GetSPValue(), i, pThis->m_bits));
// We can stop once we hit the top frame.
if (pInfo->fp == pThis->m_fpTop)
{
return SWA_ABORT;
}
else
{
return SWA_CONTINUE;
}
}
};
// Skip interceptors for JMC steppers.
// Return true if we patch something (and thus should keep stepping)
// Return false if we're done.
bool DebuggerJMCStepper::DetectHandleInterceptors(ControllerStackInfo * info)
{
LOG((LF_CORDB,LL_INFO10000,"DJMCStepper::DHI: Start DetectHandleInterceptors\n"));
// For JMC, we could stop very far way from an interceptor.
// So we have to do a stack walk to search for interceptors...
// If we find any in our stack range (from m_fp ... current fp), then we just do a trap-step-next.
// Note that this logic should also work for regular steppers, but we've left that in
// as to keep that code-path unchanged.
// ControllerStackInfo only gives us the bottom 2 frames on the stack, so we ignore it and
// have to do our own stack walk.
// @todo - for us to properly skip filters, we need to make sure that filters show up in our chains.
InterceptorStackInfo info2;
CONTEXT *context = g_pEEInterface->GetThreadFilterContext(this->GetThread());
CONTEXT tempContext;
_ASSERTE(!ISREDIRECTEDTHREAD(this->GetThread()));
if (context == NULL)
{
info2.Init(this->m_fp, this->GetThread(), &tempContext, FALSE);
}
else
{
info2.Init(this->m_fp, this->GetThread(), context, TRUE);
}
// The following casts are safe on WIN64 platforms.
int iOnStack = (int) info2.GetInterceptorsInRange();
int iSkip = ~((int) m_rgfInterceptStop);
LOG((LF_CORDB,LL_INFO10000,"DJMCStepper::DHI: iOnStack=%x, iSkip=%x\n", iOnStack, iSkip));
// If the bits on the stack contain any interceptors we want to skip, then we need to keep going.
if ((iOnStack & iSkip) != 0)
{
LOG((LF_CORDB,LL_INFO10000,"DJMCStepper::DHI: keep going!\n"));
TrapStepNext(info);
EnableUnwind(m_fp);
return true;
}
LOG((LF_CORDB,LL_INFO10000,"DJMCStepper::DHI: Done!!\n"));
return false;
}
// * ------------------------------------------------------------------------
// * DebuggerThreadStarter routines
// * ------------------------------------------------------------------------
DebuggerThreadStarter::DebuggerThreadStarter(Thread *thread)
: DebuggerController(thread, NULL)
{
LOG((LF_CORDB, LL_INFO1000, "DTS::DTS: this:0x%x Thread:0x%x\n",
this, thread));
// Check to make sure we only have 1 ThreadStarter on a given thread. (Inspired by NDPWhidbey issue 16888)
#if defined(_DEBUG)
EnsureUniqueThreadStarter(this);
#endif
}
// TP_RESULT DebuggerThreadStarter::TriggerPatch() If we're in a
// stub (module==NULL&&managed) then do a PatchTrace up the stack &
// return false. Otherwise DisableAll & return
// true
TP_RESULT DebuggerThreadStarter::TriggerPatch(DebuggerControllerPatch *patch,
Thread *thread,
TRIGGER_WHY tyWhy)
{
Module *module = patch->key.module;
BOOL managed = patch->IsManagedPatch();
LOG((LF_CORDB,LL_INFO1000, "DebuggerThreadStarter::TriggerPatch for thread 0x%x\n", Debugger::GetThreadIdHelper(thread)));
if (module == NULL && managed)
{
// This is a stub patch. If it was a TRACE_FRAME_PUSH that got us here, then the stub's frame is pushed now, so
// we tell the frame to apply the real patch. If we got here via a TRACE_MGR_PUSH, however, then there is no
// frame and we go back to the stub manager that generated the stub for where to patch next.
TraceDestination trace;
bool traceOk;
if (patch->trace.GetTraceType() == TRACE_MGR_PUSH)
{
BYTE *dummy = NULL;
CONTEXT *context = GetManagedLiveCtx(thread);
CONTRACT_VIOLATION(GCViolation);
traceOk = g_pEEInterface->TraceManager(thread, patch->trace.GetStubManager(), &trace, context, &dummy);
}
else if ((patch->trace.GetTraceType() == TRACE_FRAME_PUSH) && (thread->GetFrame()->IsTransitionToNativeFrame()))
{
// If we've got a frame that is transitioning to native, there's no reason to try to keep tracing. So we
// bail early and save ourselves some effort. This also works around a problem where we deadlock trying to
// do too much work to determine the destination of a ComPlusMethodFrame. (See issue 87103.)
//
// Note: trace call is still enabled, so we can just ignore this patch and wait for trace call to fire
// again...
return TPR_IGNORE;
}
else
{
// It's questionable whether Trace_Frame_Push is actually safe or not.
ControllerStackInfo csi;
StackTraceTicket ticket(patch);
csi.GetStackInfo(ticket, thread, LEAF_MOST_FRAME, NULL);
CONTRACT_VIOLATION(GCViolation); // TraceFrame GC-triggers
traceOk = g_pEEInterface->TraceFrame(thread, thread->GetFrame(), TRUE, &trace, &(csi.m_activeFrame.registers));
}
if (traceOk && g_pEEInterface->FollowTrace(&trace))
{
PatchTrace(&trace, LEAF_MOST_FRAME, TRUE);
}
return TPR_IGNORE;
}
else
{
// We've hit user code; trigger our event.
DisableAll();
{
// Give the helper thread a chance to get ready. The temporary helper can't handle
// execution control well, and the RS won't do any execution control until it gets a
// create Thread event, which it won't get until here.
// So now's our best time to wait for the real helper thread.
g_pDebugger->PollWaitingForHelper();
}
return TPR_TRIGGER;
}
}
void DebuggerThreadStarter::TriggerTraceCall(Thread *thread, const BYTE *ip)
{
LOG((LF_CORDB, LL_EVERYTHING, "DTS::TTC called\n"));
#ifdef DEBUGGING_SUPPORTED
if (thread->GetDomain()->IsDebuggerAttached())
{
TraceDestination trace;
if (g_pEEInterface->TraceStub(ip, &trace) && g_pEEInterface->FollowTrace(&trace))
{
PatchTrace(&trace, LEAF_MOST_FRAME, true);
}
}
#endif //DEBUGGING_SUPPORTED
}
bool DebuggerThreadStarter::SendEvent(Thread *thread, bool fIpChanged)
{
CONTRACTL
{
SO_NOT_MAINLINE;
NOTHROW;
SENDEVENT_CONTRACT_ITEMS;
}
CONTRACTL_END;
// This SendEvent can't be interupted by a SetIp because until the client
// gets a ThreadStarter event, it doesn't even know the thread exists, so
// it certainly can't change its ip.
_ASSERTE(!fIpChanged);
LOG((LF_CORDB, LL_INFO10000, "DTS::SE: in DebuggerThreadStarter's SendEvent\n"));
// Send the thread started event.
g_pDebugger->ThreadStarted(thread);
// We delete this now because its no longer needed. We can call
// delete here because the queued count is above 0. This object
// will really be deleted when its dequeued shortly after this
// call returns.
Delete();
return true;
}
// * ------------------------------------------------------------------------
// * DebuggerUserBreakpoint routines
// * ------------------------------------------------------------------------
bool DebuggerUserBreakpoint::IsFrameInDebuggerNamespace(FrameInfo * pFrame)
{
CONTRACTL
{
THROWS;
MODE_ANY;
GC_NOTRIGGER;
}
CONTRACTL_END;
// Steppers ignore internal frames, so should only be called on real frames.
_ASSERTE(pFrame->HasMethodFrame());
// Now get the namespace of the active frame
MethodDesc *pMD = pFrame->md;
if (pMD != NULL)
{
MethodTable * pMT = pMD->GetMethodTable();
LPCUTF8 szNamespace = NULL;
LPCUTF8 szClassName = pMT->GetFullyQualifiedNameInfo(&szNamespace);
if (szClassName != NULL && szNamespace != NULL)
{
MAKE_WIDEPTR_FROMUTF8(wszNamespace, szNamespace); // throw
MAKE_WIDEPTR_FROMUTF8(wszClassName, szClassName);
if (wcscmp(wszClassName, W("Debugger")) == 0 &&
wcscmp(wszNamespace, W("System.Diagnostics")) == 0)
{
// This will continue stepping
return true;
}
}
}
return false;
}
// Helper check if we're directly in a dynamic method (ignoring any chain goo
// or stuff in the Debugger namespace.
class IsLeafFrameDynamic
{
protected:
static StackWalkAction WalkStackWrapper(FrameInfo *pInfo, void *data)
{
IsLeafFrameDynamic * pThis = reinterpret_cast<IsLeafFrameDynamic*> (data);
return pThis->WalkStack(pInfo);
}
StackWalkAction WalkStack(FrameInfo *pInfo)
{
_ASSERTE(pInfo != NULL);
// A FrameInfo may have both Method + Chain rolled into one.
if (!pInfo->HasMethodFrame() && !pInfo->HasStubFrame())
{
// We're a chain. Ignore it and keep looking.
return SWA_CONTINUE;
}
// So now this is the first non-chain, non-Debugger namespace frame.
// LW frames don't have a name, so we check if it's LW first.
if (pInfo->eStubFrameType == STUBFRAME_LIGHTWEIGHT_FUNCTION)
{
m_fInLightWeightMethod = true;
return SWA_ABORT;
}
// Ignore Debugger.Break() frames.
// All Debugger.Break calls will have this on the stack.
if (DebuggerUserBreakpoint::IsFrameInDebuggerNamespace(pInfo))
{
return SWA_CONTINUE;
}
// We've now determined leafmost thing, so stop stackwalking.
_ASSERTE(m_fInLightWeightMethod == false);
return SWA_ABORT;
}
bool m_fInLightWeightMethod;
// Need this context to do stack trace.
CONTEXT m_tempContext;
public:
// On success, copies the leafmost non-chain frameinfo (including stubs) for the current thread into pInfo
// and returns true.
// On failure, returns false.
// Return true on success.
bool DoCheck(IN Thread * pThread)
{
CONTRACTL
{
GC_TRIGGERS;
THROWS;
MODE_ANY;
PRECONDITION(CheckPointer(pThread));
}
CONTRACTL_END;
m_fInLightWeightMethod = false;
DebuggerWalkStack(
pThread,
LEAF_MOST_FRAME,
&m_tempContext, false,
WalkStackWrapper,
(void *) this,
TRUE // includes everything
);
// We don't care whether the stackwalk succeeds or not because the
// callback sets our status via this field either way, so just return it.
return m_fInLightWeightMethod;
};
};
// Handle a Debug.Break() notification.
// This may create a controller to step-out out the Debug.Break() call (so that
// we appear stopped at the callsite).
// If we can't step-out (eg, we're directly in a dynamic method), then send
// the debug event immediately.
void DebuggerUserBreakpoint::HandleDebugBreak(Thread * pThread)
{
bool fDoStepOut = true;
// If the leaf frame is not a LW method, then step-out.
IsLeafFrameDynamic info;
fDoStepOut = !info.DoCheck(pThread);
if (fDoStepOut)
{
// Create a controller that will step out for us.
new (interopsafe) DebuggerUserBreakpoint(pThread);
}
else
{
// Send debug event immediately.
g_pDebugger->SendUserBreakpointAndSynchronize(pThread);
}
}
DebuggerUserBreakpoint::DebuggerUserBreakpoint(Thread *thread)
: DebuggerStepper(thread, (CorDebugUnmappedStop) (STOP_ALL & ~STOP_UNMANAGED), INTERCEPT_ALL, NULL)
{
// Setup a step out from the current frame (which we know is
// unmanaged, actually...)
// This happens to be safe, but it's a very special case (so we have a special case ticket)
// This is called while we're live (so no filter context) and from the fcall,
// and we pushed a HelperMethodFrame to protect us. We also happen to know that we have
// done anything illegal or dangerous since then.
StackTraceTicket ticket(this);
StepOut(LEAF_MOST_FRAME, ticket);
}
// Is this frame interesting?
// Use this to skip all code in the namespace "Debugger.Diagnostics"
bool DebuggerUserBreakpoint::IsInterestingFrame(FrameInfo * pFrame)
{
CONTRACTL
{
THROWS;
MODE_ANY;
GC_NOTRIGGER;
}
CONTRACTL_END;
return !IsFrameInDebuggerNamespace(pFrame);
}
bool DebuggerUserBreakpoint::SendEvent(Thread *thread, bool fIpChanged)
{
CONTRACTL
{
SO_NOT_MAINLINE;
NOTHROW;
SENDEVENT_CONTRACT_ITEMS;
}
CONTRACTL_END;
// See DebuggerStepper::SendEvent for why we assert here.
// This is technically an issue, but it's too benign to fix.
_ASSERTE(!fIpChanged);
LOG((LF_CORDB, LL_INFO10000,
"DUB::SE: in DebuggerUserBreakpoint's SendEvent\n"));
// Send the user breakpoint event.
g_pDebugger->SendRawUserBreakpoint(thread);
// We delete this now because its no longer needed. We can call
// delete here because the queued count is above 0. This object
// will really be deleted when its dequeued shortly after this
// call returns.
Delete();
return true;
}
// * ------------------------------------------------------------------------
// * DebuggerFuncEvalComplete routines
// * ------------------------------------------------------------------------
DebuggerFuncEvalComplete::DebuggerFuncEvalComplete(Thread *thread,
void *dest)
: DebuggerController(thread, NULL)
{
#ifdef _TARGET_ARM_
m_pDE = reinterpret_cast<DebuggerEvalBreakpointInfoSegment*>(((DWORD)dest) & ~THUMB_CODE)->m_associatedDebuggerEval;
#else
m_pDE = reinterpret_cast<DebuggerEvalBreakpointInfoSegment*>(dest)->m_associatedDebuggerEval;
#endif
// Add an unmanaged patch at the destination.
AddAndActivateNativePatchForAddress((CORDB_ADDRESS_TYPE*)dest, LEAF_MOST_FRAME, FALSE, TRACE_UNMANAGED);
}
TP_RESULT DebuggerFuncEvalComplete::TriggerPatch(DebuggerControllerPatch *patch,
Thread *thread,
TRIGGER_WHY tyWhy)
{
// It had better be an unmanaged patch...
_ASSERTE((patch->key.module == NULL) && !patch->IsManagedPatch());
// set ThreadFilterContext back here because we need make stack crawlable! In case,
// GC got triggered.
// Restore the thread's context to what it was before we hijacked it for this func eval.
CONTEXT *pCtx = GetManagedLiveCtx(thread);
CORDbgCopyThreadContext(reinterpret_cast<DT_CONTEXT *>(pCtx),
reinterpret_cast<DT_CONTEXT *>(&(m_pDE->m_context)));
// We've hit our patch, so simply disable all (which removes the
// patch) and trigger the event.
DisableAll();
return TPR_TRIGGER;
}
bool DebuggerFuncEvalComplete::SendEvent(Thread *thread, bool fIpChanged)
{
CONTRACTL
{
SO_NOT_MAINLINE;
THROWS;
SENDEVENT_CONTRACT_ITEMS;
}
CONTRACTL_END;
// This should not ever be interupted by a SetIp.
// The BP will be off in random native code for which SetIp would be illegal.
// However, func-eval conroller will restore the context from when we're at the patch,
// so that will look like the IP changed on us.
_ASSERTE(fIpChanged);
LOG((LF_CORDB, LL_INFO10000, "DFEC::SE: in DebuggerFuncEval's SendEvent\n"));
_ASSERTE(!ISREDIRECTEDTHREAD(thread));
// The DebuggerEval is at our faulting address.
DebuggerEval *pDE = m_pDE;
// Send the func eval complete (or exception) event.
g_pDebugger->FuncEvalComplete(thread, pDE);
// We delete this now because its no longer needed. We can call
// delete here because the queued count is above 0. This object
// will really be deleted when its dequeued shortly after this
// call returns.
Delete();
return true;
}
#ifdef EnC_SUPPORTED
// * ------------------------------------------------------------------------ *
// * DebuggerEnCBreakpoint routines
// * ------------------------------------------------------------------------ *
//---------------------------------------------------------------------------------------
//
// DebuggerEnCBreakpoint constructor - creates and activates a new EnC breakpoint
//
// Arguments:
// offset - native offset in the function to place the patch
// jitInfo - identifies the function in which the breakpoint is being placed
// fTriggerType - breakpoint type: either REMAP_PENDING or REMAP_COMPLETE
// pAppDomain - the breakpoint applies to the specified AppDomain only
//
DebuggerEnCBreakpoint::DebuggerEnCBreakpoint(SIZE_T offset,
DebuggerJitInfo *jitInfo,
DebuggerEnCBreakpoint::TriggerType fTriggerType,
AppDomain *pAppDomain)
: DebuggerController(NULL, pAppDomain),
m_fTriggerType(fTriggerType),
m_jitInfo(jitInfo)
{
_ASSERTE( jitInfo != NULL );
// Add and activate the specified patch
AddBindAndActivateNativeManagedPatch(jitInfo->m_fd, jitInfo, offset, LEAF_MOST_FRAME, pAppDomain);
LOG((LF_ENC,LL_INFO1000, "DEnCBPDEnCBP::adding %S patch!\n",
fTriggerType == REMAP_PENDING ? W("remap pending") : W("remap complete")));
}
//---------------------------------------------------------------------------------------
//
// DebuggerEnCBreakpoint::TriggerPatch
// called by the debugging infrastructure when the patch is hit.
//
// Arguments:
// patch - specifies the patch that was hit
// thread - identifies the thread on which the patch was hit
// tyWhy - TY_SHORT_CIRCUIT for normal REMAP_PENDING EnC patches
//
// Return value:
// TPR_IGNORE if the debugger chooses not to take a remap opportunity
// TPR_IGNORE_AND_STOP when a remap-complete event is sent
// Doesn't return at all if the debugger remaps execution to the new version of the method
//
TP_RESULT DebuggerEnCBreakpoint::TriggerPatch(DebuggerControllerPatch *patch,
Thread *thread,
TRIGGER_WHY tyWhy)
{
_ASSERTE(HasLock());
Module *module = patch->key.module;
mdMethodDef md = patch->key.md;
SIZE_T offset = patch->offset;
// Map the current native offset back to the IL offset in the old
// function. This will be mapped to the new native offset within
// ResumeInUpdatedFunction
CorDebugMappingResult map;
DWORD which;
SIZE_T currentIP = (SIZE_T)m_jitInfo->MapNativeOffsetToIL(offset,
&map, &which);
// We only lay DebuggerEnCBreakpoints at sequence points
_ASSERTE(map == MAPPING_EXACT);
LOG((LF_ENC, LL_ALWAYS,
"DEnCBP::TP: triggered E&C %S breakpoint: tid=0x%x, module=0x%08x, "
"method def=0x%08x, version=%d, native offset=0x%x, IL offset=0x%x\n this=0x%x\n",
m_fTriggerType == REMAP_PENDING ? W("ResumePending") : W("ResumeComplete"),
thread, module, md, m_jitInfo->m_encVersion, offset, currentIP, this));
// If this is a REMAP_COMPLETE patch, then dispatch the RemapComplete callback
if (m_fTriggerType == REMAP_COMPLETE)
{
return HandleRemapComplete(patch, thread, tyWhy);
}
// This must be a REMAP_PENDING patch
// unless we got here on an explicit short-circuit, don't do any work
if (tyWhy != TY_SHORT_CIRCUIT)
{
LOG((LF_ENC, LL_ALWAYS, "DEnCBP::TP: not short-circuit ... bailing\n"));
return TPR_IGNORE;
}
_ASSERTE(patch->IsManagedPatch());
// Grab the MethodDesc for this function.
_ASSERTE(module != NULL);
// GENERICS: @todo generics. This should be replaced by a similar loop
// over the DJIs for the DMI as in BindPatch up above.
MethodDesc *pFD = g_pEEInterface->FindLoadedMethodRefOrDef(module, md);
_ASSERTE(pFD != NULL);
LOG((LF_ENC, LL_ALWAYS,
"DEnCBP::TP: in %s::%s\n", pFD->m_pszDebugClassName,pFD->m_pszDebugMethodName));
// Grab the jit info for the original copy of the method, which is
// what we are executing right now.
DebuggerJitInfo *pJitInfo = m_jitInfo;
_ASSERTE(pJitInfo);
_ASSERTE(pJitInfo->m_fd == pFD);
// Grab the context for this thread. This is the context that was
// passed to COMPlusFrameHandler.
CONTEXT *pContext = GetManagedLiveCtx(thread);
// We use the module the current function is in.
_ASSERTE(module->IsEditAndContinueEnabled());
EditAndContinueModule *pModule = (EditAndContinueModule*)module;
// Release the controller lock for the rest of this method
CrstBase::UnsafeCrstInverseHolder inverseLock(&g_criticalSection);
// resumeIP is the native offset in the new version of the method the debugger wants
// to resume to. We'll pass the address of this variable over to the right-side
// and if it modifies the contents while we're stopped dispatching the RemapOpportunity,
// then we know it wants a remap.
// This form of side-channel communication seems like an error-prone workaround. Ideally the
// remap IP (if any) would just be returned in a response event.
SIZE_T resumeIP = (SIZE_T) -1;
// Debugging code to enable a break after N RemapOpportunities
#ifdef _DEBUG
static int breakOnRemapOpportunity = -1;
if (breakOnRemapOpportunity == -1)
breakOnRemapOpportunity = CLRConfig::GetConfigValue(CLRConfig::INTERNAL_EnCBreakOnRemapOpportunity);
static int remapOpportunityCount = 0;
++remapOpportunityCount;
if (breakOnRemapOpportunity == 1 || breakOnRemapOpportunity == remapOpportunityCount)
{
_ASSERTE(!"BreakOnRemapOpportunity");
}
#endif
// Send an event to the RS to call the RemapOpportunity callback, passing the address of resumeIP.
// If the debugger responds with a call to RemapFunction, the supplied IP will be copied into resumeIP
// and we will know to update the context and resume the function at the new IP. Otherwise we just do
// nothing and try again on next RemapFunction breakpoint
g_pDebugger->LockAndSendEnCRemapEvent(pJitInfo, currentIP, &resumeIP);
LOG((LF_ENC, LL_ALWAYS,
"DEnCBP::TP: resume IL offset is 0x%x\n", resumeIP));
// Has the debugger requested a remap?
if (resumeIP != (SIZE_T) -1)
{
// This will jit the function, update the context, and resume execution at the new location.
g_pEEInterface->ResumeInUpdatedFunction(pModule,
pFD,
(void*)pJitInfo,
resumeIP,
pContext);
_ASSERTE(!"Returned from ResumeInUpdatedFunction!");
}
LOG((LF_CORDB, LL_ALWAYS, "DEnCB::TP: We've returned from ResumeInUpd"
"atedFunction, we're going to skip the EnC patch ####\n"));
// We're returning then we'll have to re-get this lock. Be careful that we haven't kept any controller/patches
// in the caller. They can move when we unlock, so when we release the lock and reget it here, things might have
// changed underneath us.
// inverseLock holder will reaquire lock.
return TPR_IGNORE;
}
//
// HandleResumeComplete is called for an EnC patch in the newly updated function
// so that we can notify the debugger that the remap has completed and they can
// now remap their steppers or anything else that depends on the new code actually
// being on the stack. We return TPR_IGNORE_AND_STOP because it's possible that the
// function was edited after we handled remap complete and want to make sure we
// start a fresh call to TriggerPatch
//
TP_RESULT DebuggerEnCBreakpoint::HandleRemapComplete(DebuggerControllerPatch *patch,
Thread *thread,
TRIGGER_WHY tyWhy)
{
LOG((LF_ENC, LL_ALWAYS, "DEnCBP::HRC: HandleRemapComplete\n"));
// Debugging code to enable a break after N RemapCompletes
#ifdef _DEBUG
static int breakOnRemapComplete = -1;
if (breakOnRemapComplete == -1)
breakOnRemapComplete = CLRConfig::GetConfigValue(CLRConfig::INTERNAL_EnCBreakOnRemapComplete);
static int remapCompleteCount = 0;
++remapCompleteCount;
if (breakOnRemapComplete == 1 || breakOnRemapComplete == remapCompleteCount)
{
_ASSERTE(!"BreakOnRemapComplete");
}
#endif
_ASSERTE(HasLock());
bool fApplied = m_jitInfo->m_encBreakpointsApplied;
// Need to delete this before unlock below so if any other thread come in after the unlock
// they won't handle this patch.
Delete();
// We just deleted ourselves. Can't access anything any instances after this point.
// if have somehow updated this function before we resume into it then just bail
if (fApplied)
{
LOG((LF_ENC, LL_ALWAYS, "DEnCBP::HRC: function already updated, ignoring\n"));
return TPR_IGNORE_AND_STOP;
}
// GENERICS: @todo generics. This should be replaced by a similar loop
// over the DJIs for the DMI as in BindPatch up above.
MethodDesc *pFD = g_pEEInterface->FindLoadedMethodRefOrDef(patch->key.module, patch->key.md);
LOG((LF_ENC, LL_ALWAYS, "DEnCBP::HRC: unlocking controller\n"));
// Unlock the controller lock and dispatch the remap complete event
CrstBase::UnsafeCrstInverseHolder inverseLock(&g_criticalSection);
LOG((LF_ENC, LL_ALWAYS, "DEnCBP::HRC: sending RemapCompleteEvent\n"));
g_pDebugger->LockAndSendEnCRemapCompleteEvent(pFD);
// We're returning then we'll have to re-get this lock. Be careful that we haven't kept any controller/patches
// in the caller. They can move when we unlock, so when we release the lock and reget it here, things might have
// changed underneath us.
// inverseLock holder will reacquire.
return TPR_IGNORE_AND_STOP;
}
#endif //EnC_SUPPORTED
// continuable-exceptions
// * ------------------------------------------------------------------------ *
// * DebuggerContinuableExceptionBreakpoint routines
// * ------------------------------------------------------------------------ *
//---------------------------------------------------------------------------------------
//
// constructor
//
// Arguments:
// pThread - the thread on which we are intercepting an exception
// nativeOffset - This is the target native offset. It is where we are going to resume execution.
// jitInfo - the DebuggerJitInfo of the method at which we are intercepting
// pAppDomain - the AppDomain in which the thread is executing
//
DebuggerContinuableExceptionBreakpoint::DebuggerContinuableExceptionBreakpoint(Thread *pThread,
SIZE_T nativeOffset,
DebuggerJitInfo *jitInfo,
AppDomain *pAppDomain)
: DebuggerController(pThread, pAppDomain)
{
_ASSERTE( jitInfo != NULL );
// Add a native patch at the specified native offset, which is where we are going to resume execution.
AddBindAndActivateNativeManagedPatch(jitInfo->m_fd, jitInfo, nativeOffset, LEAF_MOST_FRAME, pAppDomain);
}
//---------------------------------------------------------------------------------------
//
// This function is called when the patch added in the constructor is hit. At this point,
// we have already resumed execution, and the exception is no longer in flight.
//
// Arguments:
// patch - the patch added in the constructor; unused
// thread - the thread in question; unused
// tyWhy - a flag which is only useful for EnC; unused
//
// Return Value:
// This function always returns TPR_TRIGGER, meaning that it wants to send an event to notify the RS.
//
TP_RESULT DebuggerContinuableExceptionBreakpoint::TriggerPatch(DebuggerControllerPatch *patch,
Thread *thread,
TRIGGER_WHY tyWhy)
{
LOG((LF_CORDB, LL_INFO10000, "DCEBP::TP\n"));
//
// Disable the patch
//
DisableAll();
// We will send a notification to the RS when the patch is triggered.
return TPR_TRIGGER;
}
//---------------------------------------------------------------------------------------
//
// This function is called when we want to notify the RS that an interception is complete.
// At this point, we have already resumed execution, and the exception is no longer in flight.
//
// Arguments:
// thread - the thread in question
// fIpChanged - whether the IP has changed by SetIP after the patch is hit but
// before this function is called
//
bool DebuggerContinuableExceptionBreakpoint::SendEvent(Thread *thread, bool fIpChanged)
{
CONTRACTL
{
SO_NOT_MAINLINE;
NOTHROW;
SENDEVENT_CONTRACT_ITEMS;
}
CONTRACTL_END;
LOG((LF_CORDB, LL_INFO10000,
"DCEBP::SE: in DebuggerContinuableExceptionBreakpoint's SendEvent\n"));
if (!fIpChanged)
{
g_pDebugger->SendInterceptExceptionComplete(thread);
}
// On WIN64, by the time we get here the DebuggerExState is gone already.
// ExceptionTrackers are cleaned up before we resume execution for a handled exception.
#if !defined(WIN64EXCEPTIONS)
thread->GetExceptionState()->GetDebuggerState()->SetDebuggerInterceptContext(NULL);
#endif // !WIN64EXCEPTIONS
//
// We delete this now because its no longer needed. We can call
// delete here because the queued count is above 0. This object
// will really be deleted when its dequeued shortly after this
// call returns.
//
Delete();
return true;
}
#endif // !DACCESS_COMPILE
|
parjong/coreclr
|
src/debug/ee/controller.cpp
|
C++
|
mit
| 325,373 |
---
title: ເວລາສຳລັບຄວາມດຸ່ນດ່ຽງ
date: 16/12/2020
---
`ອ່ານມັດທາຍ 12:11-13 ແລະ ລູກາ 13:10-17. ຂໍ້ພຣະຄຳພີເຫຼົ່ານີ້ສະແດງໃຫ້ພວກເຮົາເຫັນວ່າ ພຣະເຢຊູໄດ້ຊົງສອນປະຊາຊົນໃນສະໄໝນັ້ນແລະໃນສະໄໝຂອງເຮົາເຖິ່ງເລື່ອງໃດ?`
ພຣະເຢຊູໄດ້ຮັກສາຄົນເຈັບປ່ວຍໃນວັນສະບາໂຕ ການອັດສະຈັນຂອງພຣະອົງໄດ້ເຮັດໃຫ້ຊາວຢິວນັ້ນເລີ່ມສົນທະນາກັນກ່ຽວກັບຄຳຖາມຝ່າຍຈິດວິນຍານທີ່ສຳຄັນ. ຄວາມບາບນັ້ນແມ່ນຫຍັງ? ແມ່ນຫຍັງຄືເຫດຜົນຫຼືຈຸດປະສົງຂອງວັນສະບາໂຕ? ພຣະເຢຊູນັ້ນຊົງທຽບເທົ່າກັບພຣະບິດາຫຼືບໍ່? ພຣະເຢຊູນັ້ນມີອຳນາດຫຼາຍຊໍ່າໃດ?
ຄວາມຮູ້ສຶກຂອງພຣະເຢຊູກ່ຽວກັບວັນສະບາໂຕນັ້ນຖືກສະແດງອອກໃນຂໍ້ຄວນຈຳສຳລັບອາທິດນີ້: “ແລ້ວພຣະເຢຊູເຈົ້າກໍກ່າວແກ່ພວກເຂົາວ່າ ວັນສະບາໂຕຖືກຕັ້ງໄວ້ເພື່ອປະໂຫຍດອັນນຳຄວາມສຸກມາສູ່ມະນຸດ ບໍ່ແມ່ນສ້າງມະນຸດໄວ້ເພື່ອວັນສະບາໂຕ. ສະນັ້ນແຫຼະ ບຸດມະນຸດຈຶ່ງເປັນອົງພຣະຜູ້ເປັນເຈົ້າເໜືອວັນສະບາໂຕ” (ມາຣະໂກ 2:27, 28). ພຣະເຢຊູຕ້ອງການທີ່ຈະສະແດງໃຫ້ເຫັນວ່າວັນສະບາໂຕບໍ່ຄວນເປັນພາລະໜັກ. ພຣະເຈົ້າ “ໄດ້ສ້າງ” ວັນສະບາໂຕ ໃຫ້ເປັນເວລາທີ່ຄົນຈະຮຽນຮູ້ກ່ຽວກັບພຣະເຈົ້າ. ທາງໜຶ່ງທີ່ພວກເຮົາຮຽນຮູ້ກ່ຽວກັບພຣະເຈົ້າໃນວັນສະບາໂຕໄດ້ນັ້ນກໍຄືໂດຍການໃຊ້ເວລາກັບທຳມະຊາດ.
`ວັນສະບາໂຕແມ່ນອັນໃດສຳລັບທ່ານ? ມັນເປັນພຽງມື້ສຳລັບການບໍ່ໃຫ້ເຮັດອັນນັ້ນ ແລະ ບໍ່ໃຫ້ເຮັດອັນນີ້ບໍ່? ຫຼື ມັນເປັນເວລາທີ່ຈະພັກຜ່ອນໃນອົງພຣະຜູ້ເປັນເຈົ້າ ແລະ ຮຽນຮູ້ພຣະອົງຫຼາຍຂຶ້ນ? ຖ້າເປັນດັ່ງນັ້ນແລ້ວ ທ່ານສາມາດປ່ຽນແປງແນວໃດ ເພື່ອວ່າທ່ານຈະສາມາດໄດ້ຮັບພຣະພອນຈາກວັນສະບາໂຕທີ່ພຣະເຈົ້າຕ້ອງການໃຫ້ທ່ານໄດ້ຮັບ?`
|
imasaru/sabbath-school-lessons
|
src/lo/2020-04/12/05.md
|
Markdown
|
mit
| 3,507 |
[](https://registry.hub.docker.com/u/hopsoft/ruby-rbx/)
[](https://gratipay.com/hopsoft/)
# Trusted Docker Image for Rubinius Ruby
## Use the Trusted Image
```
sudo docker run -i -t hopsoft/ruby-rbx:2.5.3 bash
ruby -v
```
## Build the Image Manually
#### Dependencies
* [Virtual Box](https://www.virtualbox.org/)
* [Vagrant](http://www.vagrantup.com/)
```
git clone https://github.com/hopsoft/docker-ruby-rbx.git
cd docker-ruby-rbx
vagrant up
vagrant ssh
sudo docker build -t hopsoft/ruby-rbx /vagrant
```
Once the build finishes, you can [use the image](#use-the-trusted-image).
|
hopsoft/docker-ruby-rbx
|
README.md
|
Markdown
|
mit
| 751 |
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html><head><title></title>
<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<meta name="generator" content="Doxygen 1.8.13"/>
<link rel="stylesheet" type="text/css" href="search.css"/>
<script type="text/javascript" src="files_8.js"></script>
<script type="text/javascript" src="search.js"></script>
</head>
<body class="SRPage">
<div id="SRIndex">
<div class="SRStatus" id="Loading">Wczytywanie...</div>
<div id="SRResults"></div>
<script type="text/javascript"><!--
createResults();
--></script>
<div class="SRStatus" id="Searching">Szukanie...</div>
<div class="SRStatus" id="NoMatches">Brak dopasowań</div>
<script type="text/javascript"><!--
document.getElementById("Loading").style.display="none";
document.getElementById("NoMatches").style.display="none";
var searchResults = new SearchResults("searchResults");
searchResults.Search();
--></script>
</div>
</body>
</html>
|
teneusz/aplikacja_mobilna_komunikator
|
docs/zalacznik 3 - Dokumentacja Klas/html/search/files_8.html
|
HTML
|
mit
| 1,023 |
# Borrowed from: https://github.com/ahornung/octomap-release
# Copyright (c) 2009-2012, K. M. Wurm, A. Hornung, University of Freiburg
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in the
# documentation and/or other materials provided with the distribution.
# * Neither the name of the University of Freiburg nor the names of its
# contributors may be used to endorse or promote products derived from
# this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
# COMPILER SETTINGS (default: Release)
# Use "-DCMAKE_BUILD_TYPE=Debug" in cmake for a Debug-build
IF(NOT CMAKE_CONFIGURATION_TYPES AND NOT CMAKE_BUILD_TYPE)
SET(CMAKE_BUILD_TYPE Release)
ENDIF(NOT CMAKE_CONFIGURATION_TYPES AND NOT CMAKE_BUILD_TYPE)
MESSAGE ("\n")
MESSAGE (STATUS "${PROJECT_NAME} building as ${CMAKE_BUILD_TYPE}")
# COMPILER FLAGS
IF (CMAKE_COMPILER_IS_GNUCC)
SET (CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -Wall -Wno-error")
SET (CMAKE_C_FLAGS_RELEASE "-O3 -fmessage-length=0 -fno-strict-aliasing -DNDEBUG")
SET (CMAKE_C_FLAGS_DEBUG "-O0 -g3 -DTRACE=1")
SET (CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wall -Wno-error")
SET (CMAKE_CXX_FLAGS_RELEASE "-O3 -fmessage-length=0 -fno-strict-aliasing -DNDEBUG")
SET (CMAKE_CXX_FLAGS_DEBUG "-O0 -g3 -DTRACE=1")
# Shared object compilation under 64bit (vtable)
ADD_DEFINITIONS(-fPIC)
ADD_DEFINITIONS(-DL2DBUS_MAJOR_VERSION=${L2DBUS_MAJOR_VERSION})
ADD_DEFINITIONS(-DL2DBUS_MINOR_VERSION=${L2DBUS_MINOR_VERSION})
ADD_DEFINITIONS(-DL2DBUS_RELEASE_VERSION=${L2DBUS_RELEASE_VERSION})
ENDIF()
#
# See http://www.paraview.org/Wiki/CMake_RPATH_handling for additional details
#
# Use, i.e. don't skip the full RPATH for the build tree
set(CMAKE_SKIP_BUILD_RPATH FALSE)
# When building, don't use the install RPATH already (but later on
# when installing)
set(CMAKE_BUILD_WITH_INSTALL_RPATH FALSE)
# The RPATH to use when installing. Since it's empty the library must
# be found in a path search by other means (e.g. LD_LIBRARY_PATH, default
# library location, etc...)
set(CMAKE_INSTALL_RPATH "")
# Don't add teh automatically determined parts of the RPATH which point to
# directories outside the build tree to the install RPATH.
set(CMAKE_INSTALL_RPATH_USE_LINK_PATH FALSE)
# no prefix needed for Lua modules
# set(CMAKE_SHARED_MODULE_PREFIX "")
|
xs-embedded-llc/cdbus
|
test/ping_stress2/CMakeModules/CompilerSettings.cmake
|
CMake
|
mit
| 3,494 |
import * as React from "react";
import { CarbonIconProps } from "../../";
declare const Opacity24: React.ForwardRefExoticComponent<
CarbonIconProps & React.RefAttributes<SVGSVGElement>
>;
export default Opacity24;
|
mcliment/DefinitelyTyped
|
types/carbon__icons-react/lib/opacity/24.d.ts
|
TypeScript
|
mit
| 216 |
<?php
/**
* This file is part of DomainSpecificQuery
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* @author Nicolò Martini <[email protected]>
*/
namespace DSQ\Test\Compiler;
use DSQ\Compiler\CompilerChain;
use DSQ\Expression\BasicExpression;
use DSQ\Expression\Expression;
class CompilerChainTest extends \PHPUnit_Framework_TestCase
{
/**
* @param int $expectedcalls
* @return Compiler
*/
public function getCompilerMock($expectedcalls = 1)
{
$mock = $this->getMock('DSQ\Compiler\Compiler');
$mock
->expects($this->exactly($expectedcalls))
->method('compile')
->will($this->returnCallback(function(Expression $expr){
return new BasicExpression((int) $expr->getValue() + 1);
}));
return $mock;
}
public function testConstructor()
{
$chain = array($this->getMock('DSQ\Compiler\Compiler'), $this->getMock('DSQ\Compiler\Compiler'), $this->getMock('DSQ\Compiler\Compiler'));
$compiler = new CompilerChain($chain[0], $chain[1], $chain[2]);
$this->assertAttributeEquals($chain, 'chain', $compiler);
}
public function testAddCompiler()
{
$chain = array($this->getMock('DSQ\Compiler\Compiler'), $this->getMock('DSQ\Compiler\Compiler'), $this->getMock('DSQ\Compiler\Compiler'));
$compiler = new CompilerChain;
$compiler
->addCompiler($chain[0])
->addCompiler($chain[1])
->addCompiler($chain[2]);
$this->assertAttributeEquals($chain, 'chain', $compiler);
}
public function testCompile()
{
$expr = new BasicExpression(0);
$chain = new CompilerChain($this->getCompilerMock(1), $this->getCompilerMock(1), $this->getCompilerMock(1));
$compiled = $chain->compile($expr);
$this->assertEquals(3, $compiled->getValue());
}
}
|
nicmart/DomainSpecificQuery
|
tests/Compiler/CompilerChainTest.php
|
PHP
|
mit
| 1,993 |
///
/// Copyright (c) 2016 Dropbox, Inc. All rights reserved.
///
/// Auto-generated by Stone, do not modify.
///
#import <Foundation/Foundation.h>
#import "DBSerializableProtocol.h"
@class DBTEAMLOGAdminAlertSeverityEnum;
NS_ASSUME_NONNULL_BEGIN
#pragma mark - API Object
///
/// The `AdminAlertSeverityEnum` union.
///
/// Alert severity
///
/// This class implements the `DBSerializable` protocol (serialize and
/// deserialize instance methods), which is required for all Obj-C SDK API route
/// objects.
///
@interface DBTEAMLOGAdminAlertSeverityEnum : NSObject <DBSerializable, NSCopying>
#pragma mark - Instance fields
/// The `DBTEAMLOGAdminAlertSeverityEnumTag` enum type represents the possible
/// tag states with which the `DBTEAMLOGAdminAlertSeverityEnum` union can exist.
typedef NS_CLOSED_ENUM(NSInteger, DBTEAMLOGAdminAlertSeverityEnumTag){
/// (no description).
DBTEAMLOGAdminAlertSeverityEnumHigh,
/// (no description).
DBTEAMLOGAdminAlertSeverityEnumInfo,
/// (no description).
DBTEAMLOGAdminAlertSeverityEnumLow,
/// (no description).
DBTEAMLOGAdminAlertSeverityEnumMedium,
/// (no description).
DBTEAMLOGAdminAlertSeverityEnumNa,
/// (no description).
DBTEAMLOGAdminAlertSeverityEnumOther,
};
/// Represents the union's current tag state.
@property (nonatomic, readonly) DBTEAMLOGAdminAlertSeverityEnumTag tag;
#pragma mark - Constructors
///
/// Initializes union class with tag state of "high".
///
/// @return An initialized instance.
///
- (instancetype)initWithHigh;
///
/// Initializes union class with tag state of "info".
///
/// @return An initialized instance.
///
- (instancetype)initWithInfo;
///
/// Initializes union class with tag state of "low".
///
/// @return An initialized instance.
///
- (instancetype)initWithLow;
///
/// Initializes union class with tag state of "medium".
///
/// @return An initialized instance.
///
- (instancetype)initWithMedium;
///
/// Initializes union class with tag state of "na".
///
/// @return An initialized instance.
///
- (instancetype)initWithNa;
///
/// Initializes union class with tag state of "other".
///
/// @return An initialized instance.
///
- (instancetype)initWithOther;
- (instancetype)init NS_UNAVAILABLE;
#pragma mark - Tag state methods
///
/// Retrieves whether the union's current tag state has value "high".
///
/// @return Whether the union's current tag state has value "high".
///
- (BOOL)isHigh;
///
/// Retrieves whether the union's current tag state has value "info".
///
/// @return Whether the union's current tag state has value "info".
///
- (BOOL)isInfo;
///
/// Retrieves whether the union's current tag state has value "low".
///
/// @return Whether the union's current tag state has value "low".
///
- (BOOL)isLow;
///
/// Retrieves whether the union's current tag state has value "medium".
///
/// @return Whether the union's current tag state has value "medium".
///
- (BOOL)isMedium;
///
/// Retrieves whether the union's current tag state has value "na".
///
/// @return Whether the union's current tag state has value "na".
///
- (BOOL)isNa;
///
/// Retrieves whether the union's current tag state has value "other".
///
/// @return Whether the union's current tag state has value "other".
///
- (BOOL)isOther;
///
/// Retrieves string value of union's current tag state.
///
/// @return A human-readable string representing the union's current tag state.
///
- (NSString *)tagName;
@end
#pragma mark - Serializer Object
///
/// The serialization class for the `DBTEAMLOGAdminAlertSeverityEnum` union.
///
@interface DBTEAMLOGAdminAlertSeverityEnumSerializer : NSObject
///
/// Serializes `DBTEAMLOGAdminAlertSeverityEnum` instances.
///
/// @param instance An instance of the `DBTEAMLOGAdminAlertSeverityEnum` API
/// object.
///
/// @return A json-compatible dictionary representation of the
/// `DBTEAMLOGAdminAlertSeverityEnum` API object.
///
+ (nullable NSDictionary<NSString *, id> *)serialize:(DBTEAMLOGAdminAlertSeverityEnum *)instance;
///
/// Deserializes `DBTEAMLOGAdminAlertSeverityEnum` instances.
///
/// @param dict A json-compatible dictionary representation of the
/// `DBTEAMLOGAdminAlertSeverityEnum` API object.
///
/// @return An instantiation of the `DBTEAMLOGAdminAlertSeverityEnum` object.
///
+ (DBTEAMLOGAdminAlertSeverityEnum *)deserialize:(NSDictionary<NSString *, id> *)dict;
@end
NS_ASSUME_NONNULL_END
|
dropbox/dropbox-sdk-obj-c
|
Source/ObjectiveDropboxOfficial/Shared/Generated/ApiObjects/TeamLog/Headers/DBTEAMLOGAdminAlertSeverityEnum.h
|
C
|
mit
| 4,432 |
import os
import pygtk
pygtk.require('2.0')
import gtk
from gtkcodebuffer import CodeBuffer, SyntaxLoader
class Ui(object):
"""
The user interface. This dialog is the LaTeX input window and includes
widgets to display compilation logs and a preview. It uses GTK2 which
must be installed an importable.
"""
app_name = 'InkTeX'
help_text = r"""You can set a preamble file and scale factor in the <b>settings</b> tab. The preamble should not include <b>\documentclass</b> and <b>\begin{document}</b>.
The LaTeX code you write is only the stuff between <b>\begin{document}</b> and <b>\end{document}</b>. Compilation errors are reported in the <b>log</b> tab.
The preamble file and scale factor are stored on a per-drawing basis, so in a new document, these information must be set again."""
about_text = r"""Written by <a href="mailto:[email protected]">Jan Oliver Oelerich <[email protected]></a>"""
def __init__(self, render_callback, src, settings):
"""Takes the following parameters:
* render_callback: callback function to execute with "apply" button
* src: source code that should be pre-inserted into the LaTeX input"""
self.render_callback = render_callback
self.src = src if src else ""
self.settings = settings
# init the syntax highlighting buffer
lang = SyntaxLoader("latex")
self.syntax_buffer = CodeBuffer(lang=lang)
self.setup_ui()
def render(self, widget, data=None):
"""Extracts the input LaTeX code and calls the render callback. If that
returns true, we quit and are happy."""
buf = self.text.get_buffer()
tex = buf.get_text(buf.get_start_iter(), buf.get_end_iter())
settings = dict()
if self.preamble.get_filename():
settings['preamble'] = self.preamble.get_filename()
settings['scale'] = self.scale.get_value()
if self.render_callback(tex, settings):
gtk.main_quit()
return False
def cancel(self, widget, data=None):
"""Close button pressed: Exit"""
raise SystemExit(1)
def destroy(self, widget, event, data=None):
"""Destroy hook for the GTK window. Quit and return False."""
gtk.main_quit()
return False
def setup_ui(self):
"""Creates the actual UI."""
# create a floating toplevel window and set some title and border
self.window = gtk.Window(gtk.WINDOW_TOPLEVEL)
self.window.set_type_hint(gtk.gdk.WINDOW_TYPE_HINT_DIALOG)
self.window.set_title(self.app_name)
self.window.set_border_width(8)
# connect delete and destroy events
self.window.connect("destroy", self.destroy)
self.window.connect("delete-event", self.destroy)
# This is our main container, vertically ordered.
self.box_container = gtk.VBox(False, 5)
self.box_container.show()
self.notebook = gtk.Notebook()
self.page_latex = gtk.HBox(False, 5)
self.page_latex.set_border_width(8)
self.page_latex.show()
self.page_log = gtk.HBox(False, 5)
self.page_log.set_border_width(8)
self.page_log.show()
self.page_settings = gtk.HBox(False, 5)
self.page_settings.set_border_width(8)
self.page_settings.show()
self.page_help = gtk.VBox(False, 5)
self.page_help.set_border_width(8)
self.page_help.show()
self.notebook.append_page(self.page_latex, gtk.Label("LaTeX"))
self.notebook.append_page(self.page_log, gtk.Label("Log"))
self.notebook.append_page(self.page_settings, gtk.Label("Settings"))
self.notebook.append_page(self.page_help, gtk.Label("Help"))
self.notebook.show()
# First component: The input text view for the LaTeX code.
# It lives in a ScrolledWindow so we can get some scrollbars when the
# text is too long.
self.text = gtk.TextView(self.syntax_buffer)
self.text.get_buffer().set_text(self.src)
self.text.show()
self.text_container = gtk.ScrolledWindow()
self.text_container.set_policy(gtk.POLICY_AUTOMATIC,
gtk.POLICY_AUTOMATIC)
self.text_container.set_shadow_type(gtk.SHADOW_IN)
self.text_container.add(self.text)
self.text_container.set_size_request(400, 200)
self.text_container.show()
self.page_latex.pack_start(self.text_container)
# Second component: The log view
self.log_view = gtk.TextView()
self.log_view.show()
self.log_container = gtk.ScrolledWindow()
self.log_container.set_policy(gtk.POLICY_AUTOMATIC,
gtk.POLICY_AUTOMATIC)
self.log_container.set_shadow_type(gtk.SHADOW_IN)
self.log_container.add(self.log_view)
self.log_container.set_size_request(400, 200)
self.log_container.show()
self.page_log.pack_start(self.log_container)
# third component: settings
self.settings_container = gtk.Table(2,2)
self.settings_container.set_row_spacings(8)
self.settings_container.show()
self.label_preamble = gtk.Label("Preamble")
self.label_preamble.set_alignment(0, 0.5)
self.label_preamble.show()
self.preamble = gtk.FileChooserButton("...")
if 'preamble' in self.settings and os.path.exists(self.settings['preamble']):
self.preamble.set_filename(self.settings['preamble'])
self.preamble.set_action(gtk.FILE_CHOOSER_ACTION_OPEN)
self.preamble.show()
self.settings_container.attach(self.label_preamble, yoptions=gtk.SHRINK,
left_attach=0, right_attach=1, top_attach=0, bottom_attach=1)
self.settings_container.attach(self.preamble, yoptions=gtk.SHRINK,
left_attach=1, right_attach=2, top_attach=0, bottom_attach=1)
self.label_scale = gtk.Label("Scale")
self.label_scale.set_alignment(0, 0.5)
self.label_scale.show()
self.scale_adjustment = gtk.Adjustment(value=1.0, lower=0, upper=100,
step_incr=0.1)
self.scale = gtk.SpinButton(adjustment=self.scale_adjustment, digits=1)
if 'scale' in self.settings:
self.scale.set_value(float(self.settings['scale']))
self.scale.show()
self.settings_container.attach(self.label_scale, yoptions=gtk.SHRINK,
left_attach=0, right_attach=1, top_attach=1, bottom_attach=2)
self.settings_container.attach(self.scale, yoptions=gtk.SHRINK,
left_attach=1, right_attach=2, top_attach=1, bottom_attach=2)
self.page_settings.pack_start(self.settings_container)
# help tab
self.help_label = gtk.Label()
self.help_label.set_markup(Ui.help_text)
self.help_label.set_line_wrap(True)
self.help_label.show()
self.about_label = gtk.Label()
self.about_label.set_markup(Ui.about_text)
self.about_label.set_line_wrap(True)
self.about_label.show()
self.separator_help = gtk.HSeparator()
self.separator_help.show()
self.page_help.pack_start(self.help_label)
self.page_help.pack_start(self.separator_help)
self.page_help.pack_start(self.about_label)
self.box_container.pack_start(self.notebook, True, True)
# separator between buttonbar and notebook
self.separator_buttons = gtk.HSeparator()
self.separator_buttons.show()
self.box_container.pack_start(self.separator_buttons, False, False)
# the button bar
self.box_buttons = gtk.HButtonBox()
self.box_buttons.set_layout(gtk.BUTTONBOX_END)
self.box_buttons.show()
self.button_render = gtk.Button(stock=gtk.STOCK_APPLY)
self.button_cancel = gtk.Button(stock=gtk.STOCK_CLOSE)
self.button_render.set_flags(gtk.CAN_DEFAULT)
self.button_render.connect("clicked", self.render, None)
self.button_cancel.connect("clicked", self.cancel, None)
self.button_render.show()
self.button_cancel.show()
self.box_buttons.pack_end(self.button_cancel)
self.box_buttons.pack_end(self.button_render)
self.box_container.pack_start(self.box_buttons, False, False)
self.window.add(self.box_container)
self.window.set_default(self.button_render)
self.window.show()
def log(self, msg):
buffer = self.log_view.get_buffer()
buffer.set_text(msg)
self.notebook.set_current_page(1)
def main(self):
gtk.main()
|
hvwaldow/inktex
|
inktex/ui.py
|
Python
|
mit
| 8,707 |
#Javascript Introduction/Javascript简介
JavaScript is the programming language of the Web. The overwhelming majority of modern websites use JavaScript, and all modern web browsers—on desktops, game consoles, tablets, and smart phones—include JavaScript interpreters, making Java-Script the most ubiquitous programming language in history. JavaScript is part of the triad of technologies that all Web developers must learn: HTML to specify the content of web pages, CSS to specify the presentation of web pages, and JavaScript to specify the behavior of web pages.
JavaScript是面向web的编程语言。大多数现代浏览器都在使用JavaScript,并且所有的现代web浏览器——基于pc桌面、游戏机、平板电脑和智能手机的浏览器,都包含了JavaScript解释器。这使得JavaScript成为史上应用最广泛的编程语言。JavaScript也是前端工程师必须掌握的三大技能之一:展示网页内容的HTML、描述网页样式的CSS以及描述网页行为的JavaScript。
|
fullStackStudies/notes
|
en/content/front-end-development/javascript/README.md
|
Markdown
|
mit
| 1,028 |
'use strict';
var convert = require('./convert'),
func = convert('findLastIndexFrom', require('../findLastIndex'));
func.placeholder = require('./placeholder');
module.exports = func;
//# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbIi4uLy4uLy4uLy4uLy4uL2NsaWVudC9saWIvbG9kYXNoL2ZwL2ZpbmRMYXN0SW5kZXhGcm9tLmpzIl0sIm5hbWVzIjpbXSwibWFwcGluZ3MiOiI7O0FBQUEsSUFBSSxVQUFVLFFBQVEsV0FBUixDQUFkO0lBQ0ksT0FBTyxRQUFRLG1CQUFSLEVBQTZCLFFBQVEsa0JBQVIsQ0FBN0IsQ0FEWDs7QUFHQSxLQUFLLFdBQUwsR0FBbUIsUUFBUSxlQUFSLENBQW5CO0FBQ0EsT0FBTyxPQUFQLEdBQWlCLElBQWpCIiwiZmlsZSI6ImZpbmRMYXN0SW5kZXhGcm9tLmpzIiwic291cmNlc0NvbnRlbnQiOlsidmFyIGNvbnZlcnQgPSByZXF1aXJlKCcuL2NvbnZlcnQnKSxcbiAgICBmdW5jID0gY29udmVydCgnZmluZExhc3RJbmRleEZyb20nLCByZXF1aXJlKCcuLi9maW5kTGFzdEluZGV4JykpO1xuXG5mdW5jLnBsYWNlaG9sZGVyID0gcmVxdWlyZSgnLi9wbGFjZWhvbGRlcicpO1xubW9kdWxlLmV4cG9ydHMgPSBmdW5jO1xuIl19
|
vickeetran/hackd.in
|
compiled/client/lib/lodash/fp/findLastIndexFrom.js
|
JavaScript
|
mit
| 888 |
<?php
/**
* Functions related to starring private messages.
*
* @package BuddyPress
* @subpackage MessagesStar
* @since 2.3.0
*/
// Exit if accessed directly.
defined( 'ABSPATH' ) || exit;
/** UTILITY **************************************************************/
/**
* Return the starred messages slug. Defaults to 'starred'.
*
* @since 2.3.0
*
* @return string
*/
function bp_get_messages_starred_slug() {
/**
* Filters the starred message slug.
*
* @since 2.3.0
*
* @param string
*/
return sanitize_title( apply_filters( 'bp_get_messages_starred_slug', 'starred' ) );
}
/**
* Function to determine if a message ID is starred.
*
* @since 2.3.0
*
* @param int $mid The message ID. Please note that this isn't the message thread ID.
* @param int $user_id The user ID.
* @return bool
*/
function bp_messages_is_message_starred( $mid = 0, $user_id = 0 ) {
if ( empty( $user_id ) ) {
$user_id = bp_displayed_user_id();
}
if ( empty( $mid ) ) {
return false;
}
$starred = array_flip( (array) bp_messages_get_meta( $mid, 'starred_by_user', false ) );
if ( isset( $starred[$user_id] ) ) {
return true;
} else {
return false;
}
}
/**
* Output the link or raw URL for starring or unstarring a message.
*
* @since 2.3.0
*
* @param array $args See bp_get_the_message_star_action_link() for full documentation.
*/
function bp_the_message_star_action_link( $args = array() ) {
echo bp_get_the_message_star_action_link( $args );
}
/**
* Return the link or raw URL for starring or unstarring a message.
*
* @since 2.3.0
*
* @param array $args {
* Array of arguments.
* @type int $user_id The user ID. Defaults to the logged-in user ID.
* @type int $thread_id The message thread ID. Default: 0. If not zero, this takes precedence over
* $message_id.
* @type int $message_id The individual message ID. If on a single thread page, defaults to the
* current message ID in the message loop.
* @type bool $url_only Whether to return the URL only. If false, returns link with markup.
* Default: false.
* @type string $text_unstar Link text for the 'unstar' action. Only applicable if $url_only is false.
* @type string $text_star Link text for the 'star' action. Only applicable if $url_only is false.
* @type string $title_unstar Link title for the 'unstar' action. Only applicable if $url_only is false.
* @type string $title_star Link title for the 'star' action. Only applicable if $url_only is false.
* @type string $title_unstar_thread Link title for the 'unstar' action when displayed in a thread loop.
* Only applicable if $message_id is set and if $url_only is false.
* @type string $title_star_thread Link title for the 'star' action when displayed in a thread loop.
* Only applicable if $message_id is set and if $url_only is false.
* }
* @return string
*/
function bp_get_the_message_star_action_link( $args = array() ) {
// Default user ID.
$user_id = bp_displayed_user_id()
? bp_displayed_user_id()
: bp_loggedin_user_id();
$r = bp_parse_args( $args, array(
'user_id' => (int) $user_id,
'thread_id' => 0,
'message_id' => (int) bp_get_the_thread_message_id(),
'url_only' => false,
'text_unstar' => __( 'Unstar', 'buddypress' ),
'text_star' => __( 'Star', 'buddypress' ),
'title_unstar' => __( 'Starred', 'buddypress' ),
'title_star' => __( 'Not starred', 'buddypress' ),
'title_unstar_thread' => __( 'Remove all starred messages in this thread', 'buddypress' ),
'title_star_thread' => __( 'Star the first message in this thread', 'buddypress' ),
), 'messages_star_action_link' );
// Check user ID and determine base user URL.
switch ( $r['user_id'] ) {
// Current user.
case bp_loggedin_user_id() :
$user_domain = bp_loggedin_user_domain();
break;
// Displayed user.
case bp_displayed_user_id() :
$user_domain = bp_displayed_user_domain();
break;
// Empty or other.
default :
$user_domain = bp_core_get_user_domain( $r['user_id'] );
break;
}
// Bail if no user domain was calculated.
if ( empty( $user_domain ) ) {
return '';
}
// Define local variables.
$retval = $bulk_attr = '';
// Thread ID.
if ( (int) $r['thread_id'] > 0 ) {
// See if we're in the loop.
if ( bp_get_message_thread_id() == $r['thread_id'] ) {
// Grab all message ids.
$mids = wp_list_pluck( $GLOBALS['messages_template']->thread->messages, 'id' );
// Make sure order is ASC.
// Order is DESC when used in the thread loop by default.
$mids = array_reverse( $mids );
// Pull up the thread.
} else {
$thread = new BP_Messages_Thread( $r['thread_id'] );
$mids = wp_list_pluck( $thread->messages, 'id' );
}
$is_starred = false;
$message_id = 0;
foreach ( $mids as $mid ) {
// Try to find the first msg that is starred in a thread.
if ( true === bp_messages_is_message_starred( $mid ) ) {
$is_starred = true;
$message_id = $mid;
break;
}
}
// No star, so default to first message in thread.
if ( empty( $message_id ) ) {
$message_id = $mids[0];
}
$message_id = (int) $message_id;
// Nonce.
$nonce = wp_create_nonce( "bp-messages-star-{$message_id}" );
if ( true === $is_starred ) {
$action = 'unstar';
$bulk_attr = ' data-star-bulk="1"';
$retval = $user_domain . bp_get_messages_slug() . '/unstar/' . $message_id . '/' . $nonce . '/all/';
} else {
$action = 'star';
$retval = $user_domain . bp_get_messages_slug() . '/star/' . $message_id . '/' . $nonce . '/';
}
$title = $r["title_{$action}_thread"];
// Message ID.
} else {
$message_id = (int) $r['message_id'];
$is_starred = bp_messages_is_message_starred( $message_id );
$nonce = wp_create_nonce( "bp-messages-star-{$message_id}" );
if ( true === $is_starred ) {
$action = 'unstar';
$retval = $user_domain . bp_get_messages_slug() . '/unstar/' . $message_id . '/' . $nonce . '/';
} else {
$action = 'star';
$retval = $user_domain . bp_get_messages_slug() . '/star/' . $message_id . '/' . $nonce . '/';
}
$title = $r["title_{$action}"];
}
/**
* Filters the star action URL for starring / unstarring a message.
*
* @since 2.3.0
*
* @param string $retval URL for starring / unstarring a message.
* @param array $r Parsed link arguments. See $args in bp_get_the_message_star_action_link().
*/
$retval = esc_url( apply_filters( 'bp_get_the_message_star_action_urlonly', $retval, $r ) );
if ( true === (bool) $r['url_only'] ) {
return $retval;
}
/**
* Filters the star action link, including markup.
*
* @since 2.3.0
*
* @param string $retval Link for starring / unstarring a message, including markup.
* @param array $r Parsed link arguments. See $args in bp_get_the_message_star_action_link().
*/
return apply_filters( 'bp_get_the_message_star_action_link', '<a data-bp-tooltip="' . esc_attr( $title ) . '" class="bp-tooltip message-action-' . esc_attr( $action ) . '" data-star-status="' . esc_attr( $action ) .'" data-star-nonce="' . esc_attr( $nonce ) . '"' . $bulk_attr . ' data-message-id="' . esc_attr( (int) $message_id ) . '" href="' . $retval . '" role="button" aria-pressed="false"><span class="icon"></span> <span class="bp-screen-reader-text">' . $r['text_' . $action] . '</span></a>', $r );
}
/**
* Save or delete star message meta according to a message's star status.
*
* @since 2.3.0
*
* @param array $args {
* Array of arguments.
* @type string $action The star action. Either 'star' or 'unstar'. Default: 'star'.
* @type int $thread_id The message thread ID. Default: 0. If not zero, this takes precedence over
* $message_id.
* @type int $message_id The indivudal message ID to star or unstar. Default: 0.
* @type int $user_id The user ID. Defaults to the logged-in user ID.
* @type bool $bulk Whether to mark all messages in a thread as a certain action. Only relevant
* when $action is 'unstar' at the moment. Default: false.
* }
* @return bool
*/
function bp_messages_star_set_action( $args = array() ) {
$r = wp_parse_args( $args, array(
'action' => 'star',
'thread_id' => 0,
'message_id' => 0,
'user_id' => bp_displayed_user_id(),
'bulk' => false
) );
// Set thread ID.
if ( ! empty( $r['thread_id'] ) ) {
$thread_id = (int) $r['thread_id'];
} else {
$thread_id = messages_get_message_thread_id( $r['message_id'] );
}
if ( empty( $thread_id ) ) {
return false;
}
// Check if user has access to thread.
if( ! messages_check_thread_access( $thread_id, $r['user_id'] ) ) {
return false;
}
$is_starred = bp_messages_is_message_starred( $r['message_id'], $r['user_id'] );
// Star.
if ( 'star' == $r['action'] ) {
if ( true === $is_starred ) {
return true;
} else {
bp_messages_add_meta( $r['message_id'], 'starred_by_user', $r['user_id'] );
return true;
}
// Unstar.
} else {
// Unstar one message.
if ( false === $r['bulk'] ) {
if ( false === $is_starred ) {
return true;
} else {
bp_messages_delete_meta( $r['message_id'], 'starred_by_user', $r['user_id'] );
return true;
}
// Unstar all messages in a thread.
} else {
$thread = new BP_Messages_Thread( $thread_id );
$mids = wp_list_pluck( $thread->messages, 'id' );
foreach ( $mids as $mid ) {
if ( true === bp_messages_is_message_starred( $mid, $r['user_id'] ) ) {
bp_messages_delete_meta( $mid, 'starred_by_user', $r['user_id'] );
}
}
return true;
}
}
}
/** SCREENS **************************************************************/
/**
* Screen handler to display a user's "Starred" private messages page.
*
* @since 2.3.0
*/
function bp_messages_star_screen() {
add_action( 'bp_template_content', 'bp_messages_star_content' );
/**
* Fires right before the loading of the "Starred" messages box.
*
* @since 2.3.0
*/
do_action( 'bp_messages_screen_star' );
bp_core_load_template( 'members/single/plugins' );
}
/**
* Screen content callback to display a user's "Starred" messages page.
*
* @since 2.3.0
*/
function bp_messages_star_content() {
// Add our message thread filter.
add_filter( 'bp_after_has_message_threads_parse_args', 'bp_messages_filter_starred_message_threads' );
// Load the message loop template part.
bp_get_template_part( 'members/single/messages/messages-loop' );
// Remove our filter.
remove_filter( 'bp_after_has_message_threads_parse_args', 'bp_messages_filter_starred_message_threads' );
}
/**
* Filter message threads by those starred by the logged-in user.
*
* @since 2.3.0
*
* @param array $r Current message thread arguments.
* @return array $r Array of starred message threads.
*/
function bp_messages_filter_starred_message_threads( $r = array() ) {
$r['box'] = 'starred';
$r['meta_query'] = array( array(
'key' => 'starred_by_user',
'value' => $r['user_id']
) );
return $r;
}
/** ACTIONS **************************************************************/
/**
* Action handler to set a message's star status for those not using JS.
*
* @since 2.3.0
*/
function bp_messages_star_action_handler() {
if ( ! bp_is_user_messages() ) {
return;
}
if ( false === ( bp_is_current_action( 'unstar' ) || bp_is_current_action( 'star' ) ) ) {
return;
}
if ( ! wp_verify_nonce( bp_action_variable( 1 ), 'bp-messages-star-' . bp_action_variable( 0 ) ) ) {
wp_die( "Oops! That's a no-no!" );
}
// Check capability.
if ( ! is_user_logged_in() || ! bp_core_can_edit_settings() ) {
return;
}
// Mark the star.
bp_messages_star_set_action( array(
'action' => bp_current_action(),
'message_id' => bp_action_variable(),
'bulk' => (bool) bp_action_variable( 2 )
) );
// Redirect back to previous screen.
$redirect = wp_get_referer() ? wp_get_referer() : bp_displayed_user_domain() . bp_get_messages_slug();
bp_core_redirect( $redirect );
die();
}
add_action( 'bp_actions', 'bp_messages_star_action_handler' );
/**
* Bulk manage handler to set the star status for multiple messages.
*
* @since 2.3.0
*/
function bp_messages_star_bulk_manage_handler() {
if ( empty( $_POST['messages_bulk_nonce' ] ) ) {
return;
}
// Check the nonce.
if ( ! wp_verify_nonce( $_POST['messages_bulk_nonce'], 'messages_bulk_nonce' ) ) {
return;
}
// Check capability.
if ( ! is_user_logged_in() || ! bp_core_can_edit_settings() ) {
return;
}
$action = ! empty( $_POST['messages_bulk_action'] ) ? $_POST['messages_bulk_action'] : '';
$threads = ! empty( $_POST['message_ids'] ) ? $_POST['message_ids'] : '';
$threads = wp_parse_id_list( $threads );
// Bail if action doesn't match our star actions or no IDs.
if ( false === in_array( $action, array( 'star', 'unstar' ), true ) || empty( $threads ) ) {
return;
}
// It's star time!
switch ( $action ) {
case 'star' :
$count = count( $threads );
// If we're starring a thread, we only star the first message in the thread.
foreach ( $threads as $thread ) {
$thread = new BP_Messages_thread( $thread );
$mids = wp_list_pluck( $thread->messages, 'id' );
bp_messages_star_set_action( array(
'action' => 'star',
'message_id' => $mids[0],
) );
}
bp_core_add_message( sprintf( _n( '%s message was successfully starred', '%s messages were successfully starred', $count, 'buddypress' ), $count ) );
break;
case 'unstar' :
$count = count( $threads );
foreach ( $threads as $thread ) {
bp_messages_star_set_action( array(
'action' => 'unstar',
'thread_id' => $thread,
'bulk' => true
) );
}
bp_core_add_message( sprintf( _n( '%s message was successfully unstarred', '%s messages were successfully unstarred', $count, 'buddypress' ), $count ) );
break;
}
// Redirect back to message box.
bp_core_redirect( bp_displayed_user_domain() . bp_get_messages_slug() . '/' . bp_current_action() . '/' );
die();
}
add_action( 'bp_actions', 'bp_messages_star_bulk_manage_handler', 5 );
/** HOOKS ****************************************************************/
/**
* Enqueues the dashicons font.
*
* The dashicons font is used for the star / unstar icon.
*
* @since 2.3.0
*/
function bp_messages_star_enqueue_scripts() {
if ( ! bp_is_user_messages() ) {
return;
}
wp_enqueue_style( 'dashicons' );
}
add_action( 'bp_enqueue_scripts', 'bp_messages_star_enqueue_scripts' );
/**
* Add the "Add star" and "Remove star" options to the bulk management list.
*
* @since 2.3.0
*/
function bp_messages_star_bulk_management_dropdown() {
?>
<option value="star"><?php _e( 'Add star', 'buddypress' ); ?></option>
<option value="unstar"><?php _e( 'Remove star', 'buddypress' ); ?></option>
<?php
}
add_action( 'bp_messages_bulk_management_dropdown', 'bp_messages_star_bulk_management_dropdown', 1 );
/**
* Add CSS class for the current message depending on starred status.
*
* @since 2.3.0
*
* @param array $retval Current CSS classes.
* @return array
*/
function bp_messages_star_message_css_class( $retval = array() ) {
if ( true === bp_messages_is_message_starred( bp_get_the_thread_message_id() ) ) {
$status = 'starred';
} else {
$status = 'not-starred';
}
// Add css class based on star status for the current message.
$retval[] = "message-{$status}";
return $retval;
}
add_filter( 'bp_get_the_thread_message_css_class', 'bp_messages_star_message_css_class' );
|
jmelgarejo/Clan
|
wordpress/wp-content/plugins/buddypress/bp-messages/bp-messages-star.php
|
PHP
|
mit
| 15,966 |
<!doctype html>
<html>
<head>
<title>Radian to degree</title>
<script src="/require.js"></script>
<!-- ATTENTION: Remove in non-test code -->
<script src="/requireconfig.js"></script>
</head>
<body>
</body>
</html>
|
jeffreyjw/experimentA
|
testorial/tests/B medium/1 angle converter/1 radian to degree/index.html
|
HTML
|
mit
| 246 |
<?php
namespace Illuminate\Cache;
use Closure;
use Exception;
use Carbon\Carbon;
use Illuminate\Contracts\Cache\Store;
use Illuminate\Database\ConnectionInterface;
class DatabaseStore implements Store
{
use RetrievesMultipleKeys;
/**
* The database connection instance.
*
* @var \Illuminate\Database\ConnectionInterface
*/
protected $connection;
/**
* The name of the cache table.
*
* @var string
*/
protected $table;
/**
* A string that should be prepended to keys.
*
* @var string
*/
protected $prefix;
/**
* Create a new database store.
*
* @param \Illuminate\Database\ConnectionInterface $connection
* @param string $table
* @param string $prefix
* @return void
*/
public function __construct(ConnectionInterface $connection, $table, $prefix = '')
{
$this->table = $table;
$this->prefix = $prefix;
$this->connection = $connection;
}
/**
* Retrieve an item from the cache by key.
*
* @param string|array $key
* @return mixed
*/
public function get($key)
{
$prefixed = $this->prefix.$key;
$cache = $this->table()->where('key', '=', $prefixed)->first();
// If we have a cache record we will check the expiration time against current
// time on the system and see if the record has expired. If it has, we will
// remove the records from the database table so it isn't returned again.
if (is_null($cache)) {
return;
}
$cache = is_array($cache) ? (object) $cache : $cache;
// If this cache expiration date is past the current time, we will remove this
// item from the cache. Then we will return a null value since the cache is
// expired. We will use "Carbon" to make this comparison with the column.
if (Carbon::now()->getTimestamp() >= $cache->expiration) {
$this->forget($key);
return;
}
return unserialize($cache->value);
}
/**
* Store an item in the cache for a given number of minutes.
*
* @param string $key
* @param mixed $value
* @param float|int $minutes
* @return void
*/
public function put($key, $value, $minutes)
{
$key = $this->prefix.$key;
$value = serialize($value);
$expiration = $this->getTime() + (int) ($minutes * 60);
try {
$this->table()->insert(compact('key', 'value', 'expiration'));
} catch (Exception $e) {
$this->table()->where('key', $key)->update(compact('value', 'expiration'));
}
}
/**
* Increment the value of an item in the cache.
*
* @param string $key
* @param mixed $value
* @return int|bool
*/
public function increment($key, $value = 1)
{
return $this->incrementOrDecrement($key, $value, function ($current, $value) {
return $current + $value;
});
}
/**
* Decrement the value of an item in the cache.
*
* @param string $key
* @param mixed $value
* @return int|bool
*/
public function decrement($key, $value = 1)
{
return $this->incrementOrDecrement($key, $value, function ($current, $value) {
return $current - $value;
});
}
/**
* Increment or decrement an item in the cache.
*
* @param string $key
* @param mixed $value
* @param \Closure $callback
* @return int|bool
*/
protected function incrementOrDecrement($key, $value, Closure $callback)
{
return $this->connection->transaction(function () use ($key, $value, $callback) {
$prefixed = $this->prefix.$key;
$cache = $this->table()->where('key', $prefixed)
->lockForUpdate()->first();
// If there is no value in the cache, we will return false here. Otherwise the
// value will be decrypted and we will proceed with this function to either
// increment or decrement this value based on the given action callbacks.
if (is_null($cache)) {
return false;
}
$cache = is_array($cache) ? (object) $cache : $cache;
$current = unserialize($cache->value);
// Here we'll call this callback function that was given to the function which
// is used to either increment or decrement the function. We use a callback
// so we do not have to recreate all this logic in each of the functions.
$new = $callback((int) $current, $value);
if (! is_numeric($current)) {
return false;
}
// Here we will update the values in the table. We will also encrypt the value
// since database cache values are encrypted by default with secure storage
// that can't be easily read. We will return the new value after storing.
$this->table()->where('key', $prefixed)->update([
'value' => serialize($new),
]);
return $new;
});
}
/**
* Get the current system time.
*
* @return int
*/
protected function getTime()
{
return Carbon::now()->getTimestamp();
}
/**
* Store an item in the cache indefinitely.
*
* @param string $key
* @param mixed $value
* @return void
*/
public function forever($key, $value)
{
$this->put($key, $value, 5256000);
}
/**
* Remove an item from the cache.
*
* @param string $key
* @return bool
*/
public function forget($key)
{
$this->table()->where('key', '=', $this->prefix.$key)->delete();
return true;
}
/**
* Remove all items from the cache.
*
* @return bool
*/
public function flush()
{
return (bool) $this->table()->delete();
}
/**
* Get a query builder for the cache table.
*
* @return \Illuminate\Database\Query\Builder
*/
protected function table()
{
return $this->connection->table($this->table);
}
/**
* Get the underlying database connection.
*
* @return \Illuminate\Database\ConnectionInterface
*/
public function getConnection()
{
return $this->connection;
}
/**
* Get the cache key prefix.
*
* @return string
*/
public function getPrefix()
{
return $this->prefix;
}
}
|
vetruvet/framework
|
src/Illuminate/Cache/DatabaseStore.php
|
PHP
|
mit
| 6,680 |
package net.sf.esfinge.metadata.validate.minValue;
|
pedrocavalero/metadata
|
src/test/java/net/sf/esfinge/metadata/validate/minValue/package-info.java
|
Java
|
mit
| 50 |
/*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for
* license information.
*
* Code generated by Microsoft (R) AutoRest Code Generator.
* Changes may cause incorrect behavior and will be lost if the code is
* regenerated.
*/
'use strict';
/**
* Person object.
*
*/
class PersonResult {
/**
* Create a PersonResult.
* @member {string} personId personId of the target face list.
* @member {array} [persistedFaceIds] persistedFaceIds of registered faces in
* the person. These persistedFaceIds are returned from Person - Add a Person
* Face, and will not expire.
* @member {string} [name] Person's display name.
* @member {string} [userData] User-provided data attached to this person.
*/
constructor() {
}
/**
* Defines the metadata of PersonResult
*
* @returns {object} metadata of PersonResult
*
*/
mapper() {
return {
required: false,
serializedName: 'PersonResult',
type: {
name: 'Composite',
className: 'PersonResult',
modelProperties: {
personId: {
required: true,
serializedName: 'personId',
type: {
name: 'String'
}
},
persistedFaceIds: {
required: false,
serializedName: 'persistedFaceIds',
type: {
name: 'Sequence',
element: {
required: false,
serializedName: 'StringElementType',
type: {
name: 'String'
}
}
}
},
name: {
required: false,
serializedName: 'name',
type: {
name: 'String'
}
},
userData: {
required: false,
serializedName: 'userData',
type: {
name: 'String'
}
}
}
}
};
}
}
module.exports = PersonResult;
|
lmazuel/azure-sdk-for-node
|
lib/services/face/lib/models/personResult.js
|
JavaScript
|
mit
| 2,087 |
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <[email protected]>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Bundle\FrameworkBundle\Test;
use Symfony\Bundle\FrameworkBundle\Client;
use Symfony\Component\Finder\Finder;
use Symfony\Component\HttpKernel\HttpKernelInterface;
/**
* WebTestCase is the base class for functional tests.
*
* @author Fabien Potencier <[email protected]>
*/
abstract class WebTestCase extends \PHPUnit_Framework_TestCase
{
protected static $class;
protected static $kernel;
/**
* Creates a Client.
*
* @param array $options An array of options to pass to the createKernel class
* @param array $server An array of server parameters
*
* @return Client A Client instance
*/
protected static function createClient(array $options = array(), array $server = array())
{
if (null !== static::$kernel) {
static::$kernel->shutdown();
}
static::$kernel = static::createKernel($options);
static::$kernel->boot();
$client = static::$kernel->getContainer()->get('test.client');
$client->setServerParameters($server);
return $client;
}
/**
* Finds the directory where the phpunit.xml(.dist) is stored.
*
* If you run tests with the PHPUnit CLI tool, everything will work as expected.
* If not, override this method in your test classes.
*
* @return string The directory where phpunit.xml(.dist) is stored
*/
protected static function getPhpUnitXmlDir()
{
if (!isset($_SERVER['argv']) || false === strpos($_SERVER['argv'][0], 'phpunit')) {
throw new \RuntimeException('You must override the WebTestCase::createKernel() method.');
}
$dir = static::getPhpUnitCliConfigArgument();
if ($dir === null &&
(is_file(getcwd().DIRECTORY_SEPARATOR.'phpunit.xml') ||
is_file(getcwd().DIRECTORY_SEPARATOR.'phpunit.xml.dist'))) {
$dir = getcwd();
}
// Can't continue
if ($dir === null) {
throw new \RuntimeException('Unable to guess the Kernel directory.');
}
if (!is_dir($dir)) {
$dir = dirname($dir);
}
return $dir;
}
/**
* Finds the value of configuration flag from cli
*
* PHPUnit will use the last configuration argument on the command line, so this only returns
* the last configuration argument
*
* @return string The value of the phpunit cli configuration option
*/
private static function getPhpUnitCliConfigArgument()
{
$dir = null;
$reversedArgs = array_reverse($_SERVER['argv']);
foreach ($reversedArgs as $argIndex => $testArg) {
if ($testArg === '-c' || $testArg === '--configuration') {
$dir = realpath($reversedArgs[$argIndex - 1]);
break;
} elseif (strpos($testArg, '--configuration=') === 0) {
$argPath = substr($testArg, strlen('--configuration='));
$dir = realpath($argPath);
break;
}
}
return $dir;
}
/**
* Attempts to guess the kernel location.
*
* When the Kernel is located, the file is required.
*
* @return string The Kernel class name
*/
protected static function getKernelClass()
{
$dir = isset($_SERVER['KERNEL_DIR']) ? $_SERVER['KERNEL_DIR'] : static::getPhpUnitXmlDir();
$finder = new Finder();
$finder->name('*Kernel.php')->depth(0)->in($dir);
$results = iterator_to_array($finder);
if (!count($results)) {
throw new \RuntimeException('Either set KERNEL_DIR in your phpunit.xml according to http://symfony.com/doc/current/book/testing.html#your-first-functional-test or override the WebTestCase::createKernel() method.');
}
$file = current($results);
$class = $file->getBasename('.php');
require_once $file;
return $class;
}
/**
* Creates a Kernel.
*
* Available options:
*
* * environment
* * debug
*
* @param array $options An array of options
*
* @return HttpKernelInterface A HttpKernelInterface instance
*/
protected static function createKernel(array $options = array())
{
if (null === static::$class) {
static::$class = static::getKernelClass();
}
return new static::$class(
isset($options['environment']) ? $options['environment'] : 'test',
isset($options['debug']) ? $options['debug'] : true
);
}
/**
* Shuts the kernel down if it was used in the test.
*/
protected function tearDown()
{
if (null !== static::$kernel) {
static::$kernel->shutdown();
}
}
}
|
lrt/lrt
|
vendor/symfony/symfony/src/Symfony/Bundle/FrameworkBundle/Test/WebTestCase.php
|
PHP
|
mit
| 5,211 |
using System;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;
using Ical.Net.DataTypes;
namespace Ical.Net.Serialization.DataTypes
{
public class RequestStatusSerializer : StringSerializer
{
public RequestStatusSerializer() { }
public RequestStatusSerializer(SerializationContext ctx) : base(ctx) { }
public override Type TargetType => typeof (RequestStatus);
public override string SerializeToString(object obj)
{
try
{
var rs = obj as RequestStatus;
if (rs == null)
{
return null;
}
// Push the object onto the serialization stack
SerializationContext.Push(rs);
try
{
var factory = GetService<ISerializerFactory>();
var serializer = factory?.Build(typeof (StatusCode), SerializationContext) as IStringSerializer;
if (serializer == null)
{
return null;
}
var builder = new StringBuilder();
builder.Append(Escape(serializer.SerializeToString(rs.StatusCode)));
builder.Append(";");
builder.Append(Escape(rs.Description));
if (!string.IsNullOrWhiteSpace(rs.ExtraData))
{
builder.Append(";");
builder.Append(Escape(rs.ExtraData));
}
return Encode(rs, builder.ToString());
}
finally
{
// Pop the object off the serialization stack
SerializationContext.Pop();
}
}
catch
{
return null;
}
}
internal static readonly Regex NarrowRequestMatch = new Regex(@"(.*?[^\\]);(.*?[^\\]);(.+)", RegexOptions.Compiled);
internal static readonly Regex BroadRequestMatch = new Regex(@"(.*?[^\\]);(.+)", RegexOptions.Compiled);
public override object Deserialize(TextReader tr)
{
var value = tr.ReadToEnd();
var rs = CreateAndAssociate() as RequestStatus;
if (rs == null)
{
return null;
}
// Decode the value as needed
value = Decode(rs, value);
// Push the object onto the serialization stack
SerializationContext.Push(rs);
try
{
var factory = GetService<ISerializerFactory>();
if (factory == null)
{
return null;
}
var match = NarrowRequestMatch.Match(value);
if (!match.Success)
{
match = BroadRequestMatch.Match(value);
}
if (match.Success)
{
var serializer = factory.Build(typeof(StatusCode), SerializationContext) as IStringSerializer;
if (serializer == null)
{
return null;
}
rs.StatusCode = serializer.Deserialize(new StringReader(Unescape(match.Groups[1].Value))) as StatusCode;
rs.Description = Unescape(match.Groups[2].Value);
if (match.Groups.Count == 4)
{
rs.ExtraData = Unescape(match.Groups[3].Value);
}
return rs;
}
}
finally
{
// Pop the object off the serialization stack
SerializationContext.Pop();
}
return null;
}
}
}
|
rianjs/ical.net
|
src/Ical.Net/Serialization/DataTypes/RequestStatusSerializer.cs
|
C#
|
mit
| 3,938 |
# angucomplete-alt contributors (sorted alphabeticaly)
---
### [@alexbeletsky: Alexander Beletsky](https://github.com/alexbeletsky)
* Publish to NPM #111, #121
### [@alindber: Andy Lindberg](https://github.com/alindber)
* Required support #23
* Auto match #29
### [@andretw: Andre Lee](https://github.com/andretw)
* Bug fix #109
### [@annmirosh](https://github.com/annmirosh)
* Fix input event for mobile device #232 #178
### [@antony: Antony Jones](https://github.com/antony)
* Allow the user to set an initial value OBJECT instead of just a string #173
* Documentation update #180
### [@baloo2401](https://github.com/baloo2401)
* display-searching and display-no-result #129
### [@boshen](https://github.com/Boshen)
* Collaborator and excellent developer
* Add autocapitalize="off" autocorrect="off" autocomplete="off" #15
### [@davidgeary: David Geary](https://github.com/davidgeary)
* Missing 'type' field on input element when not specified #167
### [@Freezystem: Nico](https://github.com/Freezystem)
* Add focus-first #92 #242
### [@handiwijoyo: Handi Wijoyo](https://github.com/handiwijoyo)
* Add css to bower.json main #68
### [@iamgurdip](https://github.com/iamgurdip)
* Escape regular expression #123
### [@jbuquet: Javier Buquet](https://github.com/jbuquet)
* Add custom API handler #128
### [@jermspeaks: Jeremy Wong](https://github.com/jermspeaks)
* Support withCredentials for $http #113
### [@Leocrest](https://github.com/Leocrest)
* Clear input #61
### [@mcnocopo: Pachito Marco Calabrese](https://github.com/mcnocopo)
* Add input name and a not-empty class #124
### [@mmBs](https://github.com/mmBs)
* Add type attribute #96
### [@mrdevin: David Hartman](https://github.com/mrdevin)
* Set the form field to valid when the initialValue is added #59
### [@nekcih](https://github.com/nekcih)
* New callback handler, response translator, better template code format, and css fix #6
* Fixed support for IE8 #13
### [@peterjkirby: Peter Kirby](https://github.com/peterjkirby)
* Bug fix #97
### [@sdbondi: Stan Bondi](https://github.com/sdbondi)
* Custom template #74
### [@SpaceK33z: Kees Kluskens](https://github.com/SpaceK33z)
* Bug fix #62
### [@termleech](https://github.com/termleech)
* Add maxlength #136
### [@tomgutz: Tomas Gutierrez](https://github.com/tomgutz)
* Added delete keystroke together with backspace #4
### [@tuduong2](https://github.com/tuduong2)
* Encode search parameter #119
### [@urecio](https://github.com/urecio)
* Added input changed callback #12
### [@vhuerta: Victor Huerta Hernández](https://github.com/vhuerta)
* Custom strings for "searching" and "no results" #22
### [@YasuhiroYoshida: Yasuhiro Yoshida](https://github.com/YasuhiroYoshida)
* Fix pressing enter without selecting an item results in "No results found" message #31
* Implement 'update input field' #42
|
ItRuns/prototyping
|
public/lib/angucomplete-alt/CONTRIBUTORS.md
|
Markdown
|
mit
| 2,869 |
<?php return array(
//Use the below link to get the parameters to be passed.
//http://www.tig12.net/downloads/apidocs/wp/wp-includes/PHPMailer.class.html#det_fields_to
"type"=>array(
// Sets Mailer to send message using PHP mail() function. (true, false)
"IsMail"=>false,
// Sets Mailer to send message using SMTP. If set to true, other options are also available. (true, false )
"IsSMTP"=>true,
// Sets Mailer to send message using the Sendmail program. (true, false)
"IsSendmail"=>false,
// Sets Mailer to send message using the qmail MTA. (true, false )
"IsQmail"=>false
),
"smtp"=>array(
//Enable SMTP debugging
// 0 = off (for production use)
// 1 = client messages
// 2 = client and server messages
"SMTPDebug" => 0,
//Ask for HTML-friendly debug output
"Debugoutput" => 'html',
//Set the hostname of the mail server
"Host" => 'smtp.gmail.com',
//Set the SMTP port number - 587 for authenticated TLS, a.k.a. RFC4409 SMTP submission
"Port" => 587,
//Set the encryption system to use - ssl (deprecated) or tls
"SMTPSecure" => 'tls',
//Whether to use SMTP authentication
"SMTPAuth" => true,
//Username to use for SMTP authentication - use full email address for gmail
"Username" => "",
//Password to use for SMTP authentication
"Password" => "",
//Set who the message is to be sent from
"From" =>"",
//Set Name of the sender
"FromName"=>""
),
//Authenticate via POP3 (true, false)
//Now you should be clear to submit messages over SMTP for a while
//Only applies if your host supports POP-before-SMTP
"pop"=>array(false,"'pop3.example.com', 110, 30, 'username', 'password', 1")
);
|
alaksandarjesus/foreach2BiSmarty_master
|
app/mail.php
|
PHP
|
mit
| 1,634 |
<?php
namespace Oro\Bundle\ApiBundle\Tests\Unit\Processor;
use Doctrine\Common\Annotations\AnnotationReader;
use Symfony\Component\Form\Extension\Validator\ValidatorExtension;
use Symfony\Component\Form\FormBuilder;
use Symfony\Component\Form\FormExtensionInterface;
use Symfony\Component\Form\Forms;
use Symfony\Component\Validator\Validation;
use Oro\Bundle\ApiBundle\Config\EntityDefinitionConfigExtra;
use Oro\Bundle\ApiBundle\Processor\FormContext;
use Oro\Bundle\ApiBundle\Processor\SingleItemContext;
use Oro\Bundle\ApiBundle\Request\RequestType;
class FormProcessorTestCase extends \PHPUnit_Framework_TestCase
{
const TEST_VERSION = '1.1';
const TEST_REQUEST_TYPE = RequestType::REST;
/** @var FormContext|SingleItemContext */
protected $context;
/** @var \PHPUnit_Framework_MockObject_MockObject */
protected $configProvider;
/** @var \PHPUnit_Framework_MockObject_MockObject */
protected $metadataProvider;
protected function setUp()
{
$this->configProvider = $this->getMockBuilder('Oro\Bundle\ApiBundle\Provider\ConfigProvider')
->disableOriginalConstructor()
->getMock();
$this->metadataProvider = $this->getMockBuilder('Oro\Bundle\ApiBundle\Provider\MetadataProvider')
->disableOriginalConstructor()
->getMock();
$this->context = $this->createContext();
$this->context->setVersion(self::TEST_VERSION);
$this->context->getRequestType()->add(self::TEST_REQUEST_TYPE);
$this->context->setConfigExtras(
[
new EntityDefinitionConfigExtra($this->context->getAction())
]
);
}
/**
* @return FormContext
*/
protected function createContext()
{
return new FormContextStub($this->configProvider, $this->metadataProvider);
}
/**
* @param FormExtensionInterface[] $extensions
*
* @return FormBuilder
*/
protected function createFormBuilder(array $extensions = [])
{
$formFactory = Forms::createFormFactoryBuilder()
->addExtensions(array_merge($this->getFormExtensions(), $extensions))
->getFormFactory();
$dispatcher = $this->createMock('Symfony\Component\EventDispatcher\EventDispatcherInterface');
return new FormBuilder(null, null, $dispatcher, $formFactory);
}
/**
* @return FormExtensionInterface[]
*/
protected function getFormExtensions()
{
$validator = Validation::createValidatorBuilder()
->enableAnnotationMapping(new AnnotationReader())
->getValidator();
return [new ValidatorExtension($validator)];
}
}
|
Djamy/platform
|
src/Oro/Bundle/ApiBundle/Tests/Unit/Processor/FormProcessorTestCase.php
|
PHP
|
mit
| 2,709 |
# How to write your own technology
Starting with ENB version 0.8, we recommend using the `BuildFlow` helper for writing technologies.
[The helper source code](https://github.com/enb/enb/blob/master/lib/build-flow.js)
This guide doesn't cover all `BuildFlow` features. For a complete list of methods with descriptions, see the JSDoc file `build-flow.js`.
## Theory
A technology is aimed at building a [target](../../terms/terms.en.md) in the node. For example, the `css` technology can build `index.css` in the `pages/index` node from the `css` files for the [redefinition levels](https://en.beta.bem.info/methodology/key-concepts/#redefinition-level).
Each technology can accept settings.
The `BuildFlow` helper ensures that the maximum number of parameters is customizable.
Technologies can use the result of other technologies. For example, the list of source `css` files is built using the `files` technology.
## Technology for combining files by suffix
In general, the technology for combining files with a certain suffix looks like this:
```javascript
module.exports = require('enb/lib/build-flow').create() // Creates a BuildFlow instance
.name('js') // Choose the technology name
.target('target', '?.js') // Name of the option that sets the name for the output file and the default value
.useFileList('js') // Specify the suffixes for the build
.justJoinFilesWithComments() // One more helper. Joins the result and wraps it in /* ... */ comments
// The comments contain the path to the file from which the fragment was formed.
.createTech(); // Creates the technology with the helper
```
Consider a similar technology that doesn't use `justJoinFilesWithComments`:
```javascript
var Vow = require('vow'); // Promise library used in ENB
var vowFs = require('vow-fs'); // Using Vow to work with file system
module.exports = require('enb/lib/build-flow').create()
.name('js')
.target('target', '?.js')
.useFileList('js')
.builder(function(jsFiles) { // Returns the promise for ENB to wait until the asynchronous technology is executed
var node = this.node; // Saves the link to the `Node` class instance.
return Vow.all(jsFiles.map(function(file) { // Waits until the promises are resolved
return vowFs.read(file.fullname, 'utf8').then(function(data) { // Reads each source file
var filename = node.relativePath(file.fullname); // Receives the path from the node
// Builds fragments from the source file content
return '/* begin: ' + filename + ' *' + '/\n' + data + '\n/* end: ' + filename + ' *' + '/';
});
})).then(function(contents) { // Received the result of processing all source files
return contents.join('\n'); // Joins the received fragments using the line feed
});
})
.createTech();
```
Since we used the `useFileList` method, the `builder` received an argument with a list of files for the specified suffix.
Each `use` method adds an argument to the `builder`. The type and content of the arguments depend on which `use` method is used.
Let's add internationalization files to the resulting technology:
```javascript
var Vow = require('vow'); // The promise library used in ENB
var vowFs = require('vow-fs'); // Using Vow to work with the file system
module.exports = require('enb/lib/build-flow').create()
.name('js')
.target('target', '?.js')
.defineRequiredOption('lang') // Defines the required 'lang' option to set the language
.useFileList('js')
.useSourceText('allLangTarget', '?.lang.all.js') // Connects internationalization common for all languages,
// using the useSourceText, that adds the content of the specified source file
// to the builder as an argument
.useSourceText('langTarget', '?.lang.{lang}.js') // Connects the keysets of the specified language;
// here the lang option value is used to
// form the default value
.builder(function(jsFiles, allLangText, langText) {
var node = this.node;
return Vow.all(jsFiles.map(function(file) {
return vowFs.read(file.fullname, 'utf8').then(function(data) {
var filename = node.relativePath(file.fullname);
return '/* begin: ' + filename + ' *' + '/\n' + data + '\n/* end: ' + filename + ' *' + '/';
});
})).then(function(contents) {
return contents
.concat([allLangText, langText]) // Adds content fragments from internationalization files
.join('\n');
});
})
.createTech();
```
## Technology for joining multiple targets
Consider a ready-made example:
```javascript
// This example builds a localized priv.js
module.exports = require('enb/lib/build-flow').create()
.name('priv-js-i18n')
.target('target', '?.{lang}.priv.js')
.defineRequiredOption('lang')
// All the targets are prepared by other technologies:
.useSourceFilename('allLangTarget', '?.lang.all.js') // Sets the dependency from the name of the
// common internationalization file
.useSourceFilename('langTarget', '?.lang.{lang}.js') // Sets the dependency from the name of the
// specific language file
.useSourceFilename('privJsTarget', '?.priv.js') // Sets the dependency from the name of the
// priv-js file
.justJoinFilesWithComments() // Uses the helper to join the files
.createTech();
```
Joining without the helper:
```javascript
module.exports = require('enb/lib/build-flow').create()
.name('priv-js-i18n')
.target('target', '?.{lang}.priv.js')
.defineRequiredOption('lang')
.useSourceFilename('allLangTarget', '?.lang.all.js')
.useSourceFilename('langTarget', '?.lang.{lang}.js')
.useSourceFilename('privJsTarget', '?.priv.js')
.builder(function(allLangFilename, langFilename, privJsFilename) {
var node = this.node;
// Iterates through the source files
return Vow.all([allLangFilename, langFilename, privJsFilename].map(function(absoluteFilename) {
// Reads each source file
return vowFs.read(absoluteFilename, 'utf8').then(function(data) {
// Receives a relative file path
var filename = node.relativePath(absoluteFilename);
// Forms a fragment
return '/* begin: ' + filename + ' *' + '/\n' + data + '\n/* end: ' + filename + ' *' + '/';
});
})).then(function(contents) {
return contents.join('\n'); // Combines the fragments
});
})
.createTech();
```
## Dependencies from the files not included in the build
If you need to add a modular system in the beginning of a file and save the result with a new name:
```javascript
var vowFs = require('vow-fs'); // Connects the module for working with the file system
var path = require('path'); // Connects utilities for working with paths
module.exports = require('enb/lib/build-flow').create()
.name('prepend-modules')
.target('target', '?.js')
.defineRequiredOption('source') // Specifies the required option
.useSourceText('source', '?') // Sets the dependency from the content of the target defined by the 'source' option
.needRebuild(function(cache) { // Specifies an additional cache check
// In this case, the modular system isn't located at the source redefinition levels,
// but it can be found in the 'ym' package; for the rebuild to work correctly if
// the modules.js content changes, add the check
this._modulesFile = path.join(__dirname, '..', 'node_modules', 'ym', 'modules.js'); // Forms the path
return cache.needRebuildFile( // Checks if the file changed
'modules-file', // Key for caching the file information; must be unique within the technology
this._modulesFile // Path to the file for which the cache should be checked
);
})
.saveCache(function(cache) { // Saves the cache data in the used file
cache.cacheFileInfo( // Saves the file information
'modules-file', // Key for caching the file information; must be unique within the technology
this._modulesFile // Path to the file for which the cache should be checked
);
})
.builder(function(preTargetSource) {
// Reads the content of the modular system file
return vowFs.read(this._modulesFile, 'utf8').then(function(modulesRes) {
return modulesRes + preTargetSource; // Joins the results
});
})
.createTech();
```
### Creating a new technology from an existing one
Sometimes you need to to extend existing technologies.
Every technology made with `BuildFlow` contains the `buildFlow()` method that can be called to create a new technology from the functionality of the existing one.
For example, there is a `css` technology:
```javascript
module.exports = require('enb/lib/build-flow').create()
.name('css')
.target('target', '?.css')
.useFileList('css')
.builder(function(cssFiles) {
// ...
})
.methods({
// ...
})
.createTech();
```
To build `light.css` suffixes together with `css` suffixes, you need to write a new technology that borrows the functionality of the old one:
```javascript
module.exports = require('enb/techs/css').buildFlow()
.name('css-light') // Changes the name
.useFileList(['css', 'light.css']) // Changes the necessary parameters
.createTech();
```
|
enb-make/enb
|
docs/guides/write-tech/write-tech.en.md
|
Markdown
|
mit
| 9,910 |
.help {
cursor: help;
display: inline-block;
font-size: 18px;
margin-left: .33em;
vertical-align: middle;
}
|
dmitru/react-redux-router-expense-tracker-example-app
|
app/components/FormFields/Help.css
|
CSS
|
mit
| 128 |
---
layout: page-fullwidth
subheadline: "Celebration"
title: "Tết Nguyên Đán 2015"
meta_teaser: "Tet Nguyen Đan 2015 at VACSF"
teaser: 'Celebration of <font face="Open Sans">Tết Nguyên Đán</font> (Lunar New Year) of 2015 at <font face="Open Sans">Hội Thánh Tin Lành Việt Nam</font> in the city of San Francisco (VACSF). Enjoy this collection of photos.'
header: no
categories:
- events
---
<!--more-->
<div class="flex-video"> <iframe width="100%" height="720" src="http://rgb-scale.com/vacsfj336/index.php/photo-galleries/135-t-t-nguyen-dan-2015" frameborder="0" allowfullscreen=""></iframe></div>
<div class="small-12 columns" style="padding: 0px; border-bottom: none;">
<p> </p>
{% include next-previous-post-in-category %}
</div>
|
nghin318/vacsf.org
|
_posts/events/2015-02-18-Tet-Nguyen-Dan.md
|
Markdown
|
mit
| 768 |
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = function (fn /*, ...args*/) {
var args = (0, _slice2.default)(arguments, 1);
return function () /*callArgs*/{
var callArgs = (0, _slice2.default)(arguments);
return fn.apply(null, args.concat(callArgs));
};
};
var _slice = require('./internal/slice');
var _slice2 = _interopRequireDefault(_slice);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
;
/**
* Creates a continuation function with some arguments already applied.
*
* Useful as a shorthand when combined with other control flow functions. Any
* arguments passed to the returned function are added to the arguments
* originally passed to apply.
*
* @name apply
* @static
* @memberOf module:Utils
* @method
* @category Util
* @param {Function} fn - The function you want to eventually apply all
* arguments to. Invokes with (arguments...).
* @param {...*} arguments... - Any number of arguments to automatically apply
* when the continuation is called.
* @returns {Function} the partially-applied function
* @example
*
* // using apply
* async.parallel([
* async.apply(fs.writeFile, 'testfile1', 'test1'),
* async.apply(fs.writeFile, 'testfile2', 'test2')
* ]);
*
*
* // the same process without using apply
* async.parallel([
* function(callback) {
* fs.writeFile('testfile1', 'test1', callback);
* },
* function(callback) {
* fs.writeFile('testfile2', 'test2', callback);
* }
* ]);
*
* // It's possible to pass any number of additional arguments when calling the
* // continuation:
*
* node> var fn = async.apply(sys.puts, 'one');
* node> fn('two', 'three');
* one
* two
* three
*/
module.exports = exports['default'];
|
Moccine/global-service-plus.com
|
web/libariries/bootstrap/node_modules/phantomjs/node_modules/async/apply.js
|
JavaScript
|
mit
| 1,910 |
/****************************************************************************
Copyright (c) 2010-2012 cocos2d-x.org
Copyright (c) 2009-2010 Ricardo Quesada
Copyright (c) 2011 Zynga Inc.
http://www.cocos2d-x.org
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
****************************************************************************/
#ifndef __CCTMX_LAYER_H__
#define __CCTMX_LAYER_H__
#include "CCTMXObjectGroup.h"
#include "base_nodes/CCAtlasNode.h"
#include "sprite_nodes/CCSpriteBatchNode.h"
#include "CCTMXXMLParser.h"
#include "support/data_support/ccCArray.h"
NS_CC_BEGIN
class TMXMapInfo;
class TMXLayerInfo;
class TMXTilesetInfo;
struct _ccCArray;
/**
* @addtogroup tilemap_parallax_nodes
* @{
*/
/** @brief TMXLayer represents the TMX layer.
It is a subclass of SpriteBatchNode. By default the tiles are rendered using a TextureAtlas.
If you modify a tile on runtime, then, that tile will become a Sprite, otherwise no Sprite objects are created.
The benefits of using Sprite objects as tiles are:
- tiles (Sprite) can be rotated/scaled/moved with a nice API
If the layer contains a property named "cc_vertexz" with an integer (in can be positive or negative),
then all the tiles belonging to the layer will use that value as their OpenGL vertex Z for depth.
On the other hand, if the "cc_vertexz" property has the "automatic" value, then the tiles will use an automatic vertex Z value.
Also before drawing the tiles, GL_ALPHA_TEST will be enabled, and disabled after drawing them. The used alpha func will be:
glAlphaFunc( GL_GREATER, value )
"value" by default is 0, but you can change it from Tiled by adding the "cc_alpha_func" property to the layer.
The value 0 should work for most cases, but if you have tiles that are semi-transparent, then you might want to use a different
value, like 0.5.
For further information, please see the programming guide:
http://www.cocos2d-iphone.org/wiki/doku.php/prog_guide:tiled_maps
@since v0.8.1
Tiles can have tile flags for additional properties. At the moment only flip horizontal and flip vertical are used. These bit flags are defined in TMXXMLParser.h.
@since 1.1
*/
class CC_DLL TMXLayer : public SpriteBatchNode
{
public:
/** creates a TMXLayer with an tileset info, a layer info and a map info */
static TMXLayer * create(TMXTilesetInfo *tilesetInfo, TMXLayerInfo *layerInfo, TMXMapInfo *mapInfo);
TMXLayer();
virtual ~TMXLayer();
/** initializes a TMXLayer with a tileset info, a layer info and a map info */
bool initWithTilesetInfo(TMXTilesetInfo *tilesetInfo, TMXLayerInfo *layerInfo, TMXMapInfo *mapInfo);
/** dealloc the map that contains the tile position from memory.
Unless you want to know at runtime the tiles positions, you can safely call this method.
If you are going to call layer->tileGIDAt() then, don't release the map
*/
void releaseMap();
/** returns the tile (Sprite) at a given a tile coordinate.
The returned Sprite will be already added to the TMXLayer. Don't add it again.
The Sprite can be treated like any other Sprite: rotated, scaled, translated, opacity, color, etc.
You can remove either by calling:
- layer->removeChild(sprite, cleanup);
- or layer->removeTileAt(Point(x,y));
*/
Sprite* getTileAt(const Point& tileCoordinate);
CC_DEPRECATED_ATTRIBUTE Sprite* tileAt(const Point& tileCoordinate) { return getTileAt(tileCoordinate); };
/** returns the tile gid at a given tile coordinate. It also returns the tile flags.
This method requires the the tile map has not been previously released (eg. don't call [layer releaseMap])
*/
unsigned int getTileGIDAt(const Point& tileCoordinate, ccTMXTileFlags* flags = nullptr);
CC_DEPRECATED_ATTRIBUTE unsigned int tileGIDAt(const Point& tileCoordinate, ccTMXTileFlags* flags = nullptr){
return getTileGIDAt(tileCoordinate, flags);
};
/** sets the tile gid (gid = tile global id) at a given tile coordinate.
The Tile GID can be obtained by using the method "tileGIDAt" or by using the TMX editor -> Tileset Mgr +1.
If a tile is already placed at that position, then it will be removed.
*/
void setTileGID(unsigned int gid, const Point& tileCoordinate);
/** sets the tile gid (gid = tile global id) at a given tile coordinate.
The Tile GID can be obtained by using the method "tileGIDAt" or by using the TMX editor -> Tileset Mgr +1.
If a tile is already placed at that position, then it will be removed.
Use withFlags if the tile flags need to be changed as well
*/
void setTileGID(unsigned int gid, const Point& tileCoordinate, ccTMXTileFlags flags);
/** removes a tile at given tile coordinate */
void removeTileAt(const Point& tileCoordinate);
/** returns the position in points of a given tile coordinate */
Point getPositionAt(const Point& tileCoordinate);
CC_DEPRECATED_ATTRIBUTE Point positionAt(const Point& tileCoordinate) { return getPositionAt(tileCoordinate); };
/** return the value for the specific property name */
String* getProperty(const char *propertyName) const;
CC_DEPRECATED_ATTRIBUTE String* propertyNamed(const char *propertyName) const { return getProperty(propertyName); };
/** Creates the tiles */
void setupTiles();
inline const char* getLayerName(){ return _layerName.c_str(); }
inline void setLayerName(const char *layerName){ _layerName = layerName; }
/** size of the layer in tiles */
inline const Size& getLayerSize() const { return _layerSize; };
inline void setLayerSize(const Size& size) { _layerSize = size; };
/** size of the map's tile (could be different from the tile's size) */
inline const Size& getMapTileSize() const { return _mapTileSize; };
inline void setMapTileSize(const Size& size) { _mapTileSize = size; };
/** pointer to the map of tiles */
inline unsigned int* getTiles() const { return _tiles; };
inline void setTiles(unsigned int* tiles) { _tiles = tiles; };
/** Tileset information for the layer */
inline TMXTilesetInfo* getTileSet() const { return _tileSet; };
inline void setTileSet(TMXTilesetInfo* info) {
CC_SAFE_RETAIN(info);
CC_SAFE_RELEASE(_tileSet);
_tileSet = info;
};
/** Layer orientation, which is the same as the map orientation */
inline unsigned int getLayerOrientation() const { return _layerOrientation; };
inline void setLayerOrientation(unsigned int orientation) { _layerOrientation = orientation; };
/** properties from the layer. They can be added using Tiled */
inline Dictionary* getProperties() const { return _properties; };
inline void setProperties(Dictionary* properties) {
CC_SAFE_RETAIN(properties);
CC_SAFE_RELEASE(_properties);
_properties = properties;
};
//
// Override
//
/** TMXLayer doesn't support adding a Sprite manually.
@warning addchild(z, tag); is not supported on TMXLayer. Instead of setTileGID.
*/
virtual void addChild(Node * child, int zOrder, int tag) override;
// super method
void removeChild(Node* child, bool cleanup) override;
private:
Point getPositionForIsoAt(const Point& pos);
Point getPositionForOrthoAt(const Point& pos);
Point getPositionForHexAt(const Point& pos);
Point calculateLayerOffset(const Point& offset);
/* optimization methods */
Sprite* appendTileForGID(unsigned int gid, const Point& pos);
Sprite* insertTileForGID(unsigned int gid, const Point& pos);
Sprite* updateTileForGID(unsigned int gid, const Point& pos);
/* The layer recognizes some special properties, like cc_vertez */
void parseInternalProperties();
void setupTileSprite(Sprite* sprite, Point pos, unsigned int gid);
Sprite* reusedTileWithRect(Rect rect);
int getVertexZForPos(const Point& pos);
// index
unsigned int atlasIndexForExistantZ(unsigned int z);
unsigned int atlasIndexForNewZ(int z);
protected:
//! name of the layer
std::string _layerName;
//! TMX Layer supports opacity
unsigned char _opacity;
unsigned int _minGID;
unsigned int _maxGID;
//! Only used when vertexZ is used
int _vertexZvalue;
bool _useAutomaticVertexZ;
//! used for optimization
Sprite *_reusedTile;
ccCArray *_atlasIndexArray;
// used for retina display
float _contentScaleFactor;
/** size of the layer in tiles */
Size _layerSize;
/** size of the map's tile (could be different from the tile's size) */
Size _mapTileSize;
/** pointer to the map of tiles */
unsigned int* _tiles;
/** Tileset information for the layer */
TMXTilesetInfo* _tileSet;
/** Layer orientation, which is the same as the map orientation */
unsigned int _layerOrientation;
/** properties from the layer. They can be added using Tiled */
Dictionary* _properties;
};
// end of tilemap_parallax_nodes group
/// @}
NS_CC_END
#endif //__CCTMX_LAYER_H__
|
qq2588258/floweers
|
libs/cocos2dx/tilemap_parallax_nodes/CCTMXLayer.h
|
C
|
mit
| 10,152 |
# app
The `app` module is responsible for controlling the application's lifecycle.
The following example shows how to quit the application when the last window is
closed:
```javascript
const app = require('electron').app;
app.on('window-all-closed', function() {
app.quit();
});
```
## Events
The `app` object emits the following events:
### Event: 'will-finish-launching'
Emitted when the application has finished basic startup. On Windows and Linux,
the `will-finish-launching` event is the same as the `ready` event; on OS X,
this event represents the `applicationWillFinishLaunching` notification of
`NSApplication`. You would usually set up listeners for the `open-file` and
`open-url` events here, and start the crash reporter and auto updater.
In most cases, you should just do everything in the `ready` event handler.
### Event: 'ready'
Emitted when Electron has finished initialization.
### Event: 'window-all-closed'
Emitted when all windows have been closed.
This event is only emitted when the application is not going to quit. If the
user pressed `Cmd + Q`, or the developer called `app.quit()`, Electron will
first try to close all the windows and then emit the `will-quit` event, and in
this case the `window-all-closed` event would not be emitted.
### Event: 'before-quit'
Returns:
* `event` Event
Emitted before the application starts closing its windows.
Calling `event.preventDefault()` will prevent the default behaviour, which is
terminating the application.
### Event: 'will-quit'
Returns:
* `event` Event
Emitted when all windows have been closed and the application will quit.
Calling `event.preventDefault()` will prevent the default behaviour, which is
terminating the application.
See the description of the `window-all-closed` event for the differences between
the `will-quit` and `window-all-closed` events.
### Event: 'quit'
Returns:
* `event` Event
* `exitCode` Integer
Emitted when the application is quitting.
### Event: 'open-file' _OS X_
Returns:
* `event` Event
* `path` String
Emitted when the user wants to open a file with the application. The `open-file`
event is usually emitted when the application is already open and the OS wants
to reuse the application to open the file. `open-file` is also emitted when a
file is dropped onto the dock and the application is not yet running. Make sure
to listen for the `open-file` event very early in your application startup to
handle this case (even before the `ready` event is emitted).
You should call `event.preventDefault()` if you want to handle this event.
On Windows, you have to parse `process.argv` to get the filepath.
### Event: 'open-url' _OS X_
Returns:
* `event` Event
* `url` String
Emitted when the user wants to open a URL with the application. The URL scheme
must be registered to be opened by your application.
You should call `event.preventDefault()` if you want to handle this event.
### Event: 'activate' _OS X_
Returns:
* `event` Event
* `hasVisibleWindows` Boolean
Emitted when the application is activated, which usually happens when clicks on
the applications's dock icon.
### Event: 'browser-window-blur'
Returns:
* `event` Event
* `window` BrowserWindow
Emitted when a [browserWindow](browser-window.md) gets blurred.
### Event: 'browser-window-focus'
Returns:
* `event` Event
* `window` BrowserWindow
Emitted when a [browserWindow](browser-window.md) gets focused.
### Event: 'browser-window-created'
Returns:
* `event` Event
* `window` BrowserWindow
Emitted when a new [browserWindow](browser-window.md) is created.
### Event: 'certificate-error'
Returns:
* `event` Event
* `webContents` [WebContents](web-contents.md)
* `url` URL
* `error` String - The error code
* `certificate` Object
* `data` Buffer - PEM encoded data
* `issuerName` String
* `callback` Function
Emitted when failed to verify the `certificate` for `url`, to trust the
certificate you should prevent the default behavior with
`event.preventDefault()` and call `callback(true)`.
```javascript
session.on('certificate-error', function(event, webContents, url, error, certificate, callback) {
if (url == "https://github.com") {
// Verification logic.
event.preventDefault();
callback(true);
} else {
callback(false);
}
});
```
### Event: 'select-client-certificate'
Returns:
* `event` Event
* `webContents` [WebContents](web-contents.md)
* `url` URL
* `certificateList` [Objects]
* `data` Buffer - PEM encoded data
* `issuerName` String - Issuer's Common Name
* `callback` Function
Emitted when a client certificate is requested.
The `url` corresponds to the navigation entry requesting the client certificate
and `callback` needs to be called with an entry filtered from the list. Using
`event.preventDefault()` prevents the application from using the first
certificate from the store.
```javascript
app.on('select-client-certificate', function(event, webContents, url, list, callback) {
event.preventDefault();
callback(list[0]);
})
```
### Event: 'login'
Returns:
* `event` Event
* `webContents` [WebContents](web-contents.md)
* `request` Object
* `method` String
* `url` URL
* `referrer` URL
* `authInfo` Object
* `isProxy` Boolean
* `scheme` String
* `host` String
* `port` Integer
* `realm` String
* `callback` Function
Emitted when `webContents` wants to do basic auth.
The default behavior is to cancel all authentications, to override this you
should prevent the default behavior with `event.preventDefault()` and call
`callback(username, password)` with the credentials.
```javascript
app.on('login', function(event, webContents, request, authInfo, callback) {
event.preventDefault();
callback('username', 'secret');
})
```
### Event: 'gpu-process-crashed'
Emitted when the gpu process crashes.
## Methods
The `app` object has the following methods:
**Note:** Some methods are only available on specific operating systems and are labeled as such.
### `app.quit()`
Try to close all windows. The `before-quit` event will be emitted first. If all
windows are successfully closed, the `will-quit` event will be emitted and by
default the application will terminate.
This method guarantees that all `beforeunload` and `unload` event handlers are
correctly executed. It is possible that a window cancels the quitting by
returning `false` in the `beforeunload` event handler.
### `app.hide()` _OS X_
Hides all application windows without minimising them.
### `app.show()` _OS X_
Shows application windows after they were hidden. Does not automatically focus them.
### `app.exit(exitCode)`
* `exitCode` Integer
Exits immediately with `exitCode`.
All windows will be closed immediately without asking user and the `before-quit`
and `will-quit` events will not be emitted.
### `app.getAppPath()`
Returns the current application directory.
### `app.getPath(name)`
* `name` String
Retrieves a path to a special directory or file associated with `name`. On
failure an `Error` is thrown.
You can request the following paths by the name:
* `home` User's home directory.
* `appData` Per-user application data directory, which by default points to:
* `%APPDATA%` on Windows
* `$XDG_CONFIG_HOME` or `~/.config` on Linux
* `~/Library/Application Support` on OS X
* `userData` The directory for storing your app's configuration files, which by
default it is the `appData` directory appended with your app's name.
* `temp` Temporary directory.
* `exe` The current executable file.
* `module` The `libchromiumcontent` library.
* `desktop` The current user's Desktop directory.
* `documents` Directory for a user's "My Documents".
* `downloads` Directory for a user's downloads.
* `music` Directory for a user's music.
* `pictures` Directory for a user's pictures.
* `videos` Directory for a user's videos.
### `app.setPath(name, path)`
* `name` String
* `path` String
Overrides the `path` to a special directory or file associated with `name`. If
the path specifies a directory that does not exist, the directory will be
created by this method. On failure an `Error` is thrown.
You can only override paths of a `name` defined in `app.getPath`.
By default, web pages' cookies and caches will be stored under the `userData`
directory. If you want to change this location, you have to override the
`userData` path before the `ready` event of the `app` module is emitted.
### `app.getVersion()`
Returns the version of the loaded application. If no version is found in the
application's `package.json` file, the version of the current bundle or
executable is returned.
### `app.getName()`
Returns the current application's name, which is the name in the application's
`package.json` file.
Usually the `name` field of `package.json` is a short lowercased name, according
to the npm modules spec. You should usually also specify a `productName`
field, which is your application's full capitalized name, and which will be
preferred over `name` by Electron.
### `app.getLocale()`
Returns the current application locale.
### `app.addRecentDocument(path)` _OS X_ _Windows_
* `path` String
Adds `path` to the recent documents list.
This list is managed by the OS. On Windows you can visit the list from the task
bar, and on OS X you can visit it from dock menu.
### `app.clearRecentDocuments()` _OS X_ _Windows_
Clears the recent documents list.
### `app.setUserTasks(tasks)` _Windows_
* `tasks` Array - Array of `Task` objects
Adds `tasks` to the [Tasks][tasks] category of the JumpList on Windows.
`tasks` is an array of `Task` objects in the following format:
`Task` Object:
* `program` String - Path of the program to execute, usually you should
specify `process.execPath` which opens the current program.
* `arguments` String - The command line arguments when `program` is
executed.
* `title` String - The string to be displayed in a JumpList.
* `description` String - Description of this task.
* `iconPath` String - The absolute path to an icon to be displayed in a
JumpList, which can be an arbitrary resource file that contains an icon. You
can usually specify `process.execPath` to show the icon of the program.
* `iconIndex` Integer - The icon index in the icon file. If an icon file
consists of two or more icons, set this value to identify the icon. If an
icon file consists of one icon, this value is 0.
### `app.allowNTLMCredentialsForAllDomains(allow)`
* `allow` Boolean
Dynamically sets whether to always send credentials for HTTP NTLM or Negotiate
authentication - normally, Electron will only send NTLM/Kerberos credentials for
URLs that fall under "Local Intranet" sites (i.e. are in the same domain as you).
However, this detection often fails when corporate networks are badly configured,
so this lets you co-opt this behavior and enable it for all URLs.
### `app.makeSingleInstance(callback)`
* `callback` Function
This method makes your application a Single Instance Application - instead of
allowing multiple instances of your app to run, this will ensure that only a
single instance of your app is running, and other instances signal this
instance and exit.
`callback` will be called with `callback(argv, workingDirectory)` when a second
instance has been executed. `argv` is an Array of the second instance's command
line arguments, and `workingDirectory` is its current working directory. Usually
applications respond to this by making their primary window focused and
non-minimized.
The `callback` is guaranteed to be executed after the `ready` event of `app`
gets emitted.
This method returns `false` if your process is the primary instance of the
application and your app should continue loading. And returns `true` if your
process has sent its parameters to another instance, and you should immediately
quit.
On OS X the system enforces single instance automatically when users try to open
a second instance of your app in Finder, and the `open-file` and `open-url`
events will be emitted for that. However when users start your app in command
line the system's single instance machanism will be bypassed and you have to
use this method to ensure single instance.
An example of activating the window of primary instance when a second instance
starts:
```js
var myWindow = null;
var shouldQuit = app.makeSingleInstance(function(commandLine, workingDirectory) {
// Someone tried to run a second instance, we should focus our window.
if (myWindow) {
if (myWindow.isMinimized()) myWindow.restore();
myWindow.focus();
}
return true;
});
if (shouldQuit) {
app.quit();
return;
}
// Create myWindow, load the rest of the app, etc...
app.on('ready', function() {
});
```
### `app.setAppUserModelId(id)` _Windows_
* `id` String
Changes the [Application User Model ID][app-user-model-id] to `id`.
### `app.isAeroGlassEnabled()` _Windows_
This method returns `true` if [DWM composition](https://msdn.microsoft.com/en-us/library/windows/desktop/aa969540.aspx)
(Aero Glass) is enabled, and `false` otherwise. You can use it to determine if
you should create a transparent window or not (transparent windows won't work
correctly when DWM composition is disabled).
Usage example:
```js
let browserOptions = {width: 1000, height: 800};
// Make the window transparent only if the platform supports it.
if (process.platform !== 'win32' || app.isAeroGlassEnabled()) {
browserOptions.transparent = true;
browserOptions.frame = false;
}
// Create the window.
win = new BrowserWindow(browserOptions);
// Navigate.
if (browserOptions.transparent) {
win.loadURL('file://' + __dirname + '/index.html');
} else {
// No transparency, so we load a fallback that uses basic styles.
win.loadURL('file://' + __dirname + '/fallback.html');
}
```
### `app.commandLine.appendSwitch(switch[, value])`
Append a switch (with optional `value`) to Chromium's command line.
**Note:** This will not affect `process.argv`, and is mainly used by developers
to control some low-level Chromium behaviors.
### `app.commandLine.appendArgument(value)`
Append an argument to Chromium's command line. The argument will be quoted
correctly.
**Note:** This will not affect `process.argv`.
### `app.dock.bounce([type])` _OS X_
* `type` String (optional) - Can be `critical` or `informational`. The default is
`informational`
When `critical` is passed, the dock icon will bounce until either the
application becomes active or the request is canceled.
When `informational` is passed, the dock icon will bounce for one second.
However, the request remains active until either the application becomes active
or the request is canceled.
Returns an ID representing the request.
### `app.dock.cancelBounce(id)` _OS X_
* `id` Integer
Cancel the bounce of `id`.
### `app.dock.setBadge(text)` _OS X_
* `text` String
Sets the string to be displayed in the dock’s badging area.
### `app.dock.getBadge()` _OS X_
Returns the badge string of the dock.
### `app.dock.hide()` _OS X_
Hides the dock icon.
### `app.dock.show()` _OS X_
Shows the dock icon.
### `app.dock.setMenu(menu)` _OS X_
* `menu` Menu
Sets the application's [dock menu][dock-menu].
### `app.dock.setIcon(image)` _OS X_
* `image` [NativeImage](native-image.md)
Sets the `image` associated with this dock icon.
[dock-menu]:https://developer.apple.com/library/mac/documentation/Carbon/Conceptual/customizing_docktile/concepts/dockconcepts.html#//apple_ref/doc/uid/TP30000986-CH2-TPXREF103
[tasks]:http://msdn.microsoft.com/en-us/library/windows/desktop/dd378460(v=vs.85).aspx#tasks
[app-user-model-id]: https://msdn.microsoft.com/en-us/library/windows/desktop/dd378459(v=vs.85).aspx
|
thingsinjars/electron
|
docs/api/app.md
|
Markdown
|
mit
| 15,646 |
'use strict';
var path = require('path');
var helpers = require('yeoman-generator').test;
var assert = require('yeoman-assert');
describe('test framework', function () {
describe('mocha', function () {
before(function (done) {
helpers.run(path.join(__dirname, '../app'))
.inDir(path.join(__dirname, '.tmp'))
.withOptions({
'skip-install': true,
'test-framework': 'mocha'
})
.withPrompts({features: []})
.on('end', done);
});
it('adds the Grunt plugin', function () {
assert.fileContent('package.json', '"grunt-mocha"');
});
it('adds the Grunt task', function () {
assert.fileContent('Gruntfile.js', 'mocha');
});
it('uses the ESLint environment', function () {
assert.fileContent('package.json', '"mocha"');
});
});
describe('jasmine', function () {
before(function (done) {
helpers.run(path.join(__dirname, '../app'))
.inDir(path.join(__dirname, '.tmp'))
.withOptions({
'skip-install': true,
'test-framework': 'jasmine'
})
.withPrompts({features: []})
.on('end', done);
});
it('adds the Grunt plugin', function () {
assert.fileContent('package.json', '"grunt-contrib-jasmine"');
});
it('adds the Grunt task', function () {
assert.fileContent('Gruntfile.js', 'jasmine');
});
it('uses the ESLint environment', function () {
assert.fileContent('package.json', '"jasmine"');
});
});
});
|
snatera15/generator-webapp-material
|
test/test-framework.js
|
JavaScript
|
mit
| 1,532 |
/*jshint maxstatements:false*/
define(function (require, exports) {
"use strict";
var moment = require("moment"),
Promise = require("bluebird"),
_ = brackets.getModule("thirdparty/lodash"),
CodeInspection = brackets.getModule("language/CodeInspection"),
CommandManager = brackets.getModule("command/CommandManager"),
Commands = brackets.getModule("command/Commands"),
Dialogs = brackets.getModule("widgets/Dialogs"),
DocumentManager = brackets.getModule("document/DocumentManager"),
EditorManager = brackets.getModule("editor/EditorManager"),
FileUtils = brackets.getModule("file/FileUtils"),
FileViewController = brackets.getModule("project/FileViewController"),
KeyBindingManager = brackets.getModule("command/KeyBindingManager"),
LanguageManager = brackets.getModule("language/LanguageManager"),
FileSystem = brackets.getModule("filesystem/FileSystem"),
Menus = brackets.getModule("command/Menus"),
FindInFiles = brackets.getModule("search/FindInFiles"),
PanelManager = brackets.getModule("view/PanelManager"),
ProjectManager = brackets.getModule("project/ProjectManager"),
StringUtils = brackets.getModule("utils/StringUtils"),
Svn = require("src/svn/Svn"),
Events = require("./Events"),
EventEmitter = require("./EventEmitter"),
Preferences = require("./Preferences"),
ErrorHandler = require("./ErrorHandler"),
ExpectedError = require("./ExpectedError"),
Main = require("./Main"),
GutterManager = require("./GutterManager"),
Strings = require("../strings"),
Utils = require("src/Utils"),
SettingsDialog = require("./SettingsDialog"),
PANEL_COMMAND_ID = "brackets-git.panel";
var svnPanelTemplate = require("text!templates/svn-panel.html"),
gitPanelResultsTemplate = require("text!templates/git-panel-results.html"),
gitAuthorsDialogTemplate = require("text!templates/authors-dialog.html"),
gitCommitDialogTemplate = require("text!templates/git-commit-dialog.html"),
gitDiffDialogTemplate = require("text!templates/git-diff-dialog.html"),
questionDialogTemplate = require("text!templates/git-question-dialog.html");
var showFileWhiteList = /^\.gitignore$/;
var gitPanel = null,
$gitPanel = $(null),
gitPanelDisabled = null,
gitPanelMode = null,
showingUntracked = true,
$tableContainer = $(null);
/**
* Reloads the Document's contents from disk, discarding any unsaved changes in the editor.
*
* @param {!Document} doc
* @return {Promise} Resolved after editor has been refreshed; rejected if unable to load the
* file's new content. Errors are logged but no UI is shown.
*/
function _reloadDoc(doc) {
return Promise.cast(FileUtils.readAsText(doc.file))
.then(function (text) {
doc.refreshText(text, new Date());
})
.catch(function (err) {
ErrorHandler.logError("Error reloading contents of " + doc.file.fullPath);
ErrorHandler.logError(err);
});
}
function lintFile(filename) {
return CodeInspection.inspectFile(FileSystem.getFileForPath(Utils.getProjectRoot() + filename));
}
function _makeDialogBig($dialog) {
var $wrapper = $dialog.parents(".modal-wrapper").first();
if ($wrapper.length === 0) { return; }
// We need bigger commit dialog
var minWidth = 500,
minHeight = 300,
maxWidth = $wrapper.width(),
maxHeight = $wrapper.height(),
desiredWidth = maxWidth / 2,
desiredHeight = maxHeight / 2;
if (desiredWidth < minWidth) { desiredWidth = minWidth; }
if (desiredHeight < minHeight) { desiredHeight = minHeight; }
$dialog
.width(desiredWidth)
.children(".modal-body")
.css("max-height", desiredHeight)
.end();
return { width: desiredWidth, height: desiredHeight };
}
function _showCommitDialog(stagedDiff, lintResults, prefilledMessage) {
// Flatten the error structure from various providers
lintResults.forEach(function (lintResult) {
lintResult.errors = [];
if (Array.isArray(lintResult.result)) {
lintResult.result.forEach(function (resultSet) {
if (!resultSet.result || !resultSet.result.errors) { return; }
var providerName = resultSet.provider.name;
resultSet.result.errors.forEach(function (e) {
lintResult.errors.push((e.pos.line + 1) + ": " + e.message + " (" + providerName + ")");
});
});
} else {
ErrorHandler.logError("[brackets-git] lintResults contain object in unexpected format: " + JSON.stringify(lintResult));
}
lintResult.hasErrors = lintResult.errors.length > 0;
});
// Filter out only results with errors to show
lintResults = _.filter(lintResults, function (lintResult) {
return lintResult.hasErrors;
});
// Open the dialog
var compiledTemplate = Mustache.render(gitCommitDialogTemplate, {
Strings: Strings,
hasLintProblems: lintResults.length > 0,
lintResults: lintResults
}),
dialog = Dialogs.showModalDialogUsingTemplate(compiledTemplate),
$dialog = dialog.getElement();
// We need bigger commit dialog
_makeDialogBig($dialog);
// Show nicely colored commit diff
$dialog.find(".commit-diff").append(Utils.formatDiff(stagedDiff));
function getCommitMessageElement() {
var r = $dialog.find("[name='commit-message']:visible");
if (r.length !== 1) {
r = $dialog.find("[name='commit-message']");
for (var i = 0; i < r.length; i++) {
if ($(r[i]).css("display") !== "none") {
return $(r[i]);
}
}
}
return r;
}
var $commitMessageCount = $dialog.find("input[name='commit-message-count']");
// Add event to count characters in commit message
var recalculateMessageLength = function () {
var val = getCommitMessageElement().val().trim(),
length = val.length;
if (val.indexOf("\n")) {
// longest line
length = Math.max.apply(null, val.split("\n").map(function (l) { return l.length; }));
}
$commitMessageCount
.val(length)
.toggleClass("over50", length > 50 && length <= 100)
.toggleClass("over100", length > 100);
};
var usingTextArea = false;
// commit message handling
function switchCommitMessageElement() {
usingTextArea = !usingTextArea;
var findStr = "[name='commit-message']",
currentValue = $dialog.find(findStr + ":visible").val();
$dialog.find(findStr).toggle();
$dialog.find(findStr + ":visible")
.val(currentValue)
.focus();
recalculateMessageLength();
}
$dialog.find("button.primary").on("click", function (e) {
var $commitMessage = getCommitMessageElement();
if ($commitMessage.val().trim().length === 0) {
e.stopPropagation();
$commitMessage.addClass("invalid");
} else {
$commitMessage.removeClass("invalid");
}
});
$dialog.find("button.extendedCommit").on("click", function () {
switchCommitMessageElement();
// this value will be set only when manually triggered
Preferences.set("useTextAreaForCommitByDefault", usingTextArea);
});
function prefillMessage(msg) {
if (msg.indexOf("\n") !== -1 && !usingTextArea) {
switchCommitMessageElement();
}
$dialog.find("[name='commit-message']:visible").val(msg);
recalculateMessageLength();
}
if (Preferences.get("useTextAreaForCommitByDefault")) {
switchCommitMessageElement();
}
if (prefilledMessage) {
prefillMessage(prefilledMessage.trim());
}
// Add focus to commit message input
getCommitMessageElement().focus();
$dialog.find("[name='commit-message']")
.on("keyup", recalculateMessageLength)
.on("change", recalculateMessageLength);
recalculateMessageLength();
dialog.done(function (buttonId) {
if (buttonId === "ok") {
// this event won't launch when commit-message is empty so its safe to assume that it is not
var commitMessage = getCommitMessageElement().val();
// if commit message is extended and has a newline, put an empty line after first line to separate subject and body
var s = commitMessage.split("\n");
if (s.length > 1 && s[1].trim() !== "") {
s.splice(1, 0, "");
}
commitMessage = s.join("\n");
// now we are going to be paranoid and we will check if some mofo didn't change our diff
_getStagedDiff().then(function (diff) {
if (diff === stagedDiff) {
return Svn.commit(commitMessage);
} else {
throw new Error("Index was changed while commit dialog was shown!");
}
}).catch(function (err) {
ErrorHandler.showError(err, "Git Commit failed");
}).finally(function () {
EventEmitter.emit(Events.GIT_COMMITED);
refresh();
});
} else {
// this will trigger refreshing where appropriate
Svn.status();
}
});
}
function _showAuthors(file, blame, fromLine, toLine) {
var linesTotal = blame.length;
var blameStats = blame.reduce(function (stats, lineInfo) {
var name = lineInfo.author + " " + lineInfo["author-mail"];
if (stats[name]) {
stats[name] += 1;
} else {
stats[name] = 1;
}
return stats;
}, {});
blameStats = _.reduce(blameStats, function (arr, val, key) {
arr.push({
authorName: key,
lines: val,
percentage: Math.round(val / (linesTotal / 100))
});
return arr;
}, []);
blameStats = _.sortBy(blameStats, "lines").reverse();
if (fromLine || toLine) {
file += " (" + Strings.LINES + " " + fromLine + "-" + toLine + ")";
}
var compiledTemplate = Mustache.render(gitAuthorsDialogTemplate, {
file: file,
blameStats: blameStats,
Strings: Strings
});
Dialogs.showModalDialogUsingTemplate(compiledTemplate);
}
function _getCurrentFilePath(editor) {
var projectRoot = Utils.getProjectRoot(),
document = editor ? editor.document : DocumentManager.getCurrentDocument(),
filePath = document.file.fullPath;
if (filePath.indexOf(projectRoot) === 0) {
filePath = filePath.substring(projectRoot.length);
}
return filePath;
}
function handleAuthorsSelection() {
var editor = EditorManager.getActiveEditor(),
filePath = _getCurrentFilePath(editor),
currentSelection = editor.getSelection(),
fromLine = currentSelection.start.line + 1,
toLine = currentSelection.end.line + 1;
// fix when nothing is selected on that line
if (currentSelection.end.ch === 0) { toLine = toLine - 1; }
var isSomethingSelected = currentSelection.start.line !== currentSelection.end.line ||
currentSelection.start.ch !== currentSelection.end.ch;
if (!isSomethingSelected) {
ErrorHandler.showError(new ExpectedError("Nothing is selected!"));
return;
}
Svn.getBlame(filePath, fromLine, toLine).then(function (blame) {
return _showAuthors(filePath, blame, fromLine, toLine);
}).catch(function (err) {
ErrorHandler.showError(err, "Git Blame failed");
});
}
function handleAuthorsFile() {
var filePath = _getCurrentFilePath();
Svn.getBlame(filePath).then(function (blame) {
return _showAuthors(filePath, blame);
}).catch(function (err) {
ErrorHandler.showError(err, "Git Blame failed");
});
}
function handleGitDiff(file) {
Svn.diffFileNice(file).then(function (diff) {
// show the dialog with the diff
var compiledTemplate = Mustache.render(gitDiffDialogTemplate, { file: file, Strings: Strings }),
dialog = Dialogs.showModalDialogUsingTemplate(compiledTemplate),
$dialog = dialog.getElement();
_makeDialogBig($dialog);
$dialog.find(".commit-diff").append(Utils.formatDiff(diff));
}).catch(function (err) {
ErrorHandler.showError(err, "SVN Diff failed");
});
}
function handleGitUndo(file) {
var compiledTemplate = Mustache.render(questionDialogTemplate, {
title: Strings.UNDO_CHANGES,
question: StringUtils.format(Strings.Q_UNDO_CHANGES, _.escape(file)),
Strings: Strings
});
Dialogs.showModalDialogUsingTemplate(compiledTemplate).done(function (buttonId) {
if (buttonId === "ok") {
Svn.discardFileChanges(file).then(function () {
var currentProjectRoot = Utils.getProjectRoot();
DocumentManager.getAllOpenDocuments().forEach(function (doc) {
if (doc.file.fullPath === currentProjectRoot + file) {
_reloadDoc(doc);
}
});
refresh();
}).catch(function (err) {
ErrorHandler.showError(err, "Git Checkout failed");
});
}
});
}
function handleGitDelete(file) {
var compiledTemplate = Mustache.render(questionDialogTemplate, {
title: Strings.DELETE_FILE,
question: StringUtils.format(Strings.Q_DELETE_FILE, _.escape(file)),
Strings: Strings
});
Dialogs.showModalDialogUsingTemplate(compiledTemplate).done(function (buttonId) {
if (buttonId === "ok") {
FileSystem.resolve(Utils.getProjectRoot() + file, function (err, fileEntry) {
if (err) {
ErrorHandler.showError(err, "Could not resolve file");
return;
}
Promise.cast(ProjectManager.deleteItem(fileEntry))
.then(function () {
refresh();
})
.catch(function (err) {
ErrorHandler.showError(err, "File deletion failed");
});
});
}
});
}
function handleGlobalUpdate(){
var files = [];
return handleSvnUpdate(files);
}
function handleSvnUpdate(files){
if(!_.isArray(files)) return;
return Svn.updateFile(files).then(function(stdout){
refresh();
});
}
/**
* strips trailing whitespace from all the diffs and adds \n to the end
*/
function stripWhitespaceFromFile(filename, clearWholeFile) {
return new Promise(function (resolve, reject) {
var fullPath = Utils.getProjectRoot() + filename,
removeBom = Preferences.get("removeByteOrderMark"),
normalizeLineEndings = Preferences.get("normalizeLineEndings");
var _cleanLines = function (lineNumbers) {
// clean the file
var fileEntry = FileSystem.getFileForPath(fullPath);
return FileUtils.readAsText(fileEntry).then(function (text) {
if (removeBom) {
// remove BOM - \ufeff
text = text.replace(/\ufeff/g, "");
}
if (normalizeLineEndings) {
// normalizes line endings
text = text.replace(/\r\n/g, "\n");
}
// process lines
var lines = text.split("\n");
if (lineNumbers) {
lineNumbers.forEach(function (lineNumber) {
lines[lineNumber] = lines[lineNumber].replace(/\s+$/, "");
});
} else {
lines.forEach(function (ln, lineNumber) {
lines[lineNumber] = lines[lineNumber].replace(/\s+$/, "");
});
}
// add empty line to the end, i've heard that git likes that for some reason
if (Preferences.get("addEndlineToTheEndOfFile")) {
var lastLineNumber = lines.length - 1;
if (lines[lastLineNumber].length > 0) {
lines[lastLineNumber] = lines[lastLineNumber].replace(/\s+$/, "");
}
if (lines[lastLineNumber].length > 0) {
lines.push("");
}
}
//-
text = lines.join("\n");
return Promise.cast(FileUtils.writeText(fileEntry, text))
.catch(function (err) {
ErrorHandler.logError("Wasn't able to clean whitespace from file: " + fullPath);
resolve();
throw err;
})
.then(function () {
// refresh the file if it's open in the background
DocumentManager.getAllOpenDocuments().forEach(function (doc) {
if (doc.file.fullPath === fullPath) {
_reloadDoc(doc);
}
});
// diffs were cleaned in this file
resolve();
});
});
};
if (clearWholeFile) {
_cleanLines(null);
} else {
Svn.diffFile(filename).then(function (diff) {
if (!diff) { return resolve(); }
var modified = [],
changesets = diff.split("\n").filter(function (l) { return l.match(/^@@/) !== null; });
// collect line numbers to clean
changesets.forEach(function (line) {
var i,
m = line.match(/^@@ -([,0-9]+) \+([,0-9]+) @@/),
s = m[2].split(","),
from = parseInt(s[0], 10),
to = from - 1 + (parseInt(s[1], 10) || 1);
for (i = from; i <= to; i++) { modified.push(i > 0 ? i - 1 : 0); }
});
_cleanLines(modified);
}).catch(function (ex) {
// This error will bubble up to preparing commit dialog so just log here
ErrorHandler.logError(ex);
reject(ex);
});
}
});
}
function _getStagedDiff() {
return Svn.getDiffOfStagedFiles().then(function (diff) {
if (!diff) {
return Svn.getListOfStagedFiles().then(function (filesList) {
return Strings.DIFF_FAILED_SEE_FILES + "\n\n" + filesList;
});
}
return diff;
});
}
// whatToDo gets values "continue" "skip" "abort"
function handleRebase(whatToDo) {
Svn.rebase(whatToDo).then(function () {
EventEmitter.emit(Events.REFRESH_ALL);
}).catch(function (err) {
ErrorHandler.showError(err, "Rebase " + whatToDo + " failed");
});
}
function abortMerge() {
Svn.discardAllChanges().then(function () {
EventEmitter.emit(Events.REFRESH_ALL);
}).catch(function (err) {
ErrorHandler.showError(err, "Merge abort failed");
});
}
function findConflicts() {
FindInFiles.doSearch(/^<<<<<<<\s|^=======\s|^>>>>>>>\s/gm);
}
function commitMerge() {
Utils.loadPathContent(Utils.getProjectRoot() + "/.git/MERGE_MSG").then(function (msg) {
handleGitCommit(msg);
}).catch(function (err) {
ErrorHandler.showError(err, "Merge commit failed");
});
}
function handleGitCommit(prefilledMessage) {
var codeInspectionEnabled = Preferences.get("useCodeInspection");
var stripWhitespace = Preferences.get("stripWhitespaceFromCommits");
// Disable button (it will be enabled when selecting files after reset)
Utils.setLoading($gitPanel.find(".git-commit"));
// First reset staged files, then add selected files to the index.
Svn.status().then(function (files) {
files = _.filter(files, function (file) {
return file.status.indexOf(Svn.FILE_STATUS.MODIFIED) !== -1;
});
if (files.length === 0) {
return ErrorHandler.showError(new Error("Commit button should have been disabled"), "Nothing staged to commit");
}
var lintResults = [],
promises = [];
files.forEach(function (fileObj) {
var queue = Promise.resolve();
var isDeleted = fileObj.status.indexOf(Svn.FILE_STATUS.DELETED) !== -1,
updateIndex = isDeleted;
// strip whitespace if configured to do so and file was not deleted
if (stripWhitespace && !isDeleted) {
// strip whitespace only for recognized languages so binary files won't get corrupted
var langId = LanguageManager.getLanguageForPath(fileObj.file).getId();
if (["unknown", "binary", "image", "markdown"].indexOf(langId) === -1) {
queue = queue.then(function () {
var clearWholeFile = fileObj.status.indexOf(Svn.FILE_STATUS.UNTRACKED) !== -1 ||
fileObj.status.indexOf(Svn.FILE_STATUS.RENAMED) !== -1;
return stripWhitespaceFromFile(fileObj.file, clearWholeFile);
});
}
}
// do a code inspection for the file, if it was not deleted
if (codeInspectionEnabled && !isDeleted) {
queue = queue.then(function () {
return lintFile(fileObj.file).then(function (result) {
if (result) {
lintResults.push({
filename: fileObj.file,
result: result
});
}
});
});
}
promises.push(queue);
});
return Promise.all(promises).then(function () {
// All files are in the index now, get the diff and show dialog.
return _getStagedDiff().then(function (diff) {
return _showCommitDialog(diff, lintResults, prefilledMessage);
});
});
}).catch(function (err) {
ErrorHandler.showError(err, "Preparing commit dialog failed");
}).finally(function () {
Utils.unsetLoading($gitPanel.find(".git-commit"));
});
}
function refreshCurrentFile() {
var currentProjectRoot = Utils.getProjectRoot();
var currentDoc = DocumentManager.getCurrentDocument();
if (currentDoc) {
$gitPanel.find("tr").each(function () {
var currentFullPath = currentDoc.file.fullPath,
thisFile = $(this).attr("x-file");
$(this).toggleClass("selected", currentProjectRoot + thisFile === currentFullPath);
});
} else {
$gitPanel.find("tr").removeClass("selected");
}
}
function shouldShow(fileObj) {
if (showFileWhiteList.test(fileObj.name)) {
return true;
}
return ProjectManager.shouldShow(fileObj);
}
function _refreshTableContainer(files) {
if (!gitPanel.isVisible()) {
return;
}
// remove files that we should not show
files = _.filter(files, function (file) {
return shouldShow(file);
});
var allStaged = files.length > 0 && _.all(files, function (file) { return file.status.indexOf(Svn.FILE_STATUS.STAGED) !== -1; });
$gitPanel.find(".check-all").prop("checked", allStaged).prop("disabled", files.length === 0);
var $editedList = $tableContainer.find(".git-edited-list");
var visibleBefore = $editedList.length ? $editedList.is(":visible") : true;
$editedList.remove();
if (files.length === 0) {
$tableContainer.append($("<p class='git-edited-list nothing-to-commit' />").text(Strings.NOTHING_TO_COMMIT));
} else {
// if desired, remove untracked files from the results
if (showingUntracked === false) {
files = _.filter(files, function (file) {
return file.status.indexOf(Svn.FILE_STATUS.UNTRACKED) === -1;
});
}
// -
files.forEach(function (file) {
file.staged = file.status.indexOf(Svn.FILE_STATUS.STAGED) !== -1;
file.statusText = file.status.map(function (status) {
return Strings["FILE_" + status];
}).join(", ");
file.allowDiff = file.status.indexOf(Svn.FILE_STATUS.UNTRACKED) === -1 &&
file.status.indexOf(Svn.FILE_STATUS.RENAMED) === -1 &&
file.status.indexOf(Svn.FILE_STATUS.DELETED) === -1;
file.allowDelete = file.status.indexOf(Svn.FILE_STATUS.UNTRACKED) !== -1;
file.allowUndo = !file.allowDelete && file.status.indexOf(Svn.FILE_STATUS.MODIFIED) !== -1;
file.allowUpdate = file.status.indexOf(Svn.FILE_STATUS.OUTOFDATE) !== -1;
file.allowAdd = file.status.indexOf(Svn.FILE_STATUS.UNTRACKED) > -1;
});
$tableContainer.append(Mustache.render(gitPanelResultsTemplate, {
files: files,
Strings: Strings
}));
refreshCurrentFile();
}
$tableContainer.find(".git-edited-list").toggle(visibleBefore);
}
function refresh() {
// set the history panel to false and remove the class that show the button history active when refresh
$gitPanel.find(".git-history-toggle").removeClass("active").attr("title", Strings.TOOLTIP_SHOW_HISTORY);
$gitPanel.find(".git-file-history").removeClass("active").attr("title", Strings.TOOLTIP_SHOW_FILE_HISTORY);
if (gitPanelMode === "not-repo") {
$tableContainer.empty();
return Promise.resolve();
}
$tableContainer.find("#git-history-list").remove();
$tableContainer.find(".git-edited-list").show();
var p1 = Svn.status(true);
//- push button
//var $pushBtn = $gitPanel.find(".git-push");
// var p2 = Svn.getCommitsAhead().then(function (commits) {
// $pushBtn.children("span").remove();
// if (commits.length > 0) {
// $pushBtn.append($("<span/>").text(" (" + commits.length + ")"));
// }
// }).catch(function () {
// $pushBtn.children("span").remove();
// });
// FUTURE: who listens for this?
return Promise.all([p1]);
}
function toggle(bool) {
if (gitPanelDisabled === true) {
return;
}
if (typeof bool !== "boolean") {
bool = !gitPanel.isVisible();
}
Preferences.persist("panelEnabled", bool);
Main.$icon.toggleClass("on", bool);
gitPanel.setVisible(bool);
// Mark menu item as enabled/disabled.
CommandManager.get(PANEL_COMMAND_ID).setChecked(bool);
if (bool) {
refresh();
}
}
function handleToggleUntracked() {
showingUntracked = !showingUntracked;
$gitPanel
.find(".git-toggle-untracked")
.text(showingUntracked ? Strings.HIDE_UNTRACKED : Strings.SHOW_UNTRACKED);
refresh();
}
function commitCurrentFile() {
return Promise.cast(CommandManager.execute("file.save"))
.then(function () {
return Svn.resetIndex();
})
.then(function () {
var currentProjectRoot = Utils.getProjectRoot();
var currentDoc = DocumentManager.getCurrentDocument();
if (currentDoc) {
var relativePath = currentDoc.file.fullPath.substring(currentProjectRoot.length);
return Svn.stage(relativePath).then(function () {
return handleGitCommit();
});
}
});
}
function commitAllFiles() {
return Promise.cast(CommandManager.execute("file.saveAll"))
.then(function () {
return Svn.resetIndex();
})
.then(function () {
return Svn.stageAll().then(function () {
return handleGitCommit();
});
});
}
// Disable "commit" button if there aren't staged files to commit
function _toggleCommitButton(files) {
var anyStaged = _.any(files, function (file) { return file.status.indexOf(Svn.FILE_STATUS.STAGED) !== -1; });
$gitPanel.find(".git-commit").prop("disabled", !anyStaged);
}
EventEmitter.on(Events.GIT_STATUS_RESULTS, function (results) {
_refreshTableContainer(results);
_toggleCommitButton(results);
});
function undoLastLocalCommit() {
Svn.undoLastLocalCommit()
.catch(function (err) {
ErrorHandler.showError(err, "Impossible to undo last commit");
})
.finally(function () {
refresh();
});
}
var lastCheckOneClicked = null;
function attachDefaultTableHandlers() {
$tableContainer = $gitPanel.find(".table-container")
.off()
.on("click", ".check-one", function (e) {
e.stopPropagation();
var $tr = $(this).closest("tr"),
file = $tr.attr("x-file"),
status = $tr.attr("x-status"),
isChecked = $(this).is(":checked");
if (e.shiftKey) {
// do something if we press shift. Right now? Nothing.
}
lastCheckOneClicked = file;
})
.on("dblclick", ".check-one", function (e) {
e.stopPropagation();
})
.on("click", ".btn-git-diff", function (e) {
e.stopPropagation();
handleGitDiff($(e.target).closest("tr").attr("x-file"));
})
.on("click", ".btn-git-undo", function (e) {
e.stopPropagation();
handleGitUndo($(e.target).closest("tr").attr("x-file"));
})
.on("click", ".btn-git-delete", function (e) {
e.stopPropagation();
handleGitDelete($(e.target).closest("tr").attr("x-file"));
})
.on("click", ".btn-svn-add", function(e) {
e.stopPropagation();
handleSvnAdd($(e.target).closest("tr").attr("x-file"));
})
.on("click", ".btn-svn-update", function (e) {
e.stopPropagation();
handleSvnUpdate([$(e.target).closest("tr").attr("x-file")]);
})
.on("click", ".modified-file", function (e) {
var $this = $(e.currentTarget);
if ($this.attr("x-status") === Svn.FILE_STATUS.DELETED) {
return;
}
CommandManager.execute(Commands.FILE_OPEN, {
fullPath: Utils.getProjectRoot() + $this.attr("x-file")
});
})
.on("dblclick", ".modified-file", function (e) {
var $this = $(e.currentTarget);
if ($this.attr("x-status") === Svn.FILE_STATUS.DELETED) {
return;
}
FileViewController.addToWorkingSetAndSelect(Utils.getProjectRoot() + $this.attr("x-file"));
});
}
function discardAllChanges() {
return Utils.askQuestion(Strings.RESET_LOCAL_REPO, Strings.RESET_LOCAL_REPO_CONFIRM, { booleanResponse: true })
.then(function (response) {
if (response) {
return Svn.discardAllChanges().catch(function (err) {
ErrorHandler.showError(err, "Reset of local repository failed");
}).then(function () {
refresh();
});
}
});
}
function init() {
// Add panel
var panelHtml = Mustache.render(svnPanelTemplate, {
enableAdvancedFeatures: Preferences.get("enableAdvancedFeatures"),
showBashButton: Preferences.get("showBashButton"),
showReportBugButton: Preferences.get("showReportBugButton"),
S: Strings
});
var $panelHtml = $(panelHtml);
$panelHtml.find(".git-available, .git-not-available").hide();
gitPanel = PanelManager.createBottomPanel("brackets-git.panel", $panelHtml, 100);
$gitPanel = gitPanel.$panel;
$gitPanel
.on("click", ".close", toggle)
.on("click", ".check-all", function () {
$('.check-one').attr('checked',true);
})
.on("click", ".git-refresh", EventEmitter.emitFactory(Events.REFRESH_ALL))
.on("click", ".git-commit", EventEmitter.emitFactory(Events.HANDLE_GIT_COMMIT))
.on("click", ".git-commit-merge", commitMerge)
.on("click", ".svn-update", handleGlobalUpdate)
.on("click", ".git-find-conflicts", findConflicts)
.on("click", ".git-prev-gutter", GutterManager.goToPrev)
.on("click", ".git-next-gutter", GutterManager.goToNext)
.on("click", ".git-toggle-untracked", handleToggleUntracked)
.on("click", ".authors-selection", handleAuthorsSelection)
.on("click", ".authors-file", handleAuthorsFile)
.on("click", ".git-file-history", EventEmitter.emitFactory(Events.HISTORY_SHOW, "FILE"))
.on("click", ".git-history-toggle", EventEmitter.emitFactory(Events.HISTORY_SHOW, "GLOBAL"))
.on("click", ".git-bug", ErrorHandler.reportBug)
.on("click", ".git-settings", SettingsDialog.show)
.on("contextmenu", "tr", function (e) {
var $this = $(this);
if ($this.hasClass("history-commit")) { return; }
$this.click();
setTimeout(function () {
Menus.getContextMenu("git-panel-context-menu").open(e);
}, 1);
})
.on("click", ".git-bash", EventEmitter.emitFactory(Events.TERMINAL_OPEN))
.on("click", ".reset-all", discardAllChanges);
// Attaching table handlers
attachDefaultTableHandlers();
// Commit current and all shortcuts
var COMMIT_CURRENT_CMD = "brackets-git.commitCurrent",
COMMIT_ALL_CMD = "brackets-git.commitAll",
BASH_CMD = "brackets-git.launchBash",
PUSH_CMD = "brackets-git.push",
PULL_CMD = "brackets-git.pull",
GOTO_PREV_CHANGE = "brackets-git.gotoPrevChange",
GOTO_NEXT_CHANGE = "brackets-git.gotoNextChange";
// Add command to menu.
// Register command for opening bottom panel.
CommandManager.register(Strings.PANEL_COMMAND, PANEL_COMMAND_ID, toggle);
KeyBindingManager.addBinding(PANEL_COMMAND_ID, Preferences.get("panelShortcut"));
CommandManager.register(Strings.COMMIT_CURRENT_SHORTCUT, COMMIT_CURRENT_CMD, commitCurrentFile);
KeyBindingManager.addBinding(COMMIT_CURRENT_CMD, Preferences.get("commitCurrentShortcut"));
CommandManager.register(Strings.COMMIT_ALL_SHORTCUT, COMMIT_ALL_CMD, commitAllFiles);
KeyBindingManager.addBinding(COMMIT_ALL_CMD, Preferences.get("commitAllShortcut"));
CommandManager.register(Strings.LAUNCH_BASH_SHORTCUT, BASH_CMD, EventEmitter.emitFactory(Events.TERMINAL_OPEN));
KeyBindingManager.addBinding(BASH_CMD, Preferences.get("bashShortcut"));
CommandManager.register(Strings.PUSH_SHORTCUT, PUSH_CMD, EventEmitter.emitFactory(Events.HANDLE_PUSH));
KeyBindingManager.addBinding(PUSH_CMD, Preferences.get("pushShortcut"));
CommandManager.register(Strings.PULL_SHORTCUT, PULL_CMD, EventEmitter.emitFactory(Events.HANDLE_PULL));
KeyBindingManager.addBinding(PULL_CMD, Preferences.get("pullShortcut"));
CommandManager.register(Strings.GOTO_PREVIOUS_GIT_CHANGE, GOTO_PREV_CHANGE, GutterManager.goToPrev);
KeyBindingManager.addBinding(GOTO_PREV_CHANGE, Preferences.get("gotoPrevChangeShortcut"));
CommandManager.register(Strings.GOTO_NEXT_GIT_CHANGE, GOTO_NEXT_CHANGE, GutterManager.goToNext);
KeyBindingManager.addBinding(GOTO_NEXT_CHANGE, Preferences.get("gotoNextChangeShortcut"));
// Init moment - use the correct language
moment.lang(brackets.getLocale());
if(Svn.isWorkingCopy()){
enable();
}
// Show gitPanel when appropriate
if (Preferences.get("panelEnabled")) {
toggle(true);
}
}
function enable() {
EventEmitter.emit(Events.SVN_ENABLED);
// this function is called after every Branch.refresh
gitPanelMode = null;
//
$gitPanel.find(".git-available").show();
$gitPanel.find(".git-not-available").hide();
//
Main.$icon.removeClass("warning").removeAttr("title");
gitPanelDisabled = false;
// after all is enabled
refresh();
}
function disable(cause) {
EventEmitter.emit(Events.GIT_DISABLED, cause);
gitPanelMode = cause;
// causes: not-repo
if (gitPanelMode === "not-repo") {
$gitPanel.find(".git-available").hide();
$gitPanel.find(".git-not-available").show();
} else {
Main.$icon.addClass("warning").attr("title", cause);
toggle(false);
gitPanelDisabled = true;
}
refresh();
}
// Event listeners
EventEmitter.on(Events.BRACKETS_CURRENT_DOCUMENT_CHANGE, function () {
if (!gitPanel) { return; }
refreshCurrentFile();
});
EventEmitter.on(Events.BRACKETS_DOCUMENT_SAVED, function () {
if (!gitPanel) { return; }
refresh();
});
EventEmitter.on(Events.REBASE_MERGE_MODE, function (rebaseEnabled, mergeEnabled) {
$gitPanel.find(".git-rebase").toggle(rebaseEnabled);
$gitPanel.find(".git-merge").toggle(mergeEnabled);
$gitPanel.find("button.git-commit").toggle(!rebaseEnabled && !mergeEnabled);
});
EventEmitter.on(Events.HANDLE_GIT_COMMIT, function () {
handleGitCommit();
});
exports.init = init;
exports.refresh = refresh;
exports.toggle = toggle;
exports.enable = enable;
exports.disable = disable;
exports.getPanel = function () { return $gitPanel; };
});
|
seshurajup/brackets-svn
|
src/Panel.js
|
JavaScript
|
mit
| 41,379 |
#!/bin/bash
source ../common.sh
subsection "oh-my-zsh"
sh -c "$(curl -fsSL https://raw.githubusercontent.com/robbyrussell/oh-my-zsh/master/tools/install.sh)"
chsh -s /bin/zsh
mv "${HOME}/.zshrc.pre-oh-my-zsh" "${HOME}/.zshrc"
|
dawikur/dotfiles
|
scripts/oh_my_zsh.sh
|
Shell
|
mit
| 230 |
<article id="post-<?php print $ID ?>" <?php post_class(); ?>>
<div class="tb-short-img">
<?php
toebox\inc\ToeBox::HandleFeaturedImage();
?>
</div>
<?php
print \toebox\inc\ToeBox::FormatListTitle($post_title, get_the_permalink());
?>
<div class="entry-metadata">
<!-- TODO: allow setting for turning author and date off on posts -->
<span class="tb-date"><?php the_time(get_option('date_format')); ?></span>
|
<span class="tb-author"><?php print get_the_author(); ?></span>
|
<span class="tb-category"><?php the_category(', ') ?></span>
|
<span class="tb-tags"><?php the_tags( 'Tags: ', ', ', '' ); ?></span>
</div>
<div class="entry-excerpt">
<?php print $body ?>
</div>
</article>
|
drydenmaker/Noga
|
theme/tpl/content/list_short_img.php
|
PHP
|
mit
| 823 |
<!DOCTYPE html>
<html lang="en">
<head>
<title>ABNFImportError Enumeration Reference</title>
<link rel="stylesheet" type="text/css" href="../css/jazzy.css" />
<link rel="stylesheet" type="text/css" href="../css/highlight.css" />
<meta charset="utf-8">
<script src="../js/jquery.min.js" defer></script>
<script src="../js/jazzy.js" defer></script>
<script src="../js/lunr.min.js" defer></script>
<script src="../js/typeahead.jquery.js" defer></script>
<script src="../js/jazzy.search.js" defer></script>
</head>
<body>
<a name="//apple_ref/swift/Enum/ABNFImportError" class="dashAnchor"></a>
<a title="ABNFImportError Enumeration Reference"></a>
<header class="header">
<p class="header-col header-col--primary">
<a class="header-link" href="../index.html">
Covfefe 0.6.1 Docs
</a>
(99% documented)
</p>
<p class="header-col--secondary">
<form role="search" action="../search.json">
<input type="text" placeholder="Search documentation" data-typeahead>
</form>
</p>
<p class="header-col header-col--secondary">
<a class="header-link" href="https://github.com/palle-k/Covfefe">
<img class="header-icon" src="../img/gh.png"/>
View on GitHub
</a>
</p>
</header>
<p class="breadcrumbs">
<a class="breadcrumb" href="../index.html">Covfefe Reference</a>
<img class="carat" src="../img/carat.png" />
ABNFImportError Enumeration Reference
</p>
<div class="content-wrapper">
<nav class="navigation">
<ul class="nav-groups">
<li class="nav-group-name">
<a class="nav-group-name-link" href="../Guides.html">Guides</a>
<ul class="nav-group-tasks">
<li class="nav-group-task">
<a class="nav-group-task-link" href="../bnf.html">BNF</a>
</li>
</ul>
</li>
<li class="nav-group-name">
<a class="nav-group-name-link" href="../Enums.html">Enumerations</a>
<ul class="nav-group-tasks">
<li class="nav-group-task">
<a class="nav-group-task-link" href="../Enums/ABNFImportError.html">ABNFImportError</a>
</li>
<li class="nav-group-task">
<a class="nav-group-task-link" href="../Enums/Symbol.html">Symbol</a>
</li>
<li class="nav-group-task">
<a class="nav-group-task-link" href="../Enums/SyntaxTree.html">SyntaxTree</a>
</li>
<li class="nav-group-task">
<a class="nav-group-task-link" href="../Enums/Terminal.html">Terminal</a>
</li>
</ul>
</li>
<li class="nav-group-name">
<a class="nav-group-name-link" href="../Extensions.html">Extensions</a>
<ul class="nav-group-tasks">
<li class="nav-group-task">
<a class="nav-group-task-link" href="../Extensions/Character.html">Character</a>
</li>
<li class="nav-group-task">
<a class="nav-group-task-link" href="../Extensions/ClosedRange.html">ClosedRange</a>
</li>
<li class="nav-group-task">
<a class="nav-group-task-link" href="../Extensions/String.html">String</a>
</li>
</ul>
</li>
<li class="nav-group-name">
<a class="nav-group-name-link" href="../Functions.html">Functions</a>
<ul class="nav-group-tasks">
<li class="nav-group-task">
<a class="nav-group-task-link" href="../Functions.html#/s:7Covfefe3ssgoiyAA10ProductionVAA11NonTerminalV_AA0C6StringVtF">-->(_:_:)</a>
</li>
<li class="nav-group-task">
<a class="nav-group-task-link" href="../Functions.html#/s:7Covfefe3ssgoiyAA10ProductionVAA11NonTerminalV_AA6SymbolOtF">-->(_:_:)</a>
</li>
<li class="nav-group-task">
<a class="nav-group-task-link" href="../Functions.html#/s:7Covfefe3ssgoiySayAA10ProductionVGAA11NonTerminalV_AA0C6ResultVtF">-->(_:_:)</a>
</li>
<li class="nav-group-task">
<a class="nav-group-task-link" href="../Functions.html#/s:7Covfefe3lpgoiyAA16ProductionResultVAA0C6StringV_ADtF"><+>(_:_:)</a>
</li>
<li class="nav-group-task">
<a class="nav-group-task-link" href="../Functions.html#/s:7Covfefe3lpgoiyAA16ProductionResultVAD_AA0C6StringVtF"><+>(_:_:)</a>
</li>
<li class="nav-group-task">
<a class="nav-group-task-link" href="../Functions.html#/s:7Covfefe3lpgoiyAA16ProductionResultVAD_ADtF"><+>(_:_:)</a>
</li>
<li class="nav-group-task">
<a class="nav-group-task-link" href="../Functions.html#/s:7Covfefe3lpgoiyAA16ProductionStringVAA6SymbolO_ADtF"><+>(_:_:)</a>
</li>
<li class="nav-group-task">
<a class="nav-group-task-link" href="../Functions.html#/s:7Covfefe3lpgoiyAA16ProductionStringVAA6SymbolO_AFtF"><+>(_:_:)</a>
</li>
<li class="nav-group-task">
<a class="nav-group-task-link" href="../Functions.html#/s:7Covfefe3lpgoiyAA16ProductionStringVAD_AA6SymbolOtF"><+>(_:_:)</a>
</li>
<li class="nav-group-task">
<a class="nav-group-task-link" href="../Functions.html#/s:7Covfefe3lpgoiyAA16ProductionStringVAD_ADtF"><+>(_:_:)</a>
</li>
<li class="nav-group-task">
<a class="nav-group-task-link" href="../Functions.html#/s:7Covfefe3logoiyAA16ProductionResultVAA0C6StringV_AA6SymbolOtF"><|>(_:_:)</a>
</li>
<li class="nav-group-task">
<a class="nav-group-task-link" href="../Functions.html#/s:7Covfefe3logoiyAA16ProductionResultVAA0C6StringV_ADtF"><|>(_:_:)</a>
</li>
<li class="nav-group-task">
<a class="nav-group-task-link" href="../Functions.html#/s:7Covfefe3logoiyAA16ProductionResultVAA0C6StringV_AFtF"><|>(_:_:)</a>
</li>
<li class="nav-group-task">
<a class="nav-group-task-link" href="../Functions.html#/s:7Covfefe3logoiyAA16ProductionResultVAA6SymbolO_AA0C6StringVtF"><|>(_:_:)</a>
</li>
<li class="nav-group-task">
<a class="nav-group-task-link" href="../Functions.html#/s:7Covfefe3logoiyAA16ProductionResultVAA6SymbolO_ADtF"><|>(_:_:)</a>
</li>
<li class="nav-group-task">
<a class="nav-group-task-link" href="../Functions.html#/s:7Covfefe3logoiyAA16ProductionResultVAA6SymbolO_AFtF"><|>(_:_:)</a>
</li>
<li class="nav-group-task">
<a class="nav-group-task-link" href="../Functions.html#/s:7Covfefe3logoiyAA16ProductionResultVAD_AA0C6StringVtF"><|>(_:_:)</a>
</li>
<li class="nav-group-task">
<a class="nav-group-task-link" href="../Functions.html#/s:7Covfefe3logoiyAA16ProductionResultVAD_AA6SymbolOtF"><|>(_:_:)</a>
</li>
<li class="nav-group-task">
<a class="nav-group-task-link" href="../Functions.html#/s:7Covfefe3logoiyAA16ProductionResultVAD_ADtF"><|>(_:_:)</a>
</li>
<li class="nav-group-task">
<a class="nav-group-task-link" href="../Functions.html#/s:7Covfefe2eeoiySbAA10SyntaxTreeOyxq_G_AEtSQRzSQR_r0_lF">==(_:_:)</a>
</li>
<li class="nav-group-task">
<a class="nav-group-task-link" href="../Functions.html#/s:7Covfefe1nyAA6SymbolOSSF">n(_:)</a>
</li>
<li class="nav-group-task">
<a class="nav-group-task-link" href="../Functions.html#/s:7Covfefe2rtyAA6SymbolOSSKF">rt(_:)</a>
</li>
<li class="nav-group-task">
<a class="nav-group-task-link" href="../Functions.html#/s:7Covfefe1tyAA6SymbolOSSF">t(_:)</a>
</li>
</ul>
</li>
<li class="nav-group-name">
<a class="nav-group-name-link" href="../Protocols.html">Protocols</a>
<ul class="nav-group-tasks">
<li class="nav-group-task">
<a class="nav-group-task-link" href="../Protocols/AmbiguousGrammarParser.html">AmbiguousGrammarParser</a>
</li>
<li class="nav-group-task">
<a class="nav-group-task-link" href="../Protocols/Parser.html">Parser</a>
</li>
<li class="nav-group-task">
<a class="nav-group-task-link" href="../Protocols/Tokenizer.html">Tokenizer</a>
</li>
</ul>
</li>
<li class="nav-group-name">
<a class="nav-group-name-link" href="../Structs.html">Structures</a>
<ul class="nav-group-tasks">
<li class="nav-group-task">
<a class="nav-group-task-link" href="../Structs/CYKParser.html">CYKParser</a>
</li>
<li class="nav-group-task">
<a class="nav-group-task-link" href="../Structs/DefaultTokenizer.html">DefaultTokenizer</a>
</li>
<li class="nav-group-task">
<a class="nav-group-task-link" href="../Structs/EarleyParser.html">EarleyParser</a>
</li>
<li class="nav-group-task">
<a class="nav-group-task-link" href="../Structs/Grammar.html">Grammar</a>
</li>
<li class="nav-group-task">
<a class="nav-group-task-link" href="../Structs/NonTerminal.html">NonTerminal</a>
</li>
<li class="nav-group-task">
<a class="nav-group-task-link" href="../Structs/NonTerminalString.html">NonTerminalString</a>
</li>
<li class="nav-group-task">
<a class="nav-group-task-link" href="../Structs/Production.html">Production</a>
</li>
<li class="nav-group-task">
<a class="nav-group-task-link" href="../Structs/ProductionResult.html">ProductionResult</a>
</li>
<li class="nav-group-task">
<a class="nav-group-task-link" href="../Structs/ProductionString.html">ProductionString</a>
</li>
<li class="nav-group-task">
<a class="nav-group-task-link" href="../Structs/SymbolSet.html">SymbolSet</a>
</li>
<li class="nav-group-task">
<a class="nav-group-task-link" href="../Structs/SyntaxError.html">SyntaxError</a>
</li>
<li class="nav-group-task">
<a class="nav-group-task-link" href="../Structs/SyntaxError/Reason.html">– Reason</a>
</li>
</ul>
</li>
<li class="nav-group-name">
<a class="nav-group-name-link" href="../Typealiases.html">Type Aliases</a>
<ul class="nav-group-tasks">
<li class="nav-group-task">
<a class="nav-group-task-link" href="../Typealiases.html#/s:7Covfefe9ParseTreea">ParseTree</a>
</li>
</ul>
</li>
</ul>
</nav>
<article class="main-content">
<section class="section">
<div class="section-content top-matter">
<h1>ABNFImportError</h1>
<div class="declaration">
<div class="language">
<pre class="highlight swift"><code><span class="kd">public</span> <span class="kd">enum</span> <span class="kt">ABNFImportError</span> <span class="p">:</span> <span class="kt">Error</span></code></pre>
</div>
</div>
<p>Errors specific to the import of ABNF grammars</p>
</div>
</section>
<section class="section">
<div class="section-content">
<div class="task-group">
<ul class="item-container">
<li class="item">
<div>
<code>
<a name="/s:7Covfefe15ABNFImportErrorO12invalidRangeyACSi_SitcACmF"></a>
<a name="//apple_ref/swift/Element/invalidRange(line:column:)" class="dashAnchor"></a>
<a class="token" href="#/s:7Covfefe15ABNFImportErrorO12invalidRangeyACSi_SitcACmF">invalidRange(line:<wbr>column:<wbr>)</a>
</code>
</div>
<div class="height-container">
<div class="pointer-container"></div>
<section class="section">
<div class="pointer"></div>
<div class="abstract">
<p>The grammar contains a range expression with a lower bound higher than the upper bound</p>
</div>
<div class="declaration">
<h4>Declaration</h4>
<div class="language">
<p class="aside-title">Swift</p>
<pre class="highlight swift"><code><span class="k">case</span> <span class="nf">invalidRange</span><span class="p">(</span><span class="nv">line</span><span class="p">:</span> <span class="kt">Int</span><span class="p">,</span> <span class="nv">column</span><span class="p">:</span> <span class="kt">Int</span><span class="p">)</span></code></pre>
</div>
</div>
</section>
</div>
</li>
<li class="item">
<div>
<code>
<a name="/s:7Covfefe15ABNFImportErrorO15invalidCharcodeyACSi_SitcACmF"></a>
<a name="//apple_ref/swift/Element/invalidCharcode(line:column:)" class="dashAnchor"></a>
<a class="token" href="#/s:7Covfefe15ABNFImportErrorO15invalidCharcodeyACSi_SitcACmF">invalidCharcode(line:<wbr>column:<wbr>)</a>
</code>
</div>
<div class="height-container">
<div class="pointer-container"></div>
<section class="section">
<div class="pointer"></div>
<div class="abstract">
<p>The grammar contains a charcode that is not a valid unicode scalar</p>
</div>
<div class="declaration">
<h4>Declaration</h4>
<div class="language">
<p class="aside-title">Swift</p>
<pre class="highlight swift"><code><span class="k">case</span> <span class="nf">invalidCharcode</span><span class="p">(</span><span class="nv">line</span><span class="p">:</span> <span class="kt">Int</span><span class="p">,</span> <span class="nv">column</span><span class="p">:</span> <span class="kt">Int</span><span class="p">)</span></code></pre>
</div>
</div>
</section>
</div>
</li>
<li class="item">
<div>
<code>
<a name="/s:7Covfefe15ABNFImportErrorO21invalidCharacterRangeyACSi_SitcACmF"></a>
<a name="//apple_ref/swift/Element/invalidCharacterRange(line:column:)" class="dashAnchor"></a>
<a class="token" href="#/s:7Covfefe15ABNFImportErrorO21invalidCharacterRangeyACSi_SitcACmF">invalidCharacterRange(line:<wbr>column:<wbr>)</a>
</code>
</div>
<div class="height-container">
<div class="pointer-container"></div>
<section class="section">
<div class="pointer"></div>
<div class="abstract">
<p>The grammar contains a charcode range with a lower bound higher than the upper bound</p>
</div>
<div class="declaration">
<h4>Declaration</h4>
<div class="language">
<p class="aside-title">Swift</p>
<pre class="highlight swift"><code><span class="k">case</span> <span class="nf">invalidCharacterRange</span><span class="p">(</span><span class="nv">line</span><span class="p">:</span> <span class="kt">Int</span><span class="p">,</span> <span class="nv">column</span><span class="p">:</span> <span class="kt">Int</span><span class="p">)</span></code></pre>
</div>
</div>
</section>
</div>
</li>
</ul>
</div>
</div>
</section>
</article>
</div>
<section class="footer">
<p>© 2020 <a class="link" href="https://github.com/palle-k" target="_blank" rel="external">palle-k</a>. All rights reserved. (Last updated: 2020-05-24)</p>
<p>Generated by <a class="link" href="https://github.com/realm/jazzy" target="_blank" rel="external">jazzy ♪♫ v0.13.3</a>, a <a class="link" href="https://realm.io" target="_blank" rel="external">Realm</a> project.</p>
</section>
</body>
</div>
</html>
|
palle-k/Covfefe
|
docs/docsets/Covfefe.docset/Contents/Resources/Documents/Enums/ABNFImportError.html
|
HTML
|
mit
| 17,791 |
#include "stdafx.h"
#include "light.h"
using namespace graphic;
cLight::cLight()
{
}
cLight::~cLight()
{
}
void cLight::Init(TYPE type,
const Vector4 &ambient, // Vector4(1, 1, 1, 1),
const Vector4 &diffuse, // Vector4(0.2, 0.2, 0.2, 1)
const Vector4 &specular, // Vector4(1,1,1,1)
const Vector3 &direction) // Vector3(0,-1,0)
{
ZeroMemory(&m_light, sizeof(m_light));
m_light.Type = (D3DLIGHTTYPE)type;
m_light.Ambient = *(D3DCOLORVALUE*)&ambient;
m_light.Diffuse = *(D3DCOLORVALUE*)&diffuse;
m_light.Specular = *(D3DCOLORVALUE*)&specular;
m_light.Direction = *(D3DXVECTOR3*)&direction;
}
void cLight::SetDirection( const Vector3 &direction )
{
m_light.Direction = *(D3DXVECTOR3*)&direction;
}
void cLight::SetPosition( const Vector3 &pos )
{
m_light.Position = *(D3DXVECTOR3*)&pos;
}
// ±×¸²ÀÚ¸¦ Ãâ·ÂÇϱâ À§ÇÑ Á¤º¸¸¦ ¸®ÅÏÇÑ´Ù.
// modelPos : ±×¸²ÀÚ¸¦ Ãâ·ÂÇÒ ¸ðµ¨ÀÇ À§Ä¡ (¿ùµå»óÀÇ)
// lightPos : ±¤¿øÀÇ À§Ä¡°¡ ÀúÀåµÇ¾î ¸®ÅÏ.
// view : ±¤¿ø¿¡¼ ¸ðµ¨À» ¹Ù¶óº¸´Â ºä Çà·Ä
// proj : ±¤¿ø¿¡¼ ¸ðµ¨À» ¹Ù¶óº¸´Â Åõ¿µ Çà·Ä
// tt : Åõ¿µ ÁÂÇ¥¿¡¼ ÅØ½ºÃÄ ÁÂÇ¥·Î º¯È¯ÇÏ´Â Çà·Ä.
void cLight::GetShadowMatrix( const Vector3 &modelPos,
OUT Vector3 &lightPos, OUT Matrix44 &view, OUT Matrix44 &proj,
OUT Matrix44 &tt )
{
if (D3DLIGHT_DIRECTIONAL == m_light.Type)
{
// ¹æÇ⼺ Á¶¸íÀ̸é Direction º¤Å͸¦ ÅëÇØ À§Ä¡¸¦ °è»êÇÏ°Ô ÇÑ´Ù.
Vector3 pos = *(Vector3*)&m_light.Position;
Vector3 dir = *(Vector3*)&m_light.Direction;
lightPos = -dir * pos.Length();
}
else
{
lightPos = *(Vector3*)&m_light.Position;
}
view.SetView2( lightPos, modelPos, Vector3(0,1,0));
proj.SetProjection( D3DX_PI/8.f, 1, 0.1f, 10000);
D3DXMATRIX mTT= D3DXMATRIX(0.5f, 0.0f, 0.0f, 0.0f
, 0.0f,-0.5f, 0.0f, 0.0f
, 0.0f, 0.0f, 1.0f, 0.0f
, 0.5f, 0.5f, 0.0f, 1.0f);
tt = *(Matrix44*)&mTT;
}
void cLight::Bind(cRenderer &renderer, int lightIndex) const
{
renderer.GetDevice()->SetLight(lightIndex, &m_light); // ±¤¿ø ¼³Á¤.
}
// ¼ÎÀÌ´õ º¯¼ö¿¡ ¶óÀÌÆÃ¿¡ °ü·ÃµÈ º¯¼ö¸¦ ÃʱâÈ ÇÑ´Ù.
void cLight::Bind(cShader &shader) const
{
static cShader *oldPtr = NULL;
static D3DXHANDLE hDir = NULL;
static D3DXHANDLE hPos = NULL;
static D3DXHANDLE hAmbient = NULL;
static D3DXHANDLE hDiffuse = NULL;
static D3DXHANDLE hSpecular = NULL;
static D3DXHANDLE hTheta = NULL;
static D3DXHANDLE hPhi = NULL;
if (oldPtr != &shader)
{
hDir = shader.GetValueHandle("light.dir");
hPos = shader.GetValueHandle("light.pos");
hAmbient = shader.GetValueHandle("light.ambient");
hDiffuse = shader.GetValueHandle("light.diffuse");
hSpecular = shader.GetValueHandle("light.specular");
hTheta = shader.GetValueHandle("light.spotInnerCone");
hPhi = shader.GetValueHandle("light.spotOuterCone");
oldPtr = &shader;
}
shader.SetVector( hDir, *(Vector3*)&m_light.Direction);
shader.SetVector( hPos, *(Vector3*)&m_light.Position);
shader.SetVector( hAmbient, *(Vector4*)&m_light.Ambient);
shader.SetVector( hDiffuse, *(Vector4*)&m_light.Diffuse);
shader.SetVector( hSpecular, *(Vector4*)&m_light.Specular);
shader.SetFloat( hTheta, m_light.Theta);
shader.SetFloat( hPhi, m_light.Phi);
//shader.SetFloat( "light.radius", m_light.r);
}
|
jjuiddong/Point-Cloud
|
Src/Sample/Graphic/base/light.cpp
|
C++
|
mit
| 3,142 |
/**
* \file
*
* \brief Autogenerated API include file for the Atmel Software Framework (ASF)
*
* Copyright (c) 2012 Atmel Corporation. All rights reserved.
*
* \asf_license_start
*
* \page License
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* 3. The name of Atmel may not be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* 4. This software may only be redistributed and used in connection with an
* Atmel microcontroller product.
*
* THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE
* EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL 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.
*
* \asf_license_stop
*
*/
#ifndef ASF_H
#define ASF_H
/*
* This file includes all API header files for the selected drivers from ASF.
* Note: There might be duplicate includes required by more than one driver.
*
* The file is automatically generated and will be re-written when
* running the ASF driver selector tool. Any changes will be discarded.
*/
// From module: Common SAM compiler driver
#include <compiler.h>
#include <status_codes.h>
// From module: GPIO - General purpose Input/Output
#include <gpio.h>
// From module: Generic board support
#include <board.h>
// From module: Generic components of unit test framework
#include <unit_test/suite.h>
// From module: IOPORT - General purpose I/O service
#include <ioport.h>
// From module: Interrupt management - SAM implementation
#include <interrupt.h>
// From module: PIO - Parallel Input/Output Controller
#include <pio.h>
// From module: PMC - Power Management Controller
#include <pmc.h>
#include <sleep.h>
// From module: Part identification macros
#include <parts.h>
// From module: SAM3S EK LED support enabled
#include <led.h>
// From module: SAM3S startup code
#include <exceptions.h>
// From module: SSC - Synchronous Serial Controller
#include <ssc.h>
// From module: Standard serial I/O (stdio) - SAM implementation
#include <stdio_serial.h>
// From module: System Clock Control - SAM3S implementation
#include <sysclk.h>
// From module: UART - Univ. Async Rec/Trans
#include <uart.h>
// From module: USART - Serial interface - SAM implementation for devices with both UART and USART
#include <serial.h>
// From module: USART - Univ. Syn Async Rec/Trans
#include <usart.h>
// From module: pio_handler support enabled
#include <pio_handler.h>
#endif // ASF_H
|
femtoio/femto-usb-blink-example
|
blinky/blinky/asf-3.21.0/sam/drivers/ssc/unit_tests/sam3s4c_sam3s_ek/iar/asf.h
|
C
|
mit
| 3,578 |
<?php
declare(strict_types=1);
/*
* This file is part of eelly package.
*
* (c) eelly.com
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Eelly\SDK\Order\Api;
use Eelly\SDK\EellyClient;
use Eelly\SDK\Order\Service\LikeInterface;
/**
* 订单点赞记录表
*
* @author zhangyingdi<[email protected]>
*/
class Like
{
/**
* 新增订单点赞记录
*
* @param array $data 订单点赞记录数据
* @param int $orderData["orderId"] 订单id
* @param int $orderData["userId"] 用户id
*
* @throws \Eelly\SDK\Order\Exception\OrderException
*
* @return bool 新增结果
* @requestExample({
* "data":{
* "orderId":123,
* "userId":148086
* }
* })
* @returnExample(true)
*
* @author zhangyingdi<[email protected]>
* @since 2018.04.28
*/
public function addOrderLike(array $data): bool
{
return EellyClient::request('order/like', 'addOrderLike', true, $data);
}
/**
* 新增订单点赞记录
*
* @param array $data 订单点赞记录数据
* @param int $orderData["orderId"] 订单id
* @param int $orderData["userId"] 用户id
*
* @throws \Eelly\SDK\Order\Exception\OrderException
*
* @return bool 新增结果
* @requestExample({
* "data":{
* "orderId":123,
* "userId":148086
* }
* })
* @returnExample(true)
*
* @author zhangyingdi<[email protected]>
* @since 2018.04.28
*/
public function addOrderLikeAsync(array $data)
{
return EellyClient::request('order/like', 'addOrderLike', false, $data);
}
/**
* 获取订单点赞信息
*
* @param $orderId 订单id
* @return array
*
* @requestExample({"orderId":162})
* @returnExample([{"oliId":"4","orderId":"161","userId":"148086","createdTime":"1524899508","updateTime":"2018-04-28 15:11:31"},{"oliId":"5","orderId":"161","userId":"11","createdTime":"1524899533","updateTime":"2018-04-28 15:11:55"}])
*
* @author wechan
* @since 2018年05月02日
*/
public function getOrderLikeInfo(int $orderId): array
{
return EellyClient::request('order/like', 'getOrderLikeInfo', true, $orderId);
}
/**
* 获取订单点赞信息
*
* @param $orderId 订单id
* @return array
*
* @requestExample({"orderId":162})
* @returnExample([{"oliId":"4","orderId":"161","userId":"148086","createdTime":"1524899508","updateTime":"2018-04-28 15:11:31"},{"oliId":"5","orderId":"161","userId":"11","createdTime":"1524899533","updateTime":"2018-04-28 15:11:55"}])
*
* @author wechan
* @since 2018年05月02日
*/
public function getOrderLikeInfoAsync(int $orderId)
{
return EellyClient::request('order/like', 'getOrderLikeInfo', false, $orderId);
}
/**
* 新增订单点赞记录 (新版--自定义商品点赞数控制).
*
* @param array $data 订单点赞记录数据
* @param int $orderData["orderId"] 订单id
* @param int $orderData["userId"] 用户id
* @param int $orderData["goodsId"] 商品id
* @param \Eelly\DTO\UidDTO $user 登录用户信息
*
* @throws \Eelly\SDK\Order\Exception\OrderException
*
* @return bool 新增结果
* @requestExample({
* "data":{
* "orderId":123,
* "userId":148086,
* "goodsId":123
* }
* })
* @returnExample(true)
*
* @author zhangyingdi<[email protected]>
*
* @since 2018.06.28
*/
public function addOrderLikeNew(array $data, UidDTO $user = null): bool
{
return EellyClient::request('order/like', 'addOrderLikeNew', true, $data, $user);
}
/**
* 新增订单点赞记录 (新版--自定义商品点赞数控制).
*
* @param array $data 订单点赞记录数据
* @param int $orderData["orderId"] 订单id
* @param int $orderData["userId"] 用户id
* @param int $orderData["goodsId"] 商品id
* @param \Eelly\DTO\UidDTO $user 登录用户信息
*
* @throws \Eelly\SDK\Order\Exception\OrderException
*
* @return bool 新增结果
* @requestExample({
* "data":{
* "orderId":123,
* "userId":148086,
* "goodsId":123
* }
* })
* @returnExample(true)
*
* @author zhangyingdi<[email protected]>
*
* @since 2018.06.28
*/
public function addOrderLikeNewAsync(array $data, UidDTO $user = null)
{
return EellyClient::request('order/like', 'addOrderLikeNew', false, $data, $user);
}
/**
* @return self
*/
public static function getInstance(): self
{
static $instance;
if (null === $instance) {
$instance = new self();
}
return $instance;
}
}
|
EellyDev/eelly-sdk-php
|
src/SDK/Order/Api/Like.php
|
PHP
|
mit
| 5,298 |
#region "Copyright"
/*
FOR FURTHER DETAILS ABOUT LICENSING, PLEASE VISIT "LICENSE.txt" INSIDE THE SAGEFRAME FOLDER
*/
#endregion
#region "References"
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.SqlClient;
using SageFrame.Web.Utilities;
#endregion
namespace SageFrame.Core.TemplateManagement
{
/// <summary>
/// Manipulates the data needed for template.
/// </summary>
public class TemplateDataProvider
{
/// <summary>
/// Connects to database and returns list of template list.
/// </summary>
/// <param name="PortalID">Portal ID.</param>
/// <param name="UserName">User's name.</param>
/// <returns>List of template.</returns>
public static List<TemplateInfo> GetTemplateList(int PortalID, string UserName)
{
string sp = "[dbo].[sp_TemplateGetList]";
SQLHandler sagesql = new SQLHandler();
List<KeyValuePair<string, object>> ParamCollInput = new List<KeyValuePair<string, object>>();
ParamCollInput.Add(new KeyValuePair<string, object>("@PortalID", PortalID));
ParamCollInput.Add(new KeyValuePair<string, object>("@UserName", UserName));
List<TemplateInfo> lstTemplate = new List<TemplateInfo>();
SqlDataReader reader = null;
try
{
reader = sagesql.ExecuteAsDataReader(sp, ParamCollInput);
while (reader.Read())
{
TemplateInfo obj = new TemplateInfo();
obj.TemplateID = int.Parse(reader["TemplateID"].ToString());
obj.TemplateTitle = reader["TemplateTitle"].ToString();
obj.PortalID = int.Parse(reader["PortalID"].ToString());
obj.Author = reader["Author"].ToString();
obj.AuthorURL = reader["AuthorURL"].ToString();
obj.Description = reader["Description"].ToString();
lstTemplate.Add(obj);
}
reader.Close();
return lstTemplate;
}
catch (Exception ex)
{
throw (ex);
}
finally
{
if (reader != null)
{
reader.Close();
}
}
}
/// <summary>
/// Connects to database and adds template.
/// </summary>
/// <param name="obj">TemplateInfo object containing the template details.</param>
/// <returns>True if the template is added successfully.</returns>
public static bool AddTemplate(TemplateInfo obj)
{
string sp = "[dbo].[sp_TemplateAdd]";
SQLHandler sagesql = new SQLHandler();
List<KeyValuePair<string, object>> ParamCollInput = new List<KeyValuePair<string, object>>();
ParamCollInput.Add(new KeyValuePair<string, object>("@TemplateTitle", obj.TemplateTitle));
ParamCollInput.Add(new KeyValuePair<string, object>("@Author",obj.Author));
ParamCollInput.Add(new KeyValuePair<string, object>("@Description", obj.Description));
ParamCollInput.Add(new KeyValuePair<string, object>("@AuthorURL", obj.AuthorURL));
ParamCollInput.Add(new KeyValuePair<string, object>("@PortalID", obj.PortalID));
ParamCollInput.Add(new KeyValuePair<string, object>("@UserName", obj.AddedBy));
try
{
sagesql.ExecuteNonQuery(sp, ParamCollInput);
return true;
}
catch (Exception ex)
{
throw (ex);
}
}
}
}
|
AspxCommerce/AspxCommerce2.7
|
SageFrame.Core/TemplateManagement/TemplateDataProvider.cs
|
C#
|
mit
| 3,799 |
# -*- coding: utf-8 -*-
# Copyright (c) 2020, Frappe Technologies and contributors
# For license information, please see license.txt
from __future__ import unicode_literals
# import frappe
from frappe.model.document import Document
class WebPageBlock(Document):
pass
|
adityahase/frappe
|
frappe/website/doctype/web_page_block/web_page_block.py
|
Python
|
mit
| 272 |
//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by Fernflower decompiler)
//
package cn.sharesdk.demo.utils;
import android.annotation.TargetApi;
import android.content.Context;
import android.database.ContentObserver;
import android.database.Cursor;
import android.graphics.BitmapFactory;
import android.graphics.BitmapFactory.Options;
import android.graphics.Point;
import android.net.Uri;
import android.os.Build.VERSION;
import android.os.Handler;
import android.os.Looper;
import android.provider.MediaStore.Images.Media;
import android.text.TextUtils;
import android.util.Log;
import android.view.Display;
import android.view.WindowManager;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;
@TargetApi(17)
public class ScreenShotListenManager {
private static final String TAG = "ScreenShotListenManager";
private static final String[] MEDIA_PROJECTIONS = new String[]{"_data", "datetaken"};
private static final String[] MEDIA_PROJECTIONS_API_16 = new String[]{"_data", "datetaken", "width", "height"};
private static final String[] KEYWORDS = new String[]{"screenshot", "screen_shot", "screen-shot", "screen shot", "screencapture",
"screen_capture", "screen-capture", "screen capture", "screencap", "screen_cap", "screen-cap", "screen cap"};
private static Point sScreenRealSize;
private final List<String> sHasCallbackPaths = new ArrayList();
private Context context;
private OnScreenShotListener listener;
private long startListenTime;
private MediaContentObserver internalObserver;
private MediaContentObserver externalObserver;
private final Handler uiHandler = new Handler(Looper.getMainLooper());
private ScreenShotListenManager(Context context) {
if(context == null) {
throw new IllegalArgumentException("The context must not be null.");
} else {
this.context = context;
if(sScreenRealSize == null) {
sScreenRealSize = this.getRealScreenSize();
if(sScreenRealSize != null) {
Log.d("ScreenShotListenManager", "Screen Real Size: " + sScreenRealSize.x + " * " + sScreenRealSize.y);
} else {
Log.w("ScreenShotListenManager", "Get screen real size failed.");
}
}
}
}
public static ScreenShotListenManager newInstance(Context context) {
assertInMainThread();
return new ScreenShotListenManager(context);
}
public void startListen() {
assertInMainThread();
this.sHasCallbackPaths.clear();
this.startListenTime = System.currentTimeMillis();
this.internalObserver = new MediaContentObserver(Media.INTERNAL_CONTENT_URI, this.uiHandler);
this.externalObserver = new MediaContentObserver(Media.EXTERNAL_CONTENT_URI, this.uiHandler);
this.context.getContentResolver().registerContentObserver(Media.INTERNAL_CONTENT_URI, false, this.internalObserver);
this.context.getContentResolver().registerContentObserver(Media.EXTERNAL_CONTENT_URI, false, this.externalObserver);
}
public void stopListen() {
assertInMainThread();
if(this.internalObserver != null) {
try {
this.context.getContentResolver().unregisterContentObserver(this.internalObserver);
} catch (Exception var3) {
var3.printStackTrace();
}
this.internalObserver = null;
}
if(this.externalObserver != null) {
try {
this.context.getContentResolver().unregisterContentObserver(this.externalObserver);
} catch (Exception var2) {
var2.printStackTrace();
}
this.externalObserver = null;
}
this.startListenTime = 0L;
this.sHasCallbackPaths.clear();
}
private void handleMediaContentChange(Uri contentUri) {
Cursor cursor = null;
try {
cursor = this.context.getContentResolver().query(contentUri, VERSION.SDK_INT < 16 ? MEDIA_PROJECTIONS : MEDIA_PROJECTIONS_API_16,
(String)null, (String[])null, "date_added desc limit 1");
if(cursor == null) {
Log.e("ScreenShotListenManager", "Deviant logic.");
return;
}
if(cursor.moveToFirst()) {
int e = cursor.getColumnIndex("_data");
int dateTakenIndex = cursor.getColumnIndex("datetaken");
int widthIndex = -1;
int heightIndex = -1;
if(VERSION.SDK_INT >= 16) {
widthIndex = cursor.getColumnIndex("width");
heightIndex = cursor.getColumnIndex("height");
}
String data = cursor.getString(e);
long dateTaken = cursor.getLong(dateTakenIndex);
boolean width = false;
boolean height = false;
int width1;
int height1;
if(widthIndex >= 0 && heightIndex >= 0) {
width1 = cursor.getInt(widthIndex);
height1 = cursor.getInt(heightIndex);
} else {
Point size = this.getImageSize(data);
width1 = size.x;
height1 = size.y;
}
this.handleMediaRowData(data, dateTaken, width1, height1);
return;
}
Log.d("ScreenShotListenManager", "Cursor no data.");
} catch (Exception var16) {
var16.printStackTrace();
return;
} finally {
if(cursor != null && !cursor.isClosed()) {
cursor.close();
}
}
}
private Point getImageSize(String imagePath) {
Options options = new Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeFile(imagePath, options);
return new Point(options.outWidth, options.outHeight);
}
private void handleMediaRowData(String data, long dateTaken, int width, int height) {
if(this.checkScreenShot(data, dateTaken, width, height)) {
Log.d("ScreenShotListenManager", "ScreenShot: path = " + data + "; size = " + width + " * " + height + "; date = " + dateTaken);
if(this.listener != null && !this.checkCallback(data)) {
this.listener.onShot(data);
}
} else {
Log.w("ScreenShotListenManager", "Media content changed, but not screenshot: path = " + data + "; size = " + width + " * "
+ height + "; date = " + dateTaken);
}
}
private boolean checkScreenShot(String data, long dateTaken, int width, int height) {
long currentTime = System.currentTimeMillis() - dateTaken;
if(dateTaken >= this.startListenTime && currentTime <= 20000L) {
if(sScreenRealSize == null || width <= sScreenRealSize.x && height <= sScreenRealSize.y || height <= sScreenRealSize.x
&& width <= sScreenRealSize.y) {
if(TextUtils.isEmpty(data)) {
return false;
} else {
data = data.toLowerCase();
String[] var11 = KEYWORDS;
int var10 = KEYWORDS.length;
for(int var9 = 0; var9 < var10; var9++) {
String keyWork = var11[var9];
if(data.contains(keyWork)) {
return true;
}
}
return false;
}
} else {
return false;
}
} else {
return false;
}
}
private boolean checkCallback(String imagePath) {
if(this.sHasCallbackPaths.contains(imagePath)) {
return true;
} else {
if(this.sHasCallbackPaths.size() >= 20) {
for(int i = 0; i < 5; i++) {
this.sHasCallbackPaths.remove(0);
}
}
this.sHasCallbackPaths.add(imagePath);
return false;
}
}
private Point getRealScreenSize() {
Point screenSize = null;
try {
screenSize = new Point();
WindowManager e = (WindowManager)this.context.getSystemService("window");
Display defaultDisplay = e.getDefaultDisplay();
if(VERSION.SDK_INT >= 17) {
defaultDisplay.getRealSize(screenSize);
} else {
try {
Method e1 = Display.class.getMethod("getRawWidth", new Class[0]);
Method getRawH = Display.class.getMethod("getRawHeight", new Class[0]);
screenSize.set(((Integer)e1.invoke(defaultDisplay, new Object[0])).intValue(),
((Integer)getRawH.invoke(defaultDisplay, new Object[0])).intValue());
} catch (Exception var6) {
screenSize.set(defaultDisplay.getWidth(), defaultDisplay.getHeight());
var6.printStackTrace();
}
}
} catch (Exception var7) {
var7.printStackTrace();
}
return screenSize;
}
public void setListener(ScreenShotListenManager.OnScreenShotListener listener) {
this.listener = listener;
}
private static void assertInMainThread() {
if(Looper.myLooper() != Looper.getMainLooper()) {
StackTraceElement[] elements = Thread.currentThread().getStackTrace();
String methodMsg = null;
if(elements != null && elements.length >= 4) {
methodMsg = elements[3].toString();
}
throw new IllegalStateException("Call the method must be in main thread: " + methodMsg);
}
}
private class MediaContentObserver extends ContentObserver {
private Uri contentUri;
public MediaContentObserver(Uri contentUri, Handler handler) {
super(handler);
this.contentUri = contentUri;
}
public void onChange(boolean selfChange) {
super.onChange(selfChange);
handleMediaContentChange(this.contentUri);
}
}
public interface OnScreenShotListener {
void onShot(String var1);
}
}
|
ShareSDKPlatform/ShareSDK-for-Android
|
SampleFresh/app/src/main/java/cn/sharesdk/demo/utils/ScreenShotListenManager.java
|
Java
|
mit
| 8,651 |
var Path = require('path');
var Hapi = require('hapi');
var server = new Hapi.Server();
var port = process.env.PORT || 5000;
server.connection({ port: port });
server.views({
engines: {
html: require('handlebars')
},
path: Path.join(__dirname, 'views')
});
server.route([
{ path: '/',
method: 'GET',
config: {
auth: false,
handler: function(request, reply) {
reply.view("index");
}
}
},
{
method: 'GET',
path: '/public/{param*}',
handler: {
directory: {
path: Path.normalize(__dirname + '/public')
}
}
}
]);
server.start(function(){
console.log('Static Server Listening on : http://127.0.0.1:' +port);
});
module.exports = server;
|
rorysedgwick/learn-hapi
|
examples/staticfiles.js
|
JavaScript
|
mit
| 753 |
//
// Copyright (c) 2014-2015, THUNDERBEAST GAMES LLC 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 <Atomic/Atomic3D/StaticModel.h>
#include <Atomic/Atomic3D/CustomGeometry.h>
#include <Atomic/Atomic3D/BillboardSet.h>
#include "JSAtomic3D.h"
namespace Atomic
{
static int StaticModel_SetMaterialIndex(duk_context* ctx) {
unsigned index = (unsigned) duk_require_number(ctx, 0);
Material* material = js_to_class_instance<Material>(ctx, 1, 0);
duk_push_this(ctx);
// event receiver
StaticModel* model = js_to_class_instance<StaticModel>(ctx, -1, 0);
model->SetMaterial(index, material);
return 0;
}
static int CustomGeometry_SetMaterialIndex(duk_context* ctx) {
unsigned index = (unsigned)duk_require_number(ctx, 0);
Material* material = js_to_class_instance<Material>(ctx, 1, 0);
duk_push_this(ctx);
// event receiver
CustomGeometry* geometry = js_to_class_instance<CustomGeometry>(ctx, -1, 0);
geometry->SetMaterial(index, material);
return 0;
}
static int BillboardSet_GetBillboard(duk_context* ctx)
{
duk_push_this(ctx);
BillboardSet* billboardSet = js_to_class_instance<BillboardSet>(ctx, -1, 0);
unsigned index = (unsigned)duk_to_number(ctx, 0);
Billboard* billboard = billboardSet->GetBillboard(index);
js_push_class_object_instance(ctx, billboard, "Billboard");
return 1;
}
void jsapi_init_atomic3d(JSVM* vm)
{
duk_context* ctx = vm->GetJSContext();
js_class_get_prototype(ctx, "Atomic", "StaticModel");
duk_push_c_function(ctx, StaticModel_SetMaterialIndex, 2);
duk_put_prop_string(ctx, -2, "setMaterialIndex");
duk_pop(ctx); // pop AObject prototype
js_class_get_prototype(ctx, "Atomic", "CustomGeometry");
duk_push_c_function(ctx, CustomGeometry_SetMaterialIndex, 2);
duk_put_prop_string(ctx, -2, "setMaterialIndex");
duk_pop(ctx); // pop AObject prototype
js_class_get_prototype(ctx, "Atomic", "BillboardSet");
duk_push_c_function(ctx, BillboardSet_GetBillboard, 1);
duk_put_prop_string(ctx, -2, "getBillboard");
duk_pop(ctx); // pop AObject prototype
}
}
|
rsredsq/AtomicGameEngine
|
Source/AtomicJS/Javascript/JSAtomic3D.cpp
|
C++
|
mit
| 3,193 |
//-----------------------------------------------------------------------------
// Verve
// Copyright (C) - Violent Tulip
//-----------------------------------------------------------------------------
function VControllerPropertyList::CreateInspectorGroup( %this, %targetStack )
{
%baseGroup = Parent::CreateInspectorGroup( %this, %targetStack );
if ( %baseGroup.getClassName() !$= "ScriptGroup" )
{
// Temp Store.
%temp = %baseGroup;
// Create SimSet.
%baseGroup = new SimSet();
// Add Original Control.
%baseGroup.add( %temp );
}
// Create Data Table Group.
%groupRollout = %targetStack.CreatePropertyRollout( "VController DataTable" );
%propertyStack = %groupRollout.Stack;
// Reference.
%propertyStack.InternalName = "DataTableStack";
// Store.
%baseGroup.add( %groupRollout );
// Return.
return %baseGroup;
}
function VControllerPropertyList::InspectObject( %this, %object )
{
if ( !%object.isMemberOfClass( "VController" ) )
{
// Invalid Object.
return;
}
// Default Inspect.
Parent::InspectObject( %this, %object );
// Update Data Table.
%dataTableStack = %this.ControlCache.findObjectByInternalName( "DataTableStack", true );
if ( !isObject( %dataTableStack ) )
{
// Invalid Table.
return;
}
// Clear Stack.
while ( %dataTableStack.getCount() > 1 )
{
// Delete Object.
%dataTableStack.getObject( 1 ).delete();
}
%dataFieldCount = %object.getDataFieldCount();
for ( %i = 0; %i < %dataFieldCount; %i++ )
{
// Add To List.
%dataFieldList = trim( %dataFieldList SPC %object.getDataFieldName( %i ) );
}
// Sort Word List.
%dataFieldList = sortWordList( %dataFieldList );
for ( %i = 0; %i < %dataFieldCount; %i++ )
{
// Fetch Field Name.
%dataFieldName = getWord( %dataFieldList, %i );
// Create Field.
VerveEditor::CreateField( %dataTableStack, %dataFieldName, "Data" );
}
// Create Add Field.
VerveEditor::CreateAddDataField( %dataTableStack );
// Update.
%dataTableStack.InspectObject( %object );
}
function VController::DisplayContextMenu( %this, %x, %y )
{
%contextMenu = $VerveEditor::VController::ContextMenu;
if ( !isObject( %contextMenu ) )
{
%contextMenu = new PopupMenu()
{
SuperClass = "VerveWindowMenu";
IsPopup = true;
Label = "VControllerContextMenu";
Position = 0;
Item[0] = "Add Group" TAB "";
Item[1] = "" TAB "";
Item[2] = "Cu&t" TAB "" TAB "";
Item[3] = "&Copy" TAB "" TAB "";
Item[4] = "&Paste" TAB "" TAB "VerveEditor::Paste();";
Item[5] = "" TAB "";
Item[6] = "&Delete" TAB "" TAB "";
PasteIndex = 4;
};
%contextMenu.Init();
// Disable Cut, Copy & Delete.
%contextMenu.enableItem( 2, false );
%contextMenu.enableItem( 3, false );
%contextMenu.enableItem( 6, false );
// Cache.
$VerveEditor::VController::ContextMenu = %contextMenu;
}
// Remove Add Menu.
%contextMenu.removeItem( %contextMenu.AddIndex );
// Insert Menu.
%contextMenu.insertSubMenu( %contextMenu.AddIndex, getField( %contextMenu.Item[0], 0 ), %this.GetAddGroupMenu() );
// Enable/Disable Pasting.
%contextMenu.enableItem( %contextMenu.PasteIndex, VerveEditor::CanPaste() );
if ( %x $= "" || %y $= "" )
{
%position = %this.getGlobalPosition();
%extent = %this.getExtent();
%x = getWord( %position, 0 ) + getWord( %extent, 0 );
%y = getWord( %position, 1 );
}
// Display.
%contextMenu.showPopup( VerveEditorWindow, %x, %y );
}
function VController::GetAddGroupMenu( %this )
{
%contextMenu = $VerveEditor::VController::ContextMenu[%this.getClassName()];
if ( !isObject( %contextMenu ) )
{
%customTemplateMenu = new PopupMenu()
{
Class = "VerveCustomTemplateMenu";
SuperClass = "VerveWindowMenu";
IsPopup = true;
Label = "VGroupAddGroupMenu";
Position = 0;
};
%customTemplateMenu.Init();
%contextMenu = new PopupMenu()
{
SuperClass = "VerveWindowMenu";
IsPopup = true;
Label = "VGroupAddGroupMenu";
Position = 0;
Item[0] = "Add Camera Group" TAB "" TAB "VerveEditor::AddGroup(\"VCameraGroup\");";
Item[1] = "Add Director Group" TAB "" TAB "VerveEditor::AddGroup(\"VDirectorGroup\");";
Item[2] = "Add Light Object Group" TAB "" TAB "VerveEditor::AddGroup(\"VLightObjectGroup\");";
Item[3] = "Add Particle Effect Group" TAB "" TAB "VerveEditor::AddGroup(\"VParticleEffectGroup\");";
Item[4] = "Add Scene Object Group" TAB "" TAB "VerveEditor::AddGroup(\"VSceneObjectGroup\");";
Item[5] = "Add Spawn Sphere Group" TAB "" TAB "VerveEditor::AddGroup(\"VSpawnSphereGroup\");";
Item[6] = "" TAB "";
Item[7] = "Add Custom Group" TAB %customTemplateMenu;
DirectorIndex = 1;
CustomIndex = 7;
CustomMenu = %customTemplateMenu;
};
%contextMenu.Init();
// Refresh Menu.
%customTemplateMenu = %contextMenu.CustomMenu;
if ( %customTemplateMenu.getItemCount() == 0 )
{
// Remove Item.
%contextMenu.removeItem( %contextMenu.CustomIndex );
// Add Dummy.
%contextMenu.insertItem( %contextMenu.CustomIndex, getField( %contextMenu.Item[%contextMenu.CustomIndex], 0 ) );
// Disable Custom Menu.
%contextMenu.enableItem( %contextMenu.CustomIndex, false );
}
// Cache.
$VerveEditor::VController::ContextMenu[%this.getClassName()] = %contextMenu;
}
// Enable / Disable Director Group.
%contextMenu.enableItem( %contextMenu.DirectorIndex, %this.CanAdd( "VDirectorGroup" ) );
// Return Menu.
return %contextMenu;
}
|
AnteSim/Verve
|
Templates/Verve/game/tools/VerveEditor/Scripts/Controller/VControllerProperties.cs
|
C#
|
mit
| 6,641 |
module Cms::PublicFilter
extend ActiveSupport::Concern
include Cms::PublicFilter::Node
include Cms::PublicFilter::Page
include Mobile::PublicFilter
include Kana::PublicFilter
included do
rescue_from StandardError, with: :rescue_action
before_action :set_site
before_action :set_request_path
#before_action :redirect_slash, if: ->{ request.env["REQUEST_PATH"] =~ /\/[^\.]+[^\/]$/ }
before_action :deny_path
before_action :parse_path
before_action :compile_scss
before_action :x_sendfile, if: ->{ filters.blank? }
end
public
def index
if @cur_path =~ /\.p[1-9]\d*\.html$/
page = @cur_path.sub(/.*\.p(\d+)\.html$/, '\\1')
params[:page] = page.to_i
@cur_path.sub!(/\.p\d+\.html$/, ".html")
end
if @html =~ /\.part\.html$/
part = find_part(@html)
raise "404" unless part
@cur_path = params[:ref] || "/"
send_part render_part(part)
elsif page = find_page(@cur_path)
self.response = render_page(page)
send_page page
elsif node = find_node(@cur_path)
self.response = render_node(node)
send_page node
else
raise "404"
end
end
private
def set_site
host = request.env["HTTP_X_FORWARDED_HOST"] || request.env["HTTP_HOST"]
@cur_site ||= SS::Site.find_by_domain host
raise "404" if !@cur_site
end
def set_request_path
@cur_path ||= request.env["REQUEST_PATH"]
cur_path = @cur_path.dup
filter_methods = self.class.private_instance_methods.select { |m| m =~ /^set_request_path_with_/ }
filter_methods.each do |name|
send(name)
break if cur_path != @cur_path
end
end
def redirect_slash
return unless request.get?
redirect_to "#{request.path}/"
end
def deny_path
raise "404" if @cur_path =~ /^\/sites\/.\//
end
def parse_path
@cur_path.sub!(/\/$/, "/index.html")
@html = @cur_path.sub(/\.\w+$/, ".html")
@file = File.join(@cur_site.path, @cur_path)
end
def compile_scss
return if @cur_path !~ /\.css$/
return if @cur_path =~ /\/_[^\/]*$/
return unless Fs.exists? @scss = @file.sub(/\.css$/, ".scss")
css_mtime = Fs.exists?(@file) ? Fs.stat(@file).mtime : 0
return if Fs.stat(@scss).mtime.to_i <= css_mtime.to_i
css = ""
begin
opts = Rails.application.config.sass
sass = Sass::Engine.new Fs.read(@scss), filename: @scss, syntax: :scss, cache: false,
load_paths: opts.load_paths[1..-1],
style: :compressed,
debug_info: false
css = sass.render
rescue Sass::SyntaxError => e
msg = e.backtrace[0].sub(/.*?\/_\//, "")
msg = "[#{msg}]\\A #{e}".gsub('"', '\\"')
css = "body:before { position: absolute; top: 8px; right: 8px; display: block;"
css << " padding: 4px 8px; border: 1px solid #b88; background-color: #fff;"
css << " color: #822; font-size: 85%; font-family: tahoma, sans-serif; line-height: 1.6;"
css << " white-space: pre; z-index: 9; content: \"#{msg}\"; }"
end
Fs.write @file, css
end
def x_sendfile(file = @file)
return unless Fs.file?(file)
response.headers["Expires"] = 1.days.from_now.httpdate if file =~ /\.(css|js|gif|jpg|png)$/
response.headers["Last-Modified"] = CGI::rfc1123_date(Fs.stat(file).mtime)
if Fs.mode == :file
send_file file, disposition: :inline, x_sendfile: true
else
send_data Fs.binread(file), type: Fs.content_type(file)
end
end
def send_part(body)
respond_to do |format|
format.html { render inline: body, layout: false }
format.json { render json: body.to_json }
end
end
def send_page(page)
raise "404" unless response
if response.content_type == "text/html" && page.layout
render inline: render_layout(page.layout), layout: (request.xhr? ? false : "cms/page")
else
@_response_body = response.body
end
end
def rescue_action(e = nil)
return render_error(e, status: e.to_s.to_i) if e.to_s =~ /^\d+$/
return render_error(e, status: 404) if e.is_a? Mongoid::Errors::DocumentNotFound
return render_error(e, status: 404) if e.is_a? ActionController::RoutingError
raise e
end
def render_error(e, opts = {})
# for development
raise e if Rails.application.config.consider_all_requests_local
self.response = ActionDispatch::Response.new
status = opts[:status].presence || 500
render status: status, file: error_template(status), layout: false
end
def error_template(status)
if @cur_site
file = "#{@cur_site.path}/#{status}.html"
return file if Fs.exists?(file)
end
file = "#{Rails.public_path}/#{status}.html"
Fs.exists?(file) ? file : "#{Rails.public_path}/500.html"
end
end
|
gouf/shirasagi
|
app/controllers/concerns/cms/public_filter.rb
|
Ruby
|
mit
| 4,976 |
<h1>Home</h1>
<p>You're logged in!!</p>
<p><a href="#/login">Logout</a></a></p>
|
santutoshi/angularjs.test
|
modules/home/views/home.html
|
HTML
|
mit
| 79 |
// Copyright 2019 The Gitea Authors. All rights reserved.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file.
package queue
import (
"errors"
"strings"
"code.gitea.io/gitea/modules/log"
"github.com/go-redis/redis"
)
// RedisQueueType is the type for redis queue
const RedisQueueType Type = "redis"
// RedisQueueConfiguration is the configuration for the redis queue
type RedisQueueConfiguration struct {
ByteFIFOQueueConfiguration
RedisByteFIFOConfiguration
}
// RedisQueue redis queue
type RedisQueue struct {
*ByteFIFOQueue
}
// NewRedisQueue creates single redis or cluster redis queue
func NewRedisQueue(handle HandlerFunc, cfg, exemplar interface{}) (Queue, error) {
configInterface, err := toConfig(RedisQueueConfiguration{}, cfg)
if err != nil {
return nil, err
}
config := configInterface.(RedisQueueConfiguration)
byteFIFO, err := NewRedisByteFIFO(config.RedisByteFIFOConfiguration)
if err != nil {
return nil, err
}
byteFIFOQueue, err := NewByteFIFOQueue(RedisQueueType, byteFIFO, handle, config.ByteFIFOQueueConfiguration, exemplar)
if err != nil {
return nil, err
}
queue := &RedisQueue{
ByteFIFOQueue: byteFIFOQueue,
}
queue.qid = GetManager().Add(queue, RedisQueueType, config, exemplar)
return queue, nil
}
type redisClient interface {
RPush(key string, args ...interface{}) *redis.IntCmd
LPop(key string) *redis.StringCmd
LLen(key string) *redis.IntCmd
SAdd(key string, members ...interface{}) *redis.IntCmd
SRem(key string, members ...interface{}) *redis.IntCmd
SIsMember(key string, member interface{}) *redis.BoolCmd
Ping() *redis.StatusCmd
Close() error
}
var _ (ByteFIFO) = &RedisByteFIFO{}
// RedisByteFIFO represents a ByteFIFO formed from a redisClient
type RedisByteFIFO struct {
client redisClient
queueName string
}
// RedisByteFIFOConfiguration is the configuration for the RedisByteFIFO
type RedisByteFIFOConfiguration struct {
Network string
Addresses string
Password string
DBIndex int
QueueName string
}
// NewRedisByteFIFO creates a ByteFIFO formed from a redisClient
func NewRedisByteFIFO(config RedisByteFIFOConfiguration) (*RedisByteFIFO, error) {
fifo := &RedisByteFIFO{
queueName: config.QueueName,
}
dbs := strings.Split(config.Addresses, ",")
if len(dbs) == 0 {
return nil, errors.New("no redis host specified")
} else if len(dbs) == 1 {
fifo.client = redis.NewClient(&redis.Options{
Network: config.Network,
Addr: strings.TrimSpace(dbs[0]), // use default Addr
Password: config.Password, // no password set
DB: config.DBIndex, // use default DB
})
} else {
fifo.client = redis.NewClusterClient(&redis.ClusterOptions{
Addrs: dbs,
})
}
if err := fifo.client.Ping().Err(); err != nil {
return nil, err
}
return fifo, nil
}
// PushFunc pushes data to the end of the fifo and calls the callback if it is added
func (fifo *RedisByteFIFO) PushFunc(data []byte, fn func() error) error {
if fn != nil {
if err := fn(); err != nil {
return err
}
}
return fifo.client.RPush(fifo.queueName, data).Err()
}
// Pop pops data from the start of the fifo
func (fifo *RedisByteFIFO) Pop() ([]byte, error) {
data, err := fifo.client.LPop(fifo.queueName).Bytes()
if err == nil || err == redis.Nil {
return data, nil
}
return data, err
}
// Close this fifo
func (fifo *RedisByteFIFO) Close() error {
return fifo.client.Close()
}
// Len returns the length of the fifo
func (fifo *RedisByteFIFO) Len() int64 {
val, err := fifo.client.LLen(fifo.queueName).Result()
if err != nil {
log.Error("Error whilst getting length of redis queue %s: Error: %v", fifo.queueName, err)
return -1
}
return val
}
func init() {
queuesMap[RedisQueueType] = NewRedisQueue
}
|
lafriks/gitea
|
modules/queue/queue_redis.go
|
GO
|
mit
| 3,795 |
/**
* @file fly_id3.h
*
* Declaration of the pianobarfly ID3 helper functions. These are helper
* functions to assist with creating an ID3 tag using the libid3tag library.
*/
/*
* Copyright (c) 2011
* Author: Ted Jordan
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to
* deal in the Software without restriction, including without limitation the
* rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
* sell copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
* IN THE SOFTWARE.
*/
#ifndef _FLY_ID3_H
#define _FLY_ID3_H
#if defined ENABLE_MAD && defined ENABLE_ID3TAG
#include <id3tag.h>
#include <stdint.h>
/**
* Creates and attaches an image frame with the cover art to the given tag.
*
* @param tag A pointer to the tag.
* @param cover_art A buffer containing the cover art image.
* @param cover_size The size of the buffer.
* @param settings A pointer to the application settings structure.
* @return If successful 0 is returned otherwise -1 is returned.
*/
int BarFlyID3AddCover(struct id3_tag* tag, uint8_t const* cover_art,
size_t cover_size, BarSettings_t const* settings);
/**
* Creates and attaches a frame of the given type to the tag with the given
* string value. All values are written to the string list field of the frame.
*
* @param tag A pointer to the tag.
* @param type A string containing the frame type, ex. TIT2.
* @param value A string containing the value.
* @param settings A pointer to the application settings structure.
* @return If the frame was successfully added 0 is returned, otherwise -1 is
* returned.
*/
int BarFlyID3AddFrame(struct id3_tag* tag, char const* type,
char const* value, BarSettings_t const* settings);
/**
* Physically writes the ID3 tag to the audio file. A temproary file is create
* into which the tag is written. After which the contents of the audio file is
* copied into it. Once the temporary file is complete the audio file is
* overwritten with it.
*
* @param file_path A pointer to a string containing the path to the audio file.
* @param tag A pointer to the tag structure to be written to the file.
* @param settings A pointer to the application settings structure.
* @return If successful 0 is returned otherwise -1 is returned.
*/
int BarFlyID3WriteFile(char const* file_path, struct id3_tag const* tag,
BarSettings_t const* settings);
#endif
#endif
// vim: set noexpandtab:
|
Vi1i/pianobarfly
|
src/fly_id3.h
|
C
|
mit
| 3,217 |
package velir.intellij.cq5.util;
import javax.jcr.Node;
import javax.jcr.NodeIterator;
import javax.jcr.RepositoryException;
import javax.jcr.Session;
import java.util.ArrayList;
import java.util.List;
/**
* Utility class for helping work with Repository objects.
*/
public class RepositoryUtils {
/**
* Hide default constructor for true static class.
*/
private RepositoryUtils() {
}
public static List<String> getAllNodeTypeNames(Session session) throws RepositoryException {
//get our child nodeTypes from our root
NodeIterator nodeTypes = getAllNodeTypes(session);
//go through each node type and pull out the name
List<String> nodeTypeNames = new ArrayList<String>();
while (nodeTypes.hasNext()) {
Node node = nodeTypes.nextNode();
nodeTypeNames.add(node.getName());
}
//return our node type names
return nodeTypeNames;
}
/**
* Will get all the nodes that represent the different node types.
*
* @param session Repository session to use for pulling out this information.
* @return
* @throws RepositoryException
*/
public static NodeIterator getAllNodeTypes(Session session) throws RepositoryException {
//get our node types root
Node nodeTypesRoot = session.getNode("/jcr:system/jcr:nodeTypes");
//get our child nodeTypes from our root
return nodeTypesRoot.getNodes();
}
}
|
tmowad/intellij-jcr-plugin
|
source/src/velir/intellij/cq5/util/RepositoryUtils.java
|
Java
|
mit
| 1,342 |
<html>
<META HTTP-EQUIV=Content-Type Content="text/html; charset=utf8">
<!-- Mirrored from lis.ly.gov.tw/lghtml/lawstat/version2/02409/0240996011200.htm by HTTrack Website Copier/3.x [XR&CO'2010], Sun, 24 Mar 2013 09:19:03 GMT -->
<head><title>法編號:02409 版本:096011200</title>
<link rel="stylesheet" type="text/css" href="../../version.css" >
</HEAD>
<body><left>
<table><tr><td><FONT COLOR=blue SIZE=5>有線廣播電視法(02409)</font>
<table><tr><td> </td><td>
<table><tr><td> </td><td>
<table><tr><td> </td>
<tr><td align=left valign=top>
<a href=0240982071600.html target=law02409><nobr><font size=2>中華民國 82 年 7 月 16 日</font></nobr></a>
</td>
<td valign=top><font size=2>制定71條</font></td>
<tr><td align=left valign=top><nobr><font size=2>中華民國 82 年 8 月 11 日公布</font></nobr></td>
<tr><td align=left valign=top>
<a href=0240988011500.html target=law02409><nobr><font size=2>中華民國 88 年 1 月 15 日</font></nobr></a>
</td>
<td valign=top><font size=2>修正前[有線電視法]為本法<br>
並修正全文76條</font></td>
<tr><td align=left valign=top><nobr><font size=2>中華民國 88 年 2 月 3 日公布</font></nobr></td>
<tr><td align=left valign=top>
<a href=0240988123000.html target=law02409><nobr><font size=2>中華民國 88 年 12 月 30 日</font></nobr></a>
</td>
<td valign=top><font size=2>修正第3條</font></td>
<tr><td align=left valign=top><nobr><font size=2>中華民國 89 年 1 月 19 日公布</font></nobr></td>
<tr><td align=left valign=top>
<a href=0240990051800.html target=law02409><nobr><font size=2>中華民國 90 年 5 月 18 日</font></nobr></a>
</td>
<td valign=top><font size=2>修正第19, 51, 63條</font></td>
<tr><td align=left valign=top><nobr><font size=2>中華民國 90 年 5 月 30 日公布</font></nobr></td>
<tr><td align=left valign=top>
<a href=0240991122700.html target=law02409><nobr><font size=2>中華民國 91 年 12 月 27 日</font></nobr></a>
</td>
<td valign=top><font size=2>修正第16, 19, 23, 39條</font></td>
<tr><td align=left valign=top><nobr><font size=2>中華民國 92 年 1 月 15 日公布</font></nobr></td>
<tr><td align=left valign=top>
<a href=0240992120900.html target=law02409><nobr><font size=2>中華民國 92 年 12 月 9 日</font></nobr></a>
</td>
<td valign=top><font size=2>修正第19, 20, 24, 68條<br>
增訂第37之1條</font></td>
<tr><td align=left valign=top><nobr><font size=2>中華民國 92 年 12 月 24 日公布</font></nobr></td>
<tr><td align=left valign=top>
<a href=0240996011200.html target=law02409><nobr><font size=2>中華民國 96 年 1 月 12 日</font></nobr></a>
</td>
<td valign=top><font size=2>增訂第35之1條</font></td>
<tr><td align=left valign=top><nobr><font size=2>中華民國 96 年 1 月 29 日公布</font></nobr></td>
</table></table></table></table>
<p><table><tr><td><font color=blue size=4>民國96年1月12日</font></td>
<td><a href=http://lis.ly.gov.tw/lghtml/lawstat/reason2/0240996011200.htm target=reason><font size=2>立法理由</font></a></td>
<td><a href=http://lis.ly.gov.tw/lgcgi/lglawproc?0240996011200 target=proc><font size=2>立法紀錄</font></a></td>
</table>
<table><tr><td> </td>
<td><font color=4000ff size=4>第一章 總則</font>
<table><tr><td> </td><td><font color=8000ff>第一條</font>
<font size=2>(立法目的)</font>
<table><tr><td> </td>
<td>
為促進有線廣播電視事業之健全發展,保障公眾視聽之權益,增進社會福祉,特制定本法。<br>
</td>
</table>
</table>
</table>
<table><tr><td> </td><td>
<table><tr><td> </td><td><font color=8000ff>第二條</font>
<font size=2>(用辭定義)</font>
<table><tr><td> </td>
<td>
本法用辭定義如下:<br>
一、有線廣播電視:指以設置纜線方式傳播影像、聲音供公眾直接視、聽。<br>
二、有線廣播電視系統(以下簡稱系統):指有線廣播電視之傳輸網路及包括纜線、微波、衛星地面接收等設備。<br>
三、有線廣播電視系統經營者(以下簡稱系統經營者):指依法核准經營有線廣播電視者。<br>
四、頻道供應者:指以節目及廣告為內容,將之以一定名稱授權予有線電視系統經營者播送之供應事業,其以自己或代理名義為之者,亦屬之。<br>
五、基本頻道:指訂戶定期繳交基本費用,始可視、聽之頻道。<br>
六、付費頻道:指基本頻道以外,須額外付費,始可視、聽之頻道。<br>
七、計次付費節目:指按次付費,始可視、聽之節目。<br>
八、鎖碼:指需經特殊解碼程序始得視、聽節目之技術。<br>
九、頭端:指接收、處理、傳送有線廣播、電視信號,並將其播送至分配線網路之設備及其所在之場所。<br>
十、幹線網路:指連接系統經營者之頭端至頭端間傳輸有線廣播、電視信號之網路。<br>
十一、分配線網路:指連接頭端至訂戶間之纜線網路及設備。<br>
十二、插播式字幕:指另經編輯製作而在電視螢幕上展現,且非屬於原有播出內容之文字或圖形。<br>
十三、有線廣播電視節目(以下簡稱節目):指系統經營者播送之影像、聲音,內容不涉及廣告者。<br>
十四、有線廣播電視廣告(以下簡稱廣告):指系統經營者播送之影像、聲音,內容為推廣商品、觀念、服務或形象者。<br>
</td>
</table>
</table>
</table>
<table><tr><td> </td><td>
<table><tr><td> </td><td><font color=8000ff>第三條</font>
<font size=2>(主管機關)</font>
<table><tr><td> </td>
<td>
本法所稱主管機關:在中央為行政院新聞局(以下簡稱新聞局);在直轄市為直轄市政府;在縣(市)為縣(市)政府。<br>
有線廣播電視系統工程技術管理之主管機關為交通部。<br>
前項有關工程技術管理之規則,由交通部定之。<br>
</td>
</table>
</table>
</table>
<table><tr><td> </td><td>
<table><tr><td> </td><td><font color=8000ff>第四條</font>
<font size=2>(經營電信業務之規定)</font>
<table><tr><td> </td>
<td>
系統經營者經營電信業務,應依電信法相關規定辦理。<br>
</td>
</table>
</table>
</table>
<table><tr><td> </td><td>
<table><tr><td> </td><td><font color=8000ff>第五條</font>
<font size=2>(幹線網路之鋪設)</font>
<table><tr><td> </td>
<td>
系統經營者自行設置之網路,其屬鋪設者,向路權管理機關申請;其屬附掛者,向電信、電業等機構申請。經許可籌設有線廣播電視者,亦同。<br>
系統經營者前項網路之鋪設,得承租現有之地下管溝及終端設備;其鋪設網路及附掛網路應依有關法令規定辦理。<br>
中央主管機關應會同交通部協助解決偏遠地區幹線網路之設置。<br>
</td>
</table>
</table>
</table>
<table><tr><td> </td><td>
<table><tr><td> </td><td><font color=8000ff>第六條</font>
<font size=2>(網路通過他人土地或建物之鋪設方法、通知及變更鋪設)</font>
<table><tr><td> </td>
<td>
前條第一項網路非通過他人土地或建築物不能鋪設,或雖能鋪設需費過鉅者,得通過他人土地或建築物鋪設之。但應擇其損害最少之處所及方法為之,並應為相當之補償。<br>
前項網路之鋪設,應於施工三十日前以書面通知土地、建築物所有人或占有人。<br>
依第一項規定鋪設網路後,如情事變更時,土地、建築物所有人或占有人得請求變更其鋪設。<br>
對於前三項情形有異議者,得申請轄區內調解委員會調解之或逕行提起民事訴訟。<br>
</td>
</table>
</table>
</table>
<table><tr><td> </td><td>
<table><tr><td> </td><td><font color=8000ff>第七條</font>
<font size=2>(天然災害或緊急事故之應變)</font>
<table><tr><td> </td>
<td>
遇有天然災害或緊急事故時,主管機關為維護公共安全與公眾福利,得通知系統經營者停止播送節目,或指定其播送特定之節目或訊息。<br>
前項原因消滅後,主管機關應即通知該系統經營者回復原狀繼續播送。<br>
第一項之天然災害及緊急事故應變辦理,由中央主管機關定之。<br>
</td>
</table>
</table>
</table>
<table><tr><td> </td>
<td><font color=4000ff size=4>第二章 有線廣播電視審議委員會</font>
<table><tr><td> </td><td><font color=8000ff>第八條</font>
<font size=2>(審議委員會及審議事項)</font>
<table><tr><td> </td>
<td>
中央主管機關設有線廣播電視審議委員會(以下簡稱審議委員會),審議下列事項:<br>
一、有線廣播電視籌設之許可或撤銷許可。<br>
二、有線廣播電視營運之許可或撤銷許可。<br>
三、執行營運計畫之評鑑。<br>
四、系統經營者與頻道供應者間節目使用費用及其他爭議之調處。<br>
五、系統經營者間爭議之調處。<br>
六、其他依本法規定或經中央主管機關提請審議之事項。<br>
</td>
</table>
</table>
</table>
<table><tr><td> </td><td>
<table><tr><td> </td><td><font color=8000ff>第九條</font>
<font size=2>(審議委員會之組成)</font>
<table><tr><td> </td>
<td>
審議委員會置委員十三人至十五人,由下列人員組成之:<br>
一、專家學者十人至十二人。<br>
二、交通部、新聞局、行政院消費者保護委員會代表各一人。<br>
審議委員會審議相關地區議案時,應邀請各該直轄市或縣(市)政府代表一人出席。出席代表之職權與審議委員相同。<br>
審議委員中,同一政黨者不得超過二分之一;其擔任委員期間不得參加政黨活動。<br>
</td>
</table>
</table>
</table>
<table><tr><td> </td><td>
<table><tr><td> </td><td><font color=8000ff>第十條</font>
<font size=2>(審議委員之產生及任期)</font>
<table><tr><td> </td>
<td>
前條第一項第一款之委員由行政院院長遴聘,並報請立法院備查,聘期三年,期滿得續聘之,但續聘以一次為限。聘期未滿之委員因辭職、死亡或因故無法執行職務時,應予解聘,並得另聘其他人選繼任,至原聘期任滿時為止。<br>
</td>
</table>
</table>
</table>
<table><tr><td> </td><td>
<table><tr><td> </td><td><font color=8000ff>第十一條</font>
<font size=2>(審議會之主席)</font>
<table><tr><td> </td>
<td>
審議委員會開會時由委員互推一人為主席,主持會議之進行。<br>
</td>
</table>
</table>
</table>
<table><tr><td> </td><td>
<table><tr><td> </td><td><font color=8000ff>第十二條</font>
<font size=2>(開議及決議人數)</font>
<table><tr><td> </td>
<td>
審議委員會應有五分之三以上委員出席,始得開議,以出席委員過半數之同意,始得決議。<br>
</td>
</table>
</table>
</table>
<table><tr><td> </td><td>
<table><tr><td> </td><td><font color=8000ff>第十三條</font>
<font size=2>(決議方式)</font>
<table><tr><td> </td>
<td>
審議委員會之決議方式,由審議委員會討論後決定之。<br>
</td>
</table>
</table>
</table>
<table><tr><td> </td><td>
<table><tr><td> </td><td><font color=8000ff>第十四條</font>
<font size=2>(審議委員之自行迴避)</font>
<table><tr><td> </td>
<td>
審議委員會委員應本公正客觀之立場行使職權,有下列各款情形之一者,應自行迴避:<br>
一、審議委員會委員或其配偶、前配偶或未婚配偶,為申請經營有線廣播電視之董事、監察人或經理人者。<br>
二、審議委員會委員與申請經營有線廣播電視者之董事、監察人或經理人為五親等內之血親、三親等內之姻親或曾有此親屬關係者。<br>
</td>
</table>
</table>
</table>
<table><tr><td> </td><td>
<table><tr><td> </td><td><font color=8000ff>第十五條</font>
<font size=2>(申請迴避及裁決)</font>
<table><tr><td> </td>
<td>
申請經營有線廣播電視者對於審議委員會委員,認為有偏頗之虞或其他不適格之原因,得申請迴避。<br>
前項申請由主席裁決之。<br>
</td>
</table>
</table>
</table>
<table><tr><td> </td><td>
<table><tr><td> </td><td><font color=8000ff>第十六條</font>
<font size=2>(未自行迴避時所為決議之撤銷)</font>
<table><tr><td> </td>
<td>
審議委員會委員應自行迴避而不迴避時,中央主管機關於會議決議後一個月內,得逕行或應利害關係人之申請,撤銷該會議所為之決議。其經籌設許可或營運許可者,中央主管機關應撤銷其許可,並註銷其許可證。<br>
審議委員會對前項撤銷之事項,應重行審議及決議。<br>
</td>
</table>
</table>
</table>
<table><tr><td> </td><td>
<table><tr><td> </td><td><font color=8000ff>第十七條</font>
<font size=2>(審議規則之訂定)</font>
<table><tr><td> </td>
<td>
審議委員會之審議規則,由中央主管機關定之。<br>
</td>
</table>
</table>
</table>
<table><tr><td> </td>
<td><font color=4000ff size=4>第三章 營運管理</font>
<table><tr><td> </td><td><font color=8000ff>第十八條</font>
<font size=2>(申請許可)</font>
<table><tr><td> </td>
<td>
有線廣播電視之籌設、營運,應申請中央主管機關許可。<br>
</td>
</table>
</table>
</table>
<table><tr><td> </td><td>
<table><tr><td> </td><td><font color=8000ff>第十九條</font>
<font size=2>(經營者身分之限制)</font>
<table><tr><td> </td>
<td>
系統經營者之組織,以股份有限公司為限。<br>
外國人直接及間接持有系統經營者之股份,合計應低於該系統經營者已發行股份總數百分之六十,外國人直接持有者,以法人為限,且合計應低於該系統經營者已發行股份總數百分之二十。<br>
系統經營者最低實收資本額,由中央主管機關定之。<br>
政府、政黨、其捐助成立之財團法人及其受託人不得直接、間接投資系統經營者。<br>
本法修正施行前,政府、政黨、其捐助成立之財團法人及其受託人有不符前項所定情形者,應自本法修正施行之日起二年內改正。<br>
系統經營者不得播送有候選人參加,且由政府出資或製作之節目、短片及廣告;政府出資或製作以候選人為題材之節目、短片及廣告,亦同。<br>
</td>
</table>
</table>
</table>
<table><tr><td> </td><td>
<table><tr><td> </td><td><font color=8000ff>第二十條</font>
<font size=2>(本國籍董事、政黨公職人員之限制)</font>
<table><tr><td> </td>
<td>
系統經營者具有中華民國國籍之董事,不得少於董事人數三分之二;監察人,亦同。<br>
董事長應具有中華民國國籍。<br>
政黨黨務工作人員、政務人員及選任公職人員不得投資系統經營者;其配偶、二親等血親、直系姻親投資同一系統經營者,其持有之股份,合計不得逾該事業已發行股份總數百分之一。本法修正施行前,系統經營者有不符規定者,應自本法修正施行之日起二年內改正。<br>
政府、政黨、政黨黨務工作人員及選任公職人員不得擔任系統經營者之發起人、董事、監察人或經理人。本法修正施行前已擔任者,系統經營者應自本法修正施行之日起六個月內解除其職務。<br>
前二項所稱政黨黨務工作人員、政務人員及選任公職人員之範圍,於本法施行細則定之。<br>
</td>
</table>
</table>
</table>
<table><tr><td> </td><td>
<table><tr><td> </td><td><font color=8000ff>第二十一條</font>
<font size=2>(系統經營者與其關係企業及直接間接控制者間之限制)</font>
<table><tr><td> </td>
<td>
系統經營者與其關係企業及直接、間接控制之系統經營者不得有下列情形之一:<br>
一、訂戶數合計超過全國總訂戶數三分之一。<br>
二、超過同一行政區域系統經營者總家數二分之一。但同一行政區域只有一系統經營者,不在此限。<br>
三、超過全國系統經營者總家數三分之一。<br>
前項全國總訂戶數、同一行政區域系統經營者總家數及全國系統經營者總家數,由中央主管機關公告之。<br>
</td>
</table>
</table>
</table>
<table><tr><td> </td><td>
<table><tr><td> </td><td><font color=8000ff>第二十二條</font>
<font size=2>(營運計畫之載明及提出)</font>
<table><tr><td> </td>
<td>
申請有線廣播電視之籌設,應填具申請書連同營運計畫,於公告期間內向中央主管機關提出。<br>
營運計畫應載明下列事項:<br>
一、有線廣播電視經營地區。<br>
二、系統設置時程及預定開播時間。<br>
三、財務結構。<br>
四、組織架構。<br>
五、頻道之規劃及其類型。<br>
六、自製節目製播計畫。<br>
七、收費標準及計算方式。<br>
八、訂戶服務。<br>
九、服務滿意度及頻道收視意願調查計畫。<br>
十、工程技術及設備說明。<br>
十一、業務推展計畫。<br>
十二、人材培訓計畫。<br>
十三、技術發展計畫。<br>
十四、董事、監察人、經理人,或發起人之姓名(名稱)及相關資料。<br>
十五、其他中央主管機關指定之事項。<br>
</td>
</table>
</table>
</table>
<table><tr><td> </td><td>
<table><tr><td> </td><td><font color=8000ff>第二十三條</font>
<font size=2>(外國人投資之限制)</font>
<table><tr><td> </td>
<td>
對於有外國人投資之申請籌設、營運有線廣播電視案件,中央主管機關認該外國人投資對國家安全、公共秩序或善良風俗有不利影響者,得不經審議委員會之決議,予以駁回。<br>
外國人申請投資有線廣播電視,有前項或違反第十九條第二項規定情形者,應駁回其投資之申請。<br>
</td>
</table>
</table>
</table>
<table><tr><td> </td><td>
<table><tr><td> </td><td><font color=8000ff>第二十四條</font>
<font size=2>(不予許可申請籌設、營運之情形)</font>
<table><tr><td> </td>
<td>
申請籌設、營運有線廣播電視之案件有下列情形之一者,審議委員會應為不予許可之決議:<br>
一、違反第十九條或第二十條規定者。<br>
二、違反第二十一條規定者。<br>
三、工程技術管理不符合交通部依第三條第三項所定之規則者。<br>
四、申請人因違反本法規定經撤銷籌設或營運許可未逾二年者。<br>
五、申請人之董事、監察人或經理人有公司法第三十條各款情事之一者。<br>
</td>
</table>
</table>
</table>
<table><tr><td> </td><td>
<table><tr><td> </td><td><font color=8000ff>第二十五條</font>
<font size=2>(許可之情形)</font>
<table><tr><td> </td>
<td>
申請籌設、營運有線廣播電視案件符合下列規定者,審議委員會得為許可之決議:<br>
一、申請人之財務規劃及技術,足以實現其營運計畫者。<br>
二、免費提供專用頻道供政府機關、學校、團體及當地民眾播送公益性、藝文性、社教性等節目者。<br>
三、提供之服務及自製節目符合當地民眾利益及需求者。<br>
</td>
</table>
</table>
</table>
<table><tr><td> </td><td>
<table><tr><td> </td><td><font color=8000ff>第二十六條</font>
<font size=2>(申請書及營運計畫之變更)</font>
<table><tr><td> </td>
<td>
申請書及營運計畫內容於獲得籌設許可後有變更時,應向中央主管機關為變更之申請。但第二十二條第二項第四款、第十一款、第十二款內容變更者,不在此限。<br>
前項變更內容屬設立登記事項者,應於中央主管機關許可變更後,始得辦理設立或變更登記。<br>
系統經營者之董事、監察人或經理人變更時,準用前二項規定。<br>
</td>
</table>
</table>
</table>
<table><tr><td> </td><td>
<table><tr><td> </td><td><font color=8000ff>第二十七條</font>
<font size=2>(申請之准駁及覆議)</font>
<table><tr><td> </td>
<td>
對於申請籌設有線廣播電視案件,審議委員會決議不予許可者,中央主管機關應附具理由駁回其申請;其決議許可者,中央主管機關應發給申請人籌設許可證。<br>
不服前項駁回之處分,申請人得於駁回通知書送達之日起三十日內,附具理由提出覆議;審議委員會應於接獲覆議申請之日起三十日內,附具理由為准駁之決定。申請覆議以一次為限。<br>
</td>
</table>
</table>
</table>
<table><tr><td> </td><td>
<table><tr><td> </td><td><font color=8000ff>第二十八條</font>
<font size=2>(許可證之內容變更及遺失)</font>
<table><tr><td> </td>
<td>
籌設許可證所載內容變更時,應於變更後十五日內向中央主管機關申請換發;遺失時,應於登報聲明作廢後十五日內申請補發。<br>
</td>
</table>
</table>
</table>
<table><tr><td> </td><td>
<table><tr><td> </td><td><font color=8000ff>第二十九條</font>
<font size=2>(設立登記及補正)</font>
<table><tr><td> </td>
<td>
申請人經許可籌設有線廣播電視後,應於中央主管機關指定之地區與期間完成設立登記並繳交必要文件。文件不全得補正者,中央主管機關應通知限期補正。<br>
</td>
</table>
</table>
</table>
<table><tr><td> </td><td>
<table><tr><td> </td><td><font color=8000ff>第三十條</font>
<font size=2>(設置時程及展期)</font>
<table><tr><td> </td>
<td>
系統之設置得分期實施,全部設置時程不得逾三年;其無法於設置時程內完成者,得於設置時程屆滿前二個月內附具正當理由,向中央主管機關申請展期。展期不得逾六個月,並以一次為限。<br>
</td>
</table>
</table>
</table>
<table><tr><td> </td><td>
<table><tr><td> </td><td><font color=8000ff>第三十一條</font>
<font size=2>(查驗)</font>
<table><tr><td> </td>
<td>
系統之籌設應於營運計畫所載系統設置時程內完成,並於設置時程內向中央主管機關提出系統工程查驗申請。<br>
前項查驗由中央主管機關會同交通部及地方主管機關,自受理申請之日起六個月內為之。<br>
系統經查驗合格後二個月內,申請人應向中央主管機關申請營運許可。非經中央主管機關發給營運許可證者,不得營運。<br>
系統經營者除有正當理由,經中央主管機關核可者外,應於取得營運許可證後一個月內開播。<br>
</td>
</table>
</table>
</table>
<table><tr><td> </td><td>
<table><tr><td> </td><td><font color=8000ff>第三十二條</font>
<font size=2>(經營地區之劃分及調整)</font>
<table><tr><td> </td>
<td>
有線廣播電視經營地區之劃分及調整,由中央主管機關會商當地直轄市或縣(市)政府審酌下列事項後公告之:<br>
一、行政區域。<br>
二、自然地理環境。<br>
三、人文分布。<br>
四、經濟效益。<br>
</td>
</table>
</table>
</table>
<table><tr><td> </td><td>
<table><tr><td> </td><td><font color=8000ff>第三十三條</font>
<font size=2>(重新受理申請之情形及處理)</font>
<table><tr><td> </td>
<td>
有下列情形之一者,中央主管機關應另行公告重新受理申請:<br>
一、在公告期間內,該地區無人申請。<br>
二、該地區無人獲得籌設許可或營運許可。<br>
三、該地區任一系統經營者終止經營,經審議委員會決議,須重新受理申請。<br>
四、該地區系統經營者係獨占、結合、聯合、違反第二十一條規定而有妨害或限制公平競爭之情事,中央主管機關為促進公平競爭,經附具理由,送請審議委員會決議,須重新受理申請。<br>
重新辦理公告,仍有前項情形者,中央主管機關得視事實需要,依下列方式擇一處理之:<br>
一、會同當地直轄市或縣(市)政府重新劃分及調整經營地區。<br>
二、獎勵或輔導其他行政區域之系統經營者經營。<br>
三、其他經審議委員會決議之方式。<br>
前項第二款獎勵之輔導及方式,由中央主管機關定之。<br>
</td>
</table>
</table>
</table>
<table><tr><td> </td><td>
<table><tr><td> </td><td><font color=8000ff>第三十四條</font>
<font size=2>(不得委託他人經營)</font>
<table><tr><td> </td>
<td>
系統經營者不得委託他人經營。<br>
</td>
</table>
</table>
</table>
<table><tr><td> </td><td>
<table><tr><td> </td><td><font color=8000ff>第三十五條</font>
<font size=2>(營運許可之換發及補發)</font>
<table><tr><td> </td>
<td>
系統經營者之營運許可,有效期間為九年。系統經營者於營運許可期限屆滿,仍欲經營時,應於營運許可期限滿八年後六個月內,向中央主管機關申請換發。<br>
前項營運許可所載內容變更時,應於變更後十五日內向中央主管機關申准換發;遺失時,應於登報聲明作廢後十五日內申請補發。<br>
</td>
</table>
</table>
</table>
<table><tr><td> </td><td>
<table><tr><td> </td><td><font color=8000ff>第三十五條之一</font>
<font size=2>(申請換發之審查標準及程序)</font>
<table><tr><td> </td>
<td>
中央主管機關審查申請換發系統經營者之營運許可案件時,應審酌下列事項:<br>
一、營運計畫執行情形之評鑑結果及改正情形。<br>
二、未來之營運計畫。<br>
三、財務狀況。<br>
四、營運是否符合經營地區民眾利益及需求。<br>
五、系統經營者之獎懲紀錄及其他影響營運之事項。<br>
前項審查結果,中央主管機關認該系統經營者營運不善或未來之營運計畫有改善之必要時,應以書面通知其限期改善。屆期無正當理由而未改善者,經審議委員會審議,並經中央主管機關決議不予換發營運許可者,駁回其申請。<br>
前項審查期間及改善期間,中央主管機關得發給臨時執照,其有效期間為一年,並以一次為限。<br>
</td>
</table>
</table>
</table>
<table><tr><td> </td><td>
<table><tr><td> </td><td><font color=8000ff>第三十六條</font>
<font size=2>(營運計畫執行之評鑑)</font>
<table><tr><td> </td>
<td>
審議委員會應就系統經營者所提出之營運計畫執行情形,每三年評鑑一次。<br>
前項評鑑結果未達營運計畫且得改正者,中央主管機關應依審議委員會決議,通知限期改正;其無法改正,經審議委員會決議撤銷營運許可者,中央主管機關應註銷營運許可證。<br>
</td>
</table>
</table>
</table>
<table><tr><td> </td><td>
<table><tr><td> </td><td><font color=8000ff>第三十七條</font>
<font size=2>(基本頻道之提供)</font>
<table><tr><td> </td>
<td>
系統經營者應同時轉播依法設立無線電視電台之節目及廣告,不得變更其形式、內容及頻道,並應列為基本頻道。但經中央主管機關許可者,得變更頻道。<br>
系統經營者為前項轉播,免付費用,不構成侵害著作權。<br>
系統經營者不得播送未經中央主管機關許可之境外衛星廣播電視事業之節目或廣告。<br>
</td>
</table>
</table>
</table>
<table><tr><td> </td><td>
<table><tr><td> </td><td><font color=8000ff>第三十七條之一</font>
<font size=2>(免費播送客語原住民語言節目)</font>
<table><tr><td> </td>
<td>
為保障客家、原住民語言、文化,中央主管機關得視情形,指定系統經營者,免費提供固定頻道,播送客家語言、原住民語言之節目。<br>
</td>
</table>
</table>
</table>
<table><tr><td> </td><td>
<table><tr><td> </td><td><font color=8000ff>第三十八條</font>
<font size=2>(最大電波洩露量之規定)</font>
<table><tr><td> </td>
<td>
系統經營者在系統傳輸及處理過程中,其電波洩漏不得超過交通部所定之最大電波洩漏量限值。<br>
</td>
</table>
</table>
</table>
<table><tr><td> </td><td>
<table><tr><td> </td><td><font color=8000ff>第三十九條</font>
<font size=2>(暫停或終止經營之核備及通知)</font>
<table><tr><td> </td>
<td>
系統經營者擬暫停或終止經營時,除應於三個月前書面報請中央主管機關備查,副知地方主管機關外,並應於一個月前通知訂戶。<br>
前項所稱暫停經營之期間,最長為六個月。<br>
</td>
</table>
</table>
</table>
<table><tr><td> </td>
<td><font color=4000ff size=4>第四章 節目管理</font>
<table><tr><td> </td><td><font color=8000ff>第四十條</font>
<font size=2>(節目內容之限制)</font>
<table><tr><td> </td>
<td>
節目內容不得有下列情形之一:<br>
一、違反法律強制或禁止規定。<br>
二、妨害兒童或少年身心健康。<br>
三、妨害公共秩序或善良風俗。<br>
</td>
</table>
</table>
</table>
<table><tr><td> </td><td>
<table><tr><td> </td><td><font color=8000ff>第四十一條</font>
<font size=2>(節目分級之處理)</font>
<table><tr><td> </td>
<td>
中央主管機關應訂定節目分級處理辦法。系統經營者應依處理辦法規定播送節目。<br>
中央主管機關得指定時段,鎖碼播送特定節目。<br>
系統經營者應將鎖碼方式報請交通部會商中央主管機關核定。<br>
</td>
</table>
</table>
</table>
<table><tr><td> </td><td>
<table><tr><td> </td><td><font color=8000ff>第四十二條</font>
<font size=2>(節目與廣告之區分)</font>
<table><tr><td> </td>
<td>
節目應維持完整性,並與廣告區分。<br>
非經約定,系統經營者不得擅自合併或停止播送頻道。<br>
節目由系統經營者及其關係企業供應者,不得超過可利用頻道之四分之一。<br>
系統經營者應於播送之節目畫面標示其識別標識。<br>
</td>
</table>
</table>
</table>
<table><tr><td> </td><td>
<table><tr><td> </td><td><font color=8000ff>第四十三條</font>
<font size=2>(本國自製節目之最低佔有率)</font>
<table><tr><td> </td>
<td>
有線廣播電視節目中之本國自製節目,不得少於百分之二十。<br>
</td>
</table>
</table>
</table>
<table><tr><td> </td><td>
<table><tr><td> </td><td><font color=8000ff>第四十四條</font>
<font size=2>(主管機關得索取資料)</font>
<table><tr><td> </td>
<td>
主管機關認為有必要時,得於節目播送後十五日內向系統經營者索取該節目及相關資料。<br>
主管機關於必要時,得要求系統經營者將提供訂戶之節目,以不變更內容及形式方式裝接於主管機關指定之處所。該節目係以鎖碼方式播出者,應將解碼設備一併裝接。<br>
前項指定之處所,以二處為限。<br>
</td>
</table>
</table>
</table>
<table><tr><td> </td>
<td><font color=4000ff size=4>第五章 廣告管理</font>
<table><tr><td> </td><td><font color=8000ff>第四十五條</font>
<font size=2>(廣告插播頻率)</font>
<table><tr><td> </td>
<td>
系統經營者應同時轉播頻道供應者之廣告,除經事前書面協議外不得變更其形式與內容。<br>
廣告時間不得超過每一節目播送總時間六分之一。<br>
單則廣告時間超過三分鐘或廣告以節目型態播送者,應於播送畫面上標示廣告二字。<br>
計次付費節目或付費頻道不得播送廣告。但同頻道節目之預告不在此限。<br>
</td>
</table>
</table>
</table>
<table><tr><td> </td><td>
<table><tr><td> </td><td><font color=8000ff>第四十六條</font>
<font size=2>(廣告播送之協議)</font>
<table><tr><td> </td>
<td>
頻道供應者應每年定期向審議委員會申報預計協議分配之廣告時間、時段、播送內容、播送方式或其他條件。頻道供應者如無正當理由拒絕依其申報內容與系統經營者協議,系統經營者得向審議委員會申請調處。<br>
</td>
</table>
</table>
</table>
<table><tr><td> </td><td>
<table><tr><td> </td><td><font color=8000ff>第四十七條</font>
<font size=2>(廣告專用頻道)</font>
<table><tr><td> </td>
<td>
系統經營者得設立廣告專用頻道,不受第四十五條第二項之限制。<br>
廣告專用頻道之數量限制,由中央主管機關定之。<br>
</td>
</table>
</table>
</table>
<table><tr><td> </td><td>
<table><tr><td> </td><td><font color=8000ff>第四十八條</font>
<font size=2>(插播式字幕的使用)</font>
<table><tr><td> </td>
<td>
系統經營者非有下列情形之一者,不得使用插播式字幕:<br>
一、天然災害、緊急事故訊息之播送。<br>
二、公共服務資訊之播送。<br>
三、頻道或節目異動之通知。<br>
四、與該播送節目相關,且非屬廣告性質之內容。<br>
五、依其他法令之規定。<br>
</td>
</table>
</table>
</table>
<table><tr><td> </td><td>
<table><tr><td> </td><td><font color=8000ff>第四十九條</font>
<font size=2>(廣告內容之核准)</font>
<table><tr><td> </td>
<td>
廣告內容涉及依法應經各該目的事業主管機關核准之業務者,應先取得核准證明文件,始得播送。<br>
</td>
</table>
</table>
</table>
<table><tr><td> </td><td>
<table><tr><td> </td><td><font color=8000ff>第五十條</font>
<font size=2>(廣告內容之限制及製播標準)</font>
<table><tr><td> </td>
<td>
第四十條、第四十一條第二項、第三項、第四十二條第四項及第四十四條之規定,於廣告準用之。<br>
廣告製播標準由中央主管機關定之。<br>
</td>
</table>
</table>
</table>
<table><tr><td> </td>
<td><font color=4000ff size=4>第六章 費用</font>
<table><tr><td> </td><td><font color=8000ff>第五十一條</font>
<font size=2>(收費標準)</font>
<table><tr><td> </td>
<td>
系統經營者應於每年八月一日起一個月內向直轄市、縣(市)政府申報收視費用,由直轄市、縣(市)政府依審議委員會所訂收費標準,核准後公告之。<br>
直轄市及縣(市)政府得設費率委員會,核准前項收視費用。直轄市及縣(市)政府未設費率委員會時,應由中央主管機關行使之。<br>
系統經營者之會計制度及其標準程式,由中央主管機關定之。<br>
系統經營者應於每年一月、四月、七月及十月,向中央主管機關申報前三個月訂戶數。<br>
</td>
</table>
</table>
</table>
<table><tr><td> </td><td>
<table><tr><td> </td><td><font color=8000ff>第五十二條</font>
<font size=2>(訂戶不按期繳交費用之處置)</font>
<table><tr><td> </td>
<td>
訂戶不按期繳交費用,經定期催告仍未繳交時,系統經營者得停止對該訂戶節目之傳送。但應同時恢復訂戶原有無線電視節目之視、聽。<br>
系統經營者依前項但書規定辦理時,得向訂戶請求支付必要之器材費用。<br>
第一項但書及前項規定,於視聽法律關係終止之情形,適用之。<br>
</td>
</table>
</table>
</table>
<table><tr><td> </td><td>
<table><tr><td> </td><td><font color=8000ff>第五十三條</font>
<font size=2>(特種基金之成立運用及管理)</font>
<table><tr><td> </td>
<td>
系統經營者應每年提撥當年營業額百分之一之金額,提繳中央主管機關成立特種基金。<br>
前項系統經營者提撥之金額,由中央主管機關依下列目的運用:<br>
一、百分之三十由中央主管機關統籌用於有線廣播電視之普及發展。<br>
二、百分之四十撥付當地直轄市、縣(市)政府,從事與本法有關地方文化及公共建設使用。<br>
三、百分之三十捐贈財團法人公共電視文化事業基金會。<br>
第一項特種基金之成立、運用及管理辦法,由中央主管機關定之。<br>
</td>
</table>
</table>
</table>
<table><tr><td> </td><td>
<table><tr><td> </td><td><font color=8000ff>第五十四條</font>
<font size=2>(審查費各項費用之繳納)</font>
<table><tr><td> </td>
<td>
主管機關依本法受理申請審核、查驗、核發、換發證照,應向申請者收取審查費、證照費;其收費標準由中央主管機關定之。<br>
</td>
</table>
</table>
</table>
<table><tr><td> </td>
<td><font color=4000ff size=4>第七章 權利保護</font>
<table><tr><td> </td><td><font color=8000ff>第五十五條</font>
<font size=2>(有線電視契約)</font>
<table><tr><td> </td>
<td>
系統經營者應與訂戶訂立書面契約。<br>
前項書面契約應於給付訂戶之收據背面製作發給之。<br>
中央主管機關應公告規定定型化契約應記載或不得記載之事項。<br>
違反前項公告之定型化契約之一般條款無效。該定型化契約之效力依消費者保護法第十六條規定定之。<br>
契約內容應包括下列事項:<br>
一、各項收費標準及調整費用之限制。<br>
二、頻道數、名稱及頻道契約到期日。<br>
三、訂戶基本資料使用之限制。<br>
四、系統經營者受停播、撤銷營運許可、沒入等處分時,恢復訂戶原有無線電視節目之視、聽,及對其視、聽權益產生損害之賠償條件。<br>
五、無正當理由中斷約定之頻道信號,致訂戶視、聽權益有損害之虞時之賠償條件。<br>
六、契約之有效期間。<br>
七、訂戶申訴專線。<br>
八、其他經中央主管機關指定之項目。<br>
系統經營者對訂戶申訴案件應即妥適處理,並建檔保存三個月;主管機關得要求系統經營者以書面或於相關節目答覆訂戶。<br>
</td>
</table>
</table>
</table>
<table><tr><td> </td><td>
<table><tr><td> </td><td><font color=8000ff>第五十六條</font>
<font size=2>(系統經營者之識別標識許可證字號等資料之播出)</font>
<table><tr><td> </td>
<td>
系統經營者應設置專用頻道,載明系統經營者名稱、識別標識、許可證字號、訂戶申訴專線、營業處所地址、頻道總表、頻道授權期限及各頻道播出節目之名稱。<br>
</td>
</table>
</table>
</table>
<table><tr><td> </td><td>
<table><tr><td> </td><td><font color=8000ff>第五十七條</font>
<font size=2>(節目及廣告之合法授權播送)</font>
<table><tr><td> </td>
<td>
有線廣播電視播送之節目及廣告涉及他人權利者,應經合法授權,始得播送。<br>
</td>
</table>
</table>
</table>
<table><tr><td> </td><td>
<table><tr><td> </td><td><font color=8000ff>第五十八條</font>
<font size=2>(強制締約及提供必要之協助)</font>
<table><tr><td> </td>
<td>
系統經營者無正當理由不得拒絕該地區民眾請求付費視、聽有線廣播電視。<br>
系統經營者有正當理由無法提供民眾經由有線電視收視無線電視時,地方主管機關得提請審議委員會決議以其他方式提供收視無線電視。<br>
</td>
</table>
</table>
</table>
<table><tr><td> </td><td>
<table><tr><td> </td><td><font color=8000ff>第五十九條</font>
<font size=2>(相關線路之拆除義務)</font>
<table><tr><td> </td>
<td>
視、聽法律關係終止後,系統經營者應於一個月內將相關線路拆除。逾期不為拆除時,該土地或建築物之所有人或占有人得自行拆除,並得向系統經營者請求償還其所支出之拆除及其他必要費用。<br>
</td>
</table>
</table>
</table>
<table><tr><td> </td><td>
<table><tr><td> </td><td><font color=8000ff>第六十條</font>
<font size=2>(主管機關通知限期改善)</font>
<table><tr><td> </td>
<td>
主管機關認為有線廣播電視營運不當,有損害訂戶權益情事或有損害之虞者,應通知系統經營者限期改正或為其他必要措施。<br>
</td>
</table>
</table>
</table>
<table><tr><td> </td><td>
<table><tr><td> </td><td><font color=8000ff>第六十一條</font>
<font size=2>(利害關係人要求更正之處置)</font>
<table><tr><td> </td>
<td>
對於有線廣播電視之節目或廣告,利害關係人認有錯誤,得於播送之日起,十五日內要求更正,系統經營者應於接到要求後十五日內,在同一時間之節目或廣告中,加以更正,如認為節目或廣告無誤時,應附具理由書面答覆請求人。<br>
</td>
</table>
</table>
</table>
<table><tr><td> </td><td>
<table><tr><td> </td><td><font color=8000ff>第六十二條</font>
<font size=2>(被評論者權益受損時之答辯)</font>
<table><tr><td> </td>
<td>
有線廣播電視之節目評論涉及他人或機關、團體,致損害其權益時,被評論者,如要求給予相當答辯之機會,不得拒絕。<br>
</td>
</table>
</table>
</table>
<table><tr><td> </td>
<td><font color=4000ff size=4>第八章 罰則</font>
<table><tr><td> </td><td><font color=8000ff>第六十三條</font>
<font size=2>(處罰機關)</font>
<table><tr><td> </td>
<td>
依本法所為之處罰,由中央主管機關為之。但違反依第三條第三項所定之規則及第三十八條規定者,由交通部為之;違反節目管理、廣告管理、費用及權利保護各章規定者,由直轄市或縣(市)政府為之。直轄市或縣(市)政府未能行使職權時,得由中央主管機關為之。<br>
</td>
</table>
</table>
</table>
<table><tr><td> </td><td>
<table><tr><td> </td><td><font color=8000ff>第六十四條</font>
<font size=2>(警告)</font>
<table><tr><td> </td>
<td>
經許可籌設有線廣播電視者或系統經營者有下列情形之一時,予以警告:<br>
一、工程技術管理違反依第三條第三項所定之規則者。<br>
二、未依第二十八條或第三十五條第二項規定辦理換發或補發許可證者。<br>
三、未於第三十一條第三項規定期限內,向中央主管機關申請營運許可者。<br>
四、違反第三十七條第一項、第四十一條第一項、第三項、第四十二條第一項、第二項、第四項、第四十三條、第四十五條、第四十八條或第五十條第一項準用第四十一條第三項、第四十二條第四項規定者。<br>
五、違反第五十一條第一項、第四項、第五十二條第一項但書或第三項規定者。<br>
六、違反第五十五條、第五十六條、第五十八條、第六十一條或第六十二條規定者。<br>
</td>
</table>
</table>
</table>
<table><tr><td> </td><td>
<table><tr><td> </td><td><font color=8000ff>第六十五條</font>
<font size=2>(罰則)</font>
<table><tr><td> </td>
<td>
系統經營者違反第三十八條規定者,處新臺幣二萬元以上二十萬元以下罰鍰,並通知立即改正,未改正者,按次連續處罰。<br>
前項電波洩漏嚴重致影響飛航安全、重要通訊系統者,中央主管機關得依交通部之通知令其停播至改正為止。<br>
</td>
</table>
</table>
</table>
<table><tr><td> </td><td>
<table><tr><td> </td><td><font color=8000ff>第六十六條</font>
<font size=2>(罰則)</font>
<table><tr><td> </td>
<td>
經許可籌設有線廣播電視者或系統經營者,有下列情形之一時,處新臺幣五萬元以上五十萬元以下罰鍰,並通知限期改正:<br>
一、經依第六十四條規定警告後,仍不改正者。<br>
二、未依第五條第一項規定申准,擅自鋪設或附掛網路者。<br>
三、違反主管機關依第七條第一項、第二項所為停止、指定或繼續播送之通知者。<br>
四、經中央主管機關依第三十六條第二項規定通知限期改正,逾期不改正者。<br>
五、違反第三十七條第三項或第三十九條規定者。<br>
六、違反第四十條、第四十九條或第五十條第一項準用第四十條規定者。<br>
七、未依第四十一條第二項或第五十條第一項準用第四十一條第二項指定之時段、方式播送者。<br>
八、拒絕依第四十四條第二項或第五十條第一項準用第四十四條第二項主管機關指定之處所裝接者。<br>
九、違反第五十七條規定者。<br>
十、未依第六十條規定改正或為其他必要措施者。<br>
</td>
</table>
</table>
</table>
<table><tr><td> </td><td>
<table><tr><td> </td><td><font color=8000ff>第六十七條</font>
<font size=2>(罰則)</font>
<table><tr><td> </td>
<td>
經許可籌設有線廣播電視者或系統經營者,有下列情形之一時,處新臺幣十萬元以上一百萬元以下罰鍰,並通知限期改正,逾期不改正者,得按次連續處罰:<br>
一、一年內經依本法處罰二次,再有第六十四條或第六十六條情形之一者。<br>
二、拒絕依第四十四條第一項或第五十條第一項準用第四十四條第一項規定提供資料或提供不實資料者。<br>
三、違反第七十三條第二項規定者。<br>
系統經營者有前項第一款情形者,並得對其頻道處以三日以上三個月以下之停播處分。<br>
</td>
</table>
</table>
</table>
<table><tr><td> </td><td>
<table><tr><td> </td><td><font color=8000ff>第六十八條</font>
<font size=2>(罰則)</font>
<table><tr><td> </td>
<td>
經許可籌設有線廣播電視者或系統經營者,有下列情形之一時,處新臺幣十萬元以上一百萬元以下罰鍰,並通知限期改正,逾期不改正者,得按次連續處罰;情節重大者,得撤銷籌設許可或營運許可,並註銷籌設許可證或營運許可證:<br>
一、有第二十一條第一項各款情形之一者。<br>
二、有第二十四條第一款、第四款或第五款情形者。<br>
三、未依第二十六條第一項規定申准,擅自變更申請書內容或營運計畫者。<br>
四、未依第二十六條第二項或第三項規定,經中央主管機關許可變更,擅自辦理設立或變更登記者。<br>
五、未經中央主管機關依第三十一條第三項規定發給營運許可證,擅自營運者。<br>
六、違反第三十一條第四項規定者。<br>
七、未依第三十七條之一中央主管機關之指定提供頻道,播送節目者。<br>
八、違反第四十二條第三項規定者。<br>
九、違反第五十三條第一項規定者。<br>
十、於受停播處分期間,播送節目或廣告者。<br>
前項限期改正方式如下:<br>
一、處分全部或部分股份。<br>
二、轉讓全部或部分營業。<br>
三、免除擔任職務。<br>
四、其他必要方式。<br>
</td>
</table>
</table>
</table>
<table><tr><td> </td><td>
<table><tr><td> </td><td><font color=8000ff>第六十九條</font>
<font size=2>(罰則)</font>
<table><tr><td> </td>
<td>
經許可籌設有線廣播電視者或系統經營者,有下列情形之一時,撤銷籌設許可或營運許可,並註銷籌設許可證或營運許可證:<br>
一、以不法手段取得籌設許可或營運許可者。<br>
二、一年內經受停播處分三次,再違反本法規定者。<br>
三、設立登記經該管主管機關撤銷者。<br>
四、違反第二十九條規定者。<br>
五、違反第三十條規定未於設置時程內完成系統設置者。<br>
六、違反第三十四條規定者。<br>
七、經依第六十五條第二項規定勒令停播,拒不遵行者。<br>
</td>
</table>
</table>
</table>
<table><tr><td> </td><td>
<table><tr><td> </td><td><font color=8000ff>第七十條</font>
<font size=2>(罰則)</font>
<table><tr><td> </td>
<td>
未依本法規定獲得籌設許可或經撤銷籌設、營運許可,擅自經營有線廣播電視業務者,處新臺幣二十萬元以上二百萬元以下罰鍰,並得按次連續處罰。<br>
前項經營有線廣播電視業務之設備,不問屬於何人所有,沒入之。<br>
</td>
</table>
</table>
</table>
<table><tr><td> </td><td>
<table><tr><td> </td><td><font color=8000ff>第七十一條</font>
<font size=2>(強制執行)</font>
<table><tr><td> </td>
<td>
依本法所處罰鍰,經通知限期繳納,逾期仍不繳納者,移送法院強制執行。<br>
</td>
</table>
</table>
</table>
<table><tr><td> </td>
<td><font color=4000ff size=4>第九章 附則</font>
<table><tr><td> </td><td><font color=8000ff>第七十二條</font>
<font size=2>(管理辦法之訂定及營業登記效力)</font>
<table><tr><td> </td>
<td>
本法施行前,未依法定程序架設之有線電視節目播送系統,於本法施行後,經中央主管機關發給登記證者,得繼續營業。<br>
系統經營者自開始播送節目之日起十五日內,該地區內前項有線電視節目播送系統應停止播送,原登記證所載該地區失其效力;仍繼續播送者,依第七十條規定處罰。但經中央主管機關許可得繼續經營者,不在此限。<br>
有線電視節目播送系統登記證之發給、註銷、營運及依前項但書許可繼續經營之條件及期限等事項,由中央主管機關另定辦法管理之。<br>
有線電視節目播送系統之節目管理、廣告管理、費用及權利保護準用本法各有關之規定。違反者,依本法處罰之。<br>
系統經營者於其播送節目區域內,有有線電視節目播送系統依第二項但書規定繼續營業時,不適用第二十五條第二款及第五十三條規定。<br>
</td>
</table>
</table>
</table>
<table><tr><td> </td><td>
<table><tr><td> </td><td><font color=8000ff>第七十三條</font>
<font size=2>(主管機關得派員檢查)</font>
<table><tr><td> </td>
<td>
主管機關得派員攜帶證明文件,對系統實施檢查,要求經許可籌設有線廣播電視者或系統經營者,就其設施及本法規定事項提出報告、資料或為其他配合措施,並得扣押違反本法規定之資料或物品。<br>
對於前項之要求、檢查或扣押,不得規避、妨礙或拒絕。<br>
第一項扣押資料或物品之處理方式由中央主管機關定之,其涉及刑事責任者,依有關法律規定處理。<br>
</td>
</table>
</table>
</table>
<table><tr><td> </td><td>
<table><tr><td> </td><td><font color=8000ff>第七十四條</font>
<font size=2>(私接戶之責任及賠償)</font>
<table><tr><td> </td>
<td>
未經系統經營者同意,截取或接收系統播送之內容者,應補繳基本費用。其造成系統損害時,應負民事損害賠償責任。<br>
前項收視費用,如不能證明期間者,以二年之基本費用計算。<br>
</td>
</table>
</table>
</table>
<table><tr><td> </td><td>
<table><tr><td> </td><td><font color=8000ff>第七十五條</font>
<font size=2>(施行細則)</font>
<table><tr><td> </td>
<td>
本法施行細則,由中央主管機關定之。<br>
</td>
</table>
</table>
</table>
<table><tr><td> </td><td>
<table><tr><td> </td><td><font color=8000ff>第七十六條</font>
<font size=2>(施行日)</font>
<table><tr><td> </td>
<td>
本法自公布日施行。<br>
</td>
</table>
</table>
</table>
</left>
</body>
<!-- Mirrored from lis.ly.gov.tw/lghtml/lawstat/version2/02409/0240996011200.htm by HTTrack Website Copier/3.x [XR&CO'2010], Sun, 24 Mar 2013 09:19:03 GMT -->
</html>
|
g0v/laweasyread-data
|
rawdata/utf8_lawstat/version2/02409/0240996011200.html
|
HTML
|
mit
| 57,777 |
/****************************************************************************
Copyright (c) 2011-2013,WebJet Business Division,CYOU
http://www.genesis-3d.com.cn
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 "stdneb.h"
#include "exceptionbase.h"
namespace Exceptions
{
Exception::~Exception() throw()
{
}
Exception::Exception(const String& description_, const String& source_)
:line(0)
,type(EXT_UNDEF_TYPE)
,title("Exception")
,description(description_)
,source(source_)
{
// Log this error - not any more, allow catchers to do it
//LogManager::getSingleton().logMessage(this->getFullDescription());
}
Exception::Exception(const String& description_, const String& source_, const char* file_, long line_)
:type(EXT_UNDEF_TYPE)
,title("Exception")
,description(description_)
,source(source_)
,file(file_)
,line(line_)
{
// Log this error - not any more, allow catchers to do it
//LogManager::getSingleton().logMessage(this->getFullDescription());
}
Exception::Exception(int type_, const String& description_, const String& source_, const char* tile_, const char* file_, long line_)
:line(line_)
,type(type_)
,title(tile_)
,description(description_)
,source(source_)
,file(file_)
{
}
Exception::Exception(const Exception& rhs)
: line(rhs.line),
type(rhs.type),
title(rhs.title),
description(rhs.description),
source(rhs.source),
file(rhs.file)
{
}
void Exception::operator = (const Exception& rhs)
{
description = rhs.description;
type = rhs.type;
source = rhs.source;
file = rhs.file;
line = rhs.line;
title = rhs.title;
}
const String& Exception::GetFullDescription() const
{
if (0 == fullDesc.Length())
{
if( line > 0 )
{
fullDesc.Format("GENESIS EXCEPTION(%d:%s): \"%s\" in %s at %s(line, %d)",
type, title.AsCharPtr(), description.AsCharPtr(), source.AsCharPtr(), file.AsCharPtr(), line);
}
else
{
fullDesc.Format("GENESIS EXCEPTION(%d:%s): \"%s\" in %s", type, title.AsCharPtr(), description.AsCharPtr(), source.AsCharPtr());
}
}
return fullDesc;
}
int Exception::GetType(void) const throw()
{
return type;
}
const String &Exception::GetSource() const
{
return source;
}
const String &Exception::GetFile() const
{
return file;
}
long Exception::GetLine() const
{
return line;
}
const String &Exception::GetDescription(void) const
{
return description;
}
const char* Exception::what() const throw()
{
return GetFullDescription().AsCharPtr();
}
}
|
EngineDreamer/DreamEngine
|
Engine/foundation/exception/exceptionbase.cc
|
C++
|
mit
| 3,625 |
#include "GlobalSystems.h"
namespace globalSystem {
WindowManagerGL window;
TimeData time;
MouseData mouse;
KeyPressData keys;
TextureManager textures;
ModelManager models;
DynamicFloatMap runtimeData;
RandomNumberGenerator rng;
Font gameFont;
Font gameFontLarge;
Font gameFontHuge;
}
|
AndreSilvs/RTMasterThesis
|
RTHeightfieldScalable/GlobalSystems.cpp
|
C++
|
mit
| 347 |
/* Define to 1 if you have the <stdlib.h> header file. */
/*#define HAVE_STDLIB_H 1*/
|
sanqianyuejia/CSDK
|
src/config.h
|
C
|
mit
| 86 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.