code
stringlengths
1
2.06M
language
stringclasses
1 value
#include <iostream> using namespace std; int main() { int height; float eyesight; height = 175; eyesight = 0.8f; bool ok; ok = height >= 160 && height <=180 && eyesight >= 1.0f && eyesight <= 2.0f; cout << boolalpha; cout << ok << endl; return 0; }
C++
int main() { int a = 100; int b = 200; int c = 300; return 0; }
C++
#include<iostream> using namespace std; void main() { int a[10], i; for(i=0; i<10; i++) a[i]=i+1; for(i=0; i<10; i++) cout << a[i] << " "; cout <<"\n"; }
C++
/* * Copyright 2011, Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <stdio.h> #include <malloc.h> #include "android/bitmap.h" #include "common.h" #include "baseapi.h" #include "allheaders.h" static jfieldID field_mNativeData; struct native_data_t { tesseract::TessBaseAPI api; PIX *pix; void *data; bool debug; native_data_t() { pix = NULL; data = NULL; debug = false; } }; static inline native_data_t * get_native_data(JNIEnv *env, jobject object) { return (native_data_t *) (env->GetIntField(object, field_mNativeData)); } #ifdef __cplusplus extern "C" { #endif jint JNI_OnLoad(JavaVM* vm, void* reserved) { JNIEnv *env; if (vm->GetEnv((void**) &env, JNI_VERSION_1_6) != JNI_OK) { LOGE("Failed to get the environment using GetEnv()"); return -1; } return JNI_VERSION_1_6; } void Java_com_googlecode_tesseract_android_TessBaseAPI_nativeClassInit(JNIEnv* env, jclass clazz) { field_mNativeData = env->GetFieldID(clazz, "mNativeData", "I"); } void Java_com_googlecode_tesseract_android_TessBaseAPI_nativeConstruct(JNIEnv* env, jobject object) { native_data_t *nat = new native_data_t; if (nat == NULL) { LOGE("%s: out of memory!", __FUNCTION__); return; } env->SetIntField(object, field_mNativeData, (jint) nat); } void Java_com_googlecode_tesseract_android_TessBaseAPI_nativeFinalize(JNIEnv* env, jobject object) { native_data_t *nat = get_native_data(env, object); // Since Tesseract doesn't take ownership of the memory, we keep a pointer in the native // code struct. We need to free that pointer when we release our instance of Tesseract or // attempt to set a new image using one of the nativeSet* methods. if (nat->data != NULL) free(nat->data); else if (nat->pix != NULL) pixDestroy(&nat->pix); nat->data = NULL; nat->pix = NULL; if (nat != NULL) delete nat; } jboolean Java_com_googlecode_tesseract_android_TessBaseAPI_nativeInit(JNIEnv *env, jobject thiz, jstring dir, jstring lang) { native_data_t *nat = get_native_data(env, thiz); const char *c_dir = env->GetStringUTFChars(dir, NULL); const char *c_lang = env->GetStringUTFChars(lang, NULL); jboolean res = JNI_TRUE; if (nat->api.Init(c_dir, c_lang)) { LOGE("Could not initialize Tesseract API with language=%s!", c_lang); res = JNI_FALSE; } else { LOGI("Initialized Tesseract API with language=%s", c_lang); } env->ReleaseStringUTFChars(lang, c_dir); env->ReleaseStringUTFChars(lang, c_lang); return res; } void Java_com_googlecode_tesseract_android_TessBaseAPI_nativeSetImageBytes(JNIEnv *env, jobject thiz, jbyteArray data, jint width, jint height, jint bpp, jint bpl) { jbyte *data_array = env->GetByteArrayElements(data, NULL); int count = env->GetArrayLength(data); unsigned char* imagedata = (unsigned char *) malloc(count * sizeof(unsigned char)); // This is painfully slow, but necessary because we don't know // how many bits the JVM might be using to represent a byte for (int i = 0; i < count; i++) { imagedata[i] = (unsigned char) data_array[i]; } env->ReleaseByteArrayElements(data, data_array, JNI_ABORT); native_data_t *nat = get_native_data(env, thiz); nat->api.SetImage(imagedata, (int) width, (int) height, (int) bpp, (int) bpl); // Since Tesseract doesn't take ownership of the memory, we keep a pointer in the native // code struct. We need to free that pointer when we release our instance of Tesseract or // attempt to set a new image using one of the nativeSet* methods. if (nat->data != NULL) free(nat->data); else if (nat->pix != NULL) pixDestroy(&nat->pix); nat->data = imagedata; nat->pix = NULL; } void Java_com_googlecode_tesseract_android_TessBaseAPI_nativeSetImagePix(JNIEnv *env, jobject thiz, jint nativePix) { PIX *pixs = (PIX *) nativePix; PIX *pixd = pixClone(pixs); native_data_t *nat = get_native_data(env, thiz); nat->api.SetImage(pixd); // Since Tesseract doesn't take ownership of the memory, we keep a pointer in the native // code struct. We need to free that pointer when we release our instance of Tesseract or // attempt to set a new image using one of the nativeSet* methods. if (nat->data != NULL) free(nat->data); else if (nat->pix != NULL) pixDestroy(&nat->pix); nat->data = NULL; nat->pix = pixd; } void Java_com_googlecode_tesseract_android_TessBaseAPI_nativeSetRectangle(JNIEnv *env, jobject thiz, jint left, jint top, jint width, jint height) { native_data_t *nat = get_native_data(env, thiz); nat->api.SetRectangle(left, top, width, height); } jstring Java_com_googlecode_tesseract_android_TessBaseAPI_nativeGetUTF8Text(JNIEnv *env, jobject thiz) { native_data_t *nat = get_native_data(env, thiz); char *text = nat->api.GetUTF8Text(); jstring result = env->NewStringUTF(text); free(text); return result; } void Java_com_googlecode_tesseract_android_TessBaseAPI_nativeStop(JNIEnv *env, jobject thiz) { native_data_t *nat = get_native_data(env, thiz); // TODO How do we stop without a monitor?! } jint Java_com_googlecode_tesseract_android_TessBaseAPI_nativeMeanConfidence(JNIEnv *env, jobject thiz) { native_data_t *nat = get_native_data(env, thiz); return (jint) nat->api.MeanTextConf(); } jintArray Java_com_googlecode_tesseract_android_TessBaseAPI_nativeWordConfidences(JNIEnv *env, jobject thiz) { native_data_t *nat = get_native_data(env, thiz); int *confs = nat->api.AllWordConfidences(); if (confs == NULL) { return NULL; } int len, *trav; for (len = 0, trav = confs; *trav != -1; trav++, len++) ; LOG_ASSERT((confs != NULL), "Confidence array has %d elements", len); jintArray ret = env->NewIntArray(len); LOG_ASSERT((ret != NULL), "Could not create Java confidence array!"); env->SetIntArrayRegion(ret, 0, len, confs); delete[] confs; return ret; } jboolean Java_com_googlecode_tesseract_android_TessBaseAPI_nativeSetVariable(JNIEnv *env, jobject thiz, jstring var, jstring value) { native_data_t *nat = get_native_data(env, thiz); const char *c_var = env->GetStringUTFChars(var, NULL); const char *c_value = env->GetStringUTFChars(value, NULL); jboolean set = nat->api.SetVariable(c_var, c_value) ? JNI_TRUE : JNI_FALSE; env->ReleaseStringUTFChars(var, c_var); env->ReleaseStringUTFChars(value, c_value); return set; } void Java_com_googlecode_tesseract_android_TessBaseAPI_nativeClear(JNIEnv *env, jobject thiz) { native_data_t *nat = get_native_data(env, thiz); nat->api.Clear(); // Call between pages or documents etc to free up memory and forget adaptive data. nat->api.ClearAdaptiveClassifier(); // Since Tesseract doesn't take ownership of the memory, we keep a pointer in the native // code struct. We need to free that pointer when we release our instance of Tesseract or // attempt to set a new image using one of the nativeSet* methods. if (nat->data != NULL) free(nat->data); else if (nat->pix != NULL) pixDestroy(&nat->pix); nat->data = NULL; nat->pix = NULL; } void Java_com_googlecode_tesseract_android_TessBaseAPI_nativeEnd(JNIEnv *env, jobject thiz) { native_data_t *nat = get_native_data(env, thiz); nat->api.End(); // Since Tesseract doesn't take ownership of the memory, we keep a pointer in the native // code struct. We need to free that pointer when we release our instance of Tesseract or // attempt to set a new image using one of the nativeSet* methods. if (nat->data != NULL) free(nat->data); else if (nat->pix != NULL) pixDestroy(&nat->pix); nat->data = NULL; nat->pix = NULL; } void Java_com_googlecode_tesseract_android_TessBaseAPI_nativeSetDebug(JNIEnv *env, jobject thiz, jboolean debug) { native_data_t *nat = get_native_data(env, thiz); nat->debug = (debug == JNI_TRUE) ? TRUE : FALSE; } void Java_com_googlecode_tesseract_android_TessBaseAPI_nativeSetPageSegMode(JNIEnv *env, jobject thiz, jint mode) { native_data_t *nat = get_native_data(env, thiz); nat->api.SetPageSegMode((tesseract::PageSegMode) mode); } #ifdef __cplusplus } #endif
C++
/* * Copyright 2011, Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "common.h" #include <string.h> #include <android/bitmap.h> #ifdef __cplusplus extern "C" { #endif /* __cplusplus */ /************* * WriteFile * *************/ jint Java_com_googlecode_leptonica_android_WriteFile_nativeWriteBytes8(JNIEnv *env, jclass clazz, jint nativePix, jbyteArray data) { l_int32 w, h, d; PIX *pix = (PIX *) nativePix; pixGetDimensions(pix, &w, &h, &d); l_uint8 **lineptrs = pixSetupByteProcessing(pix, NULL, NULL); jbyte *data_buffer = env->GetByteArrayElements(data, NULL); l_uint8 *byte_buffer = (l_uint8 *) data_buffer; for (int i = 0; i < h; i++) { memcpy((byte_buffer + (i * w)), lineptrs[i], w); } env->ReleaseByteArrayElements(data, data_buffer, 0); pixCleanupByteProcessing(pix, lineptrs); return (jint)(w * h); } jboolean Java_com_googlecode_leptonica_android_WriteFile_nativeWriteFiles(JNIEnv *env, jclass clazz, jint nativePixa, jstring rootName, jint format) { PIXA *pixas = (PIXA *) nativePixa; const char *c_rootName = env->GetStringUTFChars(rootName, NULL); if (c_rootName == NULL) { LOGE("could not extract rootName string!"); return JNI_FALSE; } jboolean result = JNI_TRUE; if (pixaWriteFiles(c_rootName, pixas, (l_uint32) format)) { LOGE("could not write pixa data to %s", c_rootName); result = JNI_FALSE; } env->ReleaseStringUTFChars(rootName, c_rootName); return result; } jbyteArray Java_com_googlecode_leptonica_android_WriteFile_nativeWriteMem(JNIEnv *env, jclass clazz, jint nativePix, jint format) { PIX *pixs = (PIX *) nativePix; l_uint8 *data; size_t size; if (pixWriteMem(&data, &size, pixs, (l_uint32) format)) { LOGE("Failed to write pix data"); return NULL; } // TODO Can we just use the byte array directly? jbyteArray array = env->NewByteArray(size); env->SetByteArrayRegion(array, 0, size, (jbyte *) data); free(data); return array; } jboolean Java_com_googlecode_leptonica_android_WriteFile_nativeWriteImpliedFormat( JNIEnv *env, jclass clazz, jint nativePix, jstring fileName, jint quality, jboolean progressive) { PIX *pixs = (PIX *) nativePix; const char *c_fileName = env->GetStringUTFChars(fileName, NULL); if (c_fileName == NULL) { LOGE("could not extract fileName string!"); return JNI_FALSE; } jboolean result = JNI_TRUE; if (pixWriteImpliedFormat(c_fileName, pixs, (l_int32) quality, (progressive == JNI_TRUE))) { LOGE("could not write pix data to %s", c_fileName); result = JNI_FALSE; } env->ReleaseStringUTFChars(fileName, c_fileName); return result; } jboolean Java_com_googlecode_leptonica_android_WriteFile_nativeWriteBitmap(JNIEnv *env, jclass clazz, jint nativePix, jobject bitmap) { PIX *pixs = (PIX *) nativePix; l_int32 w, h, d; AndroidBitmapInfo info; void* pixels; int ret; if ((ret = AndroidBitmap_getInfo(env, bitmap, &info)) < 0) { LOGE("AndroidBitmap_getInfo() failed ! error=%d", ret); return JNI_FALSE; } if (info.format != ANDROID_BITMAP_FORMAT_RGBA_8888) { LOGE("Bitmap format is not RGBA_8888 !"); return JNI_FALSE; } pixGetDimensions(pixs, &w, &h, &d); if (w != info.width || h != info.height) { LOGE("Bitmap width and height do not match Pix dimensions!"); return JNI_FALSE; } if ((ret = AndroidBitmap_lockPixels(env, bitmap, &pixels)) < 0) { LOGE("AndroidBitmap_lockPixels() failed ! error=%d", ret); return JNI_FALSE; } pixEndianByteSwap(pixs); l_uint8 *dst = (l_uint8 *) pixels; l_uint8 *src = (l_uint8 *) pixGetData(pixs); l_int32 dstBpl = info.stride; l_int32 srcBpl = 4 * pixGetWpl(pixs); LOGE("Writing 32bpp RGBA bitmap (w=%d, h=%d, stride=%d) from %dbpp Pix (wpl=%d)", info.width, info.height, info.stride, d, pixGetWpl(pixs)); for (int dy = 0; dy < info.height; dy++) { l_uint8 *dstx = dst; l_uint8 *srcx = src; if (d == 32) { memcpy(dst, src, 4 * info.width); } else if (d == 8) { for (int dw = 0; dw < info.width; dw++) { dstx[0] = dstx[1] = dstx[2] = srcx[0]; dstx[3] = 0xFF; dstx += 4; srcx += 1; } } else if (d == 1) { for (int dw = 0; dw < info.width; dw++) { dstx[0] = dstx[1] = dstx[2] = (srcx[0] & (dw % 8)) ? 0xFF : 0x00; dstx[3] = 0xFF; dstx += 4; srcx += ((dw % 8) == 7) ? 1 : 0; } } dst += dstBpl; src += srcBpl; } AndroidBitmap_unlockPixels(env, bitmap); return JNI_TRUE; } #ifdef __cplusplus } #endif /* __cplusplus */
C++
/* * Copyright 2011, Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "common.h" #include <string.h> #include <android/bitmap.h> #ifdef __cplusplus extern "C" { #endif /* __cplusplus */ /*************** * AdaptiveMap * ***************/ jint Java_com_googlecode_leptonica_android_AdaptiveMap_nativeBackgroundNormMorph(JNIEnv *env, jclass clazz, jint nativePix, jint reduction, jint size, jint bgval) { // Normalizes the background of each element in pixa. PIX *pixs = (PIX *) nativePix; PIX *pixd = pixBackgroundNormMorph(pixs, NULL, (l_int32) reduction, (l_int32) size, (l_int32) bgval); return (jint) pixd; } /************ * Binarize * ************/ jint Java_com_googlecode_leptonica_android_Binarize_nativeOtsuAdaptiveThreshold(JNIEnv *env, jclass clazz, jint nativePix, jint sizeX, jint sizeY, jint smoothX, jint smoothY, jfloat scoreFract) { PIX *pixs = (PIX *) nativePix; PIX *pixd; if (pixOtsuAdaptiveThreshold(pixs, (l_int32) sizeX, (l_int32) sizeY, (l_int32) smoothX, (l_int32) smoothY, (l_float32) scoreFract, NULL, &pixd)) { return (jint) 0; } return (jint) pixd; } /*********** * Convert * ***********/ jint Java_com_googlecode_leptonica_android_Convert_nativeConvertTo8(JNIEnv *env, jclass clazz, jint nativePix) { PIX *pixs = (PIX *) nativePix; PIX *pixd = pixConvertTo8(pixs, FALSE); return (jint) pixd; } /*********** * Enhance * ***********/ jint Java_com_googlecode_leptonica_android_Enhance_nativeUnsharpMasking(JNIEnv *env, jclass clazz, jint nativePix, jint halfwidth, jfloat fract) { PIX *pixs = (PIX *) nativePix; PIX *pixd = pixUnsharpMasking(pixs, (l_int32) halfwidth, (l_float32) fract); return (jint) pixd; } /********** * JpegIO * **********/ jbyteArray Java_com_googlecode_leptonica_android_JpegIO_nativeCompressToJpeg(JNIEnv *env, jclass clazz, jint nativePix, jint quality, jboolean progressive) { PIX *pix = (PIX *) nativePix; l_uint8 *data; size_t size; if (pixWriteMemJpeg(&data, &size, pix, (l_int32) quality, progressive == JNI_TRUE ? 1 : 0)) { LOGE("Failed to write JPEG data"); return NULL; } // TODO Can we just use the byte array directly? jbyteArray array = env->NewByteArray(size); env->SetByteArrayRegion(array, 0, size, (jbyte *) data); free(data); return array; } /********* * Scale * *********/ jint Java_com_googlecode_leptonica_android_Scale_nativeScale(JNIEnv *env, jclass clazz, jint nativePix, jfloat scaleX, jfloat scaleY) { PIX *pixs = (PIX *) nativePix; PIX *pixd = pixScale(pixs, (l_float32) scaleX, (l_float32) scaleY); return (jint) pixd; } /******** * Skew * ********/ jfloat Java_com_googlecode_leptonica_android_Skew_nativeFindSkew(JNIEnv *env, jclass clazz, jint nativePix, jfloat sweepRange, jfloat sweepDelta, jint sweepReduction, jint searchReduction, jfloat searchMinDelta) { // Corrects the rotation of each element in pixa to 0 degrees. PIX *pixs = (PIX *) nativePix; l_float32 angle, conf; if (!pixFindSkewSweepAndSearch(pixs, &angle, &conf, (l_int32) sweepReduction, (l_int32) searchReduction, (l_float32) sweepRange, (l_int32) sweepDelta, (l_float32) searchMinDelta)) { if (conf <= 0) { return (jfloat) 0; } return (jfloat) angle; } return (jfloat) 0; } /********** * Rotate * **********/ jint Java_com_googlecode_leptonica_android_Rotate_nativeRotate(JNIEnv *env, jclass clazz, jint nativePix, jfloat degrees, jboolean quality) { PIX *pixd; PIX *pixs = (PIX *) nativePix; l_float32 deg2rad = 3.1415926535 / 180.0; l_float32 radians = degrees * deg2rad; l_int32 w, h, bpp, type; pixGetDimensions(pixs, &w, &h, &bpp); if (bpp == 1 && quality == JNI_TRUE) { pixd = pixRotateBinaryNice(pixs, radians, L_BRING_IN_WHITE); } else { type = quality == JNI_TRUE ? L_ROTATE_AREA_MAP : L_ROTATE_SAMPLING; pixd = pixRotate(pixs, radians, type, L_BRING_IN_WHITE, 0, 0); } return (jint) pixd; } #ifdef __cplusplus } #endif /* __cplusplus */
C++
/* * Copyright 2011, Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "common.h" #ifdef __cplusplus extern "C" { #endif /* __cplusplus */ jint Java_com_googlecode_leptonica_android_Pixa_nativeCreate(JNIEnv *env, jclass clazz, jint size) { PIXA *pixa = pixaCreate((l_int32) size); return (jint) pixa; } jint Java_com_googlecode_leptonica_android_Pixa_nativeCopy(JNIEnv *env, jclass clazz, jint nativePixa) { PIXA *pixas = (PIXA *) nativePixa; PIXA *pixad = pixaCopy(pixas, L_CLONE); return (jint) pixad; } jint Java_com_googlecode_leptonica_android_Pixa_nativeSort(JNIEnv *env, jclass clazz, jint nativePixa, jint field, jint order) { PIXA *pixas = (PIXA *) nativePixa; PIXA *pixad = pixaSort(pixas, field, order, NULL, L_CLONE); return (jint) pixad; } void Java_com_googlecode_leptonica_android_Pixa_nativeDestroy(JNIEnv *env, jclass clazz, jint nativePixa) { PIXA *pixa = (PIXA *) nativePixa; pixaDestroy(&pixa); } jboolean Java_com_googlecode_leptonica_android_Pixa_nativeJoin(JNIEnv *env, jclass clazz, jint nativePixa, jint otherPixa) { PIXA *pixa = (PIXA *) nativePixa; PIXA *pixas = (PIXA *) otherPixa; if (pixaJoin(pixa, pixas, 0, 0)) { return JNI_FALSE; } return JNI_TRUE; } jint Java_com_googlecode_leptonica_android_Pixa_nativeGetCount(JNIEnv *env, jclass clazz, jint nativePixa) { PIXA *pixa = (PIXA *) nativePixa; return (jint) pixaGetCount(pixa); } void Java_com_googlecode_leptonica_android_Pixa_nativeAddPix(JNIEnv *env, jclass clazz, jint nativePixa, jint nativePix, jint mode) { PIXA *pixa = (PIXA *) nativePixa; PIX *pix = (PIX *) nativePix; pixaAddPix(pixa, pix, mode); } void Java_com_googlecode_leptonica_android_Pixa_nativeAddBox(JNIEnv *env, jclass clazz, jint nativePixa, jint nativeBox, jint mode) { PIXA *pixa = (PIXA *) nativePixa; BOX *box = (BOX *) nativeBox; pixaAddBox(pixa, box, mode); } void Java_com_googlecode_leptonica_android_Pixa_nativeAdd(JNIEnv *env, jclass clazz, jint nativePixa, jint nativePix, jint nativeBox, jint mode) { PIXA *pixa = (PIXA *) nativePixa; PIX *pix = (PIX *) nativePix; BOX *box = (BOX *) nativeBox; pixaAddPix(pixa, pix, mode); pixaAddBox(pixa, box, mode); } void Java_com_googlecode_leptonica_android_Pixa_nativeReplacePix(JNIEnv *env, jclass clazz, jint nativePixa, jint index, jint nativePix, jint nativeBox) { PIXA *pixa = (PIXA *) nativePixa; PIX *pix = (PIX *) nativePix; BOX *box = (BOX *) nativeBox; pixaReplacePix(pixa, index, pix, box); } void Java_com_googlecode_leptonica_android_Pixa_nativeMergeAndReplacePix(JNIEnv *env, jclass clazz, jint nativePixa, jint indexA, jint indexB) { PIXA *pixa = (PIXA *) nativePixa; l_int32 op; l_int32 x, y, w, h; l_int32 dx, dy, dw, dh; PIX *pixs, *pixd; BOX *boxA, *boxB, *boxd; boxA = pixaGetBox(pixa, indexA, L_CLONE); boxB = pixaGetBox(pixa, indexB, L_CLONE); boxd = boxBoundingRegion(boxA, boxB); boxGetGeometry(boxd, &x, &y, &w, &h); pixd = pixCreate(w, h, 1); op = PIX_SRC | PIX_DST; pixs = pixaGetPix(pixa, indexA, L_CLONE); boxGetGeometry(boxA, &dx, &dy, &dw, &dh); pixRasterop(pixd, dx - x, dy - y, dw, dh, op, pixs, 0, 0); pixDestroy(&pixs); boxDestroy(&boxA); pixs = pixaGetPix(pixa, indexB, L_CLONE); boxGetGeometry(boxB, &dx, &dy, &dw, &dh); pixRasterop(pixd, dx - x, dy - y, dw, dh, op, pixs, 0, 0); pixDestroy(&pixs); boxDestroy(&boxB); pixaReplacePix(pixa, indexA, pixd, boxd); } jboolean Java_com_googlecode_leptonica_android_Pixa_nativeWriteToFileRandomCmap(JNIEnv *env, jclass clazz, jint nativePixa, jstring fileName, jint width, jint height) { PIX *pixtemp; PIXA *pixa = (PIXA *) nativePixa; const char *c_fileName = env->GetStringUTFChars(fileName, NULL); if (c_fileName == NULL) { LOGE("could not extract fileName string!"); return JNI_FALSE; } if (pixaGetCount(pixa) > 0) { pixtemp = pixaDisplayRandomCmap(pixa, (l_int32) width, (l_int32) height); } else { pixtemp = pixCreate((l_int32) width, (l_int32) height, 1); } pixWrite(c_fileName, pixtemp, IFF_BMP); pixDestroy(&pixtemp); env->ReleaseStringUTFChars(fileName, c_fileName); return JNI_TRUE; } jint Java_com_googlecode_leptonica_android_Pixa_nativeGetPix(JNIEnv *env, jclass clazz, jint nativePixa, jint index) { PIXA *pixa = (PIXA *) nativePixa; PIX *pix = pixaGetPix(pixa, (l_int32) index, L_CLONE); return (jint) pix; } jint Java_com_googlecode_leptonica_android_Pixa_nativeGetBox(JNIEnv *env, jclass clazz, jint nativePixa, jint index) { PIXA *pixa = (PIXA *) nativePixa; BOX *box = pixaGetBox(pixa, (l_int32) index, L_CLONE); return (jint) box; } jboolean Java_com_googlecode_leptonica_android_Pixa_nativeGetBoxGeometry(JNIEnv *env, jclass clazz, jint nativePixa, jint index, jintArray dimensions) { PIXA *pixa = (PIXA *) nativePixa; jint *dimensionArray = env->GetIntArrayElements(dimensions, NULL); l_int32 x, y, w, h; if (pixaGetBoxGeometry(pixa, (l_int32) index, &x, &y, &w, &h)) { return JNI_FALSE; } dimensionArray[0] = x; dimensionArray[1] = y; dimensionArray[2] = w; dimensionArray[3] = h; env->ReleaseIntArrayElements(dimensions, dimensionArray, 0); return JNI_TRUE; } #ifdef __cplusplus } #endif /* __cplusplus */
C++
/* * Copyright 2011, Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "common.h" #include <string.h> #include <android/bitmap.h> #ifdef __cplusplus extern "C" { #endif /* __cplusplus */ /************ * ReadFile * ************/ jint Java_com_googlecode_leptonica_android_ReadFile_nativeReadMem(JNIEnv *env, jclass clazz, jbyteArray image, jint length) { jbyte *image_buffer = env->GetByteArrayElements(image, NULL); int buffer_length = env->GetArrayLength(image); PIX *pix = pixReadMem((const l_uint8 *) image_buffer, buffer_length); env->ReleaseByteArrayElements(image, image_buffer, JNI_ABORT); return (jint) pix; } jint Java_com_googlecode_leptonica_android_ReadFile_nativeReadBytes8(JNIEnv *env, jclass clazz, jbyteArray data, jint w, jint h) { PIX *pix = pixCreateNoInit((l_int32) w, (l_int32) h, 8); l_uint8 **lineptrs = pixSetupByteProcessing(pix, NULL, NULL); jbyte *data_buffer = env->GetByteArrayElements(data, NULL); l_uint8 *byte_buffer = (l_uint8 *) data_buffer; for (int i = 0; i < h; i++) { memcpy(lineptrs[i], (byte_buffer + (i * w)), w); } env->ReleaseByteArrayElements(data, data_buffer, JNI_ABORT); pixCleanupByteProcessing(pix, lineptrs); l_int32 d; pixGetDimensions(pix, &w, &h, &d); LOGE("Created image width w=%d, h=%d, d=%d", w, h, d); return (jint) pix; } jboolean Java_com_googlecode_leptonica_android_ReadFile_nativeReplaceBytes8(JNIEnv *env, jclass clazz, jint nativePix, jbyteArray data, jint srcw, jint srch) { PIX *pix = (PIX *) nativePix; l_int32 w, h, d; pixGetDimensions(pix, &w, &h, &d); if (d != 8 || (l_int32) srcw != w || (l_int32) srch != h) { LOGE("Failed to replace bytes at w=%d, h=%d, d=%d with w=%d, h=%d", w, h, d, srcw, srch); return JNI_FALSE; } l_uint8 **lineptrs = pixSetupByteProcessing(pix, NULL, NULL); jbyte *data_buffer = env->GetByteArrayElements(data, NULL); l_uint8 *byte_buffer = (l_uint8 *) data_buffer; for (int i = 0; i < h; i++) { memcpy(lineptrs[i], (byte_buffer + (i * w)), w); } env->ReleaseByteArrayElements(data, data_buffer, JNI_ABORT); pixCleanupByteProcessing(pix, lineptrs); return JNI_TRUE; } jint Java_com_googlecode_leptonica_android_ReadFile_nativeReadFiles(JNIEnv *env, jclass clazz, jstring dirName, jstring prefix) { PIXA *pixad = NULL; const char *c_dirName = env->GetStringUTFChars(dirName, NULL); if (c_dirName == NULL) { LOGE("could not extract dirName string!"); return NULL; } const char *c_prefix = env->GetStringUTFChars(prefix, NULL); if (c_prefix == NULL) { LOGE("could not extract prefix string!"); return NULL; } pixad = pixaReadFiles(c_dirName, c_prefix); env->ReleaseStringUTFChars(dirName, c_dirName); env->ReleaseStringUTFChars(prefix, c_prefix); return (jint) pixad; } jint Java_com_googlecode_leptonica_android_ReadFile_nativeReadFile(JNIEnv *env, jclass clazz, jstring fileName) { PIX *pixd = NULL; const char *c_fileName = env->GetStringUTFChars(fileName, NULL); if (c_fileName == NULL) { LOGE("could not extract fileName string!"); return NULL; } pixd = pixRead(c_fileName); env->ReleaseStringUTFChars(fileName, c_fileName); return (jint) pixd; } jint Java_com_googlecode_leptonica_android_ReadFile_nativeReadBitmap(JNIEnv *env, jclass clazz, jobject bitmap) { l_int32 w, h, d; AndroidBitmapInfo info; void* pixels; int ret; if ((ret = AndroidBitmap_getInfo(env, bitmap, &info)) < 0) { LOGE("AndroidBitmap_getInfo() failed ! error=%d", ret); return JNI_FALSE; } if (info.format != ANDROID_BITMAP_FORMAT_RGBA_8888) { LOGE("Bitmap format is not RGBA_8888 !"); return JNI_FALSE; } if ((ret = AndroidBitmap_lockPixels(env, bitmap, &pixels)) < 0) { LOGE("AndroidBitmap_lockPixels() failed ! error=%d", ret); return JNI_FALSE; } PIX *pixd = pixCreate(info.width, info.height, 8); l_uint32 *src = (l_uint32 *) pixels; l_int32 srcWpl = (info.stride / 4); l_uint32 *dst = pixGetData(pixd); l_int32 dstWpl = pixGetWpl(pixd); l_uint8 a, r, g, b, pixel8; for (int y = 0; y < info.height; y++) { l_uint32 *dst_line = dst + (y * dstWpl); l_uint32 *src_line = src + (y * srcWpl); for (int x = 0; x < info.width; x++) { // Get pixel from RGBA_8888 r = *src_line >> SK_R32_SHIFT; g = *src_line >> SK_G32_SHIFT; b = *src_line >> SK_B32_SHIFT; a = *src_line >> SK_A32_SHIFT; pixel8 = (l_uint8)((r + g + b) / 3); // Set pixel to LUMA_8 SET_DATA_BYTE(dst_line, x, pixel8); // Move to the next pixel src_line++; } } AndroidBitmap_unlockPixels(env, bitmap); return (jint) pixd; } #ifdef __cplusplus } #endif /* __cplusplus */
C++
/* * Copyright 2011, Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "common.h" #ifdef __cplusplus extern "C" { #endif /* __cplusplus */ jint Java_com_googlecode_leptonica_android_Box_nativeCreate(JNIEnv *env, jclass clazz, jint x, jint y, jint w, jint h) { BOX *box = boxCreate((l_int32) x, (l_int32) y, (l_int32) w, (l_int32) h); return (jint) box; } void Java_com_googlecode_leptonica_android_Box_nativeDestroy(JNIEnv *env, jclass clazz, jint nativeBox) { BOX *box = (BOX *) nativeBox; boxDestroy(&box); } jint Java_com_googlecode_leptonica_android_Box_nativeGetX(JNIEnv *env, jclass clazz, jint nativeBox) { BOX *box = (BOX *) nativeBox; return (jint) box->x; } jint Java_com_googlecode_leptonica_android_Box_nativeGetY(JNIEnv *env, jclass clazz, jint nativeBox) { BOX *box = (BOX *) nativeBox; return (jint) box->y; } jint Java_com_googlecode_leptonica_android_Box_nativeGetWidth(JNIEnv *env, jclass clazz, jint nativeBox) { BOX *box = (BOX *) nativeBox; return (jint) box->w; } jint Java_com_googlecode_leptonica_android_Box_nativeGetHeight(JNIEnv *env, jclass clazz, jint nativeBox) { BOX *box = (BOX *) nativeBox; return (jint) box->h; } jboolean Java_com_googlecode_leptonica_android_Box_nativeGetGeometry(JNIEnv *env, jclass clazz, jint nativeBox, jintArray dimensions) { BOX *box = (BOX *) nativeBox; jint *dimensionArray = env->GetIntArrayElements(dimensions, NULL); l_int32 x, y, w, h; if (boxGetGeometry(box, &x, &y, &w, &h)) { return JNI_FALSE; } dimensionArray[0] = x; dimensionArray[1] = y; dimensionArray[2] = w; dimensionArray[3] = h; env->ReleaseIntArrayElements(dimensions, dimensionArray, 0); return JNI_TRUE; } #ifdef __cplusplus } #endif /* __cplusplus */
C++
/* * Copyright 2011, Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "common.h" #include <string.h> #ifdef __cplusplus extern "C" { #endif /* __cplusplus */ jint Java_com_googlecode_leptonica_android_Pix_nativeCreatePix(JNIEnv *env, jclass clazz, jint w, jint h, jint d) { PIX *pix = pixCreate((l_int32) w, (l_int32) h, (l_int32) d); return (jint) pix; } jint Java_com_googlecode_leptonica_android_Pix_nativeCreateFromData(JNIEnv *env, jclass clazz, jbyteArray data, jint w, jint h, jint d) { PIX *pix = pixCreateNoInit((l_int32) w, (l_int32) h, (l_int32) d); jbyte *data_buffer = env->GetByteArrayElements(data, NULL); l_uint8 *byte_buffer = (l_uint8 *) data_buffer; size_t size = 4 * pixGetWpl(pix) * pixGetHeight(pix); memcpy(pixGetData(pix), byte_buffer, size); env->ReleaseByteArrayElements(data, data_buffer, JNI_ABORT); return (jint) pix; } jboolean Java_com_googlecode_leptonica_android_Pix_nativeGetData(JNIEnv *env, jclass clazz, jint nativePix, jbyteArray data) { PIX *pix = (PIX *) nativePix; jbyte *data_buffer = env->GetByteArrayElements(data, NULL); l_uint8 *byte_buffer = (l_uint8 *) data_buffer; size_t size = 4 * pixGetWpl(pix) * pixGetHeight(pix); memcpy(byte_buffer, pixGetData(pix), size); env->ReleaseByteArrayElements(data, data_buffer, 0); return JNI_TRUE; } jint Java_com_googlecode_leptonica_android_Pix_nativeGetDataSize(JNIEnv *env, jclass clazz, jint nativePix) { PIX *pix = (PIX *) nativePix; size_t size = 4 * pixGetWpl(pix) * pixGetHeight(pix); return (jint) size; } jint Java_com_googlecode_leptonica_android_Pix_nativeClone(JNIEnv *env, jclass clazz, jint nativePix) { PIX *pixs = (PIX *) nativePix; PIX *pixd = pixClone(pixs); return (jint) pixd; } jint Java_com_googlecode_leptonica_android_Pix_nativeCopy(JNIEnv *env, jclass clazz, jint nativePix) { PIX *pixs = (PIX *) nativePix; PIX *pixd = pixCopy(NULL, pixs); return (jint) pixd; } jboolean Java_com_googlecode_leptonica_android_Pix_nativeInvert(JNIEnv *env, jclass clazz, jint nativePix) { PIX *pixs = (PIX *) nativePix; if (pixInvert(pixs, pixs)) { return JNI_FALSE; } return JNI_TRUE; } void Java_com_googlecode_leptonica_android_Pix_nativeDestroy(JNIEnv *env, jclass clazz, jint nativePix) { PIX *pix = (PIX *) nativePix; pixDestroy(&pix); } jboolean Java_com_googlecode_leptonica_android_Pix_nativeGetDimensions(JNIEnv *env, jclass clazz, jint nativePix, jintArray dimensions) { PIX *pix = (PIX *) nativePix; jint *dimensionArray = env->GetIntArrayElements(dimensions, NULL); l_int32 w, h, d; if (pixGetDimensions(pix, &w, &h, &d)) { return JNI_FALSE; } dimensionArray[0] = w; dimensionArray[1] = h; dimensionArray[2] = d; env->ReleaseIntArrayElements(dimensions, dimensionArray, 0); return JNI_TRUE; } jint Java_com_googlecode_leptonica_android_Pix_nativeGetWidth(JNIEnv *env, jclass clazz, jint nativePix) { PIX *pix = (PIX *) nativePix; return (jint) pixGetWidth(pix); } jint Java_com_googlecode_leptonica_android_Pix_nativeGetHeight(JNIEnv *env, jclass clazz, jint nativePix) { PIX *pix = (PIX *) nativePix; return (jint) pixGetHeight(pix); } jint Java_com_googlecode_leptonica_android_Pix_nativeGetDepth(JNIEnv *env, jclass clazz, jint nativePix) { PIX *pix = (PIX *) nativePix; return (jint) pixGetDepth(pix); } void Java_com_googlecode_leptonica_android_Pix_nativeSetPixel(JNIEnv *env, jclass clazz, jint nativePix, jint xCoord, jint yCoord, jint argbColor) { PIX *pix = (PIX *) nativePix; l_int32 d = pixGetDepth(pix); l_int32 x = (l_int32) xCoord; l_int32 y = (l_int32) yCoord; // These shift values are based on RGBA_8888 l_uint8 r = (argbColor >> SK_R32_SHIFT) & 0xFF; l_uint8 g = (argbColor >> SK_G32_SHIFT) & 0xFF; l_uint8 b = (argbColor >> SK_B32_SHIFT) & 0xFF; l_uint8 a = (argbColor >> SK_A32_SHIFT) & 0xFF; l_uint8 gray = ((r + g + b) / 3) & 0xFF; l_uint32 color; switch (d) { case 1: // 1-bit binary color = gray > 128 ? 1 : 0; break; case 2: // 2-bit grayscale color = gray >> 6; break; case 4: // 4-bit grayscale color = gray >> 4; break; case 8: // 8-bit grayscale color = gray; break; case 24: // 24-bit RGB SET_DATA_BYTE(&color, COLOR_RED, r); SET_DATA_BYTE(&color, COLOR_GREEN, g); SET_DATA_BYTE(&color, COLOR_BLUE, b); break; case 32: // 32-bit ARGB SET_DATA_BYTE(&color, COLOR_RED, r); SET_DATA_BYTE(&color, COLOR_GREEN, g); SET_DATA_BYTE(&color, COLOR_BLUE, b); SET_DATA_BYTE(&color, L_ALPHA_CHANNEL, a); break; default: // unsupported LOGE("Not a supported color depth: %d", d); color = 0; break; } pixSetPixel(pix, x, y, color); } jint Java_com_googlecode_leptonica_android_Pix_nativeGetPixel(JNIEnv *env, jclass clazz, jint nativePix, jint xCoord, jint yCoord) { PIX *pix = (PIX *) nativePix; l_int32 d = pixGetDepth(pix); l_int32 x = (l_int32) xCoord; l_int32 y = (l_int32) yCoord; l_uint32 pixel; l_uint32 color; l_uint8 a, r, g, b; pixGetPixel(pix, x, y, &pixel); switch (d) { case 1: // 1-bit binary a = 0xFF; r = g = b = (pixel == 0 ? 0x00 : 0xFF); break; case 2: // 2-bit grayscale a = 0xFF; r = g = b = (pixel << 6 | pixel << 4 | pixel); break; case 4: // 4-bit grayscale a = 0xFF; r = g = b = (pixel << 4 | pixel); break; case 8: // 8-bit grayscale a = 0xFF; r = g = b = pixel; break; case 24: // 24-bit RGB a = 0xFF; r = (pixel >> L_RED_SHIFT) & 0xFF; g = (pixel >> L_GREEN_SHIFT) & 0xFF; b = (pixel >> L_BLUE_SHIFT) & 0xFF; break; case 32: // 32-bit RGBA r = (pixel >> L_RED_SHIFT) & 0xFF; g = (pixel >> L_GREEN_SHIFT) & 0xFF; b = (pixel >> L_BLUE_SHIFT) & 0xFF; a = (pixel >> L_ALPHA_SHIFT) & 0xFF; break; default: // Not supported LOGE("Not a supported color depth: %d", d); a = r = g = b = 0x00; break; } color = a << SK_A32_SHIFT; color |= r << SK_R32_SHIFT; color |= g << SK_G32_SHIFT; color |= b << SK_B32_SHIFT; return (jint) color; } #ifdef __cplusplus } #endif /* __cplusplus */
C++
/* * Copyright 2011, Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "common.h" jint JNI_OnLoad(JavaVM* vm, void* reserved) { JNIEnv *env; if (vm->GetEnv((void**) &env, JNI_VERSION_1_6) != JNI_OK) { LOGE("ERROR: GetEnv failed\n"); return -1; } assert(env != NULL); return JNI_VERSION_1_6; }
C++
#ifndef __NONAME_GETPROC_H__ #define __NONAME_GETPROC_H__ #define NONAME_LIB_USE #include <ntifs.h> #include "nm_mem.h" #include "nm_undoc.h" class kgetproc { public: kgetproc(PDRIVER_OBJECT DriverObj) {m_LoadedModuleList = (PLIST_ENTRY)DriverObj->DriverSection;} PVOID GetSystemRoutineAddress(PUNICODE_STRING ModuleName, PUNICODE_STRING SystemRoutineName); private: PVOID FindExportedRoutineByName(PVOID DllBase, PANSI_STRING AnsiImageRoutineName); PLIST_ENTRY m_LoadedModuleList; }; #endif
C++
#ifndef __NM_EXCEPTION_H__ #define __NM_EXCEPTION_H__ #define NONAME_LIB_USE #include <ntifs.h> #include "nm_mem.h" class KException { public: static void Install(); NTSTATUS Status() const; PVOID const At() const; protected: KException(EXCEPTION_POINTERS const &info); static void __cdecl Translator(ULONG Code, EXCEPTION_POINTERS *info); PVOID m_IP; NTSTATUS m_Status; }; class KExceptionAccessViolation : public KException { public: PVOID const Address() const; bool IsWrite() const; protected: friend KException; KExceptionAccessViolation(EXCEPTION_POINTERS const &info); PVOID m_Addr; bool m_IsWrite; }; inline NTSTATUS KException::Status() const { return m_Status; } inline PVOID const KException::At() const { return m_IP; } inline PVOID const KExceptionAccessViolation::Address() const { return m_Addr; } inline bool KExceptionAccessViolation::IsWrite() const { return m_IsWrite; } #endif
C++
#include "nm_hashtable.h"
C++
#include "nm_mem.h" klookaside::klookaside( ULONG Size, ULONG Tag /*= NM_LOOKASIDE_TAG*/, POOL_TYPE PoolType /*= PagedPool*/ ) : m_PagedLookasideList(NULL), m_NPagedLookasideList(NULL), m_PoolType(PoolType); { if (PoolType == NonPagedPool) { m_NPagedLookasideList = new(NonPagedPool, Tag) NPAGED_LOOKASIDE_LIST; ExInitializeNPagedLookasideList(m_NPagedLookasideList, NULL, NULL, 0, Size, Tag, 0); } else { m_PagedLookasideList = new(NonPagedPool, Tag) PAGED_LOOKASIDE_LIST; ExInitializePagedLookasideList(m_PagedLookasideList, NULL, NULL, 0, Size, Tag, 0); } } void klookaside::Release() { if (m_PagedLookasideList != NULL) { ExDeletePagedLookasideList(m_PagedLookasideList); delete m_PagedLookasideList; m_PagedLookasideList = NULL; } if (m_NPagedLookasideList != NULL) { ExDeleteNPagedLookasideList(m_NPagedLookasideList); delete m_NPagedLookasideList; m_NPagedLookasideList = NULL; } } PVOID klookaside::Allocate() { PVOID Buffer = NULL; if (m_PoolType == PagedPool) { Buffer = ExAllocateFromPagedLookasideList(m_PagedLookasideList); } else if (m_PoolType == NonPagedPool) { Buffer = ExAllocateFromNPagedLookasideList(m_NPagedLookasideList); } return Buffer; } VOID klookaside::Free( PVOID Buffer ) { if (Buffer == NULL) { return; } if (m_PoolType == PagedPool) { ExFreeToPagedLookasideList(m_PagedLookasideList, Buffer); } else if (m_PoolType == NonPagedPool) { ExFreeToNPagedLookasideList(m_NPagedLookasideList, Buffer); } }
C++
#include "nm_workthread.h" kworkthread::kworkthread() : m_Stop(FALSE), m_Lookaside(sizeof(WORK_ITEM)) { RtlZeroMemory(&m_ClientId, sizeof(CLIENT_ID)); InitializeListHead(&m_ListHeader); KeInitializeEvent(&m_InsertEvent, SynchronizationEvent, FALSE); KeInitializeSpinLock(&m_Lock); PsCreateSystemThread(&m_ThreadHandle, THREAD_ALL_ACCESS, NULL, NULL, &m_ClientId, Run, this); } void kworkthread::Release() { m_Stop = TRUE; KeSetEvent(&m_InsertEvent, 0, FALSE); KeWaitForSingleObject(m_ThreadHandle, Executive, KernelMode, FALSE, NULL); ZwClose(m_ThreadHandle); } void kworkthread::Run(PVOID Context) { kworkthread *pthis = (kworkthread *)Context; LARGE_INTEGER timeout; PWORK_ITEM WorkItem; NTSTATUS ns; timeout.QuadPart = -10000 * 10 * 1000; while (TRUE) { ns = KeWaitForSingleObject((PVOID)&pthis->m_InsertEvent, Executive, KernelMode, FALSE, &timeout); if (ns == STATUS_TIMEOUT) { KdPrint(("kworkthread timeout\n")); } if (pthis->m_Stop) { break; } while ((WorkItem = CONTAINING_RECORD( ExInterlockedRemoveHeadList(&pthis->m_ListHeader, &pthis->m_Lock), WORK_ITEM, Next )) != NULL) { if (WorkItem->StartAddress != NULL) { WorkItem->StartAddress(WorkItem->Context); } KeSetEvent( &WorkItem->Event, 0, FALSE ); pthis->m_Lookaside.Free(WorkItem); } if (pthis->m_Stop) { break; } } } void kworkthread::InsertItem(WORKITEMPROC Address, PVOID Context, PRKEVENT *Event) { PWORK_ITEM WorkItem; if (!MmIsAddressValid(Address)) { return; } WorkItem = (PWORK_ITEM)m_Lookaside.Allocate(); if (WorkItem == NULL) return; WorkItem->Next.Flink = NULL; WorkItem->Next.Blink = NULL; WorkItem->StartAddress = Address; WorkItem->Context = Context; if (Event != NULL) { *Event = &WorkItem->Event; } KeInitializeEvent(&WorkItem->Event, SynchronizationEvent, FALSE); ExInterlockedInsertTailList(&m_ListHeader, &WorkItem->Next, &m_Lock); KeSetEvent(&m_InsertEvent, 0, FALSE); }
C++
#ifndef __NONAME_CRICULARQUEUE_H__ #define __NONAME_CRICULARQUEUE_H__ #define NONAME_LIB_USE #include <ntifs.h> #include "nm_mem.h" #define DEFAULT_MAX_CQ_SIZE 64 template <class T> class cirbuf { public: cirbuf( ULONG Size = DEFAULT_MAX_CQ_SIZE ) : m_Tail(0), m_Head(0), m_ItemCount(0) { m_Buffer = new T[Size]; m_MaxSize = Size; } void Release() { delete[] m_Buffer; m_MaxSize = 0; } public: void Push( T &val ) { m_Buffer[m_Tail] = val; if ((m_Tail == m_Head) && (m_ItemCount != 0)) { m_Head = ( (m_Head + 1) % m_MaxSize ); } m_Tail = ( (m_Tail + 1) % m_MaxSize ); if (m_ItemCount != m_MaxSize) m_ItemCount++; } void Pop( T &val ) { val = m_Buffer[m_Head]; m_Head = ( (m_Head + 1) % m_MaxSize ); m_ItemCount--; } bool IsEmpty() { return (m_ItemCount == 0); } ULONG GetCurSize() { return m_ItemCount; } private: ULONG m_Head; ULONG m_Tail; ULONG m_ItemCount; ULONG m_MaxSize; T *m_Buffer; }; #endif
C++
#include "nm_list.h"
C++
#include "nm_exception.h" extern "C" { typedef void (__cdecl *_se_translator_function)(ULONG ExceptionCode, EXCEPTION_POINTERS* pExceptionPointers); _se_translator_function __cdecl set_se_translator(_se_translator_function); } KException::KException(EXCEPTION_POINTERS const &info) { EXCEPTION_RECORD const &exception = *(info.ExceptionRecord); m_IP = exception.ExceptionAddress; m_Status = exception.ExceptionCode; } void KException::Install() { set_se_translator(Translator); } KExceptionAccessViolation::KExceptionAccessViolation(EXCEPTION_POINTERS const &info) : KException(info) { EXCEPTION_RECORD const &exception = *(info.ExceptionRecord); m_Addr = (PVOID) exception.ExceptionInformation[1]; m_IsWrite = (exception.ExceptionInformation[0]==1); } void __cdecl KException::Translator(ULONG Code, EXCEPTION_POINTERS *info) { if (Code != STATUS_ACCESS_VIOLATION) { throw KException(*info); } else { throw KExceptionAccessViolation(*info); } }
C++
/* --------------------------------------------------------------------------- Copyright (c) 2003, Dominik Reichl <dominik.reichl@t-online.de>, Germany. All rights reserved. Distributed under the terms of the GNU General Public License v2. This software is provided 'as is' with no explicit or implied warranties in respect of its properties, including, but not limited to, correctness and/or fitness for purpose. --------------------------------------------------------------------------- */ #include "crc32.h" // CRC-32 polynominal: // X^32+X^26+X^23+X^22+X^16+X^12+X^11+X^10+X^8+X^7+X^5+X^4+X^2+X+1 static unsigned long crc32tab[] = { 0x00000000L, 0x77073096L, 0xEE0E612CL, 0x990951BAL, 0x076DC419L, 0x706AF48FL, 0xE963A535L, 0x9E6495A3L, 0x0EDB8832L, 0x79DCB8A4L, 0xE0D5E91EL, 0x97D2D988L, 0x09B64C2BL, 0x7EB17CBDL, 0xE7B82D07L, 0x90BF1D91L, 0x1DB71064L, 0x6AB020F2L, 0xF3B97148L, 0x84BE41DEL, 0x1ADAD47DL, 0x6DDDE4EBL, 0xF4D4B551L, 0x83D385C7L, 0x136C9856L, 0x646BA8C0L, 0xFD62F97AL, 0x8A65C9ECL, 0x14015C4FL, 0x63066CD9L, 0xFA0F3D63L, 0x8D080DF5L, 0x3B6E20C8L, 0x4C69105EL, 0xD56041E4L, 0xA2677172L, 0x3C03E4D1L, 0x4B04D447L, 0xD20D85FDL, 0xA50AB56BL, 0x35B5A8FAL, 0x42B2986CL, 0xDBBBC9D6L, 0xACBCF940L, 0x32D86CE3L, 0x45DF5C75L, 0xDCD60DCFL, 0xABD13D59L, 0x26D930ACL, 0x51DE003AL, 0xC8D75180L, 0xBFD06116L, 0x21B4F4B5L, 0x56B3C423L, 0xCFBA9599L, 0xB8BDA50FL, 0x2802B89EL, 0x5F058808L, 0xC60CD9B2L, 0xB10BE924L, 0x2F6F7C87L, 0x58684C11L, 0xC1611DABL, 0xB6662D3DL, 0x76DC4190L, 0x01DB7106L, 0x98D220BCL, 0xEFD5102AL, 0x71B18589L, 0x06B6B51FL, 0x9FBFE4A5L, 0xE8B8D433L, 0x7807C9A2L, 0x0F00F934L, 0x9609A88EL, 0xE10E9818L, 0x7F6A0DBBL, 0x086D3D2DL, 0x91646C97L, 0xE6635C01L, 0x6B6B51F4L, 0x1C6C6162L, 0x856530D8L, 0xF262004EL, 0x6C0695EDL, 0x1B01A57BL, 0x8208F4C1L, 0xF50FC457L, 0x65B0D9C6L, 0x12B7E950L, 0x8BBEB8EAL, 0xFCB9887CL, 0x62DD1DDFL, 0x15DA2D49L, 0x8CD37CF3L, 0xFBD44C65L, 0x4DB26158L, 0x3AB551CEL, 0xA3BC0074L, 0xD4BB30E2L, 0x4ADFA541L, 0x3DD895D7L, 0xA4D1C46DL, 0xD3D6F4FBL, 0x4369E96AL, 0x346ED9FCL, 0xAD678846L, 0xDA60B8D0L, 0x44042D73L, 0x33031DE5L, 0xAA0A4C5FL, 0xDD0D7CC9L, 0x5005713CL, 0x270241AAL, 0xBE0B1010L, 0xC90C2086L, 0x5768B525L, 0x206F85B3L, 0xB966D409L, 0xCE61E49FL, 0x5EDEF90EL, 0x29D9C998L, 0xB0D09822L, 0xC7D7A8B4L, 0x59B33D17L, 0x2EB40D81L, 0xB7BD5C3BL, 0xC0BA6CADL, 0xEDB88320L, 0x9ABFB3B6L, 0x03B6E20CL, 0x74B1D29AL, 0xEAD54739L, 0x9DD277AFL, 0x04DB2615L, 0x73DC1683L, 0xE3630B12L, 0x94643B84L, 0x0D6D6A3EL, 0x7A6A5AA8L, 0xE40ECF0BL, 0x9309FF9DL, 0x0A00AE27L, 0x7D079EB1L, 0xF00F9344L, 0x8708A3D2L, 0x1E01F268L, 0x6906C2FEL, 0xF762575DL, 0x806567CBL, 0x196C3671L, 0x6E6B06E7L, 0xFED41B76L, 0x89D32BE0L, 0x10DA7A5AL, 0x67DD4ACCL, 0xF9B9DF6FL, 0x8EBEEFF9L, 0x17B7BE43L, 0x60B08ED5L, 0xD6D6A3E8L, 0xA1D1937EL, 0x38D8C2C4L, 0x4FDFF252L, 0xD1BB67F1L, 0xA6BC5767L, 0x3FB506DDL, 0x48B2364BL, 0xD80D2BDAL, 0xAF0A1B4CL, 0x36034AF6L, 0x41047A60L, 0xDF60EFC3L, 0xA867DF55L, 0x316E8EEFL, 0x4669BE79L, 0xCB61B38CL, 0xBC66831AL, 0x256FD2A0L, 0x5268E236L, 0xCC0C7795L, 0xBB0B4703L, 0x220216B9L, 0x5505262FL, 0xC5BA3BBEL, 0xB2BD0B28L, 0x2BB45A92L, 0x5CB36A04L, 0xC2D7FFA7L, 0xB5D0CF31L, 0x2CD99E8BL, 0x5BDEAE1DL, 0x9B64C2B0L, 0xEC63F226L, 0x756AA39CL, 0x026D930AL, 0x9C0906A9L, 0xEB0E363FL, 0x72076785L, 0x05005713L, 0x95BF4A82L, 0xE2B87A14L, 0x7BB12BAEL, 0x0CB61B38L, 0x92D28E9BL, 0xE5D5BE0DL, 0x7CDCEFB7L, 0x0BDBDF21L, 0x86D3D2D4L, 0xF1D4E242L, 0x68DDB3F8L, 0x1FDA836EL, 0x81BE16CDL, 0xF6B9265BL, 0x6FB077E1L, 0x18B74777L, 0x88085AE6L, 0xFF0F6A70L, 0x66063BCAL, 0x11010B5CL, 0x8F659EFFL, 0xF862AE69L, 0x616BFFD3L, 0x166CCF45L, 0xA00AE278L, 0xD70DD2EEL, 0x4E048354L, 0x3903B3C2L, 0xA7672661L, 0xD06016F7L, 0x4969474DL, 0x3E6E77DBL, 0xAED16A4AL, 0xD9D65ADCL, 0x40DF0B66L, 0x37D83BF0L, 0xA9BCAE53L, 0xDEBB9EC5L, 0x47B2CF7FL, 0x30B5FFE9L, 0xBDBDF21CL, 0xCABAC28AL, 0x53B39330L, 0x24B4A3A6L, 0xBAD03605L, 0xCDD70693L, 0x54DE5729L, 0x23D967BFL, 0xB3667A2EL, 0xC4614AB8L, 0x5D681B02L, 0x2A6F2B94L, 0xB40BBE37L, 0xC30C8EA1L, 0x5A05DF1BL, 0x2D02EF8DL }; void crc32Init(unsigned long *pCrc32) { *pCrc32 = 0xFFFFFFFF; } void crc32Update(unsigned long *pCrc32, unsigned char *pData, unsigned long uSize) { unsigned long i = 0; for(i = 0; i < uSize; i++) *pCrc32 = ((*pCrc32) >> 8) ^ crc32tab[(pData[i]) ^ ((*pCrc32) & 0x000000FF)]; } // Make the final adjustment void crc32Finish(unsigned long *pCrc32) { *pCrc32 = ~(*pCrc32); }
C++
#include "nm_stack.h"
C++
#ifndef __NONAME_LIST_H__ #define __NONAME_LIST_H__ #define NONAME_LIB_USE #include <ntifs.h> #include "nm_mem.h" typedef BOOLEAN (__stdcall *COMPAREPROC)(PVOID Dst, PVOID Src); template <class T> struct _klist_entry { struct _klist_entry<T> *FLink, *BLink; T Value; public: _klist_entry() {FLink = NULL; BLink = NULL;} }; template <class T> class klist { public: BOOLEAN Insert(const T &Val, BOOLEAN InsertHead = TRUE); BOOLEAN Insert(const T &Val, const T &Refer, BOOLEAN InsertAfter); BOOLEAN Delete(const T &Val); void Destroy (); public: ULONG Count() const { return m_Nodes; } T *First(); T *Last(); T *Next(); T *Prev(); T *operator[] (ULONG Index); BOOLEAN Exists(const T& Val); T* Find(const T& Val); T* Find(const T& Dst, COMPAREPROC CompareProc); public: klist() : m_Nodes(0), m_ListHead(0), m_ListTail(0), m_CurNode(0) {}; void Release() { Destroy (); } private: typedef struct _klist_entry<T> KNODE; ULONG m_Nodes; KNODE *m_ListHead, *m_ListTail, *m_CurNode; }; template <class T> BOOLEAN klist<T>::Insert(const T &Val, BOOLEAN InsertHead /*= TRUE*/) { KNODE *node; KNODE *p = m_ListHead; while (p != NULL) { if (p->Value == Val) { return TRUE; } p = p->FLink; } node = new KNODE; node->Value = Val; if (m_ListHead == NULL) { m_ListHead = m_ListTail = node; return TRUE; } if (InsertHead) { node->FLink = m_ListHead; node->FLink->BLink = node; m_ListHead = node; } else { node->BLink = m_ListTail; node->BLink->FLink = node; m_ListTail = node; } m_Nodes++; return TRUE; } template <class T> BOOLEAN klist<T>::Insert(const T &Val, const T &Refer, BOOLEAN InsertAfter) { KNODE *node; KNODE *p = m_ListHead; while (p != NULL) { if (p->Value == Refer) { break; } p = p->FLink; } if (p == NULL) { return FALSE; } node = new KNODE; node->Value = Val; if (InsertAfter) { if (p == m_ListTail) { m_ListTail = node; } node->FLink = p->FLink; node->BLink = p; if (p->FLink != NULL) { p->FLink->BLink = node; } p->FLink = node; } else { if (p == m_ListHead) m_ListHead = node; node->FLink = p; node->BLink = p->BLink; if (p->BLink != NULL) { p->BLink->FLink = node; } p->BLink = node; } m_Nodes++; return TRUE; } template <class T> BOOLEAN klist<T>::Exists( const T& Val ) { KNODE* p = m_ListHead; while( p ) { if( p->Value == Val ) return TRUE; p = p->FLink; } return FALSE; } template <class T> T* klist<T>::Find( const T& Val ) { KNODE* p = m_ListHead; while(p != NULL) { if(p->Value == Val) { return &p->Value; } p = p->FLink; } return 0; } template <class T> T* klist<T>::Find( const T& Dst, COMPAREPROC CompareProc ) { KNODE* p = m_ListHead; while(p != NULL) { if(CompareProc(&Dst, &p->Value)) { return &p->Value; } p = p->FLink; } return 0; } template <class T> BOOLEAN klist<T>::Delete(const T &Val) { KNODE *p = m_ListHead; while (p != NULL) { if (p->Value == Val) { break; } p = p->FLink; } if (p == NULL) { return FALSE; } if (p == m_CurNode) { m_CurNode = p->FLink; } if (p->FLink) { p->FLink->BLink = p->BLink; } if (p->BLink) { p->BLink->FLink = p->FLink; } if (p == m_ListHead) { m_ListHead = p->FLink; } if (p == m_ListTail) { m_ListTail = p->BLink; } delete p; m_Nodes--; return TRUE; } template <class T> void klist<T>::Destroy() { while (m_ListHead != NULL) { KNODE *p = m_ListHead; m_ListHead = p->FLink; delete p; } m_Nodes = 0; m_ListTail = NULL; } template <class T> T* klist<T>::First() { m_CurNode = m_ListHead; return m_ListHead != NULL ? &m_ListHead->Value : NULL; } template <class T> T* klist<T>::Last() { m_CurNode = m_ListTail; return m_ListTail != NULL ? &m_ListTail->Value : NULL; } template <class T> T* klist<T>::Next() { if (m_CurNode != NULL && m_CurNode->FLink != NULL) { m_CurNode = m_CurNode->FLink; return &m_CurNode->Value; } return NULL; } template <class T> T* klist<T>::Prev() { if (m_CurNode != NULL && m_CurNode->BLink != NULL) { m_CurNode = m_CurNode->BLink; return &m_CurNode->Value; } return NULL; } template <class T> T* klist<T>::operator[] (ULONG Index) { ULONG i; KNODE *p = m_ListHead; for (i = 0; p != NULL; i++) { if (i == Index) { return &p->Value; } p = p->FLink; } return NULL; } #endif
C++
#include "nm_event.h" NTSTATUS kevent::Create( EVENT_TYPE Type /*= NotificationEvent*/, BOOLEAN InitialState /*= FALSE*/ ) { NTSTATUS ns; OBJECT_ATTRIBUTES oa; m_Event = 0; InitializeObjectAttributes(&oa, NULL, OBJ_KERNEL_HANDLE, 0, NULL); ns = ZwCreateEvent(&m_Event, EVENT_ALL_ACCESS, &oa, Type, InitialState); return ns; } NTSTATUS kevent::Create( PWCHAR Name, EVENT_TYPE Type /*= NotificationEvent*/, BOOLEAN InitialState /*= FALSE*/ ) { NTSTATUS ns; OBJECT_ATTRIBUTES oa; UNICODE_STRING EventName; m_Event = 0; RtlInitUnicodeString(&EventName, Name); InitializeObjectAttributes(&oa, &EventName, OBJ_KERNEL_HANDLE, 0, NULL); ns = ZwCreateEvent(&m_Event, EVENT_ALL_ACCESS, &oa, Type, InitialState); return ns; } NTSTATUS kevent::Wait( PLARGE_INTEGER Timeout /*= NULL*/, BOOLEAN Alertable /*= FALSE*/ ) { return ZwWaitForSingleObject(m_Event, Alertable, Timeout); } NTSTATUS kevent::Set( PLONG PreviousState ) { return ZwSetEvent(m_Event, PreviousState); }
C++
#include "nm_vector.h"
C++
#ifndef __NONAME_STACK_H__ #define __NONAME_STACK_H__ #define NONAME_LIB_USE #include <ntifs.h> #define DEFAULT_STACK_SIZE 64 template <class T> class kstack { public: kstack(); kstack(ULONG Size); void Release(); ULONG Push(const T &Val); ULONG pop(T &Val); ULONG GetStackPointer() {return m_CurrentSP;} private: T *m_Stack; ULONG m_StackSize; ULONG m_CurrentSP; }; template <class T> kstack<T>::kstack() { m_StackSize = DEFAULT_STACK_SIZE; m_Stack = new T[m_StackSize]; m_CurrentSP = m_StackSize; } template <class T> kstack<T>::kstack (ULONG Size) { m_StackSize = Size; m_Stack = new T[m_StackSize]; m_CurrentSP = m_StackSize; } template <class T> void kstack<T>::Release () { if (m_Stack != NULL) delete[] m_Stack; } template <class T> ULONG kstack<T>::Push(const T &Val) { T *tmp; ULONG i, j; if (m_CurrentSP == 0) { tmp = new T[m_StackSize * 2]; for (i = 0, j = m_StackSize; i < m_StackSize; i++, j++) { tmp[j] = m_Stack[i]; } delete[] m_Stack; m_Stack = tmp; m_CurrentSP = m_StackSize; m_StackSize *= 2; } m_Stack[--m_CurrentSP] = Val; return m_CurrentSP; } template <class T> ULONG kstack<T>::pop (T &val) { if (m_CurrentSP == m_StackSize) { return 0; } val = m_Stack[cur_sp++]; return m_CurrentSP; } #endif
C++
#ifndef __NONAME_STRING_H__ #define __NONAME_STRING_H__ #define NONAME_LIB_USE #include <ntifs.h> #include "nm_mem.h" #include <ntstrsafe.h> class kstringw { public: kstringw(); kstringw(PWCHAR String); kstringw(PUNICODE_STRING UniString); void Release(); PWCHAR Allocate(ULONG size, BOOLEAN SaveData = FALSE); void Append(WCHAR ch); void Attach(PWCHAR String); INT Compare(PWCHAR String, BOOLEAN CaseInsensitive = TRUE); void Copy(PWCHAR String, ULONG Cch = 0); PWCHAR Detach(); void Empty(); INT Find(WCHAR ch, INT Start); INT Find(PWCHAR String, INT Start); INT Format(__in PWCHAR Formats, ...); WCHAR GetAt(__in ULONG idx); INT GetLength() const; PWCHAR GetString() const; PUNICODE_STRING GetUnicodeString(); BOOLEAN IsEmpty() const; void Left(ULONG Cch); void MakeUpper(); void MakeLower(); void Mid(ULONG Start, ULONG Cch); void Right(ULONG Cch); INT Replace(PWCHAR Old, PWCHAR New); INT ReverseFind(WCHAR ch); WCHAR SetAt(ULONG pos, WCHAR ch); operator PWCHAR() const; operator PUNICODE_STRING(); kstringw& operator=(PWCHAR String); kstringw& operator=(PUNICODE_STRING UniString); kstringw& operator=(const kstringw& str); BOOLEAN operator==(kstringw& str2); BOOLEAN operator==(PWCHAR str2); const kstringw& operator+=(PUNICODE_STRING UniString); const kstringw& operator+=(PWCHAR String); const kstringw& operator+=(const kstringw& str); const kstringw& operator+=(WCHAR ch); WCHAR operator[](ULONG idx); private: PWCHAR m_stringw; ULONG m_len; UNICODE_STRING m_UniString; }; #endif
C++
#include "nm_cppcrt.h" #pragma section(".CRT$XCA",long,read) KCRT_FUNCTION xc_a[] = { 0 }; #pragma section(".CRT$XCZ",long,read) KCRT_FUNCTION xc_z[] = { 0 }; #pragma data_seg() #pragma comment(linker, "/merge:.CRT=.data") AtExitCall* AtExitCall::m_ExitList = 0; #ifdef __cplusplus extern "C" { #endif PDRIVER_UNLOAD g_user_driver_unload = 0; void __cdecl crtlib_startup() { KCRT_FUNCTION* crt_func; for(crt_func = xc_a; crt_func < xc_z; crt_func++) { if(*crt_func) { (*crt_func)(); } } } void __cdecl crtlib_finalize() { AtExitCall::do_exit_calls(); } void crt_driver_unload(PDRIVER_OBJECT drvobj) { g_user_driver_unload(drvobj); crtlib_finalize(); } int __cdecl atexit(KCRT_FUNCTION crt_func) { return (new AtExitCall(crt_func) == 0) ? (*crt_func)(), 1 : 0; } NTSTATUS DriverEntry(PDRIVER_OBJECT DriverObject, PUNICODE_STRING RegPath) { NTSTATUS ns; crtlib_startup(); ns = NM_DriverEntry(DriverObject, RegPath); if(!NT_SUCCESS(ns)) { crtlib_finalize(); } g_user_driver_unload = DriverObject->DriverUnload; if(g_user_driver_unload != NULL) { DriverObject->DriverUnload = crt_driver_unload; } return ns; } #ifdef __cplusplus } #endif
C++
#include "nm_inlinehook.h" VOID __stdcall kinlinehook::DpcLock(struct _KDPC *Dpc, PVOID DeferredContext, PVOID SystemArgument1, PVOID SystemArgument2) { __asm cli; InterlockedIncrement(&((PDPCLOCK_CONTEXT)DeferredContext)->Locks); do { __asm pause; } while (!((PDPCLOCK_CONTEXT)DeferredContext)->Release); InterlockedDecrement(&((PDPCLOCK_CONTEXT)DeferredContext)->Locks); __asm sti; } BOOLEAN kinlinehook::AutoHook(PVOID Dst, PVOID Src, PVOID *Proxy) { KIRQL OldIrql; PRKDPC Dpc; DPCLOCK_CONTEXT DpcLockContext; CCHAR Processor; const ULONG MicroSeconds = 1000 * 50; const ULONG Tag = 'nmlk'; UCHAR JmpTmp[5] = {0xe9, 0x90, 0x90, 0x90, 0x90}; ULONG CodeLength = 0; PUCHAR OpCodePtr; ULONG TmpJmpAddr = 0; ULONG TmpJmpOff = 0; // // Prepare hook. // if (Dst == NULL || Src == NULL || Proxy == NULL) { return FALSE; } // // Calculate code length. // while (CodeLength < 5) { CodeLength += SizeOfCode((PUCHAR)Dst + CodeLength, &OpCodePtr); if (*OpCodePtr == 0xe8 || *OpCodePtr == 0xe9) { TmpJmpAddr = (ULONG)(OpCodePtr + 5 + *(ULONG *)(OpCodePtr + 1)); TmpJmpOff = CodeLength - 5; } // // Not support some code. // if (*OpCodePtr == 0xeb) { // // I will not support some opcode, such as 0xeb and so on. // return FALSE; } } // // Prepare proxy routine addr. And calculate jump address. // *Proxy = ExAllocatePoolWithTag(NonPagedPool, CodeLength + 5, Tag); RtlCopyMemory(*Proxy, Dst, CodeLength); *((PUCHAR)*Proxy + CodeLength) = 0xe9; *(ULONG *)((PUCHAR)*Proxy + CodeLength + 1) = (ULONG)Dst - ((ULONG)*Proxy + 5); if (TmpJmpAddr != 0) { *(ULONG *)((PUCHAR)*Proxy + TmpJmpOff + 1) = TmpJmpAddr - ((ULONG)*Proxy + TmpJmpOff + 5); } *(ULONG *)&JmpTmp[1] = (ULONG)Src - ((ULONG)Dst + 5); // // Raise Irql // OldIrql = KeRaiseIrqlToDpcLevel(); if (KeNumberProcessors > 1) { // // Let current thread work on the processor 0. // KeSetAffinityThread(PsGetCurrentThread(), (KAFFINITY)1); if (KeGetCurrentProcessorNumber() != 0) { ExFreePoolWithTag(*Proxy, Tag); *Proxy = NULL; return FALSE; } DpcLockContext.Dpcs = (PKDPC)ExAllocatePoolWithTag(NonPagedPool, (KeNumberProcessors - 1) * sizeof(KDPC), Tag); for (Processor = 1; Processor < KeNumberProcessors; Processor++) { Dpc = &DpcLockContext.Dpcs[Processor]; KeInitializeDpc(Dpc, kinlinehook::DpcLock, &DpcLockContext); KeSetImportanceDpc(Dpc, HighImportance); KeSetTargetProcessorDpc(Dpc, Processor); KeInsertQueueDpc(Dpc, NULL, NULL); } while (DpcLockContext.Locks != (KeNumberProcessors - 1)) { KeStallExecutionProcessor(MicroSeconds); } kinlinehook::WPOFF(); RtlCopyMemory(Dst, JmpTmp, 5); kinlinehook::WPOFF(); DpcLockContext.Release = TRUE; while (DpcLockContext.Locks != 0) { KeStallExecutionProcessor(MicroSeconds); } ExFreePoolWithTag(DpcLockContext.Dpcs, Tag); } else { kinlinehook::WPOFF(); RtlCopyMemory(Dst, JmpTmp, 5); kinlinehook::WPOFF(); } KeLowerIrql(OldIrql); return TRUE; } BOOLEAN kinlinehook::Hook(HOOKPROC HookProc, PVOID Context) { KIRQL OldIrql; PRKDPC Dpc; DPCLOCK_CONTEXT DpcLockContext; CCHAR Processor; const ULONG MicroSeconds = 1000 * 50; const ULONG Tag = 'nmlk'; BOOLEAN Ret = FALSE; // // Raise Irql // OldIrql = KeRaiseIrqlToDpcLevel(); if (KeNumberProcessors > 1) { // // Let current thread work on the processor 0. // KeSetAffinityThread(PsGetCurrentThread(), (KAFFINITY)1); if (KeGetCurrentProcessorNumber() != 0) { return FALSE; } DpcLockContext.Dpcs = (PKDPC)ExAllocatePoolWithTag(NonPagedPool, (KeNumberProcessors - 1) * sizeof(KDPC), Tag); for (Processor = 1; Processor < KeNumberProcessors; Processor++) { Dpc = &DpcLockContext.Dpcs[Processor]; KeInitializeDpc(Dpc, kinlinehook::DpcLock, &DpcLockContext); KeSetImportanceDpc(Dpc, HighImportance); KeSetTargetProcessorDpc(Dpc, Processor); KeInsertQueueDpc(Dpc, NULL, NULL); } while (DpcLockContext.Locks != (KeNumberProcessors - 1)) { KeStallExecutionProcessor(MicroSeconds); } kinlinehook::WPOFF(); if (ARGUMENT_PRESENT(HookProc)) { Ret = HookProc(Context); } kinlinehook::WPOFF(); DpcLockContext.Release = TRUE; while (DpcLockContext.Locks != 0) { KeStallExecutionProcessor(MicroSeconds); } ExFreePoolWithTag(DpcLockContext.Dpcs, Tag); } else { kinlinehook::WPOFF(); if (ARGUMENT_PRESENT(HookProc)) { Ret = HookProc(Context); } kinlinehook::WPOFF(); } KeLowerIrql(OldIrql); return Ret; }
C++
#include "nm_file.h" kfile::kfile() { m_filehandle = 0; m_fileobj = NULL; } void kfile::Release() { Close(); } VOID kfile::Close() { if (m_fileobj != NULL) { ObDereferenceObject(m_fileobj); m_fileobj = NULL; } if (m_filehandle != NULL) { ZwClose(m_filehandle); m_filehandle = 0; } } NTSTATUS kfile::Create( PWCHAR FileName, ULONG CreateDisposition /*= FILE_OPEN*/, ACCESS_MASK DesiredAccess /*= GENERIC_READ*/, ULONG ShareAccess /*= FILE_SHARE_READ */ ) { UNICODE_STRING Name; RtlInitUnicodeString(&Name, FileName); return Create(&Name, CreateDisposition, DesiredAccess, ShareAccess); } NTSTATUS kfile::Create( PUNICODE_STRING FileName, ULONG CreateDisposition /*= FILE_OPEN*/, ACCESS_MASK DesiredAccess /*= GENERIC_READ*/, ULONG ShareAccess /*= FILE_SHARE_READ */ ) { NTSTATUS ns; OBJECT_ATTRIBUTES oa; IO_STATUS_BLOCK Iob; Close(); InitializeObjectAttributes(&oa, FileName, OBJ_KERNEL_HANDLE | OBJ_CASE_INSENSITIVE, 0, NULL); ns = IoCreateFile(&m_filehandle, DesiredAccess | SYNCHRONIZE, &oa, &Iob, NULL, FILE_ATTRIBUTE_NORMAL, ShareAccess, CreateDisposition, FILE_NON_DIRECTORY_FILE | FILE_SYNCHRONOUS_IO_NONALERT, NULL, 0, CreateFileTypeNone, NULL, IO_NO_PARAMETER_CHECKING); if (!NT_SUCCESS(ns)) { return ns; } ns = ObReferenceObjectByHandle(m_filehandle, 0, *IoFileObjectType, KernelMode, (PVOID *)&m_fileobj, NULL); if (!NT_SUCCESS(ns)) { ZwClose(m_filehandle); m_filehandle = 0; } return ns; } NTSTATUS kfile::Create( kstringw& FileName, ULONG CreateDisposition /*= FILE_OPEN*/, ACCESS_MASK DesiredAccess /*= GENERIC_READ*/, ULONG ShareAccess /*= FILE_SHARE_READ */ ) { return Create((PUNICODE_STRING)FileName, CreateDisposition, DesiredAccess, ShareAccess); } NTSTATUS kfile::Delete( BOOLEAN Del /*= TRUE*/ ) { NTSTATUS ns; IO_STATUS_BLOCK Iob; FILE_DISPOSITION_INFORMATION FileDispInfo; FileDispInfo.DeleteFile = Del; ns = ZwSetInformationFile(m_filehandle, &Iob, &FileDispInfo, sizeof(FileDispInfo), FileDispositionInformation); return ns; } NTSTATUS kfile::Flush() { IO_STATUS_BLOCK Iob; PDEVICE_OBJECT deviceObject; PIRP irp; PIO_STACK_LOCATION irpSp; deviceObject = IoGetRelatedDeviceObject( m_fileobj ); // // Allocate and initialize the I/O Request Packet (IRP) for this operation. // irp = IoAllocateIrp( deviceObject->StackSize, FALSE ); if (!irp) { return STATUS_INSUFFICIENT_RESOURCES; } irp->Tail.Overlay.OriginalFileObject = m_fileobj; irp->Tail.Overlay.Thread = PsGetCurrentThread(); irp->RequestorMode = KernelMode; irp->UserEvent = (PKEVENT) NULL; irp->UserIosb = &Iob; irp->Overlay.AsynchronousParameters.UserApcRoutine = (PIO_APC_ROUTINE) NULL; // // Get a pointer to the stack location for the first driver. This is used // to pass the original function codes and parameters. // irpSp = IoGetNextIrpStackLocation( irp ); irpSp->MajorFunction = IRP_MJ_FLUSH_BUFFERS; irpSp->FileObject = m_fileobj; return IoCallDriver(deviceObject, irp); } HANDLE kfile::GetHandle() { return m_filehandle; } NTSTATUS kfile::GetName(kstringw& String) { kstringw Path; NTSTATUS ns; INT Pos; ULONG RightCch; ns = GetPath(Path); if (!NT_SUCCESS(ns)) { return ns; } Pos = Path.ReverseFind(L'\\'); if (Pos == -1) { return STATUS_UNSUCCESSFUL; } Pos++; RightCch = Path.GetLength() - Pos; Path.Right(RightCch); return ns; } PFILE_OBJECT kfile::GetObject() { return m_fileobj; } NTSTATUS kfile::GetPath(kstringw& String) { PUCHAR Buffer; kstringw Path; NTSTATUS ns; Buffer = new UCHAR[1024]; RtlZeroMemory(Buffer, 1024); ns = GetPath((PFILE_NAME_INFORMATION)Buffer, 1024 - sizeof(WCHAR)); if (!NT_SUCCESS(ns)) { delete[] Buffer; return ns; } String.Copy(((PFILE_NAME_INFORMATION)Buffer)->FileName, ((PFILE_NAME_INFORMATION)Buffer)->FileNameLength / sizeof(WCHAR)); delete[] Buffer; return ns; } NTSTATUS kfile::GetPath( PFILE_NAME_INFORMATION NameInfo, ULONG Length) { NTSTATUS ns; IO_STATUS_BLOCK Iob; return ZwQueryInformationFile(m_filehandle, &Iob, &NameInfo, Length, FileNameInformation); } NTSTATUS kfile::GetSize( PLARGE_INTEGER FileSize ) { NTSTATUS ns; IO_STATUS_BLOCK Iob; FILE_STANDARD_INFORMATION StandardInfo; ns = ZwQueryInformationFile(m_filehandle, &Iob, &StandardInfo, sizeof(StandardInfo), FileStandardInformation); if (!NT_SUCCESS(ns)) { return FALSE; } FileSize->QuadPart = StandardInfo.EndOfFile.QuadPart; return TRUE; } NTSTATUS kfile::Read( PVOID Buffer, ULONG Length, PULONG RetLength /*= NULL*/ ) { IO_STATUS_BLOCK Iob; return ZwReadFile(m_filehandle, 0, NULL, NULL, &Iob, Buffer, Length, NULL, NULL); } NTSTATUS kfile::Rename( PFILE_RENAME_INFORMATION RenameInfo, ULONG Length ) { IO_STATUS_BLOCK Iob; return ZwSetInformationFile(m_filehandle, &Iob, RenameInfo, Length, FileRenameInformation); } NTSTATUS kfile::Rename( kstringw& Name, BOOLEAN ReplaceIfExists ) { NTSTATUS ns; PUCHAR Buffer; PFILE_RENAME_INFORMATION RenameInfo; Buffer = new UCHAR[1024]; RtlZeroMemory(Buffer, 1024); RenameInfo = (PFILE_RENAME_INFORMATION)Buffer; RenameInfo->ReplaceIfExists = ReplaceIfExists; RenameInfo->RootDirectory = NULL; RenameInfo->FileNameLength = Name.GetLength() * sizeof(WCHAR); RtlStringCbCopyW(RenameInfo->FileName, 1024 - sizeof(FILE_RENAME_INFORMATION), Name.GetString()); ns = Rename(RenameInfo, 1024); delete[] Buffer; return ns; } BOOLEAN kfile::SetPointer( PLARGE_INTEGER DistanceToMove, ULONG Flag /*= FILE_BEGIN*/, PLARGE_INTEGER NewPointer /*= NULL*/ ) { NTSTATUS Status; IO_STATUS_BLOCK IoStatusBlock; FILE_POSITION_INFORMATION CurrentPosition; FILE_STANDARD_INFORMATION StandardInfo; LARGE_INTEGER Large; Large.QuadPart = DistanceToMove->QuadPart; switch (Flag) { case FILE_BEGIN: CurrentPosition.CurrentByteOffset = Large; break; case FILE_CURRENT: Status = ZwQueryInformationFile(m_filehandle, &IoStatusBlock, &CurrentPosition, sizeof(CurrentPosition), FilePositionInformation); if (!NT_SUCCESS(Status)) { return FALSE; } CurrentPosition.CurrentByteOffset.QuadPart += Large.QuadPart; break; case FILE_END: Status = ZwQueryInformationFile(m_filehandle, &IoStatusBlock, &StandardInfo, sizeof(StandardInfo), FileStandardInformation); if (!NT_SUCCESS(Status)) { return FALSE; } CurrentPosition.CurrentByteOffset.QuadPart = StandardInfo.EndOfFile.QuadPart + Large.QuadPart; break; default: return FALSE; } if (CurrentPosition.CurrentByteOffset.QuadPart < 0) { return FALSE; } Status = ZwSetInformationFile(m_filehandle, &IoStatusBlock, &CurrentPosition, sizeof(CurrentPosition), FilePositionInformation); if (NT_SUCCESS(Status)) { if (ARGUMENT_PRESENT(NewPointer)) { *NewPointer = CurrentPosition.CurrentByteOffset; } return TRUE; } else { return FALSE; } } NTSTATUS kfile::SetEnd(PLARGE_INTEGER EndPos) { IO_STATUS_BLOCK Iob; FILE_END_OF_FILE_INFORMATION FileEnd; FileEnd.EndOfFile.QuadPart = EndPos->QuadPart; return ZwSetInformationFile(m_filehandle, &Iob, &FileEnd, sizeof(FileEnd), FileEndOfFileInformation); } NTSTATUS kfile::Write( PVOID Buffer, ULONG Length, PULONG RetLength /*= NULL*/ ) { IO_STATUS_BLOCK Iob; return ZwWriteFile(m_filehandle, 0, NULL, NULL, &Iob, Buffer, Length, NULL, NULL); }
C++
#include "nm_crique.h"
C++
#ifndef __NONAME_CPPCRT_H__ #define __NONAME_CPPCRT_H__ #define NONAME_LIB_USE #include <ntifs.h> #include "nm_mem.h" extern "C" NTSTATUS __cdecl NM_DriverEntry(PDRIVER_OBJECT DriverObject, PUNICODE_STRING RegPath); typedef void(__cdecl* KCRT_FUNCTION)(); class AtExitCall { public: AtExitCall(KCRT_FUNCTION func) : m_Func(func), m_Next(m_ExitList) { m_ExitList = this; } ~AtExitCall() { m_Func(); m_ExitList = m_Next; } public: static void do_exit_calls() { while(m_ExitList) delete m_ExitList; } private: KCRT_FUNCTION m_Func; AtExitCall* m_Next; static AtExitCall *m_ExitList; }; #endif
C++
#ifndef __NONAME_EVENT_H__ #define __NONAME_EVENT_H__ #define NONAME_LIB_USE #include <ntifs.h> class kevent { public: kevent() : m_Event(0) {} NTSTATUS Create(EVENT_TYPE Type = NotificationEvent, BOOLEAN InitialState = FALSE); NTSTATUS Create(PWCHAR Name, EVENT_TYPE Type = NotificationEvent, BOOLEAN InitialState = FALSE); NTSTATUS Wait(PLARGE_INTEGER Timeout = NULL, BOOLEAN Alertable = FALSE); NTSTATUS Set(PLONG PreviousState); private: HANDLE m_Event; }; #endif
C++
#ifndef __NONAME_WORKTHREAD_H__ #define __NONAME_WORKTHREAD_H__ #define NONAME_LIB_USE #include <ntifs.h> #include "nm_mem.h" typedef VOID (__stdcall *WORKITEMPROC)(PVOID Context); class kworkthread { public: kworkthread(); void Release(); VOID InsertItem(WORKITEMPROC Address, PVOID Context, PRKEVENT *Event); HANDLE GetWorkThreadId() { return m_ClientId.UniqueThread; } protected: static void __stdcall Run(PVOID Context); private: typedef struct _WORK_ITEM { LIST_ENTRY Next; WORKITEMPROC StartAddress; PVOID Context; KEVENT Event; } WORK_ITEM, *PWORK_ITEM; private: klookaside m_Lookaside; KEVENT m_InsertEvent; KEVENT m_SyncEvent; HANDLE m_ThreadHandle; CLIENT_ID m_ClientId; LIST_ENTRY m_ListHeader; KSPIN_LOCK m_Lock; BOOLEAN m_Stop; }; #endif
C++
#ifndef __NONAME_MEMORY_H__ #define __NONAME_MEMORY_H__ #include <ntifs.h> #include "nm_undoc.h" #ifndef NONAME_MEM_TAG #define NONAME_MEM_TAG 'nonm' #endif #ifndef NONAME_MEM_TYPE #define NONAME_MEM_TYPE PagedPool #endif #ifdef NONAME_LIB_USE #define NONAME_INTER_MEM_TYPE NONAME_MEM_TYPE #else #define NONAME_INTER_MEM_TYPE (POOL_TYPE)(NONAME_MEM_TYPE | POOL_QUOTA_FAIL_INSTEAD_OF_RAISE) #endif __forceinline void* __cdecl operator new(size_t size, POOL_TYPE pool_type, ULONG pool_tag) { ASSERT((pool_type < MaxPoolType) && (0 != size)); if(size == 0) { return NULL; } ASSERT(pool_type == NonPagedPool || (KeGetCurrentIrql() < DISPATCH_LEVEL)); return ExAllocatePoolWithQuotaTag(pool_type, (ULONG)size, pool_tag); } __forceinline void* __cdecl operator new(size_t size) { if(size == 0) { return NULL; } ASSERT((KeGetCurrentIrql() < DISPATCH_LEVEL)); return ExAllocatePoolWithQuotaTag(NONAME_INTER_MEM_TYPE, (ULONG)size, NONAME_MEM_TAG); } __forceinline void __cdecl operator delete(void* pointer) { ASSERT(NULL != pointer); if (NULL != pointer) { ExFreePool(pointer); } } __forceinline void __cdecl operator delete[](void* pointer) { ASSERT(NULL != pointer); if (NULL != pointer) { ExFreePool(pointer); } } __forceinline void DisableMaskableInterrupt() { KIRQL Irql = KeRaiseIrqlToSynchLevel(); UCHAR i; for (i = 0; i < KeNumberProcessors; i++) { KeSetAffinityThread(KeGetCurrentThread(), 1 << i); __asm cli } KeLowerIrql(Irql); } __forceinline void EnableMaskableInterrupt() { KIRQL Irql = KeRaiseIrqlToSynchLevel(); UCHAR i; for (i = 0; i < KeNumberProcessors; i++) { KeSetAffinityThread(KeGetCurrentThread(), 1 << i); __asm sti } KeLowerIrql(Irql); } __forceinline void EnableWriteProtect() { __asm { mov eax, cr0 or eax, 10000h mov cr0, eax } EnableMaskableInterrupt(); } __forceinline void DisableWriteProtect() { DisableMaskableInterrupt(); __asm { mov eax, cr0 and eax, 0fffeffffh mov cr0, eax } } class kwps { public: kwps() {} static void Enable() { EnableWriteProtect(); kwps::m_Switch = TRUE; } static void Disable() { DisableWriteProtect(); kwps::m_Switch = FALSE; } static BOOLEAN GetSwitch() { return m_Switch; } private: static BOOLEAN m_Switch; }; __forceinline void KSleep(INT ms) { LARGE_INTEGER timeOut; timeOut.QuadPart = -10000 * ms; KeDelayExecutionThread( UserMode, false, &timeOut ); } __forceinline BOOLEAN KIsMemVaild(PVOID Addr, ULONG Length) { ULONG Pages; ULONG i; ULONG Va; Pages = ADDRESS_AND_SIZE_TO_SPAN_PAGES(Addr, Length); if (Pages > 1000) { return FALSE; } Va = (ULONG)Addr & 0xfffff000; for (i = 0; i < Pages; i++) { if (!MmIsAddressValid((PVOID)Va)) { return FALSE; } Va += 0x1000; } return TRUE; } class klookaside { #define NM_LOOKASIDE_TAG 'nmls' public: klookaside(ULONG Size, ULONG Tag = NM_LOOKASIDE_TAG, POOL_TYPE PoolType = PagedPool); void Release(); PVOID Allocate(); VOID Free(PVOID Buffer); private: PPAGED_LOOKASIDE_LIST m_PagedLookasideList; PNPAGED_LOOKASIDE_LIST m_NPagedLookasideList; POOL_TYPE m_PoolType; }; #endif
C++
#include "nm_getproc.h" PVOID kgetproc::FindExportedRoutineByName(PVOID DllBase, PANSI_STRING AnsiImageRoutineName ) { USHORT OrdinalNumber; PULONG NameTableBase; PUSHORT NameOrdinalTableBase; PULONG Addr; LONG High; LONG Low; LONG Middle; LONG Result; ULONG ExportSize; PVOID FunctionAddress; PIMAGE_EXPORT_DIRECTORY ExportDirectory; ExportDirectory = (PIMAGE_EXPORT_DIRECTORY) RtlImageDirectoryEntryToData ( DllBase, TRUE, IMAGE_DIRECTORY_ENTRY_EXPORT, &ExportSize); if (ExportDirectory == NULL) { return NULL; } NameTableBase = (PULONG)((PCHAR)DllBase + (ULONG)ExportDirectory->AddressOfNames); NameOrdinalTableBase = (PUSHORT)((PCHAR)DllBase + (ULONG)ExportDirectory->AddressOfNameOrdinals); Low = 0; Middle = 0; High = ExportDirectory->NumberOfNames - 1; while (High >= Low) { Middle = (Low + High) >> 1; Result = strcmp (AnsiImageRoutineName->Buffer, (PCHAR)DllBase + NameTableBase[Middle]); if (Result < 0) { High = Middle - 1; } else if (Result > 0) { Low = Middle + 1; } else { break; } } if (High < Low) { return NULL; } OrdinalNumber = NameOrdinalTableBase[Middle]; if ((ULONG)OrdinalNumber >= ExportDirectory->NumberOfFunctions) { return NULL; } Addr = (PULONG)((PCHAR)DllBase + (ULONG)ExportDirectory->AddressOfFunctions); FunctionAddress = (PVOID)((PCHAR)DllBase + Addr[OrdinalNumber]); return FunctionAddress; } PVOID kgetproc::GetSystemRoutineAddress(PUNICODE_STRING ModuleName, PUNICODE_STRING SystemRoutineName) { NTSTATUS Status; PKLDR_DATA_TABLE_ENTRY DataTableEntry; ANSI_STRING AnsiString; PLIST_ENTRY NextEntry; PVOID FunctionAddress; const LARGE_INTEGER ShortTime = {(ULONG)(-10 * 1000 * 10), -1}; FunctionAddress = NULL; do { Status = RtlUnicodeStringToAnsiString (&AnsiString, SystemRoutineName, TRUE); if (NT_SUCCESS (Status)) { break; } KeDelayExecutionThread (KernelMode, FALSE, (PLARGE_INTEGER)&ShortTime); } while (TRUE); NextEntry = m_LoadedModuleList->Flink; while (NextEntry != m_LoadedModuleList) { DataTableEntry = CONTAINING_RECORD(NextEntry, KLDR_DATA_TABLE_ENTRY, InLoadOrderLinks); if (DataTableEntry->BaseDllName.Buffer == NULL) { NextEntry = NextEntry->Flink; continue; } if (RtlEqualUnicodeString (ModuleName, &DataTableEntry->BaseDllName, TRUE)) { FunctionAddress = FindExportedRoutineByName (DataTableEntry->DllBase, &AnsiString); break; } NextEntry = NextEntry->Flink; } RtlFreeAnsiString (&AnsiString); return FunctionAddress; }
C++
#ifndef __NONAME_HASHTABLE_H__ #define __NONAME_HASHTABLE_H__ #define NONAME_LIB_USE #include <ntifs.h> #include "nm_mem.h" #include "algo/crc32.h" #define HASH_DEFAULT_CAP 128 template< class VAL > class khashtable { public: BOOLEAN Init( ULONG Size = HASH_DEFAULT_CAP ); BOOLEAN Resize( ULONG Size = HASH_DEFAULT_CAP ); BOOLEAN Insert( PVOID KeyBuffer, ULONG Length, const VAL& Value ); BOOLEAN Remove( PVOID KeyBuffer, ULONG Length ); VAL* Find( PVOID KeyBuffer, ULONG Length ); void Clear(); ULONG GetHashTableSize() { return m_HashSize; } ULONG GetHashedCount() { return m_HashedCount; } ULONG GetConflictCount() { return m_ConflictCount; } ULONG GetMaxConflictDepth() { return m_MaxConflictDepth; } khashtable() { Init( HASH_DEFAULT_CAP ); } void Release() { Clear(); } private: ULONG DoHash( PVOID KeyBuffer, ULONG Length ); struct _HASH_NODE { /* is Value set ? */ BOOLEAN ValSet; /* conflict link */ struct _HASH_NODE* Next; /* conflicts may exist, so _Key is also needed */ PVOID Key; VAL Value; public: _HASH_NODE() : ValSet( FALSE ), Next( NULL ), Key(NULL) {} }; typedef struct _HASH_NODE HASH_NODE; ULONG m_HashSize, m_HashedCount; ULONG m_ConflictCount, m_MaxConflictDepth; HASH_NODE m_HashTable; }; template< class VAL > ULONG khashtable<VAL>::DoHash( PVOID KeyBuffer, ULONG Length ) { ULONG crc32; crc32Init(&crc32); crc32Update(&crc32, KeyBuffer, Length); crc32Finish(&crc32); return crc32 % m_HashSize; } template< class VAL > BOOLEAN khashtable< VAL >::Init( ULONG Size /*= HASH_DEFAULT_CAP*/ ) { if( m_HashTable != NULL ) { return resize( Size ); } m_HashTable = new HASH_NODE[ Size ]; m_ConflictCount = 0; m_MaxConflictDepth = 0; m_HashSize = Size; m_HashedCount = 0, return TRUE; } template< class VAL > BOOLEAN khashtable< VAL >::Resize( ULONG Size /*= HASH_DEFAULT_CAP*/ ) { if( Size == m_HashSize ) { return TRUE; } if( m_HashTable != NULL ) { Clear(); m_HashTable = NULL; } return Init( Size ); } template< class VAL > BOOLEAN khashtable< VAL >::Insert( PVOID KeyBuffer, ULONG Length, const VAL& Value ) { ULONG key; HASH_NODE *node; ULONG depth; HASH_NODE *pn; if( m_HashTable == NULL ) { return FALSE; } key = DoHash( KeyBuffer, Length ); if( !m_HashTable[ key ].ValSet ) { m_HashTable[ key ].ValSet = TRUE; m_HashTable[ key ].Key = new UCHAR[Length]; memcpy(m_HashTable[ key ].Key, KeyBuffer, Length); m_HashTable[ key ].Value = Value; return ++m_HashedCount, TRUE; } else if( memcmp(m_HashTable[ key ].Key, KeyBuffer, Length) == 0) { return TRUE; } /* walk thru the conflict list */ node = &m_HashTable[ key ]; for(depth = 1 ; node->Next != NULL; depth++ ) { if( memcmp(node->Key, KeyBuffer, Length) == 0 ) { return TRUE; } node = node->Next; } if( memcmp(node->Key, KeyBuffer, Length) == 0 ) { return TRUE; } /* create conflict node */ pn = new HASH_NODE; pn->Key = new UCHAR[Length]; memcpy(pn->Key, KeyBuffer, Length); pn->Value = Value; pn->ValSet = TRUE; node->Next = pn; #ifndef max # define max(a,b) (((a) > (b)) ? (a) : (b)) #endif m_ConflictCount++; m_HashedCount++; m_MaxConflictDepth = max( m_MaxConflictDepth, depth ); return TRUE; } template< class VAL > BOOLEAN khashtable< VAL >::Remove( PVOID KeyBuffer, ULONG Length ) { ULONG key; HASH_NODE *tmp; HASH_NODE *node; HASH_NODE *nxt; if( m_HashTable == NULL ) { return FALSE; } key = DoHash( KeyBuffer, Length ); if( m_HashTable[ key ].ValSet && memcmp(m_HashTable[ key ].Key, KeyBuffer, Length) == 0 ) { m_HashedCount--; if (m_HashTable[ key ].Key != NULL) { delete m_HashTable[ key ].Key; m_HashTable[ key ].Key = NULL; } tmp = m_HashTable[ key ].Next; if( tmp == NULL) { m_HashTable[ key ].Value = 0; /* this may destruct some instance */ m_HashTable[ key ].ValSet = FALSE; return TRUE; } m_HashTable[ key ].Key = tmp->Key; m_HashTable[ key ].Value = tmp->Value; m_HashTable[ key ].Next = tmp->Next; delete tmp; return TRUE; } node = &m_HashTable[ key ]; while( node->Next != NULL ) { nxt = node->Next; if( nxt->ValSet && memcmp(nxt->Key, KeyBuffer, Length) == 0 ) { m_HashedCount--; node->Next = nxt->Next; if (nxt->Key != NULL) { delete nxt->Key; } delete nxt; return TRUE; } node = nxt; } return FALSE; } template< class VAL > VAL* khashtable< VAL >::Find( PVOID KeyBuffer, ULONG Length ) { ULONG key; HASH_NODE *node ; if( m_HashTable == NULL ) { return FALSE; } key = DoHash( KeyBuffer, Length ); node = &m_HashTable[ key ]; do { if( node->ValSet && memcmp(node->Key, KeyBuffer, Length) == 0 ) { return &node->Value; } node = node->Next; } while( node != NULL ); return NULL; } template< class VAL > void khashtable< VAL >::Clear() { ULONG i; HASH_NODE *node; HASH_NODE* tmp; if( m_HashTable == NULL ) return ; for( i = 0; i < m_HashSize; i++ ) { if (m_HashTable[i].ValSet && m_HashTable[i].Key != NULL) { delete m_HashTable[i].Key; m_HashTable[i].Key = NULL; } m_HashTable[i].ValSet = FALSE; node = m_HashTable[i].Next; while( node != NULL) { tmp = node; node = node->Next; if (tmp->ValSet && tmp->Key != NULL) { delete tmp->Key; } delete tmp; } } delete[] m_HashTable; m_HashTable = NULL; m_HashedCount = 0; m_ConflictCount = 0; m_MaxConflictDepth = 0; } #endif
C++
#ifndef __NONAME_FILE_H__ #define __NONAME_FILE_H__ #define NONAME_LIB_USE #include <Ntifs.h> #include "nm_mem.h" #include "nm_string.h" #define FILE_BEGIN 0 #define FILE_CURRENT 1 #define FILE_END 2 class kfile { public: kfile(); void Release(); VOID Close(); NTSTATUS Create( kstringw& FileName, ULONG CreateDisposition = FILE_OPEN, ACCESS_MASK DesiredAccess = GENERIC_READ, ULONG ShareAccess = FILE_SHARE_READ ); NTSTATUS Create( PWCHAR FileName, ULONG CreateDisposition = FILE_OPEN, ACCESS_MASK DesiredAccess = GENERIC_READ, ULONG ShareAccess = FILE_SHARE_READ ); NTSTATUS Create( PUNICODE_STRING FileName, ULONG CreateDisposition = FILE_OPEN, ACCESS_MASK DesiredAccess = GENERIC_READ, ULONG ShareAccess = FILE_SHARE_READ ); NTSTATUS Delete(BOOLEAN Del = TRUE); NTSTATUS Flush(); HANDLE GetHandle(); NTSTATUS GetName(kstringw& String); PFILE_OBJECT GetObject(); NTSTATUS GetPath(kstringw& String); NTSTATUS GetPath(PFILE_NAME_INFORMATION NameInfo, ULONG Length); NTSTATUS GetSize(PLARGE_INTEGER FileSize); NTSTATUS Read(PVOID Buffer, ULONG Length, PULONG RetLength = NULL); NTSTATUS Rename(PFILE_RENAME_INFORMATION RenameInfo, ULONG Length); NTSTATUS Rename(kstringw& Name, BOOLEAN ReplaceIfExists = FALSE); BOOLEAN SetPointer(PLARGE_INTEGER DistanceToMove, ULONG Flag = FILE_BEGIN, PLARGE_INTEGER NewPointer = NULL); NTSTATUS SetEnd(PLARGE_INTEGER EndPos); NTSTATUS Write(PVOID Buffer, ULONG Length, PULONG RetLength = NULL); private: HANDLE m_filehandle; PFILE_OBJECT m_fileobj; }; #endif
C++
#include "nm_dir.h" kdirectory::kdirectory() { m_filehandle = 0; m_fileobj = NULL; } void kdirectory::Release() { Close(); } VOID kdirectory::Close() { if (m_fileobj != NULL) { ObDereferenceObject(m_fileobj); m_fileobj = NULL; } if (m_filehandle != NULL) { ZwClose(m_filehandle); m_filehandle = 0; } } NTSTATUS kdirectory::Create( PWCHAR FileName, ULONG CreateDisposition /*= FILE_OPEN*/, ACCESS_MASK DesiredAccess /*= GENERIC_READ*/, ULONG ShareAccess /*= FILE_SHARE_READ */ ) { UNICODE_STRING Name; RtlInitUnicodeString(&Name, FileName); return Create(&Name, CreateDisposition, DesiredAccess, ShareAccess); } NTSTATUS kdirectory::Create( PUNICODE_STRING FileName, ULONG CreateDisposition /*= FILE_OPEN*/, ACCESS_MASK DesiredAccess /*= GENERIC_READ*/, ULONG ShareAccess /*= FILE_SHARE_READ */ ) { NTSTATUS ns; OBJECT_ATTRIBUTES oa; IO_STATUS_BLOCK Iob; Close(); InitializeObjectAttributes(&oa, FileName, OBJ_KERNEL_HANDLE | OBJ_CASE_INSENSITIVE, 0, NULL); ns = IoCreateFile(&m_filehandle, DesiredAccess | SYNCHRONIZE, &oa, &Iob, NULL, FILE_ATTRIBUTE_NORMAL, ShareAccess, CreateDisposition, FILE_DIRECTORY_FILE | FILE_SYNCHRONOUS_IO_NONALERT, NULL, 0, CreateFileTypeNone, NULL, IO_NO_PARAMETER_CHECKING); if (!NT_SUCCESS(ns)) { return ns; } ns = ObReferenceObjectByHandle(m_filehandle, 0, *IoFileObjectType, KernelMode, (PVOID *)&m_fileobj, NULL); if (!NT_SUCCESS(ns)) { ZwClose(m_filehandle); m_filehandle = 0; } return ns; } NTSTATUS kdirectory::Create( kstringw& FileName, ULONG CreateDisposition /*= FILE_OPEN*/, ACCESS_MASK DesiredAccess /*= GENERIC_READ*/, ULONG ShareAccess /*= FILE_SHARE_READ */ ) { return Create((PUNICODE_STRING)FileName, CreateDisposition, DesiredAccess, ShareAccess); } NTSTATUS kdirectory::Delete( BOOLEAN Del /*= TRUE*/ ) { NTSTATUS ns; IO_STATUS_BLOCK Iob; FILE_DISPOSITION_INFORMATION FileDispInfo; FileDispInfo.DeleteFile = Del; ns = ZwSetInformationFile(m_filehandle, &Iob, &FileDispInfo, sizeof(FileDispInfo), FileDispositionInformation); return ns; } HANDLE kdirectory::GetHandle() { return m_filehandle; } NTSTATUS kdirectory::GetName(kstringw& String) { kstringw Path; NTSTATUS ns; INT Pos; ULONG RightCch; ns = GetPath(Path); if (!NT_SUCCESS(ns)) { return ns; } Pos = Path.ReverseFind(L'\\'); if (Pos == -1) { return STATUS_UNSUCCESSFUL; } Pos++; RightCch = Path.GetLength() - Pos; Path.Right(RightCch); return ns; } PFILE_OBJECT kdirectory::GetObject() { return m_fileobj; } NTSTATUS kdirectory::GetPath(kstringw& String) { PUCHAR Buffer; kstringw Path; NTSTATUS ns; Buffer = new UCHAR[1024]; RtlZeroMemory(Buffer, 1024); ns = GetPath((PFILE_NAME_INFORMATION)Buffer, 1024 - sizeof(WCHAR)); if (!NT_SUCCESS(ns)) { delete[] Buffer; return ns; } String.Copy(((PFILE_NAME_INFORMATION)Buffer)->FileName, ((PFILE_NAME_INFORMATION)Buffer)->FileNameLength / sizeof(WCHAR)); delete[] Buffer; return ns; } NTSTATUS kdirectory::GetPath( PFILE_NAME_INFORMATION NameInfo, ULONG Length) { NTSTATUS ns; IO_STATUS_BLOCK Iob; return ZwQueryInformationFile(m_filehandle, &Iob, &NameInfo, Length, FileNameInformation); } NTSTATUS kdirectory::MakeDir( PUNICODE_STRING FileName ) { NTSTATUS ns; PWCHAR p = FileName->Buffer; USHORT i = 0; PWCHAR q; kstringw dir; ns = Create(FileName, FILE_OPEN_IF, GENERIC_READ | GENERIC_WRITE); if (NT_SUCCESS(ns)) { Close(); return ns; } q = dir.Allocate(FileName->Length / sizeof(WCHAR)); while (i < FileName->Length) { if (L'\\' == *p) { if (L':' != *(p - 1)) { Create(dir.GetUnicodeString(), FILE_OPEN_IF, GENERIC_READ | GENERIC_WRITE); } } *q++ = *p++; *q = L'\0'; i += 2; } ns = Create(dir.GetUnicodeString(), FILE_OPEN_IF, GENERIC_READ | GENERIC_WRITE); Close(); return ns; } NTSTATUS kdirectory::MakeDir( kstringw& FileName ) { return MakeDir(FileName.GetUnicodeString()); } NTSTATUS kdirectory::MakeDir( PWCHAR FileName ) { UNICODE_STRING UniString; RtlInitUnicodeString(&UniString, FileName); return MakeDir(&UniString); } NTSTATUS kdirectory::Rename( PFILE_RENAME_INFORMATION RenameInfo, ULONG Length ) { IO_STATUS_BLOCK Iob; return ZwSetInformationFile(m_filehandle, &Iob, RenameInfo, Length, FileRenameInformation); } NTSTATUS kdirectory::Rename( kstringw& Name, BOOLEAN ReplaceIfExists ) { NTSTATUS ns; PUCHAR Buffer; PFILE_RENAME_INFORMATION RenameInfo; Buffer = new UCHAR[1024]; RtlZeroMemory(Buffer, 1024); RenameInfo = (PFILE_RENAME_INFORMATION)Buffer; RenameInfo->ReplaceIfExists = ReplaceIfExists; RenameInfo->RootDirectory = NULL; RenameInfo->FileNameLength = Name.GetLength() * sizeof(WCHAR); RtlStringCbCopyW(RenameInfo->FileName, 1024 - sizeof(FILE_RENAME_INFORMATION), Name.GetString()); ns = Rename(RenameInfo, 1024); delete[] Buffer; return ns; } NTSTATUS kdirectory::QueryDir( PVOID FileInformation, ULONG Length, PUNICODE_STRING FileName /*= NULL*/, FILE_INFORMATION_CLASS FileInformationClass /*= FileBothDirectoryInformation*/, BOOLEAN ReturnSingleEntry /*= TRUE */ ) { IO_STATUS_BLOCK Iob; return ZwQueryDirectoryFile(m_filehandle, NULL, NULL, NULL, &Iob, FileInformation, Length, FileInformationClass, ReturnSingleEntry, FileName, FALSE); } BOOLEAN kdirectory::IsDirectory( kstringw& String ) { return kdirectory::IsDirectory(String.GetUnicodeString()); } BOOLEAN kdirectory::IsDirectory( PUNICODE_STRING UniString ) { NTSTATUS ns; OBJECT_ATTRIBUTES oa; IO_STATUS_BLOCK Iob; HANDLE FileHandle; FILE_STANDARD_INFORMATION FileInfo; InitializeObjectAttributes(&oa, UniString, OBJ_KERNEL_HANDLE | OBJ_CASE_INSENSITIVE, 0, NULL); ns = IoCreateFile(&FileHandle, GENERIC_READ, &oa, &Iob, NULL, FILE_ATTRIBUTE_NORMAL, FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, FILE_OPEN, FILE_SYNCHRONOUS_IO_NONALERT, NULL, 0, CreateFileTypeNone, NULL, IO_NO_PARAMETER_CHECKING); if (!NT_SUCCESS(ns)) { return FALSE; } ns = ZwQueryInformationFile(FileHandle, &Iob, &FileInfo, sizeof(FileInfo), FileStandardInformation); ZwClose(FileHandle); if (!NT_SUCCESS(ns)) { return FALSE; } return FileInfo.Directory; } BOOLEAN kdirectory::IsDirectory( PWCHAR String ) { UNICODE_STRING UniString; RtlInitUnicodeString(&UniString, String); return kdirectory::IsDirectory(&UniString); }
C++
#ifndef __NONAME_INLINE_HOOK_H__ #define __NONAME_INLINE_HOOK_H__ #define NONAME_LIB_USE #include <ntifs.h> #include "nm_mem.h" #include "disasm/LDasm.h" typedef BOOLEAN (__stdcall *HOOKPROC)(PVOID Context); typedef struct _DPCLOCK_CONTEXT { PKDPC Dpcs; LONG Locks; BOOLEAN Release; _DPCLOCK_CONTEXT() : Dpcs(NULL), Locks(0), Release(FALSE) {} } DPCLOCK_CONTEXT, *PDPCLOCK_CONTEXT; class kinlinehook { public: kinlinehook() {} static BOOLEAN AutoHook(PVOID Dst, PVOID Src, PVOID *Proxy); static BOOLEAN Hook(HOOKPROC HookProc, PVOID Context); static VOID __stdcall DpcLock(struct _KDPC *Dpc, PVOID DeferredContext, PVOID SystemArgument1, PVOID SystemArgument2); static VOID WPOFF(); static VOID WPON(); }; __forceinline VOID kinlinehook::WPOFF() { __asm { cli mov eax, cr0 and eax, 0fffeffffh mov cr0, eax } } __forceinline VOID kinlinehook::WPON() { __asm { mov eax, cr0 or eax, 10000h mov cr0, eax sti } } #endif
C++
#ifndef __NONAME_VECTOR_H__ #define __NONAME_VECTOR_H__ #define NONAME_LIB_USE #include <ntifs.h> #include "nm_mem.h" #define DEFAULT_INIT_VECTOR 32 template <class T> class kvector { public: kvector(); kvector(ULONG Size, ULONG Step); void Release(); ULONG Size() { return m_ItemCount; } T& operator[] (ULONG Index); private: T *m_Vector; ULONG m_ItemCount; ULONG m_Step; }; template <class T> kvector<T>::kvector() { m_Step = DEFAULT_INIT_VECTOR; m_ItemCount = DEFAULT_INIT_VECTOR; m_Vector = new T[m_ItemCount]; } template <class T> T& kvector<T>::operator[]( ULONG Index ) { ULONG Count; T *tmp; ULONG i; if (Index >= m_ItemCount) { Count = m_ItemCount; while (Index >= Count) { Count += m_Step; } tmp = new T[Count]; for (i = 0; i < m_ItemCount; i++){ tmp[i] = m_Vector[i]; } m_ItemCount = Count; delete[] m_Vector; m_Vector = tmp; } return m_Vector[Index]; } template <class T> void kvector<T>::Release() { delete[] m_Vector; } template <class T> kvector<T>::kvector( ULONG Size, ULONG Step ) { m_Step = Step; m_ItemCount = Size; m_Vector = new T[m_ItemCount]; } #endif
C++
#include "nm_string.h" kstringw::kstringw() { m_stringw = NULL; m_len = 0; } kstringw::kstringw( PWCHAR String ) { ULONG Size; Size = wcslen(String); m_stringw = Allocate(Size, FALSE); RtlStringCchCopyW(m_stringw, Size, String); m_len = Size; } kstringw::kstringw( PUNICODE_STRING UniString ) { ULONG Size; Size = (ULONG)UniString->MaximumLength; m_stringw = Allocate(Size, FALSE); RtlStringCchCopyNW(m_stringw, Size, UniString->Buffer, UniString->Length / sizeof(WCHAR)); m_len = Size; } void kstringw::Release() { if (m_stringw != NULL) { delete[] m_stringw; } m_len = 0; } PWCHAR kstringw::Allocate(ULONG Size, BOOLEAN SaveData) { PWCHAR buf; if (0 == Size) { Size = 1; } if (m_len < Size) { m_len = Size; buf = new WCHAR[m_len + 1]; RtlZeroMemory(m_stringw, (m_len + 1) * sizeof(WCHAR)); if (SaveData) { if (NULL != m_stringw) { RtlStringCchCopyW(buf, Size, m_stringw); } } if (NULL != m_stringw) { delete[] m_stringw; } m_stringw = buf; } if (!SaveData) { RtlZeroMemory(m_stringw, (m_len + 1) * sizeof(WCHAR)); } return m_stringw; } void kstringw::Append( WCHAR ch ) { DWORD len; PWCHAR buf; len = wcslen(m_stringw); buf = Allocate(len + 1, TRUE); buf[len] = ch; buf[len + 1] = L'\0'; } void kstringw::Attach( PWCHAR String ) { if (NULL != m_stringw) { delete[] m_stringw; } m_stringw = String; m_len = wcslen(String); } int kstringw::Compare( PWCHAR String, BOOLEAN CaseInsensitive ) { if (CaseInsensitive) { return _wcsicmp(m_stringw, String); } else { return wcscmp(m_stringw, String); } } void kstringw::Copy( PWCHAR String, ULONG Cch ) { ULONG len; PWCHAR p; if (Cch == 0) { len = wcslen(String); } else { len = Cch; } p = Allocate(len, FALSE); if (0 == m_len) { Empty(); } else { RtlStringCchCopyNW(p, len, String, len); } } PWCHAR kstringw::Detach() { PWCHAR ret = m_stringw; m_stringw = NULL; m_len = 0; return ret; } void kstringw::Empty() { if (NULL == m_stringw) { m_stringw = Allocate(1, FALSE); } m_stringw[0] = L'\0'; } INT kstringw::Find( WCHAR ch, INT Start ) { PWCHAR p; if (NULL == m_stringw || (INT)wcslen(m_stringw) < Start) { return -1; } p = wcschr(m_stringw + Start, ch); if (NULL == p) { return -1; } return (INT)(p - m_stringw); } INT kstringw::Find( PWCHAR String, INT Start ) { PWCHAR p; if (NULL == m_stringw || (INT)wcslen(m_stringw) < Start) { return -1; } p = wcsstr(m_stringw + Start, String); if (NULL == p) { return -1; } return (INT)(p - m_stringw); } INT kstringw::Format( __in PWCHAR Formats, ... ) { WCHAR tmp[1024]; va_list argList; INT ret; va_start(argList, Formats); ret = RtlStringCbPrintfW(tmp, 1024, Formats, argList); va_end(argList); Copy(tmp); return ret; } WCHAR kstringw::GetAt( __in ULONG idx ) { if (idx > (wcslen(m_stringw) - 1)) { idx = wcslen(m_stringw); } return m_stringw[idx]; } INT kstringw::GetLength() const { return wcslen(m_stringw); } PWCHAR kstringw::GetString() const { return m_stringw; } PUNICODE_STRING kstringw::GetUnicodeString() { RtlInitUnicodeString(&m_UniString, m_stringw); return &m_UniString; } BOOLEAN kstringw::IsEmpty() const { return (NULL == m_stringw || L'\0' == *m_stringw); } void kstringw::Left( ULONG Cch ) { if (Cch < wcslen(m_stringw)) { m_stringw[Cch] = L'\0'; } } void kstringw::Mid( ULONG Start, ULONG Cch ) { PWCHAR buf; buf = new WCHAR[Cch + 1]; RtlZeroMemory(buf, (Cch + 1) * sizeof(WCHAR)); RtlStringCchCopyNW(buf, Cch, m_stringw + Start, Cch); Copy(buf); delete[] buf; } void kstringw::MakeUpper() { _wcsupr(m_stringw); } void kstringw::MakeLower() { _wcslwr(m_stringw); } void kstringw::Right( ULONG Cch ) { PWCHAR buf; buf = new WCHAR[Cch + 1]; RtlZeroMemory(buf, (Cch + 1) * sizeof(WCHAR)); RtlStringCchCopyNW(buf, Cch, m_stringw + wcslen(m_stringw) - Cch, Cch); Copy(buf); delete[] buf; } INT kstringw::Replace( PWCHAR Old, PWCHAR New ) { ULONG StrLen = wcslen(m_stringw); ULONG OldLen = wcslen(Old); ULONG NewLen = wcslen(New); INT cnt = 0; PWCHAR Start = m_stringw; PWCHAR End = m_stringw + OldLen; PWCHAR Target; PWCHAR NewBuf; PWCHAR dst; PWCHAR src; PWCHAR p = NULL; INT CchCopy = 0; INT tmp; INT i; if (0 == StrLen) { return 0; } if (0 == OldLen) { return 0; } while (Start < End) { while ((Target = wcsstr(Start, Old)) != NULL) { cnt++; Start = Target + OldLen; } if (NULL == Target) { break; } } if (0 == cnt) { return 0; } StrLen += (NewLen - OldLen) * cnt; NewBuf = new WCHAR[StrLen]; RtlZeroMemory(NewBuf, StrLen * sizeof(WCHAR)); dst = NewBuf; src = m_stringw; tmp = StrLen; for (i = 0; i < cnt; i++) { p = wcsstr(src, Old); CchCopy = p - src; RtlStringCchCopyNW(dst, tmp, src, CchCopy); dst += CchCopy; tmp -= CchCopy; src = p; RtlStringCchCopyNW(dst, tmp, New, NewLen); dst += NewLen; tmp -= NewLen; src += OldLen; } RtlStringCchCopyW(dst, tmp, src); delete[] m_stringw; m_stringw = NewBuf; m_len = StrLen; return cnt; } INT kstringw::ReverseFind( WCHAR ch ) { PWCHAR p = wcsrchr(m_stringw, ch); if (NULL == p) return -1; return p - m_stringw; } WCHAR kstringw::SetAt( ULONG pos, WCHAR ch ) { ULONG len; WCHAR ret; if (NULL == m_stringw || L'\0' == *m_stringw) return -1; len = wcslen(m_stringw); if (pos >= len) { pos = len - 1; } ret = m_stringw[pos]; m_stringw[pos] = ch; return ret; } kstringw::operator PWCHAR() const { return m_stringw; } kstringw::operator PUNICODE_STRING() { RtlInitUnicodeString(&m_UniString, m_stringw); return &m_UniString; } kstringw& kstringw::operator=( PWCHAR String ) { Copy(String); return *this; } kstringw& kstringw::operator=( PUNICODE_STRING UniString ) { Copy(UniString->Buffer, UniString->Length / sizeof(WCHAR)); return *this; } kstringw& kstringw::operator=( const kstringw& str ) { if (this != &str) Copy((PWCHAR)str); return *this; } BOOLEAN kstringw::operator==( kstringw& str2 ) { if (this->Compare(str2.GetString()) == 0) { return TRUE; } return FALSE; } BOOLEAN kstringw::operator==( PWCHAR str2 ) { if (this->Compare(str2) == 0) { return TRUE; } return FALSE; } const kstringw& kstringw::operator+=( PUNICODE_STRING UniString ) { ULONG Len = GetLength(); Allocate(Len + UniString->Length / sizeof(WCHAR), TRUE); RtlStringCchCopyNW(&m_stringw[Len], UniString->Length / sizeof(WCHAR), UniString->Buffer, UniString->Length / sizeof(WCHAR)); return *this; } const kstringw& kstringw::operator+=( PWCHAR String ) { ULONG Len = GetLength(); Allocate(Len + wcslen(String), TRUE); RtlStringCchCopyW(&m_stringw[Len], wcslen(String), String); return *this; } const kstringw& kstringw::operator+=( WCHAR ch ) { Append(ch); return *this; } const kstringw& kstringw::operator+=( const kstringw& str ) { ULONG Len = GetLength(); Allocate(Len + str.GetLength(), TRUE); RtlStringCchCopyW(&m_stringw[Len], str.GetLength(), (PWCHAR)str); return *this; } WCHAR kstringw::operator[]( ULONG idx ) { return GetAt(idx); }
C++
#ifndef __NONAME_DIR_H__ #define __NONAME_DIR_H__ #define NONAME_LIB_USE #include <ntifs.h> #include "nm_mem.h" #include "nm_string.h" class kdirectory { public: kdirectory(); void Release(); VOID Close(); NTSTATUS Create( kstringw& FileName, ULONG CreateDisposition = FILE_OPEN, ACCESS_MASK DesiredAccess = GENERIC_READ, ULONG ShareAccess = FILE_SHARE_READ ); NTSTATUS Create( PWCHAR FileName, ULONG CreateDisposition = FILE_OPEN, ACCESS_MASK DesiredAccess = GENERIC_READ, ULONG ShareAccess = FILE_SHARE_READ ); NTSTATUS Create( PUNICODE_STRING FileName, ULONG CreateDisposition = FILE_OPEN, ACCESS_MASK DesiredAccess = GENERIC_READ, ULONG ShareAccess = FILE_SHARE_READ ); NTSTATUS Delete(BOOLEAN Del = TRUE); HANDLE GetHandle(); NTSTATUS GetName(kstringw& String); PFILE_OBJECT GetObject(); NTSTATUS GetPath(kstringw& String); NTSTATUS GetPath(PFILE_NAME_INFORMATION NameInfo, ULONG Length); NTSTATUS MakeDir(PUNICODE_STRING FileName); NTSTATUS MakeDir(kstringw& FileName); NTSTATUS MakeDir(PWCHAR FileName); NTSTATUS QueryDir( PVOID FileInformation, ULONG Length, PUNICODE_STRING FileName = NULL, FILE_INFORMATION_CLASS FileInformationClass = FileBothDirectoryInformation, BOOLEAN ReturnSingleEntry = TRUE ); NTSTATUS Rename(PFILE_RENAME_INFORMATION RenameInfo, ULONG Length); NTSTATUS Rename(kstringw& Name, BOOLEAN ReplaceIfExists = FALSE); static BOOLEAN IsDirectory(kstringw& String); static BOOLEAN IsDirectory(PUNICODE_STRING UniString); static BOOLEAN IsDirectory(PWCHAR String); private: HANDLE m_filehandle; PFILE_OBJECT m_fileobj; }; #endif
C++
#include "Skin.h" Skin::Skin(QString name, QString extension, QString path) { this->name = name; this->extension = extension; this->path = path; } /** * Create a skin instance from a path (must have at least a valid info.ini file) */ Skin* Skin::fromPath(QString path) { // Checking the ini file for Name and Extension QSettings settings(QDir::cleanPath(path + "/" + Properties::SKINSNFO), QSettings::IniFormat); QString name = settings.value("name",tr("Default skin")).toString(); QString extension = settings.value("extension",Properties::DEFAULT_EXTENSION).toString(); return new Skin(name, extension, path); } /** * Create the default skin instance. */ Skin* Skin::fromDefault() { return new Skin(tr("Default skin"), Properties::DEFAULT_EXTENSION, Properties::DEFAULT_CARDPATH); } /** * Gather a list of skins in the SKINSPATH dir. * The output is a hashmap containing dirpath-skinname pair. * (the former is used for path to skin content, the later for actual name) */ QHash<QString,QString> Skin::skins() { QHash<QString,QString> skinNames; /* Looking for Skin directories... */ QDir skinsDir(Properties::SKINSPATH); skinsDir.setFilter(QDir::Dirs | QDir::NoSymLinks | QDir::NoDotAndDotDot); skinsDir.setSorting(QDir::Name); QStringList entryList = skinsDir.entryList(); /* For each directory, looking for the name in the info.ini */ foreach(QString dir, entryList) { QString dirPath = Properties::SKINSPATH + "/" + dir; QString nfoPath = dirPath + "/" + Properties::SKINSNFO; QSettings settings(QDir::cleanPath(nfoPath), QSettings::IniFormat); // We say skin exists if there is a non-empty name present in the ini QString name = settings.value("name","").toString(); // If the skin exists, adding it if (!name.isEmpty()) skinNames[dirPath] = name; } return skinNames; } QString Skin::imageUrlNormal(QString basename) { return imageUrl(basename); } QString Skin::imageUrlThumb(QString basename) { return imageUrl(basename, Properties::CARD_APPEND); } QString Skin::imageUrlCardBackNormal() { return imageUrlNormal(Properties::FILENAME_CardBack); } QString Skin::imageUrlCardBackThumb() { return imageUrlThumb(Properties::FILENAME_CardBack); } QString Skin::imageUrlCoupFourre() { return imageUrlNormal(Properties::FILENAME_CoupFourre); } /** * According to a card basename (e.g. hazard_outofgas), will calculate the whole path to the card picture: * the skin path (or default skin internal path) + basename + extension * * The append parameter allow to have the normal or thumbnailed image. */ QString Skin::imageUrl(QString basename, QString append) { QString defaultURL = QDir::cleanPath(Properties::DEFAULT_CARDPATH + "/" + basename + append + "." + Properties::DEFAULT_EXTENSION); QString skinURL = QDir::cleanPath(path + "/" + basename + append + "." + extension); // Setting the path to default or skin path (if available) QFileInfo skinNfo(skinURL); if (skinNfo.exists() && skinNfo.isReadable()) return skinURL; return defaultURL; } QString Skin::getName() { return name; }
C++
#ifndef MAINWINDOW_H #define MAINWINDOW_H #include <QMainWindow> namespace Ui { class MainWindow; } class MainWindow : public QMainWindow { Q_OBJECT public: explicit MainWindow(QWidget *parent = 0); ~MainWindow(); private: Ui::MainWindow *ui; }; #endif // MAINWINDOW_H
C++
#include "MainWindow.h" #include "ui_MainWindow.h" MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainWindow) { ui->setupUi(this); } MainWindow::~MainWindow() { delete ui; }
C++
#ifndef SKIN_H #define SKIN_H #include "includes.h" /** * Proxy class to handle card skins. Allows to: * - Skins listing with proper names * - Skins "loading" (only loads name, properties and path) * - Proxying each card file path: skin path if it exists, default path else */ class Skin : public QObject { Q_OBJECT public: static QHash<QString,QString> skins(); static Skin* fromPath(QString path); static Skin* fromDefault(); QString imageUrlNormal(QString basename); QString imageUrlThumb(QString basename); QString imageUrlCardBackNormal(); QString imageUrlCardBackThumb(); QString imageUrlCoupFourre(); QString getName(); private: explicit Skin(QString name, QString extension, QString path); QString name; QString extension; QString path; QString imageUrl(QString basename, QString append = ""); }; #endif // SKIN_H
C++
#ifndef PROPERTIES_H #define PROPERTIES_H #include <QString> class Properties { public: // Application static const QString ORGANIZATION; static const QString APPLICATION; static const QString SETTINGS; // Networking static const quint16 DEFAULT_LISTENPORT; // Cards informations static const QString DEFAULT_EXTENSION; static const QString DEFAULT_CARDPATH; static const QString CARD_APPEND; static const QString SKINSPATH; static const QString SKINSNFO; // Cards file basenames static const QString FILENAME_Distance_25; static const QString FILENAME_Distance_50; static const QString FILENAME_Distance_75; static const QString FILENAME_Distance_100; static const QString FILENAME_Distance_200; static const QString FILENAME_Hazard_Accident; static const QString FILENAME_Hazard_OutOfGas; static const QString FILENAME_Hazard_FlatTire; static const QString FILENAME_Hazard_SpeedLimit; static const QString FILENAME_Hazard_Stop; static const QString FILENAME_Remedy_Repair; static const QString FILENAME_Remedy_Gasoline; static const QString FILENAME_Remedy_SpareTire; static const QString FILENAME_Remedy_EndOfLimit; static const QString FILENAME_Remedy_Roll; static const QString FILENAME_Safety_DrivingAce; static const QString FILENAME_Safety_ExtraTank; static const QString FILENAME_Safety_PunctureProof; static const QString FILENAME_Safety_RightOfWay; static const QString FILENAME_CardBack; static const QString FILENAME_CoupFourre; private: explicit Properties(); }; #endif // PROPERTIES_H
C++
#ifndef CARDINFO_H #define CARDINFO_H #include "includes.h" class CardInfo : public QObject { Q_OBJECT public: /* Function of the card: Distance, hazard, remedy or safety */ enum FunctionType { Function_NoFunction, // NoCard Function_Distance, Function_Hazard, Function_Remedy, Function_Safety }; typedef FunctionType CardFunction; /* Nature of the card, for compatibility between a hazard and its remedy/safety */ enum NatureTypeEnum { Nature_NoNature = 0, // Distance cards / NoCard Nature_Accident = 1, Nature_Gas = 2, Nature_Tire = 4, Nature_Speed = 8, Nature_Light = 16 }; // Declares the enum as a QFlags (typedef QFlags<NatureTypeEnum> NatureType;) Q_DECLARE_FLAGS(NatureType, NatureTypeEnum) typedef NatureType CardNature; public: explicit CardInfo(QString name, QString filename, CardFunction function, CardNature nature, int distance); QString getName() const; QString getFilename() const; CardFunction getFunction() const; CardNature getNature() const; int getDistance() const; private: QString name; QString filename; CardFunction function; CardNature nature; int distance; }; // Declares operator|() for CardNature enum-flag Q_DECLARE_OPERATORS_FOR_FLAGS(CardInfo::NatureType) typedef CardInfo::FunctionType CardFunction; typedef CardInfo::NatureType CardNature; #endif // CARDINFO_H
C++
#include "Tableau.h" Tableau::Tableau(Team* owningTeam) { this->owningTeam = owningTeam; this->winDistance = 1000; // Let's say default value. Can be set/"extended" during gameplay } Tableau::~Tableau() { this->owningTeam = NULL; } /** * The number of 200km already played. */ int Tableau::numberOf200() const { return distanceArea.count(Card::CardID_Distance_200); } /** * The distance already played. */ int Tableau::distance() const { return (200 * distanceArea.count(Card::CardID_Distance_200)) + (100 * distanceArea.count(Card::CardID_Distance_100)) + (75 * distanceArea.count(Card::CardID_Distance_75)) + (50 * distanceArea.count(Card::CardID_Distance_50)) + (25 * distanceArea.count(Card::CardID_Distance_25)); } /** * Calculates whether or not we can roll on this tableau. */ bool Tableau::canRoll() const { CardID topBattle = battlePile.isEmpty() ? Card::CardID_NoCard : battlePile.last(); // Roll if top is Roll card. if (topBattle == Card::CardID_Remedy_Roll) return true; /* Without a Roll, all other rules need the Right Of Way */ if (!safetyArea.contains(Card::CardID_Safety_RightOfWay)) return false; // Roll if battle pile empty (+ Right of Way) if (topBattle == Card::CardID_NoCard) return true; // Roll if top is a Remedy (+ Right of Way) if (Card::getInfo(topBattle)->getFunction() == CardInfo::Function_Remedy) return true; // Roll if top is a Hazard and we have the Safety (+ Right of Way) if ((Card::getInfo(topBattle)->getFunction() == CardInfo::Function_Hazard) && safetyArea.contains(Card::cardForProperties(CardInfo::Function_Safety, Card::getInfo(topBattle)->getNature()))) return true; // If everything else fails. return false; } /** * Using the canRoll() method, calculates the max value we can roll at a time. * This might be limited by: the amount of 200 played, a speed limit, or the winDistance */ int Tableau::canRollDistance() const { if (!canRoll()) return 0; // Let's juste progressively reduce the distance. int distance = 200; // Max of 200 km = 2. if (numberOf200() >= 2) distance = 100; // If there is a speed limit if (!speedPile.isEmpty() && speedPile.last() == Card::CardID_Hazard_SpeedLimit) distance = 50; // If we're still over winDistance, limiting to it. int addedDistance = this->distance() + distance; if (addedDistance > winDistance) { int excess = addedDistance - winDistance; distance = qMax(distance - excess, 0); } return distance; } /** * One of the core functions of the engine: * determine whether a player's card can be played on this tableau. */ bool Tableau::canPlay(Player* player, CardID card) const { // No valid card to play. if (card == Card::CardID_NoCard) return false; // Gathering information we need CardInfo* info = Card::getInfo(card); // card info bool allyPlayer = owningTeam->contains(player); // is this the player's tableau? //CardID safety = Card::CardID_NoCard; // the safety corresponding to the nature of the card switch (info->getFunction()) { /* Distance card */ case CardInfo::Function_Distance: // Play only on our team's tableau. if (!allyPlayer) return false; /* Play only if the card is within the "canRoll" distance. This include: - checking if we can roll (Roll card of with safeties), - checking the 200km cards, - checking speed limits, - checking whether the winDistance is exceeded. */ qDebug() << "lol" << canRollDistance(); return (info->getDistance() <= canRollDistance()); break; /* Hazard card */ case CardInfo::Function_Hazard: // Play only on enemy tableau if (allyPlayer) return false; // Cannot play if the corresponding safety is there //safety = Card::cardForProperties(CardInfo::Function_Safety, info->getNature()); if (safetyArea.keys().contains( Card::cardForProperties(CardInfo::Function_Safety, info->getNature()) )) return false; // Speed limit: empty pile or top=remedy if (info->getNature() == CardInfo::Nature_Speed) { return (speedPile.isEmpty() || speedPile.last() == Card::CardID_Remedy_EndOfLimit); } // Hazard: only if enemy can roll else { return canRoll(); } break; /* Remedy cards */ case CardInfo::Function_Remedy: // Play only on our team's tableau. if (!allyPlayer) return false; // Cannot play if the corresponding safety is there (well, useless at least) if (safetyArea.keys().contains( Card::cardForProperties(CardInfo::Function_Safety, info->getNature()) )) return false; // End of limit: !empty pile and top=limit if (info->getNature() == CardInfo::Nature_Speed) { return (!speedPile.isEmpty() && speedPile.last() == Card::CardID_Hazard_SpeedLimit); } // Remedy: only if the corresponding hazard is there else { // Special case of Roll: can play if there is no card, or a remedy (or Stop, but handled normally after) if ((card == Card::CardID_Remedy_Roll) && (battlePile.isEmpty() || Card::getInfo(battlePile.last())->getFunction() == CardInfo::Function_Remedy)) return true; return (!battlePile.isEmpty() && (battlePile.last() == Card::cardForProperties(CardInfo::Function_Hazard, info->getNature()))); } break; /* Safety card */ case CardInfo::Function_Safety: // As long as it's our tableau, we can play anytime. return allyPlayer; break; default: return false; break; } return false; } QList<CardID> Tableau::play(CardID card, bool coupFourre) { QList<CardID> discard; CardInfo* info = Card::getInfo(card); if (info == NULL) return discard; switch (info->getFunction()) { // Distance cards, added to the list case CardInfo::Function_Distance: distanceArea += card; break; // Hazards and Remedy, added to the battle or speed list (depends) case CardInfo::Function_Hazard: case CardInfo::Function_Remedy: if (info->getNature() == CardInfo::Nature_Speed) speedPile += card; else battlePile += card; break; // Safety cards in the safety area case CardInfo::Function_Safety: safetyArea[card] = coupFourre; if (coupFourre) { if ((card == Card::CardID_Safety_RightOfWay) && (speedPile.size() > 0) && (speedPile.last() == Card::CardID_Hazard_SpeedLimit)) discard += speedPile.takeLast(); if ((battlePile.size() > 0) && (Card::getInfo(battlePile.last())->getFunction() & CardInfo::Function_Hazard)) discard += battlePile.takeLast(); } break; default: break; } return discard; } //int Tableau::points(); //QDebug operator<<(QDebug dbg, const Tableau &tab); QDebug operator<<(QDebug dbg, const Tableau &tab) { dbg.nospace() << "Battle: " << tab.battlePile << " / Speed: " << tab.speedPile << " / Distance [" + QString::number(tab.numberOf200()) + "/" + QString::number(tab.distance()) + "]: " << tab.distanceArea << " / Safeties: " << tab.safetyArea; return dbg.space(); }
C++
#ifndef DISCARDPILE_H #define DISCARDPILE_H #include "includes.h" #include "Card.h" class DiscardPile : public QList<CardID> { public: explicit DiscardPile(); }; #endif // DISCARDPILE_H
C++
#include "RaceInfo.h" RaceInfo::RaceInfo() { this->numberOfCards = 0; this->extension = false; this->extensionAllowed = false; this->normalDistance = 1000; this->extensionDistance = 1000; } RaceInfo::RaceInfo(int numberOfCard, bool extension, bool extensionAllowed, int normalDistance, int extensionDistance) { this->numberOfCards = numberOfCard; this->extension = extension; this->extensionAllowed = extensionAllowed; this->normalDistance = normalDistance; this->extensionDistance = extensionDistance; } QDataStream &operator<<(QDataStream& out, const RaceInfo& raceInfo) { out << raceInfo.numberOfCards; out << raceInfo.extension; out << raceInfo.extensionAllowed; out << raceInfo.normalDistance; out << raceInfo.extensionDistance; return out; } QDataStream &operator>>(QDataStream& in, RaceInfo& raceInfo) { in >> raceInfo.numberOfCards; in >> raceInfo.extension; in >> raceInfo.extensionAllowed; in >> raceInfo.normalDistance; in >> raceInfo.extensionDistance; return in; } QDebug operator<<(QDebug dbg, const RaceInfo &raceInfo) { dbg.nospace() << raceInfo.numberOfCards << " / " << raceInfo.extension << " " << raceInfo.extensionAllowed << " / " << raceInfo.normalDistance << " " << raceInfo.extensionDistance; return dbg.space(); }
C++
#include "DiscardPile.h" DiscardPile::DiscardPile() {}
C++
#include "Card.h" QHash<CardID,CardInfo*>* Card::infoHash = NULL; Card::Card() {} CardInfo* Card::getInfo(CardID id) { // Ensures a singleton hash AND that the hash is filled before reading it. if (infoHash == NULL) createInfoHash(); return infoHash->value(id); } CardID Card::cardForProperties(CardFunction function, CardNature nature) { if (infoHash == NULL) createInfoHash(); foreach (CardID id, infoHash->keys()) { CardInfo* nfo = infoHash->value(id); if ((nfo != NULL) && (nfo->getFunction() == function) && (nfo->getNature() & nature)) return id; } return CardID_NoCard; } void Card::createInfoHash() { infoHash = new QHash<CardID,CardInfo*>(); (*infoHash)[CardID_NoCard] = new CardInfo(tr("[NoCard]"), Properties::FILENAME_CardBack, CardInfo::Function_NoFunction, CardInfo::Nature_NoNature, 0); (*infoHash)[CardID_Distance_25] = new CardInfo(tr("25 km"), Properties::FILENAME_Distance_25, CardInfo::Function_Distance, CardInfo::Nature_NoNature, 25); (*infoHash)[CardID_Distance_50] = new CardInfo(tr("50 km"), Properties::FILENAME_Distance_50, CardInfo::Function_Distance, CardInfo::Nature_NoNature, 50); (*infoHash)[CardID_Distance_75] = new CardInfo(tr("75 km"), Properties::FILENAME_Distance_75, CardInfo::Function_Distance, CardInfo::Nature_NoNature, 75); (*infoHash)[CardID_Distance_100] = new CardInfo(tr("100 km"), Properties::FILENAME_Distance_100, CardInfo::Function_Distance, CardInfo::Nature_NoNature, 100); (*infoHash)[CardID_Distance_200] = new CardInfo(tr("200 km"), Properties::FILENAME_Distance_200, CardInfo::Function_Distance, CardInfo::Nature_NoNature, 200); (*infoHash)[CardID_Hazard_Accident] = new CardInfo(tr("Accident"), Properties::FILENAME_Hazard_Accident, CardInfo::Function_Hazard, CardInfo::Nature_Accident, 0); (*infoHash)[CardID_Hazard_OutOfGas] = new CardInfo(tr("Out of Gas"), Properties::FILENAME_Hazard_OutOfGas, CardInfo::Function_Hazard, CardInfo::Nature_Gas, 0); (*infoHash)[CardID_Hazard_FlatTire] = new CardInfo(tr("Flat Tire"), Properties::FILENAME_Hazard_FlatTire, CardInfo::Function_Hazard, CardInfo::Nature_Tire, 0); (*infoHash)[CardID_Hazard_SpeedLimit] = new CardInfo(tr("Speed Limit"), Properties::FILENAME_Hazard_SpeedLimit, CardInfo::Function_Hazard, CardInfo::Nature_Speed, 0); (*infoHash)[CardID_Hazard_Stop] = new CardInfo(tr("Stop"), Properties::FILENAME_Hazard_Stop, CardInfo::Function_Hazard, CardInfo::Nature_Light, 0); (*infoHash)[CardID_Remedy_Repair] = new CardInfo(tr("Repairs"), Properties::FILENAME_Remedy_Repair, CardInfo::Function_Remedy, CardInfo::Nature_Accident, 0); (*infoHash)[CardID_Remedy_Gasoline] = new CardInfo(tr("Gasoline"), Properties::FILENAME_Remedy_Gasoline, CardInfo::Function_Remedy, CardInfo::Nature_Gas, 0); (*infoHash)[CardID_Remedy_SpareTire] = new CardInfo(tr("Spare Tire"), Properties::FILENAME_Remedy_SpareTire, CardInfo::Function_Remedy, CardInfo::Nature_Tire, 0); (*infoHash)[CardID_Remedy_EndOfLimit] = new CardInfo(tr("End of Limit"), Properties::FILENAME_Remedy_EndOfLimit, CardInfo::Function_Remedy, CardInfo::Nature_Speed, 0); (*infoHash)[CardID_Remedy_Roll] = new CardInfo(tr("Roll"), Properties::FILENAME_Remedy_Roll, CardInfo::Function_Remedy, CardInfo::Nature_Light, 0); (*infoHash)[CardID_Safety_DrivingAce] = new CardInfo(tr("Driving Ace"), Properties::FILENAME_Safety_DrivingAce, CardInfo::Function_Safety, CardInfo::Nature_Accident, 0); (*infoHash)[CardID_Safety_ExtraTank] = new CardInfo(tr("Extra Tank"), Properties::FILENAME_Safety_ExtraTank, CardInfo::Function_Safety, CardInfo::Nature_Gas, 0); (*infoHash)[CardID_Safety_PunctureProof] = new CardInfo(tr("Puncture-proof"), Properties::FILENAME_Safety_PunctureProof, CardInfo::Function_Safety, CardInfo::Nature_Tire, 0); (*infoHash)[CardID_Safety_RightOfWay] = new CardInfo(tr("Right of Way"), Properties::FILENAME_Safety_RightOfWay, CardInfo::Function_Safety, CardInfo::Nature_Speed | CardInfo::Nature_Light, 0); }
C++
#ifndef PLAYER_H #define PLAYER_H #include "includes.h" #include "Hand.h" class Player { public: explicit Player(QString name); QString getName() const; Hand getHand() const; private: QString name; Hand hand; }; #endif // PLAYER_H
C++
#include "DrawPile.h" DrawPile::DrawPile() {}
C++
#ifndef CARD_H #define CARD_H #include "includes.h" #include "CardInfo.h" class Card : public QObject { Q_OBJECT public: /* Card unique IDs */ enum ID { CardID_NoCard, CardID_Distance_25, CardID_Distance_50, CardID_Distance_75, CardID_Distance_100, CardID_Distance_200, CardID_Hazard_Accident, CardID_Hazard_OutOfGas, CardID_Hazard_FlatTire, CardID_Hazard_SpeedLimit, CardID_Hazard_Stop, CardID_Remedy_Repair, CardID_Remedy_Gasoline, CardID_Remedy_SpareTire, CardID_Remedy_EndOfLimit, CardID_Remedy_Roll, CardID_Safety_DrivingAce, CardID_Safety_ExtraTank, CardID_Safety_PunctureProof, CardID_Safety_RightOfWay }; typedef ID CardID; static CardInfo* getInfo(CardID id); static CardID cardForProperties(CardFunction function, CardNature nature); private: explicit Card(); static QHash<CardID,CardInfo*>* infoHash; static void createInfoHash(); }; typedef Card::ID CardID; #endif // CARD_H
C++
#include "CardInfo.h" CardInfo::CardInfo(QString name, QString filename, CardFunction function, CardNature nature, int distance) { this->name = name; this->filename = filename; this->function = function; this->nature = nature; this->distance = distance; } QString CardInfo::getName() const { return name; } QString CardInfo::getFilename() const { return filename; } CardFunction CardInfo::getFunction() const { return function; } CardNature CardInfo::getNature() const { return nature; } int CardInfo::getDistance() const { return distance; }
C++
#ifndef RACEINFO_H #define RACEINFO_H #include "includes.h" class RaceInfo : public QObject { Q_OBJECT public: RaceInfo(); RaceInfo(int numberOfCard, bool extension, bool extensionAllowed, int normalDistance, int extensionDistance); public: int numberOfCards; bool extension; bool extensionAllowed; int normalDistance; int extensionDistance; }; /* Serialization */ QDataStream &operator<<(QDataStream& out, const RaceInfo& raceInfo); QDataStream &operator>>(QDataStream& in, RaceInfo& raceInfo); QDebug operator<<(QDebug dbg, const RaceInfo &raceInfo); #endif // RACEINFO_H
C++
#ifndef TEAM_H #define TEAM_H #include "includes.h" #include "Player.h" #include "Tableau.h" class Tableau; class Player; class Team : public QList<Player*> { public: Team(); ~Team(); Tableau* getTableau(); void addPlayer(Player* player); private: Tableau* tableau; }; #endif // TEAM_H
C++
#include "Hand.h" Hand::Hand() {}
C++
#ifndef TABLEAU_H #define TABLEAU_H #include "includes.h" #include "Team.h" #include "Player.h" #include "Card.h" #include "CardInfo.h" class Team; /*$this->pileVitesse = array(); $this->pileCombat = array(); $this->pile200 = array(); $this->pile100 = array(); $this->pile75 = array(); $this->pile50 = array(); $this->pile25 = array(); $this->botteCiterne = NULL; $this->botteIncreuvable = NULL; $this->botteAsVolant = NULL; $this->bottePrioritaire = NULL;*/ class Tableau { public: explicit Tableau(Team* owningTeam); ~Tableau(); Team* getOwningTeam() { return owningTeam; } void setWinDistance(int winDistance) { this->winDistance = winDistance; } int numberOf200() const; int distance() const; bool canPlay(Player* player, CardID card) const; QList<CardID> play(CardID card, bool coupFourre = false); bool canRoll() const; int canRollDistance() const; int points(); public: QList<CardID> battlePile; QList<CardID> speedPile; QList<CardID> distanceArea; QHash<CardID,bool> safetyArea; private: Team* owningTeam; int winDistance; // 700 or 1000 km }; QDebug operator<<(QDebug dbg, const Tableau &tab); #endif // TABLEAU_H
C++
#ifndef HAND_H #define HAND_H #include "includes.h" #include "Card.h" class Hand : public QList<CardID> { public: explicit Hand(); private: }; #endif // HAND_H
C++
#include "Player.h" Player::Player(QString name) { this->name = name; } QString Player::getName() const { return name; } Hand Player::getHand() const { return hand; }
C++
#include "Team.h" Team::Team() { tableau = new Tableau(this); } Team::~Team() { // Deleting players and tableau qDebug() << "~Team()"; for (int i=0; i<size(); i++) { delete this->at(i); } //foreach(Player* player, this) { // delete player; //} delete tableau; } Tableau* Team::getTableau() { return tableau; } /** * Add a player to the team. * (proxy for native method, if further restrictions are needed) */ void Team::addPlayer(Player* player) { //if (this->size() < 3) this->append(player); }
C++
#ifndef DRAWPILE_H #define DRAWPILE_H #include "includes.h" #include "Card.h" class DrawPile : public QList<CardID> { public: explicit DrawPile(); }; #endif // DRAWPILE_H
C++
#include <QtGui/QApplication> #include "includes.h" #include "Tableau.h" #include "CardInfo.h" #include "Skin.h" #include "MainWindow.h" #include "RaceInfo.h" int main(int argc, char *argv[]) { QApplication a(argc, argv); MainWindow w; w.show(); /* RaceInfo info; qDebug() << info; info.numberOfCards = 42; info.extensionAllowed = true; info.normalDistance = 700; qDebug() << info; QByteArray data; //data.append("Lol"); QDataStream out(&data, QIODevice::WriteOnly); out.setVersion(QDataStream::Qt_4_6); out << info; RaceInfo n; qDebug() << n; QDataStream in(data); // in(&data,QIODevice::ReadOnly); in >> n; qDebug() << n; */ /*CardID id = Card::cardForProperties(CardInfo::Function_Safety, CardInfo::Nature_Light); CardInfo* nfo = Card::getInfo(id); if (nfo != NULL) qDebug() << nfo->getName(); else qDebug() << "NULL"; */ Team team; Tableau* t = team.getTableau(); Player *p1, *p2; p1 = new Player("Ore-sama"); p2 = new Player("Temee"); team.addPlayer(p1); t->setWinDistance(500); /* t->play(Card::CardID_Distance_200); t->play(Card::CardID_Distance_100); t->play(Card::CardID_Distance_25); qDebug() << t->canPlay(p1,Card::CardID_Hazard_Accident) << t->canPlay(p2,Card::CardID_Hazard_Accident); t->play(Card::CardID_Remedy_Roll); t->play(Card::CardID_Hazard_); t->play(Card::CardID_Safety_DrivingAce); t->play(Card::CardID_Safety_DrivingAce); qDebug() << t->canPlay(p1,Card::CardID_Hazard_Accident) << t->canPlay(p2,Card::CardID_Hazard_Accident); */ //qDebug() << "Roll: " << t->canRollDistance(); return a.exec(); }
C++
#include "Properties.h" // Application const QString Properties::ORGANIZATION = "SGC"; const QString Properties::APPLICATION = "1000 Bornes"; const QString Properties::SETTINGS = "settings.ini"; // Networking const quint16 Properties::DEFAULT_LISTENPORT = 1313; // Cards informations const QString Properties::DEFAULT_EXTENSION = "png"; const QString Properties::DEFAULT_CARDPATH = ":/cards/"; const QString Properties::CARD_APPEND = "_t"; const QString Properties::SKINSPATH = "skins/"; const QString Properties::SKINSNFO = "info.ini"; // Cards file basenames const QString Properties::FILENAME_Distance_25 = "Distance_25"; const QString Properties::FILENAME_Distance_50 = "Distance_50"; const QString Properties::FILENAME_Distance_75 = "Distance_75"; const QString Properties::FILENAME_Distance_100 = "Distance_100"; const QString Properties::FILENAME_Distance_200 = "Distance_200"; const QString Properties::FILENAME_Hazard_OutOfGas = "Hazard_OutOfGas"; const QString Properties::FILENAME_Hazard_FlatTire = "Hazard_FlatTire"; const QString Properties::FILENAME_Hazard_Accident = "Hazard_Accident"; const QString Properties::FILENAME_Hazard_SpeedLimit = "Hazard_SpeedLimit"; const QString Properties::FILENAME_Hazard_Stop = "Hazard_Stop"; const QString Properties::FILENAME_Remedy_Gasoline = "Remedy_Gasoline"; const QString Properties::FILENAME_Remedy_SpareTire = "Remedy_SpareTire"; const QString Properties::FILENAME_Remedy_Repair = "Remedy_Repair"; const QString Properties::FILENAME_Remedy_EndOfLimit = "Remedy_EndOfLimit"; const QString Properties::FILENAME_Remedy_Roll = "Remedy_Roll"; const QString Properties::FILENAME_Safety_ExtraTank = "Safety_ExtraTank"; const QString Properties::FILENAME_Safety_PunctureProof = "Safety_PunctureProof"; const QString Properties::FILENAME_Safety_DrivingAce = "Safety_DrivingAce"; const QString Properties::FILENAME_Safety_RightOfWay = "Safety_RightOfWay"; const QString Properties::FILENAME_CardBack = "cardback"; const QString Properties::FILENAME_CoupFourre = "coupfourre";
C++
/* ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0/LGPL 2.1 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * Contributor: * Chuan Qiu <qiuc12@gmail.com> * * Alternatively, the contents of this file may be used under the terms of * either the GNU General Public License Version 2 or later (the "GPL"), or * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), * in which case the provisions of the GPL or the LGPL are applicable instead * of those above. If you wish to allow use of your version of this file only * under the terms of either the GPL or the LGPL, and not to allow others to * use your version of this file under the terms of the MPL, indicate your * decision by deleting the provisions above and replace them with the notice * and other provisions required by the GPL or the LGPL. If you do not delete * the provisions above, a recipient may use your version of this file under * the terms of any one of the MPL, the GPL or the LGPL. * * ***** END LICENSE BLOCK ***** */ #pragma once #include <npruntime.h> #include <npapi.h> #include "npactivex.h" class NPVariantProxy : public NPVariant { public: NPVariantProxy() { VOID_TO_NPVARIANT(*this); } ~NPVariantProxy() { NPNFuncs.releasevariantvalue(this); } }; class NPObjectProxy { private: NPObject *object; public: NPObjectProxy() { object = NULL; } NPObjectProxy(NPObject *obj) { object = obj; } void reset() { if (object) NPNFuncs.releaseobject(object); object = NULL; } ~NPObjectProxy() { reset(); } operator NPObject*&() { return object; } NPObjectProxy& operator =(NPObject* obj) { reset(); object = obj; return *this; } };
C++
/* ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0/LGPL 2.1 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is itstructures.com code. * * The Initial Developer of the Original Code is IT Structures. * Portions created by the Initial Developer are Copyright (C) 2008 * the Initial Developer. All Rights Reserved. * * Contributor: * Ruediger Jungbeck <ruediger.jungbeck@rsj.de> * * Alternatively, the contents of this file may be used under the terms of * either the GNU General Public License Version 2 or later (the "GPL"), or * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), * in which case the provisions of the GPL or the LGPL are applicable instead * of those above. If you wish to allow use of your version of this file only * under the terms of either the GPL or the LGPL, and not to allow others to * use your version of this file under the terms of the MPL, indicate your * decision by deleting the provisions above and replace them with the notice * and other provisions required by the GPL or the LGPL. If you do not delete * the provisions above, a recipient may use your version of this file under * the terms of any one of the MPL, the GPL or the LGPL. * * ***** END LICENSE BLOCK ***** */ #include <comdef.h> #include "npactivex.h" #include "scriptable.h" #include "common/PropertyList.h" #include "common/PropertyBag.h" #include "common/ItemContainer.h" #include "common/ControlSite.h" #include "common/ControlSiteIPFrame.h" #include "common/ControlEventSink.h" #include "axhost.h" #include "HTMLDocumentContainer.h" #ifdef NO_REGISTRY_AUTHORIZE static const char *WellKnownProgIds[] = { NULL }; static const char *WellKnownClsIds[] = { NULL }; #endif static const bool AcceptOnlyWellKnown = false; static const bool TrustWellKnown = true; static bool isWellKnownProgId(const char *progid) { #ifdef NO_REGISTRY_AUTHORIZE unsigned int i = 0; if (!progid) { return false; } while (WellKnownProgIds[i]) { if (!strnicmp(WellKnownProgIds[i], progid, strlen(WellKnownProgIds[i]))) return true; ++i; } return false; #else return true; #endif } static bool isWellKnownClsId(const char *clsid) { #ifdef NO_REGISTRY_AUTHORIZE unsigned int i = 0; if (!clsid) { return false; } while (WellKnownClsIds[i]) { if (!strnicmp(WellKnownClsIds[i], clsid, strlen(WellKnownClsIds[i]))) return true; ++i; } return false; #else return true; #endif } static LRESULT CALLBACK AxHostWinProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam) { LRESULT result; CAxHost *host = (CAxHost *)GetWindowLong(hWnd, GWL_USERDATA); if (!host) { return DefWindowProc(hWnd, msg, wParam, lParam); } switch (msg) { case WM_SETFOCUS: case WM_KILLFOCUS: case WM_SIZE: if (host->Site) { host->Site->OnDefWindowMessage(msg, wParam, lParam, &result); return result; } else { return DefWindowProc(hWnd, msg, wParam, lParam); } // Window being destroyed case WM_DESTROY: break; default: return DefWindowProc(hWnd, msg, wParam, lParam); } return true; } CAxHost::CAxHost(NPP inst): CHost(inst), ClsID(CLSID_NULL), isValidClsID(false), Sink(NULL), Site(NULL), Window(NULL), OldProc(NULL), Props_(new PropertyList), isKnown(false), CodeBaseUrl(NULL), noWindow(false) { } CAxHost::~CAxHost() { np_log(instance, 0, "AxHost.~AXHost: destroying the control..."); if (Window){ if (OldProc) { ::SetWindowLong(Window, GWL_WNDPROC, (LONG)OldProc); OldProc = NULL; } ::SetWindowLong(Window, GWL_USERDATA, (LONG)NULL); } Clear(); delete Props_; } void CAxHost::Clear() { if (Sink) { Sink->UnsubscribeFromEvents(); Sink->Release(); Sink = NULL; } if (Site) { Site->Detach(); Site->Release(); Site = NULL; } if (Props_) { Props_->Clear(); } CoFreeUnusedLibraries(); } CLSID CAxHost::ParseCLSIDFromSetting(LPCSTR str, int length) { CLSID ret; CStringW input(str, length); if (SUCCEEDED(CLSIDFromString(input, &ret))) return ret; int pos = input.Find(':'); if (pos != -1) { CStringW wolestr(_T("{")); wolestr.Append(input.Mid(pos + 1)); wolestr.Append(_T("}")); if (SUCCEEDED(CLSIDFromString(wolestr.GetString(), &ret))) return ret; } return CLSID_NULL; } void CAxHost::setWindow(HWND win) { if (win != Window) { if (win) { // subclass window so we can intercept window messages and // do our drawing to it OldProc = (WNDPROC)::SetWindowLong(win, GWL_WNDPROC, (LONG)AxHostWinProc); // associate window with our CAxHost object so we can access // it in the window procedure ::SetWindowLong(win, GWL_USERDATA, (LONG)this); } else { if (OldProc) ::SetWindowLong(Window, GWL_WNDPROC, (LONG)OldProc); ::SetWindowLong(Window, GWL_USERDATA, (LONG)NULL); } Window = win; } } void CAxHost::ResetWindow() { UpdateRect(lastRect); } HWND CAxHost::getWinfow() { return Window; } void CAxHost::UpdateRect(RECT rcPos) { HRESULT hr = -1; lastRect = rcPos; if (Site && Window && !noWindow) { if (Site->GetParentWindow() == NULL) { hr = Site->Attach(Window, rcPos, NULL); if (FAILED(hr)) { np_log(instance, 0, "AxHost.UpdateRect: failed to attach control"); SIZEL zero = {0, 0}; SetRectSize(&zero); } } if (Site->CheckAndResetNeedUpdateContainerSize()) { UpdateRectSize(&rcPos); } else { Site->SetPosition(rcPos); } // Ensure clipping on parent to keep child controls happy ::SetWindowLong(Window, GWL_STYLE, ::GetWindowLong(Window, GWL_STYLE) | WS_CLIPCHILDREN); } } void CAxHost::setNoWindow(bool noWindow) { this->noWindow = noWindow; } void CAxHost::UpdateRectSize(LPRECT origRect) { if (noWindow) { return; } SIZEL szControl; if (!Site->IsVisibleAtRuntime()) { szControl.cx = 0; szControl.cy = 0; } else { if (FAILED(Site->GetControlSize(&szControl))) { return; } } SIZEL szIn; szIn.cx = origRect->right - origRect->left; szIn.cy = origRect->bottom - origRect->top; if (szControl.cx != szIn.cx || szControl.cy != szIn.cy) { SetRectSize(&szControl); } } void CAxHost::SetRectSize(LPSIZEL size) { np_log(instance, 1, "Set object size: x = %d, y = %d", size->cx, size->cy); NPObjectProxy object; NPNFuncs.getvalue(instance, NPNVPluginElementNPObject, &object); static NPIdentifier style = NPNFuncs.getstringidentifier("style"); static NPIdentifier height = NPNFuncs.getstringidentifier("height"); static NPIdentifier width = NPNFuncs.getstringidentifier("width"); NPVariant sHeight, sWidth; CStringA strHeight, strWidth; strHeight.Format("%dpx", size->cy); strWidth.Format("%dpx", size->cx); STRINGZ_TO_NPVARIANT(strHeight, sHeight); STRINGZ_TO_NPVARIANT(strWidth, sWidth); NPVariantProxy styleValue; NPNFuncs.getproperty(instance, object, style, &styleValue); NPObject *styleObject = NPVARIANT_TO_OBJECT(styleValue); NPNFuncs.setproperty(instance, styleObject, height, &sHeight); NPNFuncs.setproperty(instance, styleObject, width, &sWidth); } void CAxHost::SetNPWindow(NPWindow *window) { RECT rcPos; setWindow((HWND)window->window); rcPos.left = 0; rcPos.top = 0; rcPos.right = window->width; rcPos.bottom = window->height; UpdateRect(rcPos); } bool CAxHost::verifyClsID(LPOLESTR oleClsID) { CRegKey keyExplorer; if (ERROR_SUCCESS == keyExplorer.Open(HKEY_LOCAL_MACHINE, _T("SOFTWARE\\Microsoft\\Internet Explorer\\ActiveX Compatibility"), KEY_READ)) { CRegKey keyCLSID; if (ERROR_SUCCESS == keyCLSID.Open(keyExplorer, W2T(oleClsID), KEY_READ)) { DWORD dwType = REG_DWORD; DWORD dwFlags = 0; DWORD dwBufSize = sizeof(dwFlags); if (ERROR_SUCCESS == ::RegQueryValueEx(keyCLSID, _T("Compatibility Flags"), NULL, &dwType, (LPBYTE) &dwFlags, &dwBufSize)) { // Flags for this reg key const DWORD kKillBit = 0x00000400; if (dwFlags & kKillBit) { np_log(instance, 0, "AxHost.verifyClsID: the control is marked as unsafe by IE kill bits"); return false; } } } } return true; } bool CAxHost::setClsID(const char *clsid) { HRESULT hr = -1; USES_CONVERSION; LPOLESTR oleClsID = A2OLE(clsid); if (isWellKnownClsId(clsid)) { isKnown = true; } else if (AcceptOnlyWellKnown) { np_log(instance, 0, "AxHost.setClsID: the requested CLSID is not on the Well Known list"); return false; } // Check the Internet Explorer list of vulnerable controls if (oleClsID && verifyClsID(oleClsID)) { CLSID vclsid; hr = CLSIDFromString(oleClsID, &vclsid); if (SUCCEEDED(hr)) { return setClsID(vclsid); } } np_log(instance, 0, "AxHost.setClsID: failed to set the requested clsid"); return false; } bool CAxHost::setClsID(const CLSID& clsid) { if (clsid != CLSID_NULL) { this->ClsID = clsid; isValidClsID = true; //np_log(instance, 1, "AxHost.setClsID: CLSID %s set", clsid); return true; } return false; } void CAxHost::setCodeBaseUrl(LPCWSTR codeBaseUrl) { CodeBaseUrl = codeBaseUrl; } bool CAxHost::setClsIDFromProgID(const char *progid) { HRESULT hr = -1; CLSID clsid = CLSID_NULL; USES_CONVERSION; LPOLESTR oleClsID = NULL; LPOLESTR oleProgID = A2OLE(progid); if (AcceptOnlyWellKnown) { if (isWellKnownProgId(progid)) { isKnown = true; } else { np_log(instance, 0, "AxHost.setClsIDFromProgID: the requested PROGID is not on the Well Known list"); return false; } } hr = CLSIDFromProgID(oleProgID, &clsid); if (FAILED(hr)) { np_log(instance, 0, "AxHost.setClsIDFromProgID: could not resolve PROGID"); return false; } hr = StringFromCLSID(clsid, &oleClsID); // Check the Internet Explorer list of vulnerable controls if ( SUCCEEDED(hr) && oleClsID && verifyClsID(oleClsID)) { ClsID = clsid; if (!::IsEqualCLSID(ClsID, CLSID_NULL)) { isValidClsID = true; np_log(instance, 1, "AxHost.setClsIDFromProgID: PROGID %s resolved and set", progid); return true; } } np_log(instance, 0, "AxHost.setClsIDFromProgID: failed to set the resolved CLSID"); return false; } bool CAxHost::hasValidClsID() { return isValidClsID; } static void HTMLContainerDeleter(IUnknown *unk) { CComAggObject<HTMLDocumentContainer>* val = (CComAggObject<HTMLDocumentContainer>*)(unk); val->InternalRelease(); } bool CAxHost::CreateControl(bool subscribeToEvents) { if (!isValidClsID) { np_log(instance, 0, "AxHost.CreateControl: current location is not trusted"); return false; } // Create the control site CComObject<CControlSite>::CreateInstance(&Site); if (Site == NULL) { np_log(instance, 0, "AxHost.CreateControl: CreateInstance failed"); return false; } Site->AddRef(); Site->m_bSupportWindowlessActivation = false; if (TrustWellKnown && isKnown) { Site->SetSecurityPolicy(NULL); Site->m_bSafeForScriptingObjectsOnly = false; } else { Site->m_bSafeForScriptingObjectsOnly = true; } CComAggObject<HTMLDocumentContainer> *document; CComAggObject<HTMLDocumentContainer>::CreateInstance(Site->GetUnknown(), &document); document->m_contained.Init(instance, pHtmlLib); Site->SetInnerWindow(document, HTMLContainerDeleter); // Create the object HRESULT hr; hr = Site->Create(ClsID, *Props(), CodeBaseUrl); if (FAILED(hr)) { np_log(instance, 0, "AxHost.CreateControl: failed to create site for 0x%08x", hr); return false; } #if 0 IUnknown *control = NULL; Site->GetControlUnknown(&control); if (!control) { np_log(instance, 0, "AxHost.CreateControl: failed to create control (was it just downloaded?)"); return false; } // Create the event sink CComObject<CControlEventSink>::CreateInstance(&Sink); Sink->AddRef(); Sink->instance = instance; hr = Sink->SubscribeToEvents(control); control->Release(); if (FAILED(hr) && subscribeToEvents) { np_log(instance, 0, "AxHost.CreateControl: SubscribeToEvents failed"); // return false; // It doesn't matter. } #endif np_log(instance, 1, "AxHost.CreateControl: control created successfully"); return true; } bool CAxHost::AddEventHandler(wchar_t *name, wchar_t *handler) { HRESULT hr; DISPID id = 0; USES_CONVERSION; LPOLESTR oleName = name; if (!Sink) { np_log(instance, 0, "AxHost.AddEventHandler: no valid sink"); return false; } hr = Sink->m_spEventSinkTypeInfo->GetIDsOfNames(&oleName, 1, &id); if (FAILED(hr)) { np_log(instance, 0, "AxHost.AddEventHandler: GetIDsOfNames failed to resolve event name"); return false; } Sink->events[id] = handler; np_log(instance, 1, "AxHost.AddEventHandler: handler %S set for event %S", handler, name); return true; } int16 CAxHost::HandleEvent(void *event) { NPEvent *npEvent = (NPEvent *)event; LRESULT result = 0; if (!npEvent) { return 0; } // forward all events to the hosted control return (int16)Site->OnDefWindowMessage(npEvent->event, npEvent->wParam, npEvent->lParam, &result); } ScriptBase * CAxHost::CreateScriptableObject() { Scriptable *obj = Scriptable::FromAxHost(instance, this); if (Site == NULL) { return obj; } static int markedSafe = 0; if (!Site->m_bSafeForScriptingObjectsOnly && markedSafe == 0) { if (MessageBox(NULL, _T("Some objects are not script-safe, would you continue?"), _T("Warining"), MB_YESNO | MB_ICONINFORMATION | MB_ICONASTERISK) == IDYES) markedSafe = 1; else markedSafe = 2; } if (!Site->m_bSafeForScriptingObjectsOnly && markedSafe != 1) { // Disable scripting. obj->Invalidate(); } return obj; } HRESULT CAxHost::GetControlUnknown(IUnknown **pObj) { if (Site == NULL) { return E_FAIL; } return Site->GetControlUnknown(pObj); } NPP CAxHost::ResetNPP(NPP npp) { NPP ret = CHost::ResetNPP(npp); setWindow(NULL); Site->Detach(); if (Sink) Sink->instance = npp; return ret; }
C++
/* ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0/LGPL 2.1 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is itstructures.com code. * * The Initial Developer of the Original Code is IT Structures. * Portions created by the Initial Developer are Copyright (C) 2008 * the Initial Developer. All Rights Reserved. * * Contributor: * Ruediger Jungbeck <ruediger.jungbeck@rsj.de> * * Alternatively, the contents of this file may be used under the terms of * either the GNU General Public License Version 2 or later (the "GPL"), or * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), * in which case the provisions of the GPL or the LGPL are applicable instead * of those above. If you wish to allow use of your version of this file only * under the terms of either the GPL or the LGPL, and not to allow others to * use your version of this file under the terms of the MPL, indicate your * decision by deleting the provisions above and replace them with the notice * and other provisions required by the GPL or the LGPL. If you do not delete * the provisions above, a recipient may use your version of this file under * the terms of any one of the MPL, the GPL or the LGPL. * * ***** END LICENSE BLOCK ***** */ // npactivex.cpp : Defines the exported functions for the DLL application. // #include "npactivex.h" #include "axhost.h" #include "atlutil.h" #include "objectProxy.h" #include "authorize.h" #include "common\PropertyList.h" #include "common\ControlSite.h" #include "ObjectManager.h" // A list of trusted domains // Each domain name may start with a '*' to specify that sub domains are // trusted as well // Note that a '.' is not enforced after the '*' static const char *TrustedLocations[] = {NULL}; static const unsigned int numTrustedLocations = 0; static const char *LocalhostName = "localhost"; static const bool TrustLocalhost = true; // // Gecko API // static const char PARAM_ID[] = "id"; static const char PARAM_NAME[] = "name"; static const char PARAM_CLSID[] = "clsid"; static const char PARAM_CLASSID[] = "classid"; static const char PARAM_PROGID[] = "progid"; static const char PARAM_DYNAMIC[] = "dynamic"; static const char PARAM_DEBUG[] = "debugLevel"; static const char PARAM_CODEBASEURL [] = "codeBase"; static const char PARAM_ONEVENT[] = "Event_"; static unsigned int log_level = -1; // For catch breakpoints. HRESULT NotImpl() { return E_NOTIMPL; } void log_activex_logging(NPP instance, unsigned int level, const char* filename, int line, char *message, ...) { if (instance == NULL || level > log_level) { return; } NPObjectProxy globalObj = NULL; NPIdentifier commandId = NPNFuncs.getstringidentifier("__npactivex_log"); NPNFuncs.getvalue(instance, NPNVWindowNPObject, &globalObj); if (!NPNFuncs.hasmethod(instance, globalObj, commandId)) { return; } int size = 0; va_list list; ATL::CStringA str; ATL::CStringA str2; va_start(list, message); str.FormatV(message, list); str2.Format("0x%08x %s:%d %s", instance, filename, line, str.GetString()); va_end(list); NPVariant vars[1]; const char* formatted = str2.GetString(); STRINGZ_TO_NPVARIANT(formatted, vars[0]); NPVariantProxy result1; NPNFuncs.invoke(instance, globalObj, commandId, vars, 1, &result1); } void InstallLogAction(NPP instance) { NPVariantProxy result1; NPObjectProxy globalObj = NULL; NPIdentifier commandId = NPNFuncs.getstringidentifier("__npactivex_log"); NPNFuncs.getvalue(instance, NPNVWindowNPObject, &globalObj); if (NPNFuncs.hasmethod(instance, globalObj, commandId)) { return; } const char* definition = "function __npactivex_log(message)" "{var controlLogEvent='__npactivex_log_event__';" "var e=document.createEvent('TextEvent');e.initTextEvent(controlLogEvent,false,false,null,message);window.dispatchEvent(e)}"; NPString def; def.UTF8Characters = definition; def.UTF8Length = strlen(definition); NPNFuncs.evaluate(instance, globalObj, &def, &result1); } void log_internal_console(NPP instance, unsigned int level, char *message, ...) { NPVariantProxy result1, result2; NPVariant args; NPObjectProxy globalObj = NULL, consoleObj = NULL; bool rc = false; char *formatted = NULL; char *new_formatted = NULL; int buff_len = 0; int size = 0; va_list list; if (level > log_level) { return; } buff_len = strlen(message); char *new_message = (char *)malloc(buff_len + 10); sprintf(new_message, "%%s %%d: %s", message); buff_len += buff_len / 10; formatted = (char *)calloc(1, buff_len); while (true) { va_start(list, message); size = vsnprintf_s(formatted, buff_len, _TRUNCATE, new_message, list); va_end(list); if (size > -1 && size < buff_len) break; buff_len *= 2; new_formatted = (char *)realloc(formatted, buff_len); if (NULL == new_formatted) { free(formatted); return; } formatted = new_formatted; new_formatted = NULL; } free(new_message); if (instance == NULL) { free(formatted); return; } NPNFuncs.getvalue(instance, NPNVWindowNPObject, &globalObj); if (NPNFuncs.getproperty(instance, globalObj, NPNFuncs.getstringidentifier("console"), &result1)) { consoleObj = NPVARIANT_TO_OBJECT(result1); NPIdentifier handler = NPNFuncs.getstringidentifier("log"); STRINGZ_TO_NPVARIANT(formatted, args); bool success = NPNFuncs.invoke(instance, consoleObj, handler, &args, 1, &result2); } free(formatted); } static bool MatchURL2TrustedLocations(NPP instance, LPCTSTR matchUrl) { USES_CONVERSION; BOOL rc = false; CUrl url; if (!numTrustedLocations) { return true; } rc = url.CrackUrl(matchUrl, ATL_URL_DECODE); if (!rc) { np_log(instance, 0, "AxHost.MatchURL2TrustedLocations: failed to parse the current location URL"); return false; } if ( (url.GetScheme() == ATL_URL_SCHEME_FILE) || (!strncmp(LocalhostName, W2A(url.GetHostName()), strlen(LocalhostName)))){ return TrustLocalhost; } for (unsigned int i = 0; i < numTrustedLocations; ++i) { if (TrustedLocations[i][0] == '*') { // sub domains are trusted unsigned int len = strlen(TrustedLocations[i]); bool match = 0; if (url.GetHostNameLength() < len) { // can't be a match continue; } --len; // skip the '*' match = strncmp(W2A(url.GetHostName()) + (url.GetHostNameLength() - len), // anchor the comparison to the end of the domain name TrustedLocations[i] + 1, // skip the '*' len) == 0 ? true : false; if (match) { return true; } } else if (!strncmp(W2A(url.GetHostName()), TrustedLocations[i], url.GetHostNameLength())) { return true; } } return false; } static bool VerifySiteLock(NPP instance) { // This approach is not used. return true; #if 0 USES_CONVERSION; NPObjectProxy globalObj; NPIdentifier identifier; NPVariantProxy varLocation; NPVariantProxy varHref; bool rc = false; // Get the window object. NPNFuncs.getvalue(instance, NPNVWindowNPObject, &globalObj); // Create a "location" identifier. identifier = NPNFuncs.getstringidentifier("location"); // Get the location property from the window object (which is another object). rc = NPNFuncs.getproperty(instance, globalObj, identifier, &varLocation); if (!rc){ np_log(instance, 0, "AxHost.VerifySiteLock: could not get the location from the global object"); return false; } // Get a pointer to the "location" object. NPObject *locationObj = varLocation.value.objectValue; // Create a "href" identifier. identifier = NPNFuncs.getstringidentifier("href"); // Get the location property from the location object. rc = NPNFuncs.getproperty(instance, locationObj, identifier, &varHref); if (!rc) { np_log(instance, 0, "AxHost.VerifySiteLock: could not get the href from the location property"); return false; } rc = MatchURL2TrustedLocations(instance, A2W(varHref.value.stringValue.UTF8Characters)); if (false == rc) { np_log(instance, 0, "AxHost.VerifySiteLock: current location is not trusted"); } return rc; #endif } static bool FillProperties(CAxHost *host, NPP instance) { NPObjectProxy embed; NPNFuncs.getvalue(instance, NPNVPluginElementNPObject, &embed); // Traverse through childs NPVariantProxy var_childNodes; NPVariantProxy var_length; NPVariant str_name, str_value; if (!NPNFuncs.getproperty(instance, embed, NPNFuncs.getstringidentifier("childNodes"), &var_childNodes)) return true; if (!NPVARIANT_IS_OBJECT(var_childNodes)) return true; NPObject *childNodes = NPVARIANT_TO_OBJECT(var_childNodes); VOID_TO_NPVARIANT(var_length); if (!NPNFuncs.getproperty(instance, childNodes, NPNFuncs.getstringidentifier("length"), &var_length)) return true; USES_CONVERSION; int length = 0; if (NPVARIANT_IS_INT32(var_length)) length = NPVARIANT_TO_INT32(var_length); if (NPVARIANT_IS_DOUBLE(var_length)) length = static_cast<int>(NPVARIANT_TO_DOUBLE(var_length)); NPIdentifier idname = NPNFuncs.getstringidentifier("nodeName"); NPIdentifier idAttr = NPNFuncs.getstringidentifier("getAttribute"); STRINGZ_TO_NPVARIANT("name", str_name); STRINGZ_TO_NPVARIANT("value", str_value); for (int i = 0; i < length; ++i) { NPIdentifier id = NPNFuncs.getintidentifier(i); NPVariantProxy var_par; NPVariantProxy var_nodeName, var_parName, var_parValue; if (!NPNFuncs.getproperty(instance, childNodes, id, &var_par)) continue; if (!NPVARIANT_IS_OBJECT(var_par)) continue; NPObject *param_obj = NPVARIANT_TO_OBJECT(var_par); if (!NPNFuncs.getproperty(instance, param_obj, idname, &var_nodeName)) continue; if (_strnicmp(NPVARIANT_TO_STRING(var_nodeName).UTF8Characters, "embed", NPVARIANT_TO_STRING(var_nodeName).UTF8Length) == 0) { NPVariantProxy type; NPVariant typestr; STRINGZ_TO_NPVARIANT("type", typestr); if (!NPNFuncs.invoke(instance, param_obj, idAttr, &typestr, 1, &type)) continue; if (!NPVARIANT_IS_STRING(type)) continue; CStringA command, mimetype(NPVARIANT_TO_STRING(type).UTF8Characters, NPVARIANT_TO_STRING(type).UTF8Length); command.Format("navigator.mimeTypes[\'%s\'] != null", mimetype); NPString str = {command.GetString(), command.GetLength()}; NPVariantProxy value; NPObjectProxy window; NPNFuncs.getvalue(instance, NPNVWindowNPObject, &window); NPNFuncs.evaluate(instance, window, &str, &value); if (NPVARIANT_IS_BOOLEAN(value) && NPVARIANT_TO_BOOLEAN(value)) { // The embed is supported by chrome. Fallback automatically. return false; } } if (_strnicmp(NPVARIANT_TO_STRING(var_nodeName).UTF8Characters, "param", NPVARIANT_TO_STRING(var_nodeName).UTF8Length) != 0) continue; if (!NPNFuncs.invoke(instance, param_obj, idAttr, &str_name, 1, &var_parName)) continue; if (!NPNFuncs.invoke(instance, param_obj, idAttr, &str_value, 1, &var_parValue)) continue; if (!NPVARIANT_IS_STRING(var_parName) || !NPVARIANT_IS_STRING(var_parValue)) continue; CComBSTR paramName(NPVARIANT_TO_STRING(var_parName).UTF8Length, NPVARIANT_TO_STRING(var_parName).UTF8Characters); CComBSTR paramValue(NPVARIANT_TO_STRING(var_parValue).UTF8Length, NPVARIANT_TO_STRING(var_parValue).UTF8Characters); // Add named parameter to list CComVariant v(paramValue); host->Props()->AddOrReplaceNamedProperty(paramName, v); } return true; } NPError CreateControl(NPP instance, int16 argc, char *argn[], char *argv[], CAxHost **phost) { // Create a plugin instance, the actual control will be created once we // are given a window handle USES_CONVERSION; PropertyList events; CAxHost *host = new CAxHost(instance); *phost = host; if (!host) { np_log(instance, 0, "AxHost.NPP_New: failed to allocate memory for a new host"); return NPERR_OUT_OF_MEMORY_ERROR; } // Iterate over the arguments we've been passed for (int i = 0; i < argc; ++i) { // search for any needed information: clsid, event handling directives, etc. if (strnicmp(argn[i], PARAM_CLASSID, sizeof(PARAM_CLASSID)) == 0) { char clsid[100]; strncpy(clsid, argv[i], 80); strcat(clsid, "}"); char* id = strchr(clsid, ':'); if (id == NULL) continue; *id = '{'; host->setClsID(id); } else if (0 == strnicmp(argn[i], PARAM_NAME, sizeof(PARAM_NAME)) || 0 == strnicmp(argn[i], PARAM_ID, sizeof(PARAM_ID))) { np_log(instance, 1, "instance %s: %s", argn[i], argv[i]); } else if (0 == strnicmp(argn[i], PARAM_CLSID, sizeof(PARAM_CLSID))) { // The class id of the control we are asked to load host->setClsID(argv[i]); } else if (0 == strnicmp(argn[i], PARAM_PROGID, sizeof(PARAM_PROGID))) { // The class id of the control we are asked to load host->setClsIDFromProgID(argv[i]); } else if (0 == strnicmp(argn[i], PARAM_DEBUG, sizeof(PARAM_DEBUG))) { // Logging verbosity log_level = atoi(argv[i]); } else if (0 == strnicmp(argn[i], PARAM_ONEVENT, sizeof(PARAM_ONEVENT))) { // A request to handle one of the activex's events in JS events.AddOrReplaceNamedProperty(A2W(argn[i] + strlen(PARAM_ONEVENT)), CComVariant(A2W(argv[i]))); } else if(0 == strnicmp(argn[i], PARAM_CODEBASEURL, sizeof(PARAM_CODEBASEURL))) { if (MatchURL2TrustedLocations(instance, A2W(argv[i]))) { host->setCodeBaseUrl(A2W(argv[i])); } else { np_log(instance, 0, "AxHost.NPP_New: codeBaseUrl contains an untrusted location"); } } else if (0 == strnicmp(argn[i], PARAM_DYNAMIC, sizeof(PARAM_DYNAMIC))) { host->setNoWindow(true); } } if (!FillProperties(host, instance)) { return NPERR_GENERIC_ERROR; } // Make sure we have all the information we need to initialize a new instance if (!host->hasValidClsID()) { np_log(instance, 0, "AxHost.NPP_New: no valid CLSID or PROGID"); // create later. return NPERR_NO_ERROR; } instance->pdata = host; // if no events were requested, don't fail if subscribing fails if (!host->CreateControl(events.GetSize() ? true : false)) { np_log(instance, 0, "AxHost.NPP_New: failed to create the control"); return NPERR_GENERIC_ERROR; } for (unsigned int j = 0; j < events.GetSize(); j++) { if (!host->AddEventHandler(events.GetNameOf(j), events.GetValueOf(j)->bstrVal)) { //rc = NPERR_GENERIC_ERROR; //break; } } np_log(instance, 1, "%08x AxHost.NPP_New: Create control finished", instance); return NPERR_NO_ERROR; } /* * Create a new plugin instance, most probably through an embed/object HTML * element. * * Any private data we want to keep for this instance can be saved into * [instance->pdata]. * [saved] might hold information a previous instance that was invoked from the * same URL has saved for us. */ NPError NPP_New(NPMIMEType pluginType, NPP instance, uint16 mode, int16 argc, char *argn[], char *argv[], NPSavedData *saved) { NPError rc = NPERR_NO_ERROR; NPObject *browser = NULL; int16 i = 0; if (!instance || (0 == NPNFuncs.size)) { return NPERR_INVALID_PARAM; } instance->pdata = NULL; #ifdef NO_REGISTRY_AUTHORIZE // Verify that we're running from a trusted location if (!VerifySiteLock(instance)) { return NPERR_GENERIC_ERROR; } #else if (!TestAuthorization (instance, argc, argn, argv, pluginType)) { return NPERR_GENERIC_ERROR; } #endif InstallLogAction(instance); if (stricmp(pluginType, "application/x-itst-activex") == 0) { CAxHost *host = NULL; /* ObjectManager* manager = ObjectManager::GetManager(instance); if (manager && !(host = dynamic_cast<CAxHost*>(manager->GetPreviousObject(instance)))) { // Object is created before manager->RequestObjectOwnership(instance, host); } else */ { rc = CreateControl(instance, argc, argn, argv, &host); if (NPERR_NO_ERROR != rc) { delete host; instance->pdata = NULL; host = NULL; return rc; } } if (host) { host->RegisterObject(); instance->pdata = host; } } else if (stricmp(pluginType, "application/activex-manager") == 0) { // disabled now!! return rc = NPERR_GENERIC_ERROR; ObjectManager *manager = new ObjectManager(instance); manager->RegisterObject(); instance->pdata = manager; } return rc; } /* * Destroy an existing plugin instance. * * [save] can be used to save information for a future instance of our plugin * that'll be invoked by the same URL. */ NPError NPP_Destroy(NPP instance, NPSavedData **save) { if (!instance) { return NPERR_INVALID_PARAM; } CHost *host = (CHost *)instance->pdata; if (host) { np_log(instance, 0, "NPP_Destroy: destroying the control..."); //host->UnRegisterObject(); host->Release(); instance->pdata = NULL; /* ObjectManager *manager = ObjectManager::GetManager(instance); CAxHost *axHost = dynamic_cast<CAxHost*>(host); if (manager && axHost) { manager->RetainOwnership(axHost); } else { np_log(instance, 0, "NPP_Destroy: destroying the control..."); host->Release(); instance->pdata = NULL; }*/ } return NPERR_NO_ERROR; } /* * Sets an instance's window parameters. */ NPError NPP_SetWindow(NPP instance, NPWindow *window) { CAxHost *host = NULL; if (!instance || !instance->pdata) { return NPERR_INVALID_PARAM; } host = dynamic_cast<CAxHost*>((CHost *)instance->pdata); if (host) { host->SetNPWindow(window); } return NPERR_NO_ERROR; }
C++
/* ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0/LGPL 2.1 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * Contributor: * Chuan Qiu <qiuc12@gmail.com> * * Alternatively, the contents of this file may be used under the terms of * either the GNU General Public License Version 2 or later (the "GPL"), or * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), * in which case the provisions of the GPL or the LGPL are applicable instead * of those above. If you wish to allow use of your version of this file only * under the terms of either the GPL or the LGPL, and not to allow others to * use your version of this file under the terms of the MPL, indicate your * decision by deleting the provisions above and replace them with the notice * and other provisions required by the GPL or the LGPL. If you do not delete * the provisions above, a recipient may use your version of this file under * the terms of any one of the MPL, the GPL or the LGPL. * * ***** END LICENSE BLOCK ***** */ #include "ObjectManager.h" #include "npactivex.h" #include "host.h" #include "axhost.h" #include "objectProxy.h" #include "scriptable.h" #define MANAGER_OBJECT_ID "__activex_manager_IIID_" NPClass ObjectManager::npClass = { /* version */ NP_CLASS_STRUCT_VERSION, /* allocate */ ObjectManager::_Allocate, /* deallocate */ ObjectManager::Deallocate, /* invalidate */ NULL, /* hasMethod */ ObjectManager::HasMethod, /* invoke */ ObjectManager::Invoke, /* invokeDefault */ NULL, /* hasProperty */ ObjectManager::HasProperty, /* getProperty */ ObjectManager::GetProperty, /* setProperty */ ObjectManager::SetProperty, /* removeProperty */ NULL, /* enumerate */ NULL, /* construct */ NULL }; ObjectManager::ObjectManager(NPP npp_) : CHost(npp_) { } ObjectManager::~ObjectManager(void) { for (uint i = 0; i < hosts.size(); ++i) { hosts[i]->Release(); } for (uint i = 0; i < dynamic_hosts.size(); ++i) { dynamic_hosts[i]->Release(); } } ObjectManager* ObjectManager::GetManager(NPP npp) { NPObjectProxy window; NPNFuncs.getvalue(npp, NPNVWindowNPObject, &window); NPVariantProxy document, obj; NPVariant par; STRINGZ_TO_NPVARIANT(MANAGER_OBJECT_ID, par); if (!NPNFuncs.getproperty(npp, window, NPNFuncs.getstringidentifier("document"), &document)) return NULL; if (!NPNFuncs.invoke(npp, document.value.objectValue, NPNFuncs.getstringidentifier("getElementById"), &par, 1, &obj)) return NULL; if (NPVARIANT_IS_OBJECT(obj)) { NPObject *manager = NPVARIANT_TO_OBJECT(obj); ScriptBase *script = GetInternalObject(npp, manager); if (script) return dynamic_cast<ObjectManager*>(script->host); } return NULL; } CHost* ObjectManager::GetPreviousObject(NPP npp) { NPObjectProxy embed; NPNFuncs.getvalue(npp, NPNVPluginElementNPObject, &embed); return GetMyScriptObject()->host; } bool ObjectManager::HasMethod(NPObject *npobj, NPIdentifier name) { return name == NPNFuncs.getstringidentifier("CreateControlByProgId"); } bool ObjectManager::Invoke(NPObject *npobj, NPIdentifier name, const NPVariant *args, uint32_t argCount, NPVariant *result) { ScriptManager *obj = static_cast<ScriptManager*>(npobj); if (name == NPNFuncs.getstringidentifier("CreateControlByProgId")) { if (argCount != 1 || !NPVARIANT_IS_STRING(args[0])) { NPNFuncs.setexception(npobj, "Invalid arguments"); return false; } CAxHost* host = new CAxHost(obj->instance); CStringA str(NPVARIANT_TO_STRING(args[0]).UTF8Characters, NPVARIANT_TO_STRING(args[0]).UTF8Length); host->setClsIDFromProgID(str.GetString()); if (!host->CreateControl(false)) { NPNFuncs.setexception(npobj, "Error creating object"); return false; } ObjectManager *manager = static_cast<ObjectManager*>(obj->host); manager->dynamic_hosts.push_back(host); OBJECT_TO_NPVARIANT(host->CreateScriptableObject(), *result); return true; } return false; } bool ObjectManager::HasProperty(NPObject *npObj, NPIdentifier name) { if (name == NPNFuncs.getstringidentifier("internalId")) return true; if (name == NPNFuncs.getstringidentifier("isValid")) return true; return false; } bool ObjectManager::GetProperty(NPObject *npObj, NPIdentifier name, NPVariant *value) { if (name == NPNFuncs.getstringidentifier("internalId")) { int len = strlen(MANAGER_OBJECT_ID); char *stra = (char*)NPNFuncs.memalloc(len + 1); strcpy(stra, MANAGER_OBJECT_ID); STRINGN_TO_NPVARIANT(stra, len, *value); return true; } if (name == NPNFuncs.getstringidentifier("isValid")) { BOOLEAN_TO_NPVARIANT(TRUE, *value); return true; } return false; } bool ObjectManager::SetProperty(NPObject *npObj, NPIdentifier name, const NPVariant *value) { return false; } bool ObjectManager::RequestObjectOwnership(NPP newNpp, CAxHost* host) { // reference count of host not changed. for (uint i = 0; i < hosts.size(); ++i) { if (hosts[i] == host) { hosts[i] = hosts.back(); hosts.pop_back(); host->ResetNPP(newNpp); newNpp->pdata = host; return true; } } return false; } void ObjectManager::RetainOwnership(CAxHost* host) { hosts.push_back(host); host->ResetNPP(instance); } ScriptBase* ObjectManager::CreateScriptableObject() { ScriptBase* obj = static_cast<ScriptBase*>(NPNFuncs.createobject(instance, &npClass)); return obj; } void ObjectManager::Deallocate(NPObject *obj) { delete static_cast<ScriptManager*>(obj); }
C++
// stdafx.cpp : source file that includes just the standard includes // npactivex.pch will be the pre-compiled header // stdafx.obj will contain the pre-compiled type information #include "npactivex.h" // TODO: reference any additional headers you need in STDAFX.H // and not in this file
C++
#include "ScriptFunc.h" NPClass ScriptFunc::npClass = { /* version */ NP_CLASS_STRUCT_VERSION, /* allocate */ ScriptFunc::_Allocate, /* deallocate */ ScriptFunc::_Deallocate, /* invalidate */ NULL, /* hasMethod */ NULL, //Scriptable::_HasMethod, /* invoke */ NULL, //Scriptable::_Invoke, /* invokeDefault */ ScriptFunc::_InvokeDefault, /* hasProperty */ NULL, /* getProperty */ NULL, /* setProperty */ NULL, /* removeProperty */ NULL, /* enumerate */ NULL, /* construct */ NULL }; map<pair<Scriptable*, MEMBERID>, ScriptFunc*> ScriptFunc::M; ScriptFunc::ScriptFunc(NPP inst) { } ScriptFunc::~ScriptFunc(void) { if (script) { pair<Scriptable*, MEMBERID> index(script, dispid); NPNFuncs.releaseobject(script); M.erase(index); } } ScriptFunc* ScriptFunc::GetFunctionObject(NPP npp, Scriptable *script, MEMBERID dispid) { pair<Scriptable*, MEMBERID> index(script, dispid); if (M[index] == NULL) { ScriptFunc *new_obj = (ScriptFunc*)NPNFuncs.createobject(npp, &npClass); NPNFuncs.retainobject(script); new_obj->setControl(script, dispid); M[index] = new_obj; } else { NPNFuncs.retainobject(M[index]); } return M[index]; } bool ScriptFunc::InvokeDefault(const NPVariant *args, uint32_t argCount, NPVariant *result) { if (!script) return false; bool ret = script->InvokeID(dispid, args, argCount, result); if (!ret) { np_log(script->instance, 0, "Invoke failed, DISPID 0x%08x", dispid); } return ret; }
C++
// Copyright qiuc12@gmail.com // This file is generated autmatically by python. DONT MODIFY IT! #pragma once #include <OleAuto.h> class FakeDispatcher; HRESULT DualProcessCommand(int commandId, FakeDispatcher *disp, ...); extern "C" void DualProcessCommandWrap(); class FakeDispatcherBase : public IDispatch { private: virtual HRESULT __stdcall fv0(); virtual HRESULT __stdcall fv1(); virtual HRESULT __stdcall fv2(); virtual HRESULT __stdcall fv3(); virtual HRESULT __stdcall fv4(); virtual HRESULT __stdcall fv5(); virtual HRESULT __stdcall fv6(); virtual HRESULT __stdcall fv7(); virtual HRESULT __stdcall fv8(); virtual HRESULT __stdcall fv9(); virtual HRESULT __stdcall fv10(); virtual HRESULT __stdcall fv11(); virtual HRESULT __stdcall fv12(); virtual HRESULT __stdcall fv13(); virtual HRESULT __stdcall fv14(); virtual HRESULT __stdcall fv15(); virtual HRESULT __stdcall fv16(); virtual HRESULT __stdcall fv17(); virtual HRESULT __stdcall fv18(); virtual HRESULT __stdcall fv19(); virtual HRESULT __stdcall fv20(); virtual HRESULT __stdcall fv21(); virtual HRESULT __stdcall fv22(); virtual HRESULT __stdcall fv23(); virtual HRESULT __stdcall fv24(); virtual HRESULT __stdcall fv25(); virtual HRESULT __stdcall fv26(); virtual HRESULT __stdcall fv27(); virtual HRESULT __stdcall fv28(); virtual HRESULT __stdcall fv29(); virtual HRESULT __stdcall fv30(); virtual HRESULT __stdcall fv31(); virtual HRESULT __stdcall fv32(); virtual HRESULT __stdcall fv33(); virtual HRESULT __stdcall fv34(); virtual HRESULT __stdcall fv35(); virtual HRESULT __stdcall fv36(); virtual HRESULT __stdcall fv37(); virtual HRESULT __stdcall fv38(); virtual HRESULT __stdcall fv39(); virtual HRESULT __stdcall fv40(); virtual HRESULT __stdcall fv41(); virtual HRESULT __stdcall fv42(); virtual HRESULT __stdcall fv43(); virtual HRESULT __stdcall fv44(); virtual HRESULT __stdcall fv45(); virtual HRESULT __stdcall fv46(); virtual HRESULT __stdcall fv47(); virtual HRESULT __stdcall fv48(); virtual HRESULT __stdcall fv49(); virtual HRESULT __stdcall fv50(); virtual HRESULT __stdcall fv51(); virtual HRESULT __stdcall fv52(); virtual HRESULT __stdcall fv53(); virtual HRESULT __stdcall fv54(); virtual HRESULT __stdcall fv55(); virtual HRESULT __stdcall fv56(); virtual HRESULT __stdcall fv57(); virtual HRESULT __stdcall fv58(); virtual HRESULT __stdcall fv59(); virtual HRESULT __stdcall fv60(); virtual HRESULT __stdcall fv61(); virtual HRESULT __stdcall fv62(); virtual HRESULT __stdcall fv63(); virtual HRESULT __stdcall fv64(); virtual HRESULT __stdcall fv65(); virtual HRESULT __stdcall fv66(); virtual HRESULT __stdcall fv67(); virtual HRESULT __stdcall fv68(); virtual HRESULT __stdcall fv69(); virtual HRESULT __stdcall fv70(); virtual HRESULT __stdcall fv71(); virtual HRESULT __stdcall fv72(); virtual HRESULT __stdcall fv73(); virtual HRESULT __stdcall fv74(); virtual HRESULT __stdcall fv75(); virtual HRESULT __stdcall fv76(); virtual HRESULT __stdcall fv77(); virtual HRESULT __stdcall fv78(); virtual HRESULT __stdcall fv79(); virtual HRESULT __stdcall fv80(); virtual HRESULT __stdcall fv81(); virtual HRESULT __stdcall fv82(); virtual HRESULT __stdcall fv83(); virtual HRESULT __stdcall fv84(); virtual HRESULT __stdcall fv85(); virtual HRESULT __stdcall fv86(); virtual HRESULT __stdcall fv87(); virtual HRESULT __stdcall fv88(); virtual HRESULT __stdcall fv89(); virtual HRESULT __stdcall fv90(); virtual HRESULT __stdcall fv91(); virtual HRESULT __stdcall fv92(); virtual HRESULT __stdcall fv93(); virtual HRESULT __stdcall fv94(); virtual HRESULT __stdcall fv95(); virtual HRESULT __stdcall fv96(); virtual HRESULT __stdcall fv97(); virtual HRESULT __stdcall fv98(); virtual HRESULT __stdcall fv99(); virtual HRESULT __stdcall fv100(); virtual HRESULT __stdcall fv101(); virtual HRESULT __stdcall fv102(); virtual HRESULT __stdcall fv103(); virtual HRESULT __stdcall fv104(); virtual HRESULT __stdcall fv105(); virtual HRESULT __stdcall fv106(); virtual HRESULT __stdcall fv107(); virtual HRESULT __stdcall fv108(); virtual HRESULT __stdcall fv109(); virtual HRESULT __stdcall fv110(); virtual HRESULT __stdcall fv111(); virtual HRESULT __stdcall fv112(); virtual HRESULT __stdcall fv113(); virtual HRESULT __stdcall fv114(); virtual HRESULT __stdcall fv115(); virtual HRESULT __stdcall fv116(); virtual HRESULT __stdcall fv117(); virtual HRESULT __stdcall fv118(); virtual HRESULT __stdcall fv119(); virtual HRESULT __stdcall fv120(); virtual HRESULT __stdcall fv121(); virtual HRESULT __stdcall fv122(); virtual HRESULT __stdcall fv123(); virtual HRESULT __stdcall fv124(); virtual HRESULT __stdcall fv125(); virtual HRESULT __stdcall fv126(); virtual HRESULT __stdcall fv127(); virtual HRESULT __stdcall fv128(); virtual HRESULT __stdcall fv129(); virtual HRESULT __stdcall fv130(); virtual HRESULT __stdcall fv131(); virtual HRESULT __stdcall fv132(); virtual HRESULT __stdcall fv133(); virtual HRESULT __stdcall fv134(); virtual HRESULT __stdcall fv135(); virtual HRESULT __stdcall fv136(); virtual HRESULT __stdcall fv137(); virtual HRESULT __stdcall fv138(); virtual HRESULT __stdcall fv139(); virtual HRESULT __stdcall fv140(); virtual HRESULT __stdcall fv141(); virtual HRESULT __stdcall fv142(); virtual HRESULT __stdcall fv143(); virtual HRESULT __stdcall fv144(); virtual HRESULT __stdcall fv145(); virtual HRESULT __stdcall fv146(); virtual HRESULT __stdcall fv147(); virtual HRESULT __stdcall fv148(); virtual HRESULT __stdcall fv149(); virtual HRESULT __stdcall fv150(); virtual HRESULT __stdcall fv151(); virtual HRESULT __stdcall fv152(); virtual HRESULT __stdcall fv153(); virtual HRESULT __stdcall fv154(); virtual HRESULT __stdcall fv155(); virtual HRESULT __stdcall fv156(); virtual HRESULT __stdcall fv157(); virtual HRESULT __stdcall fv158(); virtual HRESULT __stdcall fv159(); virtual HRESULT __stdcall fv160(); virtual HRESULT __stdcall fv161(); virtual HRESULT __stdcall fv162(); virtual HRESULT __stdcall fv163(); virtual HRESULT __stdcall fv164(); virtual HRESULT __stdcall fv165(); virtual HRESULT __stdcall fv166(); virtual HRESULT __stdcall fv167(); virtual HRESULT __stdcall fv168(); virtual HRESULT __stdcall fv169(); virtual HRESULT __stdcall fv170(); virtual HRESULT __stdcall fv171(); virtual HRESULT __stdcall fv172(); virtual HRESULT __stdcall fv173(); virtual HRESULT __stdcall fv174(); virtual HRESULT __stdcall fv175(); virtual HRESULT __stdcall fv176(); virtual HRESULT __stdcall fv177(); virtual HRESULT __stdcall fv178(); virtual HRESULT __stdcall fv179(); virtual HRESULT __stdcall fv180(); virtual HRESULT __stdcall fv181(); virtual HRESULT __stdcall fv182(); virtual HRESULT __stdcall fv183(); virtual HRESULT __stdcall fv184(); virtual HRESULT __stdcall fv185(); virtual HRESULT __stdcall fv186(); virtual HRESULT __stdcall fv187(); virtual HRESULT __stdcall fv188(); virtual HRESULT __stdcall fv189(); virtual HRESULT __stdcall fv190(); virtual HRESULT __stdcall fv191(); virtual HRESULT __stdcall fv192(); virtual HRESULT __stdcall fv193(); virtual HRESULT __stdcall fv194(); virtual HRESULT __stdcall fv195(); virtual HRESULT __stdcall fv196(); virtual HRESULT __stdcall fv197(); virtual HRESULT __stdcall fv198(); virtual HRESULT __stdcall fv199(); protected: const static int kMaxVf = 200; };
C++
/* ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0/LGPL 2.1 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * Contributor: * Chuan Qiu <qiuc12@gmail.com> * * Alternatively, the contents of this file may be used under the terms of * either the GNU General Public License Version 2 or later (the "GPL"), or * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), * in which case the provisions of the GPL or the LGPL are applicable instead * of those above. If you wish to allow use of your version of this file only * under the terms of either the GPL or the LGPL, and not to allow others to * use your version of this file under the terms of the MPL, indicate your * decision by deleting the provisions above and replace them with the notice * and other provisions required by the GPL or the LGPL. If you do not delete * the provisions above, a recipient may use your version of this file under * the terms of any one of the MPL, the GPL or the LGPL. * * ***** END LICENSE BLOCK ***** */ #pragma once #include <npapi.h> #include <npruntime.h> #include <map> #include <vector> #include "Host.h" class CAxHost; class ObjectManager : public CHost { public: ObjectManager(NPP npp2); ~ObjectManager(void); static NPClass npClass; CHost* GetPreviousObject(NPP npp); static ObjectManager* GetManager(NPP npp); virtual ScriptBase *CreateScriptableObject(); void RetainOwnership(CAxHost *obj); bool RequestObjectOwnership(NPP newNpp, CAxHost* obj); private: struct ScriptManager : public ScriptBase { ScriptManager(NPP npp) : ScriptBase(npp) { } }; std::vector<CHost*> hosts; std::vector<CHost*> dynamic_hosts; static NPObject* _Allocate(NPP npp, NPClass *aClass) { ScriptManager *obj = new ScriptManager(npp); return obj; } static bool Invoke(NPObject *obj, NPIdentifier name, const NPVariant *args, uint32_t argCount, NPVariant *result); static bool HasMethod(NPObject *obj, NPIdentifier name); static bool HasProperty(NPObject *obj, NPIdentifier name); static bool GetProperty(NPObject *obj, NPIdentifier name, NPVariant *value); static bool SetProperty(NPObject *obj, NPIdentifier name, const NPVariant *value); static void Deallocate(NPObject *obj); };
C++
/* ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0/LGPL 2.1 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * Contributor: * Chuan Qiu <qiuc12@gmail.com> * * Alternatively, the contents of this file may be used under the terms of * either the GNU General Public License Version 2 or later (the "GPL"), or * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), * in which case the provisions of the GPL or the LGPL are applicable instead * of those above. If you wish to allow use of your version of this file only * under the terms of either the GPL or the LGPL, and not to allow others to * use your version of this file under the terms of the MPL, indicate your * decision by deleting the provisions above and replace them with the notice * and other provisions required by the GPL or the LGPL. If you do not delete * the provisions above, a recipient may use your version of this file under * the terms of any one of the MPL, the GPL or the LGPL. * * ***** END LICENSE BLOCK ***** */ #pragma once #include "oleidl.h" #include <npapi.h> #include <npruntime.h> #include "npactivex.h" #include "objectProxy.h" #include "FakeDispatcher.h" class HTMLDocumentContainer : public CComObjectRoot, public IOleContainer, public IServiceProviderImpl<HTMLDocumentContainer>, public IWebBrowser2 { public: HTMLDocumentContainer(); void Init(NPP instance, ITypeLib *htmlLib); ~HTMLDocumentContainer(void); // IOleContainer virtual HRESULT STDMETHODCALLTYPE EnumObjects( /* [in] */ DWORD grfFlags, /* [out] */ __RPC__deref_out_opt IEnumUnknown **ppenum) { return LogNotImplemented(npp); } virtual HRESULT STDMETHODCALLTYPE ParseDisplayName( /* [unique][in] */ __RPC__in_opt IBindCtx *pbc, /* [in] */ __RPC__in LPOLESTR pszDisplayName, /* [out] */ __RPC__out ULONG *pchEaten, /* [out] */ __RPC__deref_out_opt IMoniker **ppmkOut) { return LogNotImplemented(npp); } virtual HRESULT STDMETHODCALLTYPE LockContainer( /* [in] */ BOOL fLock) { return LogNotImplemented(npp); } // IWebBrowser2 virtual /* [helpcontext][helpstring][id] */ HRESULT STDMETHODCALLTYPE Navigate2( /* [in] */ __RPC__in VARIANT *URL, /* [unique][optional][in] */ __RPC__in_opt VARIANT *Flags, /* [unique][optional][in] */ __RPC__in_opt VARIANT *TargetFrameName, /* [unique][optional][in] */ __RPC__in_opt VARIANT *PostData, /* [unique][optional][in] */ __RPC__in_opt VARIANT *Headers) {return LogNotImplemented(npp);}; virtual /* [helpcontext][helpstring][id] */ HRESULT STDMETHODCALLTYPE QueryStatusWB( /* [in] */ OLECMDID cmdID, /* [retval][out] */ __RPC__out OLECMDF *pcmdf) {return LogNotImplemented(npp);}; virtual /* [helpcontext][helpstring][id] */ HRESULT STDMETHODCALLTYPE ExecWB( /* [in] */ OLECMDID cmdID, /* [in] */ OLECMDEXECOPT cmdexecopt, /* [unique][optional][in] */ __RPC__in_opt VARIANT *pvaIn, /* [unique][optional][out][in] */ __RPC__inout_opt VARIANT *pvaOut) {return LogNotImplemented(npp);}; virtual /* [helpcontext][helpstring][id] */ HRESULT STDMETHODCALLTYPE ShowBrowserBar( /* [in] */ __RPC__in VARIANT *pvaClsid, /* [unique][optional][in] */ __RPC__in_opt VARIANT *pvarShow, /* [unique][optional][in] */ __RPC__in_opt VARIANT *pvarSize) {return LogNotImplemented(npp);}; virtual /* [bindable][propget][id] */ HRESULT STDMETHODCALLTYPE get_ReadyState( /* [out][retval] */ __RPC__out READYSTATE *plReadyState) {return LogNotImplemented(npp);}; virtual /* [helpcontext][helpstring][propget][id] */ HRESULT STDMETHODCALLTYPE get_Offline( /* [retval][out] */ __RPC__out VARIANT_BOOL *pbOffline) {return LogNotImplemented(npp);}; virtual /* [helpcontext][helpstring][propput][id] */ HRESULT STDMETHODCALLTYPE put_Offline( /* [in] */ VARIANT_BOOL bOffline) {return LogNotImplemented(npp);}; virtual /* [helpcontext][helpstring][propget][id] */ HRESULT STDMETHODCALLTYPE get_Silent( /* [retval][out] */ __RPC__out VARIANT_BOOL *pbSilent) {return LogNotImplemented(npp);}; virtual /* [helpcontext][helpstring][propput][id] */ HRESULT STDMETHODCALLTYPE put_Silent( /* [in] */ VARIANT_BOOL bSilent) {return LogNotImplemented(npp);}; virtual /* [helpcontext][helpstring][propget][id] */ HRESULT STDMETHODCALLTYPE get_RegisterAsBrowser( /* [retval][out] */ __RPC__out VARIANT_BOOL *pbRegister) {return LogNotImplemented(npp);}; virtual /* [helpcontext][helpstring][propput][id] */ HRESULT STDMETHODCALLTYPE put_RegisterAsBrowser( /* [in] */ VARIANT_BOOL bRegister) {return LogNotImplemented(npp);}; virtual /* [helpcontext][helpstring][propget][id] */ HRESULT STDMETHODCALLTYPE get_RegisterAsDropTarget( /* [retval][out] */ __RPC__out VARIANT_BOOL *pbRegister) {return LogNotImplemented(npp);}; virtual /* [helpcontext][helpstring][propput][id] */ HRESULT STDMETHODCALLTYPE put_RegisterAsDropTarget( /* [in] */ VARIANT_BOOL bRegister) {return LogNotImplemented(npp);}; virtual /* [helpcontext][helpstring][propget][id] */ HRESULT STDMETHODCALLTYPE get_TheaterMode( /* [retval][out] */ __RPC__out VARIANT_BOOL *pbRegister) {return LogNotImplemented(npp);}; virtual /* [helpcontext][helpstring][propput][id] */ HRESULT STDMETHODCALLTYPE put_TheaterMode( /* [in] */ VARIANT_BOOL bRegister) {return LogNotImplemented(npp);}; virtual /* [helpcontext][helpstring][propget][id] */ HRESULT STDMETHODCALLTYPE get_AddressBar( /* [retval][out] */ __RPC__out VARIANT_BOOL *Value) {*Value = True;return LogNotImplemented(npp);}; virtual /* [helpcontext][helpstring][propput][id] */ HRESULT STDMETHODCALLTYPE put_AddressBar( /* [in] */ VARIANT_BOOL Value) {return LogNotImplemented(npp);}; virtual /* [helpcontext][helpstring][propget][id] */ HRESULT STDMETHODCALLTYPE get_Resizable( /* [retval][out] */ __RPC__out VARIANT_BOOL *Value) {return LogNotImplemented(npp);}; virtual /* [helpcontext][helpstring][propput][id] */ HRESULT STDMETHODCALLTYPE put_Resizable( /* [in] */ VARIANT_BOOL Value) {return LogNotImplemented(npp);}; virtual /* [helpcontext][helpstring][id] */ HRESULT STDMETHODCALLTYPE Quit( void) {return LogNotImplemented(npp);}; virtual /* [helpcontext][helpstring][id] */ HRESULT STDMETHODCALLTYPE ClientToWindow( /* [out][in] */ __RPC__inout int *pcx, /* [out][in] */ __RPC__inout int *pcy) {return LogNotImplemented(npp);}; virtual /* [helpcontext][helpstring][id] */ HRESULT STDMETHODCALLTYPE PutProperty( /* [in] */ __RPC__in BSTR Property, /* [in] */ VARIANT vtValue) {return LogNotImplemented(npp);}; virtual /* [helpcontext][helpstring][id] */ HRESULT STDMETHODCALLTYPE GetProperty( /* [in] */ __RPC__in BSTR Property, /* [retval][out] */ __RPC__out VARIANT *pvtValue) {return LogNotImplemented(npp);}; virtual /* [helpcontext][helpstring][propget][id] */ HRESULT STDMETHODCALLTYPE get_Name( /* [retval][out] */ __RPC__deref_out_opt BSTR *Name) {return LogNotImplemented(npp);}; virtual /* [helpcontext][helpstring][propget][id] */ HRESULT STDMETHODCALLTYPE get_HWND( /* [retval][out] */ __RPC__out SHANDLE_PTR *pHWND) {return LogNotImplemented(npp);}; virtual /* [helpcontext][helpstring][propget][id] */ HRESULT STDMETHODCALLTYPE get_FullName( /* [retval][out] */ __RPC__deref_out_opt BSTR *FullName) {return LogNotImplemented(npp);}; virtual /* [helpcontext][helpstring][propget][id] */ HRESULT STDMETHODCALLTYPE get_Path( /* [retval][out] */ __RPC__deref_out_opt BSTR *Path) {return LogNotImplemented(npp);}; virtual /* [helpcontext][helpstring][propget][id] */ HRESULT STDMETHODCALLTYPE get_Visible( /* [retval][out] */ __RPC__out VARIANT_BOOL *pBool) {return LogNotImplemented(npp);}; virtual /* [helpcontext][helpstring][propput][id] */ HRESULT STDMETHODCALLTYPE put_Visible( /* [in] */ VARIANT_BOOL Value) {return LogNotImplemented(npp);}; virtual /* [helpcontext][helpstring][propget][id] */ HRESULT STDMETHODCALLTYPE get_StatusBar( /* [retval][out] */ __RPC__out VARIANT_BOOL *pBool) {return LogNotImplemented(npp);}; virtual /* [helpcontext][helpstring][propput][id] */ HRESULT STDMETHODCALLTYPE put_StatusBar( /* [in] */ VARIANT_BOOL Value) {return LogNotImplemented(npp);}; virtual /* [helpcontext][helpstring][propget][id] */ HRESULT STDMETHODCALLTYPE get_StatusText( /* [retval][out] */ __RPC__deref_out_opt BSTR *StatusText) {return LogNotImplemented(npp);}; virtual /* [helpcontext][helpstring][propput][id] */ HRESULT STDMETHODCALLTYPE put_StatusText( /* [in] */ __RPC__in BSTR StatusText) {return LogNotImplemented(npp);}; virtual /* [helpcontext][helpstring][propget][id] */ HRESULT STDMETHODCALLTYPE get_ToolBar( /* [retval][out] */ __RPC__out int *Value) {return LogNotImplemented(npp);}; virtual /* [helpcontext][helpstring][propput][id] */ HRESULT STDMETHODCALLTYPE put_ToolBar( /* [in] */ int Value) {return LogNotImplemented(npp);}; virtual /* [helpcontext][helpstring][propget][id] */ HRESULT STDMETHODCALLTYPE get_MenuBar( /* [retval][out] */ __RPC__out VARIANT_BOOL *Value) {return LogNotImplemented(npp);}; virtual /* [helpcontext][helpstring][propput][id] */ HRESULT STDMETHODCALLTYPE put_MenuBar( /* [in] */ VARIANT_BOOL Value) {return LogNotImplemented(npp);}; virtual /* [helpcontext][helpstring][propget][id] */ HRESULT STDMETHODCALLTYPE get_FullScreen( /* [retval][out] */ __RPC__out VARIANT_BOOL *pbFullScreen) {*pbFullScreen = FALSE; return LogNotImplemented(npp);}; virtual /* [helpcontext][helpstring][propput][id] */ HRESULT STDMETHODCALLTYPE put_FullScreen( /* [in] */ VARIANT_BOOL bFullScreen) {return LogNotImplemented(npp);}; virtual /* [helpcontext][helpstring][id] */ HRESULT STDMETHODCALLTYPE GoBack( void) {return LogNotImplemented(npp);} virtual /* [helpcontext][helpstring][id] */ HRESULT STDMETHODCALLTYPE GoForward( void) {return LogNotImplemented(npp);} virtual /* [helpcontext][helpstring][id] */ HRESULT STDMETHODCALLTYPE GoHome( void) {return LogNotImplemented(npp);} virtual /* [helpcontext][helpstring][id] */ HRESULT STDMETHODCALLTYPE GoSearch( void) {return LogNotImplemented(npp);} virtual /* [helpcontext][helpstring][id] */ HRESULT STDMETHODCALLTYPE Navigate( /* [in] */ __RPC__in BSTR URL, /* [unique][optional][in] */ __RPC__in_opt VARIANT *Flags, /* [unique][optional][in] */ __RPC__in_opt VARIANT *TargetFrameName, /* [unique][optional][in] */ __RPC__in_opt VARIANT *PostData, /* [unique][optional][in] */ __RPC__in_opt VARIANT *Headers) {return LogNotImplemented(npp);} virtual /* [helpcontext][helpstring][id] */ HRESULT STDMETHODCALLTYPE Refresh( void) {return LogNotImplemented(npp);} virtual /* [helpcontext][helpstring][id] */ HRESULT STDMETHODCALLTYPE Refresh2( /* [unique][optional][in] */ __RPC__in_opt VARIANT *Level) {return LogNotImplemented(npp);} virtual /* [helpcontext][helpstring][id] */ HRESULT STDMETHODCALLTYPE Stop( void) {return LogNotImplemented(npp);} virtual /* [helpcontext][helpstring][propget][id] */ HRESULT STDMETHODCALLTYPE get_Application( /* [retval][out] */ __RPC__deref_out_opt IDispatch **ppDisp) {return LogNotImplemented(npp);} virtual /* [helpcontext][helpstring][propget][id] */ HRESULT STDMETHODCALLTYPE get_Parent( /* [retval][out] */ __RPC__deref_out_opt IDispatch **ppDisp) {return LogNotImplemented(npp);} virtual /* [helpcontext][helpstring][propget][id] */ HRESULT STDMETHODCALLTYPE get_Container( /* [retval][out] */ __RPC__deref_out_opt IDispatch **ppDisp) {return LogNotImplemented(npp);} virtual /* [helpcontext][helpstring][propget][id] */ HRESULT STDMETHODCALLTYPE get_Document( /* [retval][out] */ __RPC__deref_out_opt IDispatch **ppDisp); virtual /* [helpcontext][helpstring][propget][id] */ HRESULT STDMETHODCALLTYPE get_TopLevelContainer( /* [retval][out] */ __RPC__out VARIANT_BOOL *pBool) {return LogNotImplemented(npp);} virtual /* [helpcontext][helpstring][propget][id] */ HRESULT STDMETHODCALLTYPE get_Type( /* [retval][out] */ __RPC__deref_out_opt BSTR *Type) {return LogNotImplemented(npp);} virtual /* [helpcontext][helpstring][propget][id] */ HRESULT STDMETHODCALLTYPE get_Left( /* [retval][out] */ __RPC__out long *pl) {return LogNotImplemented(npp);} virtual /* [propput][id] */ HRESULT STDMETHODCALLTYPE put_Left( /* [in] */ long Left) {return LogNotImplemented(npp);} virtual /* [helpcontext][helpstring][propget][id] */ HRESULT STDMETHODCALLTYPE get_Top( /* [retval][out] */ __RPC__out long *pl) {return LogNotImplemented(npp);} virtual /* [propput][id] */ HRESULT STDMETHODCALLTYPE put_Top( /* [in] */ long Top) {return LogNotImplemented(npp);} virtual /* [helpcontext][helpstring][propget][id] */ HRESULT STDMETHODCALLTYPE get_Width( /* [retval][out] */ __RPC__out long *pl) {return LogNotImplemented(npp);} virtual /* [propput][id] */ HRESULT STDMETHODCALLTYPE put_Width( /* [in] */ long Width) {return LogNotImplemented(npp);} virtual /* [helpcontext][helpstring][propget][id] */ HRESULT STDMETHODCALLTYPE get_Height( /* [retval][out] */ __RPC__out long *pl) {return LogNotImplemented(npp);} virtual /* [propput][id] */ HRESULT STDMETHODCALLTYPE put_Height( /* [in] */ long Height) {return LogNotImplemented(npp);} virtual /* [helpcontext][helpstring][propget][id] */ HRESULT STDMETHODCALLTYPE get_LocationName( /* [retval][out] */ __RPC__deref_out_opt BSTR *LocationName) {return LogNotImplemented(npp);} virtual /* [helpcontext][helpstring][propget][id] */ HRESULT STDMETHODCALLTYPE get_LocationURL( /* [retval][out] */ __RPC__deref_out_opt BSTR *LocationURL); virtual /* [helpcontext][helpstring][propget][id] */ HRESULT STDMETHODCALLTYPE get_Busy( /* [retval][out] */ __RPC__out VARIANT_BOOL *pBool) {return LogNotImplemented(npp);} virtual HRESULT STDMETHODCALLTYPE GetTypeInfoCount( /* [out] */ __RPC__out UINT *pctinfo) {return LogNotImplemented(npp);} virtual HRESULT STDMETHODCALLTYPE GetTypeInfo( /* [in] */ UINT iTInfo, /* [in] */ LCID lcid, /* [out] */ __RPC__deref_out_opt ITypeInfo **ppTInfo) {return LogNotImplemented(npp);} virtual HRESULT STDMETHODCALLTYPE GetIDsOfNames( /* [in] */ __RPC__in REFIID riid, /* [size_is][in] */ __RPC__in_ecount_full(cNames) LPOLESTR *rgszNames, /* [range][in] */ __RPC__in_range(0,16384) UINT cNames, /* [in] */ LCID lcid, /* [size_is][out] */ __RPC__out_ecount_full(cNames) DISPID *rgDispId) {return LogNotImplemented(npp);} virtual /* [local] */ HRESULT STDMETHODCALLTYPE Invoke( /* [in] */ DISPID dispIdMember, /* [in] */ REFIID riid, /* [in] */ LCID lcid, /* [in] */ WORD wFlags, /* [out][in] */ DISPPARAMS *pDispParams, /* [out] */ VARIANT *pVarResult, /* [out] */ EXCEPINFO *pExcepInfo, /* [out] */ UINT *puArgErr) {return LogNotImplemented(npp);} BEGIN_COM_MAP(HTMLDocumentContainer) COM_INTERFACE_ENTRY(IOleContainer) COM_INTERFACE_ENTRY(IServiceProvider) COM_INTERFACE_ENTRY(IWebBrowser2) COM_INTERFACE_ENTRY_IID(IID_IWebBrowserApp, IWebBrowser2) COM_INTERFACE_ENTRY_IID(IID_IWebBrowser, IWebBrowser2) COM_INTERFACE_ENTRY_AGGREGATE_BLIND(dispatcher) END_COM_MAP() static const GUID IID_TopLevelBrowser; BEGIN_SERVICE_MAP(HTMLDocumentContainer) SERVICE_ENTRY(IID_IWebBrowserApp) SERVICE_ENTRY(IID_IWebBrowser2) SERVICE_ENTRY(IID_IWebBrowser) SERVICE_ENTRY(SID_SContainerDispatch); SERVICE_ENTRY(IID_TopLevelBrowser) END_SERVICE_MAP() private: FakeDispatcher *dispatcher; NPObjectProxy document_; NPP npp; };
C++
/* ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0/LGPL 2.1 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is itstructures.com code. * * The Initial Developer of the Original Code is IT Structures. * Portions created by the Initial Developer are Copyright (C) 2008 * the Initial Developer. All Rights Reserved. * * Alternatively, the contents of this file may be used under the terms of * either the GNU General Public License Version 2 or later (the "GPL"), or * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), * in which case the provisions of the GPL or the LGPL are applicable instead * of those above. If you wish to allow use of your version of this file only * under the terms of either the GPL or the LGPL, and not to allow others to * use your version of this file under the terms of the MPL, indicate your * decision by deleting the provisions above and replace them with the notice * and other provisions required by the GPL or the LGPL. If you do not delete * the provisions above, a recipient may use your version of this file under * the terms of any one of the MPL, the GPL or the LGPL. * * ***** END LICENSE BLOCK ***** */ #pragma once #include <atlbase.h> #include <comdef.h> #include <npapi.h> #include <npfunctions.h> #include <npruntime.h> #include "variants.h" #include "FakeDispatcher.h" #include "Host.h" extern NPNetscapeFuncs NPNFuncs; class CAxHost; struct Scriptable: public ScriptBase { private: Scriptable(const Scriptable &); // This method iterates all members of the current interface, looking for the member with the // id of member_id. If not found within this interface, it will iterate all base interfaces // recursively, until a match is found, or all the hierarchy was searched. bool find_member(ITypeInfoPtr info, TYPEATTR *attr, DISPID member_id, unsigned int invKind); DISPID ResolveName(NPIdentifier name, unsigned int invKind); //bool InvokeControl(DISPID id, WORD wFlags, DISPPARAMS *pDispParams, VARIANT *pVarResult); CComQIPtr<IDispatch> disp; bool invalid; DISPID dispid; void setControl(IUnknown *unk) { disp = unk; } bool IsProperty(DISPID member_id); public: Scriptable(NPP npp): ScriptBase(npp), invalid(false) { dispid = -1; } ~Scriptable() { } static NPClass npClass; static Scriptable* FromIUnknown(NPP npp, IUnknown *unk) { Scriptable *new_obj = (Scriptable*)NPNFuncs.createobject(npp, &npClass); new_obj->setControl(unk); return new_obj; } static Scriptable* FromAxHost(NPP npp, CAxHost* host); HRESULT getControl(IUnknown **obj) { if (disp) { *obj = disp.p; (*obj)->AddRef(); return S_OK; } return E_NOT_SET; } void Invalidate() {invalid = true;} bool HasMethod(NPIdentifier name); bool Invoke(NPIdentifier name, const NPVariant *args, uint32_t argCount, NPVariant *result); bool InvokeID(DISPID id, const NPVariant *args, uint32_t argCount, NPVariant *result); bool HasProperty(NPIdentifier name); bool GetProperty(NPIdentifier name, NPVariant *result); bool SetProperty(NPIdentifier name, const NPVariant *value); bool Enumerate(NPIdentifier **value, uint32_t *count); private: // Some wrappers to adapt NPAPI's interface. static NPObject* _Allocate(NPP npp, NPClass *aClass); static void _Deallocate(NPObject *obj); static void _Invalidate(NPObject *obj) { if (obj) { ((Scriptable *)obj)->Invalidate(); } } static bool _HasMethod(NPObject *npobj, NPIdentifier name) { return ((Scriptable *)npobj)->HasMethod(name); } static bool _Invoke(NPObject *npobj, NPIdentifier name, const NPVariant *args, uint32_t argCount, NPVariant *result) { return ((Scriptable *)npobj)->Invoke(name, args, argCount, result); } static bool _HasProperty(NPObject *npobj, NPIdentifier name) { return ((Scriptable *)npobj)->HasProperty(name); } static bool _GetProperty(NPObject *npobj, NPIdentifier name, NPVariant *result) { return ((Scriptable *)npobj)->GetProperty(name, result); } static bool _SetProperty(NPObject *npobj, NPIdentifier name, const NPVariant *value) { return ((Scriptable *)npobj)->SetProperty(name, value); } static bool _Enumerate(NPObject *npobj, NPIdentifier **value, uint32_t *count) { return ((Scriptable *)npobj)->Enumerate(value, count); } };
C++
/* ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0/LGPL 2.1 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * Contributor: * Chuan Qiu <qiuc12@gmail.com> * * Alternatively, the contents of this file may be used under the terms of * either the GNU General Public License Version 2 or later (the "GPL"), or * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), * in which case the provisions of the GPL or the LGPL are applicable instead * of those above. If you wish to allow use of your version of this file only * under the terms of either the GPL or the LGPL, and not to allow others to * use your version of this file under the terms of the MPL, indicate your * decision by deleting the provisions above and replace them with the notice * and other provisions required by the GPL or the LGPL. If you do not delete * the provisions above, a recipient may use your version of this file under * the terms of any one of the MPL, the GPL or the LGPL. * * ***** END LICENSE BLOCK ***** */ #pragma once #include <Windows.h> #include <OleAuto.h> #include <npapi.h> #include <npruntime.h> #include "FakeDispatcherBase.h" #include "objectProxy.h" extern ITypeLib *pHtmlLib; class CAxHost; EXTERN_C const IID IID_IFakeDispatcher; class FakeDispatcher : public FakeDispatcherBase { private: class FakeDispatcherEx: IDispatchEx { private: FakeDispatcher *target; public: FakeDispatcherEx(FakeDispatcher *target) : target(target) { } virtual HRESULT STDMETHODCALLTYPE QueryInterface( REFIID riid, __RPC__deref_out void __RPC_FAR *__RPC_FAR *ppvObject) { return target->QueryInterface(riid, ppvObject); } virtual ULONG STDMETHODCALLTYPE AddRef( void) { return target->AddRef(); } virtual ULONG STDMETHODCALLTYPE Release( void) { return target->Release(); } virtual HRESULT STDMETHODCALLTYPE GetTypeInfoCount( __RPC__out UINT *pctinfo) { return target->GetTypeInfoCount(pctinfo); } virtual HRESULT STDMETHODCALLTYPE GetTypeInfo( UINT iTInfo, LCID lcid, __RPC__deref_out_opt ITypeInfo **ppTInfo) { return target->GetTypeInfo(iTInfo, lcid, ppTInfo); } virtual HRESULT STDMETHODCALLTYPE GetIDsOfNames( __RPC__in REFIID riid, __RPC__in_ecount_full(cNames) LPOLESTR *rgszNames, __RPC__in_range(0,16384) UINT cNames, LCID lcid, __RPC__out_ecount_full(cNames) DISPID *rgDispId) { return target->GetIDsOfNames(riid, rgszNames, cNames, lcid, rgDispId); } virtual HRESULT STDMETHODCALLTYPE Invoke( DISPID dispIdMember, REFIID riid, LCID lcid, WORD wFlags, DISPPARAMS *pDispParams, VARIANT *pVarResult, EXCEPINFO *pExcepInfo, UINT *puArgErr) { return target->Invoke(dispIdMember, riid, lcid, wFlags, pDispParams, pVarResult, pExcepInfo, puArgErr); } virtual HRESULT STDMETHODCALLTYPE GetDispID( __RPC__in BSTR bstrName, DWORD grfdex, __RPC__out DISPID *pid); virtual HRESULT STDMETHODCALLTYPE InvokeEx( __in DISPID id, __in LCID lcid, __in WORD wFlags, __in DISPPARAMS *pdp, __out_opt VARIANT *pvarRes, __out_opt EXCEPINFO *pei, __in_opt IServiceProvider *pspCaller); virtual HRESULT STDMETHODCALLTYPE DeleteMemberByName( __RPC__in BSTR bstrName, DWORD grfdex); virtual HRESULT STDMETHODCALLTYPE DeleteMemberByDispID(DISPID id); virtual HRESULT STDMETHODCALLTYPE GetMemberProperties( DISPID id, DWORD grfdexFetch, __RPC__out DWORD *pgrfdex); virtual HRESULT STDMETHODCALLTYPE GetMemberName( DISPID id, __RPC__deref_out_opt BSTR *pbstrName); virtual HRESULT STDMETHODCALLTYPE GetNextDispID( DWORD grfdex, DISPID id, __RPC__out DISPID *pid); virtual HRESULT STDMETHODCALLTYPE GetNameSpaceParent( __RPC__deref_out_opt IUnknown **ppunk); }; public: virtual HRESULT STDMETHODCALLTYPE QueryInterface( REFIID riid, __RPC__deref_out void __RPC_FAR *__RPC_FAR *ppvObject); virtual ULONG STDMETHODCALLTYPE AddRef( void) { ++ref; return ref; } virtual ULONG STDMETHODCALLTYPE Release( void) { --ref; if (ref == 0) delete this; return ref; } virtual HRESULT STDMETHODCALLTYPE GetTypeInfoCount( __RPC__out UINT *pctinfo) { *pctinfo = 1; return S_OK; } virtual HRESULT STDMETHODCALLTYPE GetTypeInfo( UINT iTInfo, LCID lcid, __RPC__deref_out_opt ITypeInfo **ppTInfo); virtual HRESULT STDMETHODCALLTYPE GetIDsOfNames( __RPC__in REFIID riid, __RPC__in_ecount_full(cNames) LPOLESTR *rgszNames, __RPC__in_range(0,16384) UINT cNames, LCID lcid, __RPC__out_ecount_full(cNames) DISPID *rgDispId); virtual HRESULT STDMETHODCALLTYPE Invoke( DISPID dispIdMember, REFIID riid, LCID lcid, WORD wFlags, DISPPARAMS *pDispParams, VARIANT *pVarResult, EXCEPINFO *pExcepInfo, UINT *puArgErr); NPObject *getObject() { return npObject; } FakeDispatcher(NPP npInstance, ITypeLib *typeLib, NPObject *object); ~FakeDispatcher(void); HRESULT ProcessCommand(int ID, int *parlength,va_list &list); //friend HRESULT __cdecl DualProcessCommand(int parlength, int commandId, FakeDispatcher *disp, ...); private: static ITypeInfo* npTypeInfo; const static int DISPATCH_VTABLE = 7; FakeDispatcherEx *extended; NPP npInstance; NPObject *npObject; ITypeLib *typeLib; ITypeInfo *typeInfo; CAxHost *internalObj; bool HasValidTypeInfo(); int ref; DWORD dualType; #ifdef DEBUG char name[50]; char tag[100]; GUID interfaceid; #endif UINT FindFuncByVirtualId(int vtbId); };
C++
/* ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0/LGPL 2.1 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * Contributor: * Chuan Qiu <qiuc12@gmail.com> * * Alternatively, the contents of this file may be used under the terms of * either the GNU General Public License Version 2 or later (the "GPL"), or * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), * in which case the provisions of the GPL or the LGPL are applicable instead * of those above. If you wish to allow use of your version of this file only * under the terms of either the GPL or the LGPL, and not to allow others to * use your version of this file under the terms of the MPL, indicate your * decision by deleting the provisions above and replace them with the notice * and other provisions required by the GPL or the LGPL. If you do not delete * the provisions above, a recipient may use your version of this file under * the terms of any one of the MPL, the GPL or the LGPL. * * ***** END LICENSE BLOCK ***** */ #include <atlstr.h> #include "npactivex.h" #include "scriptable.h" #include "axhost.h" #include "ObjectManager.h" #include "FakeDispatcher.h" // {1DDBD54F-2F8A-4186-972B-2A84FE1135FE} static const GUID IID_IFakeDispatcher = { 0x1ddbd54f, 0x2f8a, 0x4186, { 0x97, 0x2b, 0x2a, 0x84, 0xfe, 0x11, 0x35, 0xfe } }; ITypeInfo* FakeDispatcher::npTypeInfo = (ITypeInfo*)-1; #define DispatchLog(level, message, ...) np_log(this->npInstance, level, "Disp 0x%08x " message, this, ##__VA_ARGS__) FakeDispatcher::FakeDispatcher(NPP npInstance, ITypeLib *typeLib, NPObject *object) : npInstance(npInstance), typeLib(typeLib), npObject(object), typeInfo(NULL), internalObj(NULL), extended(NULL) { ref = 1; typeLib->AddRef(); NPNFuncs.retainobject(object); ScriptBase *base = ObjectManager::GetInternalObject(npInstance, object); if (base) internalObj = dynamic_cast<CAxHost*>(base->host); #ifdef DEBUG name[0] = 0; tag[0] = 0; interfaceid = GUID_NULL; #endif NPVariantProxy npName, npTag; ATL::CStringA sname, stag; NPNFuncs.getproperty(npInstance, object, NPNFuncs.getstringidentifier("id"), &npName); if (npName.type != NPVariantType_String || npName.value.stringValue.UTF8Length == 0) NPNFuncs.getproperty(npInstance, object, NPNFuncs.getstringidentifier("name"), &npName); if (npName.type == NPVariantType_String) { sname = CStringA(npName.value.stringValue.UTF8Characters, npName.value.stringValue.UTF8Length); #ifdef DEBUG strncpy(name, npName.value.stringValue.UTF8Characters, npName.value.stringValue.UTF8Length); name[npName.value.stringValue.UTF8Length] = 0; #endif } if (NPNFuncs.hasmethod(npInstance, object, NPNFuncs.getstringidentifier("toString"))) { NPNFuncs.invoke(npInstance, object, NPNFuncs.getstringidentifier("toString"), &npTag, 0, &npTag); if (npTag.type == NPVariantType_String) { stag = CStringA(npTag.value.stringValue.UTF8Characters, npTag.value.stringValue.UTF8Length); #ifdef DEBUG strncpy(tag, npTag.value.stringValue.UTF8Characters, npTag.value.stringValue.UTF8Length); tag[npTag.value.stringValue.UTF8Length] = 0; #endif } } DispatchLog(1, "Type: %s, Name: %s", stag.GetString(), sname.GetString()); } /* [local] */ HRESULT STDMETHODCALLTYPE FakeDispatcher::Invoke( /* [in] */ DISPID dispIdMember, /* [in] */ REFIID riid, /* [in] */ LCID lcid, /* [in] */ WORD wFlags, /* [out][in] */ DISPPARAMS *pDispParams, /* [out] */ VARIANT *pVarResult, /* [out] */ EXCEPINFO *pExcepInfo, /* [out] */ UINT *puArgErr) { USES_CONVERSION; // Convert variants int nArgs = pDispParams->cArgs; NPVariantProxy *npvars = new NPVariantProxy[nArgs]; for (int i = 0; i < nArgs; ++i) { Variant2NPVar(&pDispParams->rgvarg[nArgs - 1 - i], &npvars[i], npInstance); } // Determine method to call. HRESULT hr = E_FAIL; BSTR pBstrName; NPVariantProxy result; NPIdentifier identifier = NULL; NPIdentifier itemIdentifier = NULL; if (HasValidTypeInfo() && SUCCEEDED(typeInfo->GetDocumentation(dispIdMember, &pBstrName, NULL, NULL, NULL))) { LPSTR str = OLE2A(pBstrName); SysFreeString(pBstrName); DispatchLog(2, "Invoke 0x%08x %d %s", dispIdMember, wFlags, str); if (dispIdMember == 0x401 && strcmp(str, "url") == 0) { str = "baseURI"; } else if (dispIdMember == 0x40A && strcmp(str, "parentWindow") == 0) { str = "defaultView"; } identifier = NPNFuncs.getstringidentifier(str); if (dispIdMember == 0 && (wFlags & DISPATCH_METHOD) && strcmp(str, "item") == 0) { // Item can be evaluated as the default property. if (NPVARIANT_IS_INT32(npvars[0])) itemIdentifier = NPNFuncs.getintidentifier(npvars[0].value.intValue); else if (NPVARIANT_IS_STRING(npvars[0])) itemIdentifier = NPNFuncs.getstringidentifier(npvars[0].value.stringValue.UTF8Characters); } else if (dispIdMember == 0x3E9 && (wFlags & DISPATCH_PROPERTYGET) && strcmp(str, "Script") == 0) { identifier = NPNFuncs.getstringidentifier("defaultView"); } } else if (typeInfo == npTypeInfo && dispIdMember != NULL && dispIdMember != -1) { identifier = (NPIdentifier) dispIdMember; } if (FAILED(hr) && itemIdentifier != NULL) { if (NPNFuncs.hasproperty(npInstance, npObject, itemIdentifier)) { if (NPNFuncs.getproperty(npInstance, npObject, itemIdentifier, &result)) { hr = S_OK; } } } if (FAILED(hr) && (wFlags & DISPATCH_METHOD)) { if (NPNFuncs.invoke(npInstance, npObject, identifier, npvars, nArgs, &result)) { hr = S_OK; } } if (FAILED(hr) && (wFlags & DISPATCH_PROPERTYGET)) { if (NPNFuncs.hasproperty(npInstance, npObject, identifier)) { if (NPNFuncs.getproperty(npInstance, npObject, identifier, &result)) { hr = S_OK; } } } if (FAILED(hr) && (wFlags & DISPATCH_PROPERTYPUT)) { if (nArgs == 1 && NPNFuncs.setproperty(npInstance, npObject, identifier, npvars)) hr = S_OK; } if (FAILED(hr) && dispIdMember == 0 && (wFlags & DISPATCH_METHOD)) { // Call default method. if (NPNFuncs.invokeDefault(npInstance, npObject, npvars, nArgs, &result)) { hr = S_OK; } } if (FAILED(hr) && dispIdMember == 0 && (wFlags & DISPATCH_PROPERTYGET) && pDispParams->cArgs == 0) { // Return toString() static NPIdentifier strIdentify = NPNFuncs.getstringidentifier("toString"); if (NPNFuncs.invoke(npInstance, npObject, strIdentify, NULL, 0, &result)) hr = S_OK; } if (SUCCEEDED(hr)) { NPVar2Variant(&result, pVarResult, npInstance); } else { DispatchLog(2, "Invoke failed 0x%08x %d", dispIdMember, wFlags); } delete [] npvars; return hr; } HRESULT STDMETHODCALLTYPE FakeDispatcher::QueryInterface( /* [in] */ REFIID riid, /* [iid_is][out] */ __RPC__deref_out void __RPC_FAR *__RPC_FAR *ppvObject) { HRESULT hr = E_FAIL; if (riid == IID_IDispatch || riid == IID_IUnknown) { *ppvObject = this; AddRef(); hr = S_OK; } else if (riid == IID_IDispatchEx) { if (extended == NULL) extended = new FakeDispatcherEx(this); *ppvObject = extended; AddRef(); hr = S_OK; } else if (riid == IID_IFakeDispatcher) { *ppvObject = this; AddRef(); hr = S_OK; } else if (!typeInfo) { hr = typeLib->GetTypeInfoOfGuid(riid, &typeInfo); if (SUCCEEDED(hr)) { TYPEATTR *attr; typeInfo->GetTypeAttr(&attr); dualType = attr->wTypeFlags; *ppvObject = static_cast<FakeDispatcher*>(this); AddRef(); typeInfo->ReleaseTypeAttr(attr); } } else { FakeDispatcher *another_obj = new FakeDispatcher(npInstance, typeLib, npObject); hr = another_obj->QueryInterface(riid, ppvObject); another_obj->Release(); } if (FAILED(hr) && internalObj) { IUnknown *unk; internalObj->GetControlUnknown(&unk); hr = unk->QueryInterface(riid, ppvObject); unk->Release(); /* // Try to find the internal object NPIdentifier object_id = NPNFuncs.getstringidentifier(object_property); NPVariant npVar; if (NPNFuncs.getproperty(npInstance, npObject, object_id, &npVar) && npVar.type == NPVariantType_Int32) { IUnknown *internalObject = (IUnknown*)NPVARIANT_TO_INT32(npVar); hr = internalObject->QueryInterface(riid, ppvObject); }*/ } #ifdef DEBUG if (hr == S_OK) { interfaceid = riid; } else { // Unsupported Interface! } #endif USES_CONVERSION; LPOLESTR clsid; StringFromCLSID(riid, &clsid); if (FAILED(hr)) { DispatchLog(0, "Unsupported Interface %s", OLE2A(clsid)); } else { DispatchLog(0, "QueryInterface %s", OLE2A(clsid)); } return hr; } FakeDispatcher::~FakeDispatcher(void) { if (HasValidTypeInfo()) { typeInfo->Release(); } if (extended) { delete extended; } DispatchLog(3, "Release"); NPNFuncs.releaseobject(npObject); typeLib->Release(); } // This function is used because the symbol of FakeDispatcher::ProcessCommand is not determined in asm file. extern "C" HRESULT __cdecl DualProcessCommand(int parlength, int commandId, int returnAddr, FakeDispatcher *disp, ...){ // returnAddr is a placeholder for the calling proc. va_list va; va_start(va, disp); // The parlength is on the stack, the modification will be reflect. HRESULT ret = disp->ProcessCommand(commandId, &parlength, va); va_end(va); return ret; } HRESULT FakeDispatcher::GetTypeInfo( /* [in] */ UINT iTInfo, /* [in] */ LCID lcid, /* [out] */ __RPC__deref_out_opt ITypeInfo **ppTInfo) { if (iTInfo == 0 && HasValidTypeInfo()) { *ppTInfo = typeInfo; typeInfo->AddRef(); return S_OK; } return E_INVALIDARG; } HRESULT FakeDispatcher::GetIDsOfNames( /* [in] */ __RPC__in REFIID riid, /* [size_is][in] */ __RPC__in_ecount_full(cNames) LPOLESTR *rgszNames, /* [range][in] */ __RPC__in_range(0,16384) UINT cNames, /* [in] */ LCID lcid, /* [size_is][out] */ __RPC__out_ecount_full(cNames) DISPID *rgDispId){ if (HasValidTypeInfo()) { return typeInfo->GetIDsOfNames(rgszNames, cNames, rgDispId); } else { USES_CONVERSION; typeInfo = npTypeInfo; for (UINT i = 0; i < cNames; ++i) { DispatchLog(2, "GetIDsOfNames %s", OLE2A(rgszNames[i])); rgDispId[i] = (DISPID) NPNFuncs.getstringidentifier(OLE2A(rgszNames[i])); } return S_OK; } } HRESULT FakeDispatcher::ProcessCommand(int vfid, int *parlength, va_list &args) { // This exception is critical if we can't find the size of parameters. if (!HasValidTypeInfo()) { DispatchLog(0, "VT interface %d called without type info", vfid); __asm int 3; } UINT index = FindFuncByVirtualId(vfid); if (index == (UINT)-1) { DispatchLog(0, "Unknown VT interface id"); __asm int 3; } FUNCDESC *func; // We should count pointer of "this" first. *parlength = sizeof(LPVOID); if (FAILED(typeInfo->GetFuncDesc(index, &func))) __asm int 3; DISPPARAMS varlist; // We don't need to clear them. VARIANT *list = new VARIANT[func->cParams]; varlist.cArgs = func->cParams; varlist.cNamedArgs = 0; varlist.rgdispidNamedArgs = NULL; varlist.rgvarg = list; // Thanks that there won't be any out variants in HTML. for (int i = 0; i < func->cParams; ++i) { int listPos = func->cParams - 1 - i; ELEMDESC *desc = &func->lprgelemdescParam[listPos]; memset(&list[listPos], 0, sizeof(list[listPos])); RawTypeToVariant(desc->tdesc, args, &list[listPos]); size_t varsize = VariantSize(desc->tdesc.vt); size_t intvarsz = (varsize + sizeof(int) - 1) & (~(sizeof(int) - 1)); args += intvarsz; *parlength += intvarsz; } // We needn't clear it. Caller takes ownership. VARIANT result; HRESULT ret = Invoke(func->memid, IID_NULL, NULL, func->invkind, &varlist, &result, NULL, NULL); if (SUCCEEDED(ret)) ret = ConvertVariantToGivenType(typeInfo, func->elemdescFunc.tdesc, result, args); size_t varsize = VariantSize(func->elemdescFunc.tdesc.vt); // It should always be a pointer. It always should be counted. size_t intvarsz = varsize ? sizeof(LPVOID) : 0; *parlength += intvarsz; delete[] list; return ret; } UINT FakeDispatcher::FindFuncByVirtualId(int vtbId) { if (dualType & TYPEFLAG_FDUAL) return vtbId + DISPATCH_VTABLE; else return vtbId; } bool FakeDispatcher::HasValidTypeInfo() { return typeInfo && typeInfo != npTypeInfo; } HRESULT STDMETHODCALLTYPE FakeDispatcher::FakeDispatcherEx::GetDispID( __RPC__in BSTR bstrName, DWORD grfdex, __RPC__out DISPID *pid) { return LogNotImplemented(target->npInstance); } HRESULT STDMETHODCALLTYPE FakeDispatcher::FakeDispatcherEx::InvokeEx( __in DISPID id, __in LCID lcid, __in WORD wFlags, __in DISPPARAMS *pdp, __out_opt VARIANT *pvarRes, __out_opt EXCEPINFO *pei, __in_opt IServiceProvider *pspCaller) { return LogNotImplemented(target->npInstance); } HRESULT STDMETHODCALLTYPE FakeDispatcher::FakeDispatcherEx::DeleteMemberByName( __RPC__in BSTR bstrName, DWORD grfdex) { return LogNotImplemented(target->npInstance); } HRESULT STDMETHODCALLTYPE FakeDispatcher::FakeDispatcherEx::DeleteMemberByDispID(DISPID id) { return LogNotImplemented(target->npInstance); } HRESULT STDMETHODCALLTYPE FakeDispatcher::FakeDispatcherEx::GetMemberProperties( DISPID id, DWORD grfdexFetch, __RPC__out DWORD *pgrfdex) { return LogNotImplemented(target->npInstance); } HRESULT STDMETHODCALLTYPE FakeDispatcher::FakeDispatcherEx::GetMemberName( DISPID id, __RPC__deref_out_opt BSTR *pbstrName) { return LogNotImplemented(target->npInstance); } HRESULT STDMETHODCALLTYPE FakeDispatcher::FakeDispatcherEx::GetNextDispID( DWORD grfdex, DISPID id, __RPC__out DISPID *pid) { return LogNotImplemented(target->npInstance); } HRESULT STDMETHODCALLTYPE FakeDispatcher::FakeDispatcherEx::GetNameSpaceParent( __RPC__deref_out_opt IUnknown **ppunk) { return LogNotImplemented(target->npInstance); }
C++
/* ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0/LGPL 2.1 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is itstructures.com code. * * The Initial Developer of the Original Code is IT Structures. * Portions created by the Initial Developer are Copyright (C) 2008 * the Initial Developer. All Rights Reserved. * * Contributor: * Ruediger Jungbeck <ruediger.jungbeck@rsj.de> * * Alternatively, the contents of this file may be used under the terms of * either the GNU General Public License Version 2 or later (the "GPL"), or * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), * in which case the provisions of the GPL or the LGPL are applicable instead * of those above. If you wish to allow use of your version of this file only * under the terms of either the GPL or the LGPL, and not to allow others to * use your version of this file under the terms of the MPL, indicate your * decision by deleting the provisions above and replace them with the notice * and other provisions required by the GPL or the LGPL. If you do not delete * the provisions above, a recipient may use your version of this file under * the terms of any one of the MPL, the GPL or the LGPL. * * ***** END LICENSE BLOCK ***** */ // dllmain.cpp : Defines the entry point for the DLL application. #include "npactivex.h" #include "axhost.h" #include "atlthunk.h" #include "FakeDispatcher.h" CComModule _Module; NPNetscapeFuncs NPNFuncs; BOOL APIENTRY DllMain( HMODULE hModule, DWORD ul_reason_for_call, LPVOID lpReserved ) { switch (ul_reason_for_call) { case DLL_PROCESS_ATTACH: case DLL_THREAD_ATTACH: case DLL_THREAD_DETACH: case DLL_PROCESS_DETACH: break; } return TRUE; } // ============================== // ! Scriptability related code ! // ============================== // // here the plugin is asked by Mozilla to tell if it is scriptable // we should return a valid interface id and a pointer to // nsScriptablePeer interface which we should have implemented // and which should be defined in the corressponding *.xpt file // in the bin/components folder NPError NPP_GetValue(NPP instance, NPPVariable variable, void *value) { if(instance == NULL) return NPERR_INVALID_INSTANCE_ERROR; NPError rv = NPERR_NO_ERROR; if(instance == NULL) return NPERR_GENERIC_ERROR; CAxHost *host = (CAxHost *)instance->pdata; if(host == NULL) return NPERR_GENERIC_ERROR; switch (variable) { case NPPVpluginNameString: *((char **)value) = "ITSTActiveX"; break; case NPPVpluginDescriptionString: *((char **)value) = "IT Structures ActiveX for Firefox"; break; case NPPVpluginScriptableNPObject: *(NPObject **)value = host->GetScriptableObject(); break; default: rv = NPERR_GENERIC_ERROR; } return rv; } NPError NPP_NewStream(NPP instance, NPMIMEType type, NPStream* stream, NPBool seekable, uint16* stype) { if(instance == NULL) return NPERR_INVALID_INSTANCE_ERROR; NPError rv = NPERR_NO_ERROR; return rv; } int32_t NPP_WriteReady (NPP instance, NPStream *stream) { if(instance == NULL) return NPERR_INVALID_INSTANCE_ERROR; int32 rv = 0x0fffffff; return rv; } int32_t NPP_Write (NPP instance, NPStream *stream, int32_t offset, int32_t len, void *buffer) { if(instance == NULL) return NPERR_INVALID_INSTANCE_ERROR; int32 rv = len; return rv; } NPError NPP_DestroyStream (NPP instance, NPStream *stream, NPError reason) { if(instance == NULL) return NPERR_INVALID_INSTANCE_ERROR; NPError rv = NPERR_NO_ERROR; return rv; } void NPP_StreamAsFile (NPP instance, NPStream* stream, const char* fname) { if(instance == NULL) return; } void NPP_Print (NPP instance, NPPrint* printInfo) { if(instance == NULL) return; } void NPP_URLNotify(NPP instance, const char* url, NPReason reason, void* notifyData) { if(instance == NULL) return; } NPError NPP_SetValue(NPP instance, NPNVariable variable, void *value) { if(instance == NULL) return NPERR_INVALID_INSTANCE_ERROR; NPError rv = NPERR_NO_ERROR; return rv; } int16 NPP_HandleEvent(NPP instance, void* event) { if(instance == NULL) return 0; int16 rv = 0; CAxHost *host = dynamic_cast<CAxHost*>((CHost *)instance->pdata); if (host) rv = host->HandleEvent(event); return rv; } NPError OSCALL NP_GetEntryPoints(NPPluginFuncs* pFuncs) { if(pFuncs == NULL) return NPERR_INVALID_FUNCTABLE_ERROR; if(pFuncs->size < sizeof(NPPluginFuncs)) return NPERR_INVALID_FUNCTABLE_ERROR; pFuncs->version = (NP_VERSION_MAJOR << 8) | NP_VERSION_MINOR; pFuncs->newp = NPP_New; pFuncs->destroy = NPP_Destroy; pFuncs->setwindow = NPP_SetWindow; pFuncs->newstream = NPP_NewStream; pFuncs->destroystream = NPP_DestroyStream; pFuncs->asfile = NPP_StreamAsFile; pFuncs->writeready = NPP_WriteReady; pFuncs->write = NPP_Write; pFuncs->print = NPP_Print; pFuncs->event = NPP_HandleEvent; pFuncs->urlnotify = NPP_URLNotify; pFuncs->getvalue = NPP_GetValue; pFuncs->setvalue = NPP_SetValue; pFuncs->javaClass = NULL; return NPERR_NO_ERROR; } #define MIN(x, y) ((x) < (y)) ? (x) : (y) /* * Initialize the plugin. Called the first time the browser comes across a * MIME Type this plugin is registered to handle. */ NPError OSCALL NP_Initialize(NPNetscapeFuncs* pFuncs) { #ifdef DEBUG CString text; text.Format(_T("NPActiveX Pid %d"), GetCurrentProcessId()); MessageBox(NULL, text, _T(""), MB_OK); #endif CoInitialize(NULL); InstallAtlThunkEnumeration(); if (pHtmlLib == NULL) { OLECHAR path[MAX_PATH]; GetEnvironmentVariableW(OLESTR("SYSTEMROOT"), path, MAX_PATH - 30); StrCatW(path, L"\\system32\\mshtml.tlb"); HRESULT hr = LoadTypeLib(path, &pHtmlLib); } if(pFuncs == NULL) return NPERR_INVALID_FUNCTABLE_ERROR; #ifdef NDEF // The following statements prevented usage of newer Mozilla sources than installed browser at runtime if(HIBYTE(pFuncs->version) > NP_VERSION_MAJOR) return NPERR_INCOMPATIBLE_VERSION_ERROR; if(pFuncs->size < sizeof(NPNetscapeFuncs)) return NPERR_INVALID_FUNCTABLE_ERROR; #endif if (!AtlAxWinInit()) { return NPERR_GENERIC_ERROR; } _pAtlModule = &_Module; memset(&NPNFuncs, 0, sizeof(NPNetscapeFuncs)); memcpy(&NPNFuncs, pFuncs, MIN(pFuncs->size, sizeof(NPNetscapeFuncs))); return NPERR_NO_ERROR; } /* * Shutdown the plugin. Called when no more instanced of this plugin exist and * the browser wants to unload it. */ NPError OSCALL NP_Shutdown(void) { AtlAxWinTerm(); UninstallAtlThunkEnumeration(); return NPERR_NO_ERROR; }
C++
/* ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0/LGPL 2.1 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is itstructures.com code. * * The Initial Developer of the Original Code is IT Structures. * Portions created by the Initial Developer are Copyright (C) 2008 * the Initial Developer. All Rights Reserved. * * Contributor: * Ruediger Jungbeck <ruediger.jungbeck@rsj.de> * * Alternatively, the contents of this file may be used under the terms of * either the GNU General Public License Version 2 or later (the "GPL"), or * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), * in which case the provisions of the GPL or the LGPL are applicable instead * of those above. If you wish to allow use of your version of this file only * under the terms of either the GPL or the LGPL, and not to allow others to * use your version of this file under the terms of the MPL, indicate your * decision by deleting the provisions above and replace them with the notice * and other provisions required by the GPL or the LGPL. If you do not delete * the provisions above, a recipient may use your version of this file under * the terms of any one of the MPL, the GPL or the LGPL. * * ***** END LICENSE BLOCK ***** */ #include "scriptable.h" #include "axhost.h" #include "ScriptFunc.h" #include "npactivex.h" NPClass Scriptable::npClass = { /* version */ NP_CLASS_STRUCT_VERSION, /* allocate */ Scriptable::_Allocate, /* deallocate */ Scriptable::_Deallocate, /* invalidate */ Scriptable::_Invalidate, /* hasMethod */ NULL, //Scriptable::_HasMethod, /* invoke */ NULL, //Scriptable::_Invoke, /* invokeDefault */ NULL, /* hasProperty */ Scriptable::_HasProperty, /* getProperty */ Scriptable::_GetProperty, /* setProperty */ Scriptable::_SetProperty, /* removeProperty */ NULL, /* enumerate */ Scriptable::_Enumerate, /* construct */ NULL }; bool Scriptable::find_member(ITypeInfoPtr info, TYPEATTR *attr, DISPID member_id, unsigned int invKind) { bool found = false; unsigned int i = 0; FUNCDESC *fDesc; for (i = 0; (i < attr->cFuncs) && !found; ++i) { HRESULT hr = info->GetFuncDesc(i, &fDesc); if (SUCCEEDED(hr) && fDesc && (fDesc->memid == member_id)) { if (invKind & fDesc->invkind) found = true; } info->ReleaseFuncDesc(fDesc); } #if 0 if (!found && (invKind & ~INVOKE_FUNC)) { VARDESC *vDesc; for (i = 0; (i < attr->cVars) && !found; ++i) { HRESULT hr = info->GetVarDesc(i, &vDesc); if ( SUCCEEDED(hr) && vDesc && (vDesc->memid == member_id)) { found = true; } info->ReleaseVarDesc(vDesc); } } if (!found) { // iterate inherited interfaces HREFTYPE refType = NULL; for (i = 0; (i < attr->cImplTypes) && !found; ++i) { ITypeInfoPtr baseInfo; TYPEATTR *baseAttr; if (FAILED(info->GetRefTypeOfImplType(0, &refType))) { continue; } if (FAILED(info->GetRefTypeInfo(refType, &baseInfo))) { continue; } baseInfo->AddRef(); if (FAILED(baseInfo->GetTypeAttr(&baseAttr))) { continue; } found = find_member(baseInfo, baseAttr, member_id, invKind); baseInfo->ReleaseTypeAttr(baseAttr); } } #endif return found; } bool Scriptable::IsProperty(DISPID member_id) { ITypeInfo *typeinfo; if (FAILED(disp->GetTypeInfo(0, LOCALE_SYSTEM_DEFAULT, &typeinfo))) { return false; } TYPEATTR *typeAttr; typeinfo->GetTypeAttr(&typeAttr); bool ret = find_member(typeinfo, typeAttr, member_id, DISPATCH_METHOD); typeinfo->ReleaseTypeAttr(typeAttr); typeinfo->Release(); return !ret; } DISPID Scriptable::ResolveName(NPIdentifier name, unsigned int invKind) { bool found = false; DISPID dID = -1; USES_CONVERSION; if (!name || !invKind) { return -1; } if (!disp) { return -1; } if (!NPNFuncs.identifierisstring(name)) { return -1; } NPUTF8 *npname = NPNFuncs.utf8fromidentifier(name); LPOLESTR oleName = A2W(npname); disp->GetIDsOfNames(IID_NULL, &oleName, 1, 0, &dID); return dID; #if 0 int funcInv; if (FindElementInvKind(disp, dID, &funcInv)) { if (funcInv & invKind) return dID; else return -1; } else { if ((dID != -1) && (invKind & INVOKE_PROPERTYGET)) { // Try to get property to check. // Use two parameters. It will definitely fail in property get/set, but it will return other orrer if it's not property. CComVariant var[2]; DISPPARAMS par = {var, NULL, 2, 0}; CComVariant result; HRESULT hr = disp->Invoke(dID, IID_NULL, 1, invKind, &par, &result, NULL, NULL); if (hr == DISP_E_MEMBERNOTFOUND || hr == DISP_E_TYPEMISMATCH) return -1; } } return dID; #endif if (dID != -1) { ITypeInfoPtr info; disp->GetTypeInfo(0, LOCALE_SYSTEM_DEFAULT, &info); if (!info) { return -1; } TYPEATTR *attr; if (FAILED(info->GetTypeAttr(&attr))) { return -1; } found = find_member(info, attr, dID, invKind); info->ReleaseTypeAttr(attr); } return found ? dID : -1; } bool Scriptable::Invoke(NPIdentifier name, const NPVariant *args, uint32_t argCount, NPVariant *result) { if (invalid) return false; np_log(instance, 2, "Invoke %s", NPNFuncs.utf8fromidentifier(name)); DISPID id = ResolveName(name, INVOKE_FUNC); bool ret = InvokeID(id, args, argCount, result); if (!ret) { np_log(instance, 0, "Invoke failed: %s", NPNFuncs.utf8fromidentifier(name)); } return ret; } bool Scriptable::InvokeID(DISPID id, const NPVariant *args, uint32_t argCount, NPVariant *result) { if (-1 == id) { return false; } CComVariant *vArgs = NULL; if (argCount) { vArgs = new CComVariant[argCount]; if (!vArgs) { return false; } for (unsigned int i = 0; i < argCount; ++i) { // copy the arguments in reverse order NPVar2Variant(&args[i], &vArgs[argCount - i - 1], instance); } } DISPPARAMS params = {NULL, NULL, 0, 0}; params.cArgs = argCount; params.cNamedArgs = 0; params.rgdispidNamedArgs = NULL; params.rgvarg = vArgs; CComVariant vResult; HRESULT rc = disp->Invoke(id, GUID_NULL, LOCALE_SYSTEM_DEFAULT, DISPATCH_METHOD, &params, &vResult, NULL, NULL); if (vArgs) { delete []vArgs; } if (FAILED(rc)) { return false; } Variant2NPVar(&vResult, result, instance); return true; } bool Scriptable::HasMethod(NPIdentifier name) { if (invalid) return false; DISPID id = ResolveName(name, INVOKE_FUNC); return (id != -1) ? true : false; } bool Scriptable::HasProperty(NPIdentifier name) { static NPIdentifier classid = NPNFuncs.getstringidentifier("classid"); if (name == classid) { return true; } if (invalid) return false; DISPID id = ResolveName(name, INVOKE_PROPERTYGET | INVOKE_PROPERTYPUT); return (id != -1) ? true : false; } bool Scriptable::GetProperty(NPIdentifier name, NPVariant *result) { if (invalid) return false; static NPIdentifier classid = NPNFuncs.getstringidentifier("classid"); if (name == classid) { CAxHost *host = (CAxHost*)this->host; if (this->disp == NULL) { char* cstr = (char*)NPNFuncs.memalloc(1); cstr[0] = 0; STRINGZ_TO_NPVARIANT(cstr, *result); return true; } else { USES_CONVERSION; char* cstr = (char*)NPNFuncs.memalloc(50); strcpy(cstr, "CLSID:"); LPOLESTR clsidstr; StringFromCLSID(host->getClsID(), &clsidstr); // Remove braces. clsidstr[lstrlenW(clsidstr) - 1] = '\0'; strcat(cstr, OLE2A(clsidstr + 1)); CoTaskMemFree(clsidstr); STRINGZ_TO_NPVARIANT(cstr, *result); return true; } } DISPID id = ResolveName(name, INVOKE_PROPERTYGET); if (-1 == id) { np_log(instance, 0, "Cannot find property: %s", NPNFuncs.utf8fromidentifier(name)); return false; } DISPPARAMS params; params.cArgs = 0; params.cNamedArgs = 0; params.rgdispidNamedArgs = NULL; params.rgvarg = NULL; CComVariant vResult; if (IsProperty(id)) { HRESULT hr = disp->Invoke(id, GUID_NULL, LOCALE_SYSTEM_DEFAULT, DISPATCH_PROPERTYGET, &params, &vResult, NULL, NULL); if (SUCCEEDED(hr)) { Variant2NPVar(&vResult, result, instance); np_log(instance, 2, "GetProperty %s", NPNFuncs.utf8fromidentifier(name)); return true; } } np_log(instance, 2, "GetMethodObject %s", NPNFuncs.utf8fromidentifier(name)); OBJECT_TO_NPVARIANT(ScriptFunc::GetFunctionObject(instance, this, id), *result); return true; } bool Scriptable::SetProperty(NPIdentifier name, const NPVariant *value) { static NPIdentifier classid = NPNFuncs.getstringidentifier("classid"); if (name == classid) { np_log(instance, 1, "Set classid property: %s", value->value.stringValue); CAxHost* axhost = (CAxHost*)host; CLSID newCLSID = CAxHost::ParseCLSIDFromSetting(value->value.stringValue.UTF8Characters, value->value.stringValue.UTF8Length); if (newCLSID != GUID_NULL && (!axhost->hasValidClsID() || newCLSID != axhost->getClsID())) { axhost->Clear(); if (axhost->setClsID(newCLSID)) { axhost->CreateControl(false); IUnknown *unk; if (SUCCEEDED(axhost->GetControlUnknown(&unk))) { this->setControl(unk); unk->Release(); } axhost->ResetWindow(); } } return true; } if (invalid) return false; DISPID id = ResolveName(name, INVOKE_PROPERTYPUT); if (-1 == id) { return false; } CComVariant val; NPVar2Variant(value, &val, instance); DISPPARAMS params; // Special initialization needed when using propery put. DISPID dispidNamed = DISPID_PROPERTYPUT; params.cNamedArgs = 1; params.rgdispidNamedArgs = &dispidNamed; params.cArgs = 1; params.rgvarg = &val; CComVariant vResult; WORD wFlags = DISPATCH_PROPERTYPUT; if (val.vt == VT_DISPATCH) { wFlags |= DISPATCH_PROPERTYPUTREF; } const char* pname = NPNFuncs.utf8fromidentifier(name); if (FAILED(disp->Invoke(id, GUID_NULL, LOCALE_SYSTEM_DEFAULT, wFlags, &params, &vResult, NULL, NULL))) { np_log(instance, 0, "SetProperty failed %s", pname); return false; } np_log(instance, 0, "SetProperty %s", pname); return true; } Scriptable* Scriptable::FromAxHost(NPP npp, CAxHost* host) { Scriptable *new_obj = (Scriptable*)NPNFuncs.createobject(npp, &npClass); IUnknown *unk; if (SUCCEEDED(host->GetControlUnknown(&unk))) { new_obj->setControl(unk); new_obj->host = host; unk->Release(); } return new_obj; } NPObject* Scriptable::_Allocate(NPP npp, NPClass *aClass) { return new Scriptable(npp); } void Scriptable::_Deallocate(NPObject *obj) { if (obj) { Scriptable *a = static_cast<Scriptable*>(obj); //np_log(a->instance, 3, "Dealocate obj"); delete a; } } bool Scriptable::Enumerate(NPIdentifier **value, uint32_t *count) { UINT cnt; if (!disp || FAILED(disp->GetTypeInfoCount(&cnt))) return false; *count = 0; for (UINT i = 0; i < cnt; ++i) { CComPtr<ITypeInfo> info; disp->GetTypeInfo(i, LOCALE_SYSTEM_DEFAULT, &info); TYPEATTR *attr; info->GetTypeAttr(&attr); *count += attr->cFuncs; info->ReleaseTypeAttr(attr); } uint32_t pos = 0; NPIdentifier *v = (NPIdentifier*) NPNFuncs.memalloc(sizeof(NPIdentifier) * *count); USES_CONVERSION; for (UINT i = 0; i < cnt; ++i) { CComPtr<ITypeInfo> info; disp->GetTypeInfo(i, LOCALE_SYSTEM_DEFAULT, &info); TYPEATTR *attr; info->GetTypeAttr(&attr); BSTR name; for (uint j = 0; j < attr->cFuncs; ++j) { FUNCDESC *desc; info->GetFuncDesc(j, &desc); if (SUCCEEDED(info->GetDocumentation(desc->memid, &name, NULL, NULL, NULL))) { LPCSTR str = OLE2A(name); v[pos++] = NPNFuncs.getstringidentifier(str); SysFreeString(name); } info->ReleaseFuncDesc(desc); } info->ReleaseTypeAttr(attr); } *count = pos; *value = v; return true; }
C++
/* ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0/LGPL 2.1 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is itstructures.com code. * * The Initial Developer of the Original Code is IT Structures. * Portions created by the Initial Developer are Copyright (C) 2008 * the Initial Developer. All Rights Reserved. * * Alternatively, the contents of this file may be used under the terms of * either the GNU General Public License Version 2 or later (the "GPL"), or * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), * in which case the provisions of the GPL or the LGPL are applicable instead * of those above. If you wish to allow use of your version of this file only * under the terms of either the GPL or the LGPL, and not to allow others to * use your version of this file under the terms of the MPL, indicate your * decision by deleting the provisions above and replace them with the notice * and other provisions required by the GPL or the LGPL. If you do not delete * the provisions above, a recipient may use your version of this file under * the terms of any one of the MPL, the GPL or the LGPL. * * ***** END LICENSE BLOCK ***** */ #pragma once #include <map> #include <vector> #include <atlbase.h> #include <comdef.h> #include <npapi.h> #include <npfunctions.h> #include <npruntime.h> #include "variants.h" extern NPNetscapeFuncs NPNFuncs; extern NPClass GenericNPObjectClass; typedef bool (*DefaultInvoker)(void *object, const NPVariant *args, uint32_t argCount, NPVariant *result); struct ltnum { bool operator()(long n1, long n2) const { return n1 < n2; } }; struct ltstr { bool operator()(const char* s1, const char* s2) const { return strcmp(s1, s2) < 0; } }; bool toString(void *object, const NPVariant *args, uint32_t argCount, NPVariant *result); class GenericNPObject: public NPObject { private: GenericNPObject(const GenericNPObject &); bool invalid; DefaultInvoker defInvoker; void *defInvokerObject; std::vector<NPVariant> numeric_mapper; // the members of alpha mapper can be reassigned to anything the user wishes std::map<const char *, NPVariant, ltstr> alpha_mapper; // these cannot accept other types than they are initially defined with std::map<const char *, NPVariant, ltstr> immutables; public: friend bool toString(void *, const NPVariant *, uint32_t, NPVariant *); GenericNPObject(NPP instance); GenericNPObject(NPP instance, bool isMethodObj); ~GenericNPObject(); void Invalidate() {invalid = true;} void SetDefaultInvoker(DefaultInvoker di, void *context) { defInvoker = di; defInvokerObject = context; } static bool _HasMethod(NPObject *npobj, NPIdentifier name) { return ((GenericNPObject *)npobj)->HasMethod(name); } static bool _Invoke(NPObject *npobj, NPIdentifier methodName, const NPVariant *args, uint32_t argCount, NPVariant *result) { return ((GenericNPObject *)npobj)->Invoke(methodName, args, argCount, result); } static bool _InvokeDefault(NPObject *npobj, const NPVariant *args, uint32_t argCount, NPVariant *result) { if (((GenericNPObject *)npobj)->defInvoker) { return (((GenericNPObject *)npobj)->InvokeDefault)(args, argCount, result); } else { return false; } } static bool _HasProperty(NPObject *npobj, NPIdentifier name) { return ((GenericNPObject *)npobj)->HasProperty(name); } static bool _GetProperty(NPObject *npobj, NPIdentifier name, NPVariant *result) { return ((GenericNPObject *)npobj)->GetProperty(name, result); } static bool _SetProperty(NPObject *npobj, NPIdentifier name, const NPVariant *value) { return ((GenericNPObject *)npobj)->SetProperty(name, value); } static bool _RemoveProperty(NPObject *npobj, NPIdentifier name) { return ((GenericNPObject *)npobj)->RemoveProperty(name); } static bool _Enumerate(NPObject *npobj, NPIdentifier **identifiers, uint32_t *identifierCount) { return ((GenericNPObject *)npobj)->Enumerate(identifiers, identifierCount); } bool HasMethod(NPIdentifier name); bool Invoke(NPIdentifier methodName, const NPVariant *args, uint32_t argCount, NPVariant *result); bool InvokeDefault(const NPVariant *args, uint32_t argCount, NPVariant *result); bool HasProperty(NPIdentifier name); bool GetProperty(NPIdentifier name, NPVariant *result); bool SetProperty(NPIdentifier name, const NPVariant *value); bool RemoveProperty(NPIdentifier name); bool Enumerate(NPIdentifier **identifiers, uint32_t *identifierCount); };
C++
/* ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0/LGPL 2.1 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * Contributor: * Chuan Qiu <qiuc12@gmail.com> * * Alternatively, the contents of this file may be used under the terms of * either the GNU General Public License Version 2 or later (the "GPL"), or * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), * in which case the provisions of the GPL or the LGPL are applicable instead * of those above. If you wish to allow use of your version of this file only * under the terms of either the GPL or the LGPL, and not to allow others to * use your version of this file under the terms of the MPL, indicate your * decision by deleting the provisions above and replace them with the notice * and other provisions required by the GPL or the LGPL. If you do not delete * the provisions above, a recipient may use your version of this file under * the terms of any one of the MPL, the GPL or the LGPL. * * ***** END LICENSE BLOCK ***** */ #include "atlthunk.h" #define WIN32_LEAN_AND_MEAN #include <Windows.h> #include <stdio.h> #include "ApiHook\Hook.h" typedef struct tagEXCEPTION_REGISTER { tagEXCEPTION_REGISTER *prev; _except_handler_type handler; }EXCEPTION_REGISTER, *LPEXCEPTION_REGISTER; /* Supported patterns: C7 44 24 04 XX XX XX XX mov [esp+4], imm32 E9 YY YY YY YY jmp imm32 B9 XX XX XX XX mov ecx, imm32 E9 YY YY YY YY jmp imm32 BA XX XX XX XX mov edx, imm32 B9 YY YY YY YY mov ecx, imm32 FF E1 jmp ecx B9 XX XX XX XX mov ecx, imm32 B8 YY YY YY YY mov eax, imm32 FF E0 jmp eax 59 pop ecx 58 pop eax 51 push ecx FF 60 04 jmp [eax+4] */ /* Pattern 1: C7 44 24 04 XX XX XX XX mov [esp+4], imm32 E9 YY YY YY YY jmp imm32 */ BYTE pattern1[] = {0xC7, 0x44, 0x24, 0x04, 0, 0, 0, 0, 0xE9, 0, 0, 0, 0}; void _process_pattern1(struct _CONTEXT *ContextRecord) { LPDWORD esp = (LPDWORD)(ContextRecord->Esp); DWORD imm1 = *(LPDWORD)(ContextRecord->Eip + 4); DWORD imm2 = *(LPDWORD)(ContextRecord->Eip + 9); esp[1] = imm1; ContextRecord->Eip += imm2 + 13; } /* Pattern 2: B9 XX XX XX XX mov ecx, imm32 E9 YY YY YY YY jmp imm32 */ BYTE pattern2[] = {0xB9, 0, 0, 0, 0, 0xE9, 0, 0, 0, 0}; void _process_pattern2(struct _CONTEXT *ContextRecord) { DWORD imm1 = *(LPDWORD)(ContextRecord->Eip + 1); DWORD imm2 = *(LPDWORD)(ContextRecord->Eip + 6); ContextRecord->Ecx = imm1; ContextRecord->Eip += imm2 + 10; } /* Pattern 3: BA XX XX XX XX mov edx, imm32 B9 YY YY YY YY mov ecx, imm32 FF E1 jmp ecx */ BYTE pattern3[] = {0xBA, 0, 0, 0, 0, 0xB9, 0, 0, 0, 0, 0xFF, 0xE1}; void _process_pattern3(struct _CONTEXT *ContextRecord) { DWORD imm1 = *(LPDWORD)(ContextRecord->Eip + 1); DWORD imm2 = *(LPDWORD)(ContextRecord->Eip + 6); ContextRecord->Edx = imm1; ContextRecord->Ecx = imm2; ContextRecord->Eip += imm2; } /* B9 XX XX XX XX mov ecx, imm32 B8 YY YY YY YY mov eax, imm32 FF E0 jmp eax */ BYTE pattern4[] = {0xB9, 0, 0, 0, 0, 0xB8, 0, 0, 0, 0, 0xFF, 0xE0}; void _process_pattern4(struct _CONTEXT *ContextRecord) { DWORD imm1 = *(LPDWORD)(ContextRecord->Eip + 1); DWORD imm2 = *(LPDWORD)(ContextRecord->Eip + 6); ContextRecord->Ecx = imm1; ContextRecord->Eax = imm2; ContextRecord->Eip += imm2; } /* 59 pop ecx 58 pop eax 51 push ecx FF 60 04 jmp [eax+4] */ BYTE pattern5[] = {0x59, 0x58, 0x51, 0xFF, 0x60, 0x04}; void _process_pattern5(struct _CONTEXT *ContextRecord) { LPDWORD stack = (LPDWORD)(ContextRecord->Esp); ContextRecord->Ecx = stack[0]; ContextRecord->Eax = stack[1]; stack[1] = stack[0]; ContextRecord->Esp += 4; ContextRecord->Eip = *(LPDWORD)(ContextRecord->Eax + 4); } ATL_THUNK_PATTERN patterns[] = { {pattern1, sizeof(pattern1), _process_pattern1}, {pattern2, sizeof(pattern2), _process_pattern2}, {pattern3, sizeof(pattern3), _process_pattern3}, {pattern4, sizeof(pattern4), _process_pattern4}, {pattern5, sizeof(pattern5), _process_pattern5} }; ATL_THUNK_PATTERN *match_patterns(LPVOID eip) { LPBYTE codes = (LPBYTE)eip; for (int i = 0; i < sizeof(patterns) / sizeof(patterns[0]); ++i) { BOOL match = TRUE; for (int j = 0; j < patterns[i].pattern_size && match; ++j) { if (patterns[i].pattern[j] != 0 && patterns[i].pattern[j] != codes[j]) match = FALSE; } if (match) { return &patterns[i]; } } return NULL; } EXCEPTION_DISPOSITION __cdecl _except_handler_atl_thunk( struct _EXCEPTION_RECORD *ExceptionRecord, void * EstablisherFrame, struct _CONTEXT *ContextRecord, void * DispatcherContext ) { if ((ExceptionRecord->ExceptionFlags) || ExceptionRecord->ExceptionCode != STATUS_ACCESS_VIOLATION || ExceptionRecord->ExceptionAddress != (LPVOID)ContextRecord->Eip) { // Not expected Access violation exception return ExceptionContinueSearch; } // Try to match patterns ATL_THUNK_PATTERN *pattern = match_patterns((LPVOID)ContextRecord->Eip); if (pattern) { //DWORD old; // We can't always protect the ATL by except_handler, so we mark it executable. //BOOL ret = VirtualProtect((LPVOID)ContextRecord->Eip, pattern->pattern_size, PAGE_EXECUTE_READWRITE, &old); pattern->enumerator(ContextRecord); return ExceptionContinueExecution; } else { return ExceptionContinueSearch; } } #ifndef ATL_THUNK_APIHOOK _except_handler_type original_handler4; #else HOOKINFO hook_handler; #endif #if 0 EXCEPTION_DISPOSITION __cdecl my_except_handler4( struct _EXCEPTION_RECORD *ExceptionRecord, void * EstablisherFrame, struct _CONTEXT *ContextRecord, void * DispatcherContext ) { //assert(original_handler); EXCEPTION_DISPOSITION step1 = _except_handler_atl_thunk(ExceptionRecord, EstablisherFrame, ContextRecord, DispatcherContext); if (step1 == ExceptionContinueExecution) return step1; #ifndef ATL_THUNK_APIHOOK _except_handler_type original_handler = original_handler4; #else _except_handler_type original_handler = (_except_handler_type)hook_handler4.Stub; #endif return original_handler(ExceptionRecord, EstablisherFrame, ContextRecord, DispatcherContext); } EXCEPTION_DISPOSITION __cdecl my_except_handler3( struct _EXCEPTION_RECORD *ExceptionRecord, void * EstablisherFrame, struct _CONTEXT *ContextRecord, void * DispatcherContext ) { //assert(original_handler); EXCEPTION_DISPOSITION step1 = _except_handler_atl_thunk(ExceptionRecord, EstablisherFrame, ContextRecord, DispatcherContext); if (step1 == ExceptionContinueExecution) return step1; #ifndef ATL_THUNK_APIHOOK // We won't wrap handler3, this shouldn't be used.. _except_handler_type original_handler = original_handler3; #else _except_handler_type original_handler = (_except_handler_type)hook_handler4.Stub; #endif return original_handler(ExceptionRecord, EstablisherFrame, ContextRecord, DispatcherContext); } #endif BOOL CheckDEPEnabled() { // In case of running in a XP SP2. HMODULE hInst = LoadLibrary(TEXT("Kernel32.dll")); typedef BOOL (WINAPI *SetProcessDEPPolicyType)( __in DWORD dwFlags ); typedef BOOL (WINAPI *GetProcessDEPPolicyType)( __in HANDLE hProcess, __out LPDWORD lpFlags, __out PBOOL lpPermanent ); SetProcessDEPPolicyType setProc = (SetProcessDEPPolicyType)GetProcAddress(hInst, "SetProcessDEPPolicy"); GetProcessDEPPolicyType getProc = (GetProcessDEPPolicyType)GetProcAddress(hInst, "GetProcessDEPPolicy"); if (setProc) { // This is likely to fail, but we set it first. setProc(PROCESS_DEP_ENABLE); } BOOL enabled = FALSE; DWORD lpFlags; BOOL lpPermanent; if (getProc && getProc(GetCurrentProcess(), &lpFlags, &lpPermanent)) { enabled = (lpFlags == (PROCESS_DEP_DISABLE_ATL_THUNK_EMULATION | PROCESS_DEP_ENABLE)); } return enabled; } extern "C" void _KiUserExceptionDispatcher_hook(); extern "C" DWORD _KiUserExceptionDispatcher_origin; extern "C" DWORD _KiUserExceptionDispatcher_ATL_p; typedef void (__stdcall *ZwContinueType)(struct _CONTEXT *, int); ZwContinueType ZwContinue; int __cdecl _KiUserExceptionDispatcher_ATL( struct _EXCEPTION_RECORD *ExceptionRecord, struct _CONTEXT *ContextRecord) { if (_except_handler_atl_thunk(ExceptionRecord, NULL, ContextRecord, NULL) == ExceptionContinueExecution) { ZwContinue(ContextRecord, 0); } return 0; } bool atlThunkInstalled = false; void InstallAtlThunkEnumeration() { if (atlThunkInstalled) return; if (CheckDEPEnabled()) { #ifndef ATL_THUNK_APIHOOK // Chrome is protected by DEP. EXCEPTION_REGISTER *reg; __asm { mov eax, fs:[0] mov reg, eax } while ((DWORD)reg->prev != 0xFFFFFFFF) reg = reg->prev; // replace the old handler original_handler = reg->handler; reg->handler = _except_handler; #else _KiUserExceptionDispatcher_ATL_p = (DWORD)_KiUserExceptionDispatcher_ATL; ZwContinue = (ZwContinueType) GetProcAddress(GetModuleHandle(TEXT("ntdll")), "ZwContinue"); HEInitHook(&hook_handler, GetProcAddress(GetModuleHandle(TEXT("ntdll")), "KiUserExceptionDispatcher") , _KiUserExceptionDispatcher_hook); HEStartHook(&hook_handler); _KiUserExceptionDispatcher_origin = (DWORD)hook_handler.Stub; atlThunkInstalled = true; #endif } } void UninstallAtlThunkEnumeration() { #ifdef ATL_THUNK_APIHOOK if (!atlThunkInstalled) return; HEStopHook(&hook_handler); atlThunkInstalled = false; #endif }
C++
/* ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0/LGPL 2.1 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * Contributor: * Chuan Qiu <qiuc12@gmail.com> * * Alternatively, the contents of this file may be used under the terms of * either the GNU General Public License Version 2 or later (the "GPL"), or * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), * in which case the provisions of the GPL or the LGPL are applicable instead * of those above. If you wish to allow use of your version of this file only * under the terms of either the GPL or the LGPL, and not to allow others to * use your version of this file under the terms of the MPL, indicate your * decision by deleting the provisions above and replace them with the notice * and other provisions required by the GPL or the LGPL. If you do not delete * the provisions above, a recipient may use your version of this file under * the terms of any one of the MPL, the GPL or the LGPL. * * ***** END LICENSE BLOCK ***** */ #include "HTMLDocumentContainer.h" #include "npactivex.h" #include <MsHTML.h> const GUID HTMLDocumentContainer::IID_TopLevelBrowser = {0x4C96BE40, 0x915C, 0x11CF, {0x99, 0xD3, 0x00, 0xAA, 0x00, 0x4A, 0xE8, 0x37}}; HTMLDocumentContainer::HTMLDocumentContainer() : dispatcher(NULL) { } void HTMLDocumentContainer::Init(NPP instance, ITypeLib *htmlLib) { NPObjectProxy npWindow; NPNFuncs.getvalue(instance, NPNVWindowNPObject, &npWindow); NPVariantProxy documentVariant; if (NPNFuncs.getproperty(instance, npWindow, NPNFuncs.getstringidentifier("document"), &documentVariant) && NPVARIANT_IS_OBJECT(documentVariant)) { NPObject *npDocument = NPVARIANT_TO_OBJECT(documentVariant); dispatcher = new FakeDispatcher(instance, htmlLib, npDocument); } npp = instance; } HRESULT HTMLDocumentContainer::get_LocationURL(BSTR *str) { NPObjectProxy npWindow; NPNFuncs.getvalue(npp, NPNVWindowNPObject, &npWindow); NPVariantProxy LocationVariant; if (!NPNFuncs.getproperty(npp, npWindow, NPNFuncs.getstringidentifier("location"), &LocationVariant) || !NPVARIANT_IS_OBJECT(LocationVariant)) { return E_FAIL; } NPObject *npLocation = NPVARIANT_TO_OBJECT(LocationVariant); NPVariantProxy npStr; if (!NPNFuncs.getproperty(npp, npLocation, NPNFuncs.getstringidentifier("href"), &npStr)) return E_FAIL; CComBSTR bstr(npStr.value.stringValue.UTF8Length, npStr.value.stringValue.UTF8Characters); *str = bstr.Detach(); return S_OK; } HRESULT STDMETHODCALLTYPE HTMLDocumentContainer::get_Document( __RPC__deref_out_opt IDispatch **ppDisp) { if (dispatcher) return dispatcher->QueryInterface(DIID_DispHTMLDocument, (LPVOID*)ppDisp); return E_FAIL; } HTMLDocumentContainer::~HTMLDocumentContainer(void) { }
C++
/* ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0/LGPL 2.1 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * Contributor: * Chuan Qiu <qiuc12@gmail.com> * * Alternatively, the contents of this file may be used under the terms of * either the GNU General Public License Version 2 or later (the "GPL"), or * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), * in which case the provisions of the GPL or the LGPL are applicable instead * of those above. If you wish to allow use of your version of this file only * under the terms of either the GPL or the LGPL, and not to allow others to * use your version of this file under the terms of the MPL, indicate your * decision by deleting the provisions above and replace them with the notice * and other provisions required by the GPL or the LGPL. If you do not delete * the provisions above, a recipient may use your version of this file under * the terms of any one of the MPL, the GPL or the LGPL. * * ***** END LICENSE BLOCK ***** */ #include "NPSafeArray.h" #include "npactivex.h" #include "objectProxy.h" #include <OleAuto.h> NPClass NPSafeArray::npClass = { /* version */ NP_CLASS_STRUCT_VERSION, /* allocate */ NPSafeArray::Allocate, /* deallocate */ NPSafeArray::Deallocate, /* invalidate */ NPSafeArray::Invalidate, /* hasMethod */ NPSafeArray::HasMethod, /* invoke */ NPSafeArray::Invoke, /* invokeDefault */ NPSafeArray::InvokeDefault, /* hasProperty */ NPSafeArray::HasProperty, /* getProperty */ NPSafeArray::GetProperty, /* setProperty */ NPSafeArray::SetProperty, /* removeProperty */ NULL, /* enumerate */ NULL, /* construct */ NPSafeArray::InvokeDefault }; NPSafeArray::NPSafeArray(NPP npp): ScriptBase(npp) { NPNFuncs.getvalue(npp, NPNVWindowNPObject, &window); } NPSafeArray::~NPSafeArray(void) { } // Some wrappers to adapt NPAPI's interface. NPObject* NPSafeArray::Allocate(NPP npp, NPClass *aClass) { return new NPSafeArray(npp); } void NPSafeArray::Deallocate(NPObject *obj){ delete static_cast<NPSafeArray*>(obj); } LPSAFEARRAY NPSafeArray::GetArrayPtr() { return arr_.m_psa; } NPInvokeDefaultFunctionPtr NPSafeArray::GetFuncPtr(NPIdentifier name) { if (name == NPNFuncs.getstringidentifier("getItem")) { return NPSafeArray::GetItem; } else if (name == NPNFuncs.getstringidentifier("toArray")) { return NPSafeArray::ToArray; } else if (name == NPNFuncs.getstringidentifier("lbound")) { return NPSafeArray::LBound; } else if (name == NPNFuncs.getstringidentifier("ubound")) { return NPSafeArray::UBound; } else if (name == NPNFuncs.getstringidentifier("dimensions")) { return NPSafeArray::Dimensions; } else { return NULL; } } void NPSafeArray::Invalidate(NPObject *obj) { NPSafeArray *safe = static_cast<NPSafeArray*>(obj); safe->arr_.Destroy(); } bool NPSafeArray::HasMethod(NPObject *npobj, NPIdentifier name) { return GetFuncPtr(name) != NULL; } void NPSafeArray::RegisterVBArray(NPP npp) { NPObjectProxy window; NPNFuncs.getvalue(npp, NPNVWindowNPObject, &window); NPIdentifier vbarray = NPNFuncs.getstringidentifier("VBArray"); if (!NPNFuncs.hasproperty(npp, window, vbarray)) { NPVariantProxy var; NPObject *def = NPNFuncs.createobject(npp, &npClass); OBJECT_TO_NPVARIANT(def, var); NPNFuncs.setproperty(npp, window, vbarray, &var); } } NPSafeArray *NPSafeArray::CreateFromArray(NPP instance, SAFEARRAY *array) { NPSafeArray *ret = (NPSafeArray *)NPNFuncs.createobject(instance, &npClass); ret->arr_.Attach(array); return ret; } bool NPSafeArray::Invoke(NPObject *npobj, NPIdentifier name, const NPVariant *args, uint32_t argCount, NPVariant *result) { NPSafeArray *safe = static_cast<NPSafeArray*>(npobj); if (safe->arr_.m_psa == NULL) return false; NPInvokeDefaultFunctionPtr ptr = GetFuncPtr(name); if (ptr) { return ptr(npobj, args, argCount, result); } else { return false; } } bool NPSafeArray::InvokeDefault(NPObject *npobj, const NPVariant *args, uint32_t argCount, NPVariant *result) { NPSafeArray *safe = static_cast<NPSafeArray*>(npobj); if (safe->arr_.m_psa != NULL) return false; if (argCount < 1) return false; if (!NPVARIANT_IS_OBJECT(*args)) { return false; } NPObject *obj = NPVARIANT_TO_OBJECT(*args); if (obj->_class != &NPSafeArray::npClass) { return false; } NPSafeArray *safe_original = static_cast<NPSafeArray*>(obj); if (safe_original->arr_.m_psa == NULL) { return false; } NPSafeArray *ret = CreateFromArray(safe->instance, safe_original->arr_); OBJECT_TO_NPVARIANT(ret, *result); return true; } bool NPSafeArray::GetItem(NPObject *npobj, const NPVariant *args, uint32_t argCount, NPVariant *result) { NPSafeArray *safe = static_cast<NPSafeArray*>(npobj); if (safe->arr_.m_psa == NULL) return false; LONG dim = safe->arr_.GetDimensions(); if (argCount < safe->arr_.GetDimensions()) { return false; } CAutoVectorPtr<LONG>pos(new LONG[dim]); for (int i = 0; i < dim; ++i) { if (NPVARIANT_IS_DOUBLE(args[i])) { pos[i] = (LONG)NPVARIANT_TO_DOUBLE(args[i]); } else if (NPVARIANT_IS_INT32(args[i])) { pos[i] = NPVARIANT_TO_INT32(args[i]); } else { return false; } } VARIANT var; if (!SUCCEEDED(safe->arr_.MultiDimGetAt(pos, var))) { return false; } Variant2NPVar(&var, result, safe->instance); return true; } bool NPSafeArray::Dimensions(NPObject *npobj, const NPVariant *args, uint32_t argCount, NPVariant *result) { NPSafeArray *safe = static_cast<NPSafeArray*>(npobj); if (safe->arr_.m_psa == NULL) return false; INT32_TO_NPVARIANT(safe->arr_.GetDimensions(), *result); return true; } bool NPSafeArray::UBound(NPObject *npobj, const NPVariant *args, uint32_t argCount, NPVariant *result) { NPSafeArray *safe = static_cast<NPSafeArray*>(npobj); if (safe->arr_.m_psa == NULL) return false; int dim = 1; if (argCount >= 1) { if (NPVARIANT_IS_INT32(*args)) { dim = NPVARIANT_TO_INT32(*args); } else if (NPVARIANT_IS_DOUBLE(*args)) { dim = (LONG)NPVARIANT_TO_DOUBLE(*args); } else { return false; } } try{ INT32_TO_NPVARIANT(safe->arr_.GetUpperBound(dim - 1), *result); } catch (...) { return false; } return true; } bool NPSafeArray::LBound(NPObject *npobj, const NPVariant *args, uint32_t argCount, NPVariant *result) { NPSafeArray *safe = static_cast<NPSafeArray*>(npobj); if (safe->arr_.m_psa == NULL) return false; int dim = 1; if (argCount >= 1) { if (NPVARIANT_IS_INT32(*args)) { dim = NPVARIANT_TO_INT32(*args); } else if (NPVARIANT_IS_DOUBLE(*args)) { dim = (LONG)NPVARIANT_TO_DOUBLE(*args); } else { return false; } } try{ INT32_TO_NPVARIANT(safe->arr_.GetLowerBound(dim - 1), *result); } catch (...) { return false; } return true; } bool NPSafeArray::ToArray(NPObject *npobj, const NPVariant *args, uint32_t argCount, NPVariant *result) { NPSafeArray *safe = static_cast<NPSafeArray*>(npobj); if (safe->arr_.m_psa == NULL) return false; long count = 1, dim = safe->arr_.GetDimensions(); for (int d = 0; d < dim; ++d) { count *= safe->arr_.GetCount(d); } NPString command = {"[]", 2}; if (!NPNFuncs.evaluate(safe->instance, safe->window, &command, result)) return false; VARIANT* vars = (VARIANT*)safe->arr_.m_psa->pvData; NPIdentifier push = NPNFuncs.getstringidentifier("push"); for (long i = 0; i < count; ++i) { NPVariantProxy v; NPVariant arg; Variant2NPVar(&vars[i], &arg, safe->instance); if (!NPNFuncs.invoke(safe->instance, NPVARIANT_TO_OBJECT(*result), push, &arg, 1, &v)) { return false; } } return true; } bool NPSafeArray::HasProperty(NPObject *npobj, NPIdentifier name) { return false; } bool NPSafeArray::GetProperty(NPObject *npobj, NPIdentifier name, NPVariant *result) { return false; } bool NPSafeArray::SetProperty(NPObject *npobj, NPIdentifier name, const NPVariant *value) { return false; }
C++
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ /* ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0/LGPL 2.1 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is RSJ Software GmbH code. * * The Initial Developer of the Original Code is * RSJ Software GmbH. * Portions created by the Initial Developer are Copyright (C) 2009 * the Initial Developer. All Rights Reserved. * * Contributors: * Ruediger Jungbeck <ruediger.jungbeck@rsj.de> * * Alternatively, the contents of this file may be used under the terms of * either the GNU General Public License Version 2 or later (the "GPL"), or * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), * in which case the provisions of the GPL or the LGPL are applicable instead * of those above. If you wish to allow use of your version of this file only * under the terms of either the GPL or the LGPL, and not to allow others to * use your version of this file under the terms of the MPL, indicate your * decision by deleting the provisions above and replace them with the notice * and other provisions required by the GPL or the LGPL. If you do not delete * the provisions above, a recipient may use your version of this file under * the terms of any one of the MPL, the GPL or the LGPL. * * ***** END LICENSE BLOCK ***** */ // This function is totally disabled now. #if 0 #include <stdio.h> #include <windows.h> #include <winreg.h> #include "npactivex.h" #include "atlutil.h" #include "authorize.h" // ---------------------------------------------------------------------------- #define SUB_KEY L"SOFTWARE\\MozillaPlugins\\@itstructures.com/npactivex\\MimeTypes\\application/x-itst-activex" // ---------------------------------------------------------------------------- BOOL TestExplicitAuthorizationUTF8 (const char *MimeType, const char *AuthorizationType, const char *DocumentUrl, const char *ProgramId); BOOL TestExplicitAuthorization (const wchar_t *MimeType, const wchar_t *AuthorizationType, const wchar_t *DocumentUrl, const wchar_t *ProgramId); BOOL WildcardMatch (const wchar_t *Mask, const wchar_t *Value); HKEY FindKey (const wchar_t *MimeType, const wchar_t *AuthorizationType); // --------------------------------------------------------------------------- HKEY BaseKeys[] = { HKEY_CURRENT_USER, HKEY_LOCAL_MACHINE }; // ---------------------------------------------------------------------------- BOOL TestAuthorization (NPP Instance, int16 ArgC, char *ArgN[], char *ArgV[], const char *MimeType) { BOOL ret = FALSE; NPObject *globalObj = NULL; NPIdentifier identifier; NPVariant varLocation; NPVariant varHref; bool rc = false; int16 i; char *wrkHref; #ifdef NDEF _asm{int 3}; #endif if (Instance == NULL) { return (FALSE); } // Determine owning document // Get the window object. NPNFuncs.getvalue(Instance, NPNVWindowNPObject, &globalObj); // Create a "location" identifier. identifier = NPNFuncs.getstringidentifier("location"); // Get the location property from the window object (which is another object). rc = NPNFuncs.getproperty(Instance, globalObj, identifier, &varLocation); NPNFuncs.releaseobject(globalObj); if (!rc){ np_log(Instance, 0, "AxHost.TestAuthorization: could not get the location from the global object"); return false; } // Get a pointer to the "location" object. NPObject *locationObj = varLocation.value.objectValue; // Create a "href" identifier. identifier = NPNFuncs.getstringidentifier("href"); // Get the location property from the location object. rc = NPNFuncs.getproperty(Instance, locationObj, identifier, &varHref); NPNFuncs.releasevariantvalue(&varLocation); if (!rc) { np_log(Instance, 0, "AxHost.TestAuthorization: could not get the href from the location property"); return false; } ret = TRUE; wrkHref = (char *) alloca(varHref.value.stringValue.UTF8Length + 1); memcpy(wrkHref, varHref.value.stringValue.UTF8Characters, varHref.value.stringValue.UTF8Length); wrkHref[varHref.value.stringValue.UTF8Length] = 0x00; NPNFuncs.releasevariantvalue(&varHref); for (i = 0; i < ArgC; ++i) { // search for any needed information: clsid, event handling directives, etc. if (0 == strnicmp(ArgN[i], PARAM_CLSID, strlen(PARAM_CLSID))) { ret &= TestExplicitAuthorizationUTF8(MimeType, PARAM_CLSID, wrkHref, ArgV[i]); } else if (0 == strnicmp(ArgN[i], PARAM_PROGID, strlen(PARAM_PROGID))) { // The class id of the control we are asked to load ret &= TestExplicitAuthorizationUTF8(MimeType, PARAM_PROGID, wrkHref, ArgV[i]); } else if( 0 == strnicmp(ArgN[i], PARAM_CODEBASEURL, strlen(PARAM_CODEBASEURL))) { ret &= TestExplicitAuthorizationUTF8(MimeType, PARAM_CODEBASEURL, wrkHref, ArgV[i]); } } np_log(Instance, 1, "AxHost.TestAuthorization: returning %s", ret ? "True" : "False"); return (ret); } // ---------------------------------------------------------------------------- BOOL TestExplicitAuthorizationUTF8 (const char *MimeType, const char *AuthorizationType, const char *DocumentUrl, const char *ProgramId) { USES_CONVERSION; BOOL ret; ret = TestExplicitAuthorization(A2W(MimeType), A2W(AuthorizationType), A2W(DocumentUrl), A2W(ProgramId)); return (ret); } // ---------------------------------------------------------------------------- BOOL TestExplicitAuthorization (const wchar_t *MimeType, const wchar_t *AuthorizationType, const wchar_t *DocumentUrl, const wchar_t *ProgramId) { BOOL ret = FALSE; #ifndef NO_REGISTRY_AUTHORIZE HKEY hKey; HKEY hSubKey; ULONG i; ULONG j; ULONG keyNameLen; ULONG valueNameLen; wchar_t keyName[_MAX_PATH]; wchar_t valueName[_MAX_PATH]; if (DocumentUrl == NULL) { return (FALSE); } if (ProgramId == NULL) { return (FALSE); } #ifdef NDEF MessageBox(NULL, DocumentUrl, ProgramId, MB_OK); #endif if ((hKey = FindKey(MimeType, AuthorizationType)) != NULL) { for (i = 0; !ret; i++) { keyNameLen = sizeof(keyName); if (RegEnumKey(hKey, i, keyName, keyNameLen) == ERROR_SUCCESS) { if (WildcardMatch(keyName, DocumentUrl)) { if (RegOpenKeyEx(hKey, keyName, 0, KEY_QUERY_VALUE, &hSubKey) == ERROR_SUCCESS) { for (j = 0; ; j++) { valueNameLen = sizeof(valueName); if (RegEnumValue(hSubKey, j, valueName, &valueNameLen, NULL, NULL, NULL, NULL) != ERROR_SUCCESS) { break; } if (WildcardMatch(valueName, ProgramId)) { ret = TRUE; break; } } RegCloseKey(hSubKey); } if (ret) { break; } } } else { break; } } RegCloseKey(hKey); } #endif return (ret); } // ---------------------------------------------------------------------------- BOOL WildcardMatch (const wchar_t *Mask, const wchar_t *Value) { size_t i; size_t j = 0; size_t maskLen; size_t valueLen; maskLen = wcslen(Mask); valueLen = wcslen(Value); for (i = 0; i < maskLen + 1; i++) { if (Mask[i] == '?') { j++; continue; } if (Mask[i] == '*') { for (; j < valueLen + 1; j++) { if (WildcardMatch(Mask + i + 1, Value + j)) { return (TRUE); } } return (FALSE); } if ((j <= valueLen) && (Mask[i] == tolower(Value[j]))) { j++; continue; } return (FALSE); } return (TRUE); } // ---------------------------------------------------------------------------- HKEY FindKey (const wchar_t *MimeType, const wchar_t *AuthorizationType) { HKEY ret = NULL; HKEY plugins; wchar_t searchKey[_MAX_PATH]; wchar_t pluginName[_MAX_PATH]; DWORD j; size_t i; for (i = 0; i < ARRAYSIZE(BaseKeys); i++) { if (RegOpenKeyEx(BaseKeys[i], L"SOFTWARE\\MozillaPlugins", 0, KEY_ENUMERATE_SUB_KEYS, &plugins) == ERROR_SUCCESS) { for (j = 0; ret == NULL; j++) { if (RegEnumKey(plugins, j, pluginName, sizeof(pluginName)) != ERROR_SUCCESS) { break; } wsprintf(searchKey, L"%s\\MimeTypes\\%s\\%s", pluginName, MimeType, AuthorizationType); if (RegOpenKeyEx(plugins, searchKey, 0, KEY_ENUMERATE_SUB_KEYS, &ret) == ERROR_SUCCESS) { break; } ret = NULL; } RegCloseKey(plugins); if (ret != NULL) { break; } } } return (ret); } #endif
C++
/* ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0/LGPL 2.1 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is itstructures.com code. * * The Initial Developer of the Original Code is IT Structures. * Portions created by the Initial Developer are Copyright (C) 2008 * the Initial Developer. All Rights Reserved. * * Contributor: * Ruediger Jungbeck <ruediger.jungbeck@rsj.de> * * Alternatively, the contents of this file may be used under the terms of * either the GNU General Public License Version 2 or later (the "GPL"), or * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), * in which case the provisions of the GPL or the LGPL are applicable instead * of those above. If you wish to allow use of your version of this file only * under the terms of either the GPL or the LGPL, and not to allow others to * use your version of this file under the terms of the MPL, indicate your * decision by deleting the provisions above and replace them with the notice * and other provisions required by the GPL or the LGPL. If you do not delete * the provisions above, a recipient may use your version of this file under * the terms of any one of the MPL, the GPL or the LGPL. * * ***** END LICENSE BLOCK ***** */ #include <atlbase.h> #include <atlsafe.h> #include <npapi.h> #include <npfunctions.h> #include "FakeDispatcher.h" #include <npruntime.h> #include "scriptable.h" #include "GenericNPObject.h" #include <OleAuto.h> #include "variants.h" #include "NPSafeArray.h" void BSTR2NPVar(BSTR bstr, NPVariant *npvar, NPP instance) { char *npStr = NULL; size_t sourceLen; size_t bytesNeeded; sourceLen = lstrlenW(bstr); bytesNeeded = WideCharToMultiByte(CP_UTF8, 0, bstr, sourceLen, NULL, 0, NULL, NULL); bytesNeeded += 1; // complete lack of documentation on Mozilla's part here, I have no // idea how this string is supposed to be freed npStr = (char *)NPNFuncs.memalloc(bytesNeeded); if (npStr) { int len = WideCharToMultiByte(CP_UTF8, 0, bstr, sourceLen, npStr, bytesNeeded - 1, NULL, NULL); npStr[len] = 0; STRINGN_TO_NPVARIANT(npStr, len, (*npvar)); } else { VOID_TO_NPVARIANT(*npvar); } } BSTR NPStringToBstr(const NPString npstr) { size_t bytesNeeded; bytesNeeded = MultiByteToWideChar( CP_UTF8, 0, npstr.UTF8Characters, npstr.UTF8Length, NULL, 0); bytesNeeded += 1; BSTR bstr = (BSTR)CoTaskMemAlloc(sizeof(OLECHAR) * bytesNeeded); if (bstr) { int len = MultiByteToWideChar( CP_UTF8, 0, npstr.UTF8Characters, npstr.UTF8Length, bstr, bytesNeeded); bstr[len] = 0; return bstr; } return NULL; } void Unknown2NPVar(IUnknown *unk, NPVariant *npvar, NPP instance) { FakeDispatcher *disp = NULL; if (SUCCEEDED(unk->QueryInterface(IID_IFakeDispatcher, (void**)&disp))) { OBJECT_TO_NPVARIANT(disp->getObject(), *npvar); NPNFuncs.retainobject(disp->getObject()); disp->Release(); } else { NPObject *obj = Scriptable::FromIUnknown(instance, unk); OBJECT_TO_NPVARIANT(obj, (*npvar)); } } #define GETVALUE(var, val) (((var->vt) & VT_BYREF) ? *(var->p##val) : (var->val)) void Variant2NPVar(const VARIANT *var, NPVariant *npvar, NPP instance) { NPObject *obj = NULL; if (!var || !npvar) { return; } VOID_TO_NPVARIANT(*npvar); USES_CONVERSION; switch (var->vt & ~VT_BYREF) { case VT_ARRAY | VT_VARIANT: NPSafeArray::RegisterVBArray(instance); NPSafeArray *obj; obj = NPSafeArray::CreateFromArray(instance, var->parray); OBJECT_TO_NPVARIANT(obj, (*npvar)); break; case VT_EMPTY: VOID_TO_NPVARIANT((*npvar)); break; case VT_NULL: NULL_TO_NPVARIANT((*npvar)); break; case VT_LPSTR: // not sure it can even appear in a VARIANT, but... STRINGZ_TO_NPVARIANT(var->pcVal, (*npvar)); break; case VT_BSTR: BSTR2NPVar(GETVALUE(var, bstrVal), npvar, instance); break; case VT_I1: INT32_TO_NPVARIANT((INT32)GETVALUE(var, cVal), (*npvar)); break; case VT_I2: INT32_TO_NPVARIANT((INT32)GETVALUE(var, iVal), (*npvar)); break; case VT_I4: INT32_TO_NPVARIANT((INT32)GETVALUE(var, lVal), (*npvar)); break; case VT_UI1: INT32_TO_NPVARIANT((INT32)GETVALUE(var, bVal), (*npvar)); break; case VT_UI2: INT32_TO_NPVARIANT((INT32)GETVALUE(var, uiVal), (*npvar)); break; case VT_UI4: INT32_TO_NPVARIANT((INT32)GETVALUE(var, ulVal), (*npvar)); break; case VT_INT: INT32_TO_NPVARIANT((INT32)GETVALUE(var, lVal), (*npvar)); break; case VT_BOOL: BOOLEAN_TO_NPVARIANT((GETVALUE(var, boolVal) == VARIANT_TRUE) ? true : false, (*npvar)); break; case VT_R4: DOUBLE_TO_NPVARIANT((double)GETVALUE(var, fltVal), (*npvar)); break; case VT_R8: DOUBLE_TO_NPVARIANT(GETVALUE(var, dblVal), (*npvar)); break; case VT_DISPATCH: case VT_USERDEFINED: case VT_UNKNOWN: Unknown2NPVar(GETVALUE(var, punkVal), npvar, instance); break; case VT_VARIANT: Variant2NPVar(var->pvarVal, npvar, instance); break; default: // Some unsupported type np_log(instance, 0, "Unsupported variant type %d", var->vt); VOID_TO_NPVARIANT(*npvar); break; } } #undef GETVALUE ITypeLib *pHtmlLib; void NPVar2Variant(const NPVariant *npvar, VARIANT *var, NPP instance) { if (!var || !npvar) { return; } var->vt = VT_EMPTY; switch (npvar->type) { case NPVariantType_Void: var->vt = VT_EMPTY; var->ulVal = 0; break; case NPVariantType_Null: var->vt = VT_NULL; var->byref = NULL; break; case NPVariantType_Bool: var->vt = VT_BOOL; var->ulVal = npvar->value.boolValue; break; case NPVariantType_Int32: var->vt = VT_I4; var->ulVal = npvar->value.intValue; break; case NPVariantType_Double: var->vt = VT_R8; var->dblVal = npvar->value.doubleValue; break; case NPVariantType_String: (CComVariant&)*var = NPStringToBstr(npvar->value.stringValue); break; case NPVariantType_Object: NPObject *object = NPVARIANT_TO_OBJECT(*npvar); var->vt = VT_DISPATCH; if (object->_class == &Scriptable::npClass) { Scriptable* scriptObj = (Scriptable*)object; scriptObj->getControl(&var->punkVal); } else if (object->_class == &NPSafeArray::npClass) { NPSafeArray* arrayObj = (NPSafeArray*)object; var->vt = VT_ARRAY | VT_VARIANT; var->parray = arrayObj->GetArrayPtr(); } else { IUnknown *val = new FakeDispatcher(instance, pHtmlLib, object); var->punkVal = val; } break; } } size_t VariantSize(VARTYPE vt) { if ((vt & VT_BYREF) || (vt & VT_ARRAY)) return sizeof(LPVOID); switch (vt) { case VT_EMPTY: case VT_NULL: case VT_VOID: return 0; case VT_I1: case VT_UI1: return 1; case VT_I2: case VT_UI2: return 2; case VT_R8: case VT_DATE: case VT_I8: case VT_UI8: case VT_CY: return 8; case VT_I4: case VT_R4: case VT_UI4: case VT_BOOL: return 4; case VT_BSTR: case VT_DISPATCH: case VT_ERROR: case VT_UNKNOWN: case VT_DECIMAL: case VT_INT: case VT_UINT: case VT_HRESULT: case VT_PTR: case VT_SAFEARRAY: case VT_CARRAY: case VT_USERDEFINED: case VT_LPSTR: case VT_LPWSTR: case VT_INT_PTR: case VT_UINT_PTR: return sizeof(LPVOID); case VT_VARIANT: return sizeof(VARIANT); default: return 0; } } HRESULT ConvertVariantToGivenType(ITypeInfo *baseType, const TYPEDESC &vt, const VARIANT &var, LPVOID dest) { // var is converted from NPVariant, so only limited types are possible. HRESULT hr = S_OK; switch (vt.vt) { case VT_EMPTY: case VT_VOID: case VT_NULL: return S_OK; case VT_I1: case VT_UI1: case VT_I2: case VT_UI2: case VT_I4: case VT_R4: case VT_UI4: case VT_BOOL: case VT_INT: case VT_UINT: int intvalue; intvalue = NULL; if (var.vt == VT_R8) intvalue = (int)var.dblVal; else if (var.vt == VT_BOOL) intvalue = (int)var.boolVal; else if (var.vt == VT_UI4) intvalue = var.intVal; else return E_FAIL; **(int**)dest = intvalue; hr = S_OK; break; case VT_R8: double dblvalue; dblvalue = 0.0; if (var.vt == VT_R8) dblvalue = (double)var.dblVal; else if (var.vt == VT_BOOL) dblvalue = (double)var.boolVal; else if (var.vt == VT_UI4) dblvalue = var.intVal; else return E_FAIL; **(double**)dest = dblvalue; hr = S_OK; break; case VT_DATE: case VT_I8: case VT_UI8: case VT_CY: // I don't know how to deal with these types.. __asm{int 3}; case VT_BSTR: case VT_DISPATCH: case VT_ERROR: case VT_UNKNOWN: case VT_DECIMAL: case VT_HRESULT: case VT_SAFEARRAY: case VT_CARRAY: case VT_LPSTR: case VT_LPWSTR: case VT_INT_PTR: case VT_UINT_PTR: **(ULONG***)dest = var.pulVal; break; case VT_USERDEFINED: { if (var.vt != VT_UNKNOWN && var.vt != VT_DISPATCH) { return E_FAIL; } else { ITypeInfo *newType; baseType->GetRefTypeInfo(vt.hreftype, &newType); IUnknown *unk = var.punkVal; TYPEATTR *attr; newType->GetTypeAttr(&attr); hr = unk->QueryInterface(attr->guid, (LPVOID*)dest); unk->Release(); newType->ReleaseTypeAttr(attr); newType->Release(); } } break; case VT_PTR: return ConvertVariantToGivenType(baseType, *vt.lptdesc, var, *(LPVOID*)dest); break; case VT_VARIANT: memcpy(*(VARIANT**)dest, &var, sizeof(var)); default: _asm{int 3} } return hr; } void RawTypeToVariant(const TYPEDESC &desc, LPVOID source, VARIANT* var) { BOOL pointer = FALSE; switch (desc.vt) { case VT_BSTR: case VT_DISPATCH: case VT_ERROR: case VT_UNKNOWN: case VT_SAFEARRAY: case VT_CARRAY: case VT_LPSTR: case VT_LPWSTR: case VT_INT_PTR: case VT_UINT_PTR: case VT_PTR: // These are pointers pointer = TRUE; break; default: if (var->vt & VT_BYREF) pointer = TRUE; } if (pointer) { var->vt = desc.vt; var->pulVal = *(PULONG*)source; } else if (desc.vt == VT_VARIANT) { // It passed by object, but we use as a pointer var->vt = desc.vt; var->pulVal = (PULONG)source; } else { var->vt = desc.vt | VT_BYREF; var->pulVal = (PULONG)source; } }
C++
/* ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0/LGPL 2.1 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is itstructures.com code. * * The Initial Developer of the Original Code is IT Structures. * Portions created by the Initial Developer are Copyright (C) 2008 * the Initial Developer. All Rights Reserved. * * Alternatively, the contents of this file may be used under the terms of * either the GNU General Public License Version 2 or later (the "GPL"), or * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), * in which case the provisions of the GPL or the LGPL are applicable instead * of those above. If you wish to allow use of your version of this file only * under the terms of either the GPL or the LGPL, and not to allow others to * use your version of this file under the terms of the MPL, indicate your * decision by deleting the provisions above and replace them with the notice * and other provisions required by the GPL or the LGPL. If you do not delete * the provisions above, a recipient may use your version of this file under * the terms of any one of the MPL, the GPL or the LGPL. * * ***** END LICENSE BLOCK ***** */ #include <algorithm> #include <string> #include "GenericNPObject.h" static NPObject* AllocateGenericNPObject(NPP npp, NPClass *aClass) { return new GenericNPObject(npp, false); } static NPObject* AllocateMethodNPObject(NPP npp, NPClass *aClass) { return new GenericNPObject(npp, true); } static void DeallocateGenericNPObject(NPObject *obj) { if (!obj) { return; } GenericNPObject *m = (GenericNPObject *)obj; delete m; } static void InvalidateGenericNPObject(NPObject *obj) { if (!obj) { return; } ((GenericNPObject *)obj)->Invalidate(); } NPClass GenericNPObjectClass = { /* version */ NP_CLASS_STRUCT_VERSION, /* allocate */ AllocateGenericNPObject, /* deallocate */ DeallocateGenericNPObject, /* invalidate */ InvalidateGenericNPObject, /* hasMethod */ GenericNPObject::_HasMethod, /* invoke */ GenericNPObject::_Invoke, /* invokeDefault */ GenericNPObject::_InvokeDefault, /* hasProperty */ GenericNPObject::_HasProperty, /* getProperty */ GenericNPObject::_GetProperty, /* setProperty */ GenericNPObject::_SetProperty, /* removeProperty */ GenericNPObject::_RemoveProperty, /* enumerate */ GenericNPObject::_Enumerate, /* construct */ NULL }; NPClass MethodNPObjectClass = { /* version */ NP_CLASS_STRUCT_VERSION, /* allocate */ AllocateMethodNPObject, /* deallocate */ DeallocateGenericNPObject, /* invalidate */ InvalidateGenericNPObject, /* hasMethod */ GenericNPObject::_HasMethod, /* invoke */ GenericNPObject::_Invoke, /* invokeDefault */ GenericNPObject::_InvokeDefault, /* hasProperty */ GenericNPObject::_HasProperty, /* getProperty */ GenericNPObject::_GetProperty, /* setProperty */ GenericNPObject::_SetProperty, /* removeProperty */ GenericNPObject::_RemoveProperty, /* enumerate */ GenericNPObject::_Enumerate, /* construct */ NULL }; // Some standard JavaScript methods bool toString(void *object, const NPVariant *args, uint32_t argCount, NPVariant *result) { GenericNPObject *map = (GenericNPObject *)object; if (!map || map->invalid) return false; // no args expected or cared for... std::string out; std::vector<NPVariant>::iterator it; for (it = map->numeric_mapper.begin(); it < map->numeric_mapper.end(); ++it) { if (NPVARIANT_IS_VOID(*it)) { out += ","; } else if (NPVARIANT_IS_NULL(*it)) { out += ","; } else if (NPVARIANT_IS_BOOLEAN(*it)) { if ((*it).value.boolValue) { out += "true,"; } else { out += "false,"; } } else if (NPVARIANT_IS_INT32(*it)) { char tmp[50]; memset(tmp, 0, sizeof(tmp)); _snprintf(tmp, 49, "%d,", (*it).value.intValue); out += tmp; } else if (NPVARIANT_IS_DOUBLE(*it)) { char tmp[50]; memset(tmp, 0, sizeof(tmp)); _snprintf(tmp, 49, "%f,", (*it).value.doubleValue); out += tmp; } else if (NPVARIANT_IS_STRING(*it)) { out += std::string((*it).value.stringValue.UTF8Characters, (*it).value.stringValue.UTF8Characters + (*it).value.stringValue.UTF8Length); out += ","; } else if (NPVARIANT_IS_OBJECT(*it)) { out += "[object],"; } } // calculate how much space we need std::string::size_type size = out.length(); char *s = (char *)NPNFuncs.memalloc(size * sizeof(char)); if (NULL == s) { return false; } memcpy(s, out.c_str(), size); s[size - 1] = 0; // overwrite the last "," STRINGZ_TO_NPVARIANT(s, (*result)); return true; } // Some helpers static void free_numeric_element(NPVariant elem) { NPNFuncs.releasevariantvalue(&elem); } static void free_alpha_element(std::pair<const char *, NPVariant> elem) { NPNFuncs.releasevariantvalue(&(elem.second)); } // And now the GenericNPObject implementation GenericNPObject::GenericNPObject(NPP instance, bool isMethodObj): invalid(false), defInvoker(NULL), defInvokerObject(NULL) { NPVariant val; INT32_TO_NPVARIANT(0, val); immutables["length"] = val; if (!isMethodObj) { NPObject *obj = NULL; obj = NPNFuncs.createobject(instance, &MethodNPObjectClass); if (NULL == obj) { throw NULL; } ((GenericNPObject *)obj)->SetDefaultInvoker(&toString, this); OBJECT_TO_NPVARIANT(obj, val); immutables["toString"] = val; } } GenericNPObject::~GenericNPObject() { for_each(immutables.begin(), immutables.end(), free_alpha_element); for_each(alpha_mapper.begin(), alpha_mapper.end(), free_alpha_element); for_each(numeric_mapper.begin(), numeric_mapper.end(), free_numeric_element); } bool GenericNPObject::HasMethod(NPIdentifier name) { if (invalid) return false; if (NPNFuncs.identifierisstring(name)) { char *key = NPNFuncs.utf8fromidentifier(name); if (immutables.count(key) > 0) { if (NPVARIANT_IS_OBJECT(immutables[key])) { return (NULL != immutables[key].value.objectValue->_class->invokeDefault); } } else if (alpha_mapper.count(key) > 0) { if (NPVARIANT_IS_OBJECT(alpha_mapper[key])) { return (NULL != alpha_mapper[key].value.objectValue->_class->invokeDefault); } } } return false; } bool GenericNPObject::Invoke(NPIdentifier name, const NPVariant *args, uint32_t argCount, NPVariant *result) { if (invalid) return false; if (NPNFuncs.identifierisstring(name)) { char *key = NPNFuncs.utf8fromidentifier(name); if (immutables.count(key) > 0) { if ( NPVARIANT_IS_OBJECT(immutables[key]) && immutables[key].value.objectValue->_class->invokeDefault) { return immutables[key].value.objectValue->_class->invokeDefault(immutables[key].value.objectValue, args, argCount, result); } } else if (alpha_mapper.count(key) > 0) { if ( NPVARIANT_IS_OBJECT(alpha_mapper[key]) && alpha_mapper[key].value.objectValue->_class->invokeDefault) { return alpha_mapper[key].value.objectValue->_class->invokeDefault(alpha_mapper[key].value.objectValue, args, argCount, result); } } } return true; } bool GenericNPObject::InvokeDefault(const NPVariant *args, uint32_t argCount, NPVariant *result) { if (invalid) return false; if (defInvoker) { defInvoker(defInvokerObject, args, argCount, result); } return true; } // This method is also called before the JS engine attempts to add a new // property, most likely it's trying to check that the key is supported. // It only returns false if the string name was not found, or does not // hold a callable object bool GenericNPObject::HasProperty(NPIdentifier name) { if (invalid) return false; if (NPNFuncs.identifierisstring(name)) { char *key = NPNFuncs.utf8fromidentifier(name); if (immutables.count(key) > 0) { if (NPVARIANT_IS_OBJECT(immutables[key])) { return (NULL == immutables[key].value.objectValue->_class->invokeDefault); } } else if (alpha_mapper.count(key) > 0) { if (NPVARIANT_IS_OBJECT(alpha_mapper[key])) { return (NULL == alpha_mapper[key].value.objectValue->_class->invokeDefault); } } return false; } return true; } static bool CopyNPVariant(NPVariant *dst, const NPVariant *src) { dst->type = src->type; if (NPVARIANT_IS_STRING(*src)) { NPUTF8 *str = (NPUTF8 *)NPNFuncs.memalloc((src->value.stringValue.UTF8Length + 1) * sizeof(NPUTF8)); if (NULL == str) { return false; } dst->value.stringValue.UTF8Length = src->value.stringValue.UTF8Length; memcpy(str, src->value.stringValue.UTF8Characters, src->value.stringValue.UTF8Length); str[dst->value.stringValue.UTF8Length] = 0; dst->value.stringValue.UTF8Characters = str; } else if (NPVARIANT_IS_OBJECT(*src)) { NPNFuncs.retainobject(NPVARIANT_TO_OBJECT(*src)); dst->value.objectValue = src->value.objectValue; } else { dst->value = src->value; } return true; } #define MIN(x, y) ((x) < (y)) ? (x) : (y) bool GenericNPObject::GetProperty(NPIdentifier name, NPVariant *result) { if (invalid) return false; try { if (NPNFuncs.identifierisstring(name)) { char *key = NPNFuncs.utf8fromidentifier(name); if (immutables.count(key) > 0) { if (!CopyNPVariant(result, &(immutables[key]))) { return false; } } else if (alpha_mapper.count(key) > 0) { if (!CopyNPVariant(result, &(alpha_mapper[key]))) { return false; } } } else { // assume int... unsigned long key = (unsigned long)NPNFuncs.intfromidentifier(name); if (numeric_mapper.size() > key) { if (!CopyNPVariant(result, &(numeric_mapper[key]))) { return false; } } } } catch (...) { } return true; } bool GenericNPObject::SetProperty(NPIdentifier name, const NPVariant *value) { if (invalid) return false; try { if (NPNFuncs.identifierisstring(name)) { char *key = NPNFuncs.utf8fromidentifier(name); if (immutables.count(key) > 0) { // the key is already defined as immutable, check the new value type if (value->type != immutables[key].type) { return false; } // Seems ok, copy the new value if (!CopyNPVariant(&(immutables[key]), value)) { return false; } } else if (!CopyNPVariant(&(alpha_mapper[key]), value)) { return false; } } else { // assume int... NPVariant var; if (!CopyNPVariant(&var, value)) { return false; } unsigned long key = (unsigned long)NPNFuncs.intfromidentifier(name); if (key >= numeric_mapper.size()) { // there's a gap we need to fill NPVariant pad; VOID_TO_NPVARIANT(pad); numeric_mapper.insert(numeric_mapper.end(), key - numeric_mapper.size() + 1, pad); } numeric_mapper.at(key) = var; NPVARIANT_TO_INT32(immutables["length"])++; } } catch (...) { } return true; } bool GenericNPObject::RemoveProperty(NPIdentifier name) { if (invalid) return false; try { if (NPNFuncs.identifierisstring(name)) { char *key = NPNFuncs.utf8fromidentifier(name); if (alpha_mapper.count(key) > 0) { NPNFuncs.releasevariantvalue(&(alpha_mapper[key])); alpha_mapper.erase(key); } } else { // assume int... unsigned long key = (unsigned long)NPNFuncs.intfromidentifier(name); if (numeric_mapper.size() > key) { NPNFuncs.releasevariantvalue(&(numeric_mapper[key])); numeric_mapper.erase(numeric_mapper.begin() + key); } NPVARIANT_TO_INT32(immutables["length"])--; } } catch (...) { } return true; } bool GenericNPObject::Enumerate(NPIdentifier **identifiers, uint32_t *identifierCount) { if (invalid) return false; try { *identifiers = (NPIdentifier *)NPNFuncs.memalloc(sizeof(NPIdentifier) * numeric_mapper.size()); if (NULL == *identifiers) { return false; } *identifierCount = 0; std::vector<NPVariant>::iterator it; unsigned int i = 0; char str[10] = ""; for (it = numeric_mapper.begin(); it < numeric_mapper.end(); ++it, ++i) { // skip empty (padding) elements if (NPVARIANT_IS_VOID(*it)) continue; _snprintf(str, sizeof(str), "%u", i); (*identifiers)[(*identifierCount)++] = NPNFuncs.getstringidentifier(str); } } catch (...) { } return true; }
C++
/* ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0/LGPL 2.1 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * Contributor: * Chuan Qiu <qiuc12@gmail.com> * * Alternatively, the contents of this file may be used under the terms of * either the GNU General Public License Version 2 or later (the "GPL"), or * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), * in which case the provisions of the GPL or the LGPL are applicable instead * of those above. If you wish to allow use of your version of this file only * under the terms of either the GPL or the LGPL, and not to allow others to * use your version of this file under the terms of the MPL, indicate your * decision by deleting the provisions above and replace them with the notice * and other provisions required by the GPL or the LGPL. If you do not delete * the provisions above, a recipient may use your version of this file under * the terms of any one of the MPL, the GPL or the LGPL. * * ***** END LICENSE BLOCK ***** */ /* ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0/LGPL 2.1 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * Contributor: * Chuan Qiu <qiuc12@gmail.com> * * Alternatively, the contents of this file may be used under the terms of * either the GNU General Public License Version 2 or later (the "GPL"), or * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), * in which case the provisions of the GPL or the LGPL are applicable instead * of those above. If you wish to allow use of your version of this file only * under the terms of either the GPL or the LGPL, and not to allow others to * use your version of this file under the terms of the MPL, indicate your * decision by deleting the provisions above and replace them with the notice * and other provisions required by the GPL or the LGPL. If you do not delete * the provisions above, a recipient may use your version of this file under * the terms of any one of the MPL, the GPL or the LGPL. * * ***** END LICENSE BLOCK ***** */ #include "Host.h" #include "npactivex.h" #include "ObjectManager.h" #include "objectProxy.h" #include <npapi.h> #include <npruntime.h> CHost::CHost(NPP npp) : ref_cnt_(1), instance(npp), lastObj(NULL) { } CHost::~CHost(void) { UnRegisterObject(); np_log(instance, 3, "CHost::~CHost"); } void CHost::AddRef() { ++ref_cnt_; } void CHost::Release() { --ref_cnt_; if (!ref_cnt_) delete this; } NPObject *CHost::GetScriptableObject() { return lastObj; } NPObject *CHost::RegisterObject() { lastObj = CreateScriptableObject(); if (!lastObj) return NULL; lastObj->host = this; NPObjectProxy embed; NPNFuncs.getvalue(instance, NPNVPluginElementNPObject, &embed); NPVariant var; OBJECT_TO_NPVARIANT(lastObj, var); // It doesn't matter which npp in setting. NPNFuncs.setproperty(instance, embed, NPNFuncs.getstringidentifier("object"), &var); return lastObj; } void CHost::UnRegisterObject() { return; NPObjectProxy embed; NPNFuncs.getvalue(instance, NPNVPluginElementNPObject, &embed); NPVariant var; VOID_TO_NPVARIANT(var); NPNFuncs.removeproperty(instance, embed, NPNFuncs.getstringidentifier("object")); np_log(instance, 3, "UnRegisterObject"); lastObj = NULL; } NPP CHost::ResetNPP(NPP newNPP) { // Doesn't support now.. _asm{int 3}; NPP ret = instance; UnRegisterObject(); instance = newNPP; np_log(newNPP, 3, "Reset NPP from 0x%08x to 0x%08x", ret, newNPP); RegisterObject(); return ret; } ScriptBase *CHost::GetInternalObject(NPP npp, NPObject *embed_element) { NPVariantProxy var; if (!NPNFuncs.getproperty(npp, embed_element, NPNFuncs.getstringidentifier("object"), &var)) return NULL; if (NPVARIANT_IS_OBJECT(var)) { ScriptBase *obj = static_cast<ScriptBase*>(NPVARIANT_TO_OBJECT(var)); NPNFuncs.retainobject(obj); return obj; } return NULL; } ScriptBase *CHost::GetMyScriptObject() { NPObjectProxy embed; NPNFuncs.getvalue(instance, NPNVPluginElementNPObject, &embed); return GetInternalObject(instance, embed); }
C++
/* ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0/LGPL 2.1 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is itstructures.com code. * * The Initial Developer of the Original Code is IT Structures. * Portions created by the Initial Developer are Copyright (C) 2008 * the Initial Developer. All Rights Reserved. * * Alternatively, the contents of this file may be used under the terms of * either the GNU General Public License Version 2 or later (the "GPL"), or * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), * in which case the provisions of the GPL or the LGPL are applicable instead * of those above. If you wish to allow use of your version of this file only * under the terms of either the GPL or the LGPL, and not to allow others to * use your version of this file under the terms of the MPL, indicate your * decision by deleting the provisions above and replace them with the notice * and other provisions required by the GPL or the LGPL. If you do not delete * the provisions above, a recipient may use your version of this file under * the terms of any one of the MPL, the GPL or the LGPL. * * ***** END LICENSE BLOCK ***** */ #pragma once #include "Host.h" namespace ATL { template <typename T> class CComObject; } class CControlEventSink; class CControlSite; class PropertyList; class CAxHost : public CHost{ private: CAxHost(const CAxHost &); bool isValidClsID; bool isKnown; bool noWindow; protected: // The window handle to our plugin area in the browser HWND Window; WNDPROC OldProc; // The class/prog id of the control CLSID ClsID; LPCWSTR CodeBaseUrl; CComObject<CControlEventSink> *Sink; RECT lastRect; PropertyList *Props_; public: CAxHost(NPP inst); ~CAxHost(); static CLSID ParseCLSIDFromSetting(LPCSTR clsid, int length); virtual NPP ResetNPP(NPP npp); CComObject<CControlSite> *Site; void SetNPWindow(NPWindow *window); void ResetWindow(); PropertyList *Props() { return Props_; } void Clear(); void setWindow(HWND win); HWND getWinfow(); void UpdateRect(RECT rcPos); bool verifyClsID(LPOLESTR oleClsID); bool setClsID(const char *clsid); bool setClsID(const CLSID& clsid); CLSID getClsID() { return this->ClsID; } void setNoWindow(bool value); bool setClsIDFromProgID(const char *progid); void setCodeBaseUrl(LPCWSTR clsid); bool hasValidClsID(); bool CreateControl(bool subscribeToEvents); void UpdateRectSize(LPRECT origRect); void SetRectSize(LPSIZEL size); bool AddEventHandler(wchar_t *name, wchar_t *handler); HRESULT GetControlUnknown(IUnknown **pObj); short HandleEvent(void *event); ScriptBase *CreateScriptableObject(); };
C++
#pragma once #include <npapi.h> #include <npruntime.h> #include <OleAuto.h> #include "scriptable.h" #include "npactivex.h" #include <map> using std::map; using std::pair; class ScriptFunc : public NPObject { private: static NPClass npClass; Scriptable *script; MEMBERID dispid; void setControl(Scriptable *script, MEMBERID dispid) { NPNFuncs.retainobject(script); this->script = script; this->dispid = dispid; } static map<pair<Scriptable*, MEMBERID>, ScriptFunc*> M; bool InvokeDefault(const NPVariant *args, uint32_t argCount, NPVariant *result); public: ScriptFunc(NPP inst); ~ScriptFunc(void); static NPObject *_Allocate(NPP npp, NPClass *npClass) { return new ScriptFunc(npp); } static void _Deallocate(NPObject *object) { ScriptFunc *obj = (ScriptFunc*)(object); delete obj; } static ScriptFunc* GetFunctionObject(NPP npp, Scriptable *script, MEMBERID dispid); static bool _InvokeDefault(NPObject *npobj, const NPVariant *args, uint32_t argCount, NPVariant *result) { return ((ScriptFunc *)npobj)->InvokeDefault(args, argCount, result); } };
C++
// (c) Code By Extreme // Description:Inline Hook Engine // Last update:2010-6-26 #include <Windows.h> #include <stdio.h> #include "Hook.h" #define JMPSIZE 5 #define NOP 0x90 extern DWORD ade_getlength(LPVOID Start, DWORD WantLength); static VOID BuildJmp(PBYTE Buffer,DWORD JmpFrom, DWORD JmpTo) { DWORD JmpAddr; JmpAddr = JmpFrom - JmpTo - JMPSIZE; Buffer[0] = 0xE9; Buffer[1] = (BYTE)(JmpAddr & 0xFF); Buffer[2] = (BYTE)((JmpAddr >> 8) & 0xFF); Buffer[3] = (BYTE)((JmpAddr >> 16) & 0xFF); Buffer[4] = (BYTE)((JmpAddr >> 24) & 0xFF); } VOID HEInitHook(PHOOKINFO HookInfo, LPVOID FuncAddr, LPVOID FakeAddr) { HookInfo->FakeAddr = FakeAddr; HookInfo->FuncAddr = FuncAddr; return; } BOOL HEStartHook(PHOOKINFO HookInfo) { BOOL CallRet; BOOL FuncRet = 0; PVOID BufAddr; DWORD dwTmp; DWORD OldProtect; LPVOID FuncAddr; DWORD CodeLength; // Init the basic value FuncAddr = HookInfo->FuncAddr; CodeLength = ade_getlength(FuncAddr, JMPSIZE); HookInfo->CodeLength = CodeLength; if (HookInfo->FakeAddr == NULL || FuncAddr == NULL || CodeLength == NULL) { FuncRet = 1; goto Exit1; } // Alloc buffer to store the code then write them to the head of the function BufAddr = malloc(CodeLength); if (BufAddr == NULL) { FuncRet = 2; goto Exit1; } // Alloc buffer to store original code HookInfo->Stub = (PBYTE)malloc(CodeLength + JMPSIZE); if (HookInfo->Stub == NULL) { FuncRet = 3; goto Exit2; } // Fill buffer to nop. This could make hook stable FillMemory(BufAddr, CodeLength, NOP); // Build buffers BuildJmp((PBYTE)BufAddr, (DWORD)HookInfo->FakeAddr, (DWORD)FuncAddr); BuildJmp(&(HookInfo->Stub[CodeLength]), (DWORD)((PBYTE)FuncAddr + CodeLength), (DWORD)((PBYTE)HookInfo->Stub + CodeLength)); // [V1.1] Bug fixed: VirtualProtect Stub CallRet = VirtualProtect(HookInfo->Stub, CodeLength, PAGE_EXECUTE_READWRITE, &OldProtect); if (!CallRet) { FuncRet = 4; goto Exit3; } // Set the block of memory could be read and write CallRet = VirtualProtect(FuncAddr, CodeLength, PAGE_EXECUTE_READWRITE, &OldProtect); if (!CallRet) { FuncRet = 4; goto Exit3; } // Copy the head of function to stub CallRet = ReadProcessMemory(GetCurrentProcess(), FuncAddr, HookInfo->Stub, CodeLength, &dwTmp); if (!CallRet || dwTmp != CodeLength) { FuncRet = 5; goto Exit3; } // Write hook code back to the head of the function CallRet = WriteProcessMemory(GetCurrentProcess(), FuncAddr, BufAddr, CodeLength, &dwTmp); if (!CallRet || dwTmp != CodeLength) { FuncRet = 6; goto Exit3; } // Make hook stable FlushInstructionCache(GetCurrentProcess(), FuncAddr, CodeLength); VirtualProtect(FuncAddr, CodeLength, OldProtect, &dwTmp); // All done goto Exit2; // Error handle Exit3: free(HookInfo->Stub); Exit2: free (BufAddr); Exit1: return FuncRet; } BOOL HEStopHook(PHOOKINFO HookInfo) { BOOL CallRet; DWORD dwTmp; DWORD OldProtect; LPVOID FuncAddr = HookInfo->FuncAddr; DWORD CodeLength = HookInfo->CodeLength; CallRet = VirtualProtect(FuncAddr, CodeLength, PAGE_EXECUTE_READWRITE, &OldProtect); if (!CallRet) { return 1; } CallRet = WriteProcessMemory(GetCurrentProcess(), FuncAddr, HookInfo->Stub, CodeLength, &dwTmp); if (!CallRet || dwTmp != CodeLength) { return 2; } FlushInstructionCache(GetCurrentProcess(), FuncAddr, CodeLength); VirtualProtect(FuncAddr, CodeLength, OldProtect, &dwTmp); free(HookInfo->Stub); return 0; }
C++
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ /* ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0/LGPL 2.1 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is mozilla.org code. * * The Initial Developer of the Original Code is * Netscape Communications Corporation. * Portions created by the Initial Developer are Copyright (C) 1998 * the Initial Developer. All Rights Reserved. * * Contributor(s): * * Alternatively, the contents of this file may be used under the terms of * either the GNU General Public License Version 2 or later (the "GPL"), or * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), * in which case the provisions of the GPL or the LGPL are applicable instead * of those above. If you wish to allow use of your version of this file only * under the terms of either the GPL or the LGPL, and not to allow others to * use your version of this file under the terms of the MPL, indicate your * decision by deleting the provisions above and replace them with the notice * and other provisions required by the GPL or the LGPL. If you do not delete * the provisions above, a recipient may use your version of this file under * the terms of any one of the MPL, the GPL or the LGPL. * * ***** END LICENSE BLOCK ***** */ #include "StdAfx.h" #include "PropertyBag.h" CPropertyBag::CPropertyBag() { } CPropertyBag::~CPropertyBag() { } /////////////////////////////////////////////////////////////////////////////// // IPropertyBag implementation HRESULT STDMETHODCALLTYPE CPropertyBag::Read(/* [in] */ LPCOLESTR pszPropName, /* [out][in] */ VARIANT __RPC_FAR *pVar, /* [in] */ IErrorLog __RPC_FAR *pErrorLog) { if (pszPropName == NULL) { return E_INVALIDARG; } if (pVar == NULL) { return E_INVALIDARG; } VARTYPE vt = pVar->vt; VariantInit(pVar); for (unsigned long i = 0; i < m_PropertyList.GetSize(); i++) { if (wcsicmp(m_PropertyList.GetNameOf(i), pszPropName) == 0) { const VARIANT *pvSrc = m_PropertyList.GetValueOf(i); if (!pvSrc) { return E_FAIL; } CComVariant vNew; HRESULT hr = (vt == VT_EMPTY) ? vNew.Copy(pvSrc) : vNew.ChangeType(vt, pvSrc); if (FAILED(hr)) { return E_FAIL; } // Copy the new value vNew.Detach(pVar); return S_OK; } } // Property does not exist in the bag return E_FAIL; } HRESULT STDMETHODCALLTYPE CPropertyBag::Write(/* [in] */ LPCOLESTR pszPropName, /* [in] */ VARIANT __RPC_FAR *pVar) { if (pszPropName == NULL) { return E_INVALIDARG; } if (pVar == NULL) { return E_INVALIDARG; } CComBSTR bstrName(pszPropName); m_PropertyList.AddOrReplaceNamedProperty(bstrName, *pVar); return S_OK; }
C++
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ /* ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0/LGPL 2.1 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is mozilla.org code. * * The Initial Developer of the Original Code is * Netscape Communications Corporation. * Portions created by the Initial Developer are Copyright (C) 1998 * the Initial Developer. All Rights Reserved. * * Contributor(s): * Adam Lock <adamlock@eircom.net> * * Alternatively, the contents of this file may be used under the terms of * either the GNU General Public License Version 2 or later (the "GPL"), or * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), * in which case the provisions of the GPL or the LGPL are applicable instead * of those above. If you wish to allow use of your version of this file only * under the terms of either the GPL or the LGPL, and not to allow others to * use your version of this file under the terms of the MPL, indicate your * decision by deleting the provisions above and replace them with the notice * and other provisions required by the GPL or the LGPL. If you do not delete * the provisions above, a recipient may use your version of this file under * the terms of any one of the MPL, the GPL or the LGPL. * * ***** END LICENSE BLOCK ***** */ #ifndef PROPERTYBAG_H #define PROPERTYBAG_H #include "PropertyList.h" // Object wrapper for property list. This class can be set up with a // list of properties and used to initialise a control with them class CPropertyBag : public CComObjectRootEx<CComSingleThreadModel>, public IPropertyBag { // List of properties in the bag PropertyList m_PropertyList; public: // Constructor CPropertyBag(); // Destructor virtual ~CPropertyBag(); BEGIN_COM_MAP(CPropertyBag) COM_INTERFACE_ENTRY(IPropertyBag) END_COM_MAP() // IPropertyBag methods virtual /* [local] */ HRESULT STDMETHODCALLTYPE Read(/* [in] */ LPCOLESTR pszPropName, /* [out][in] */ VARIANT __RPC_FAR *pVar, /* [in] */ IErrorLog __RPC_FAR *pErrorLog); virtual HRESULT STDMETHODCALLTYPE Write(/* [in] */ LPCOLESTR pszPropName, /* [in] */ VARIANT __RPC_FAR *pVar); }; typedef CComObject<CPropertyBag> CPropertyBagInstance; #endif
C++
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ /* ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0/LGPL 2.1 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is mozilla.org code. * * The Initial Developer of the Original Code is * Netscape Communications Corporation. * Portions created by the Initial Developer are Copyright (C) 1998 * the Initial Developer. All Rights Reserved. * * Contributor(s): * Adam Lock <adamlock@netscape.com> * * Alternatively, the contents of this file may be used under the terms of * either the GNU General Public License Version 2 or later (the "GPL"), or * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), * in which case the provisions of the GPL or the LGPL are applicable instead * of those above. If you wish to allow use of your version of this file only * under the terms of either the GPL or the LGPL, and not to allow others to * use your version of this file under the terms of the MPL, indicate your * decision by deleting the provisions above and replace them with the notice * and other provisions required by the GPL or the LGPL. If you do not delete * the provisions above, a recipient may use your version of this file under * the terms of any one of the MPL, the GPL or the LGPL. * * ***** END LICENSE BLOCK ***** */ #ifndef CONTROLSITE_H #define CONTROLSITE_H #include "IOleCommandTargetImpl.h" #include "PropertyList.h" // Temoporarily removed by bug 200680. Stops controls misbehaving and calling // windowless methods when they shouldn't. // COM_INTERFACE_ENTRY_IID(IID_IOleInPlaceSiteWindowless, IOleInPlaceSiteWindowless) \ // Class that defines the control's security policy with regards to // what controls it hosts etc. class CControlSiteSecurityPolicy { public: // Test if the class is safe to host virtual BOOL IsClassSafeToHost(const CLSID & clsid) = 0; // Test if the specified class is marked safe for scripting virtual BOOL IsClassMarkedSafeForScripting(const CLSID & clsid, BOOL &bClassExists) = 0; // Test if the instantiated object is safe for scripting on the specified interface virtual BOOL IsObjectSafeForScripting(IUnknown *pObject, const IID &iid) = 0; }; // // Class for hosting an ActiveX control // // This class supports both windowed and windowless classes. The normal // steps to hosting a control are this: // // CControlSiteInstance *pSite = NULL; // CControlSiteInstance::CreateInstance(&pSite); // pSite->AddRef(); // pSite->Create(clsidControlToCreate); // pSite->Attach(hwndParentWindow, rcPosition); // // Where propertyList is a named list of values to initialise the new object // with, hwndParentWindow is the window in which the control is being created, // and rcPosition is the position in window coordinates where the control will // be rendered. // // Destruction is this: // // pSite->Detach(); // pSite->Release(); // pSite = NULL; class CControlSite : public CComObjectRootEx<CComSingleThreadModel>, public IOleClientSite, public IOleInPlaceSiteWindowless, public IOleControlSite, public IAdviseSinkEx, public IDispatch, public IOleCommandTargetImpl<CControlSite>, public IBindStatusCallback, public IWindowForBindingUI { private: // Site management values // Handle to parent window HWND m_hWndParent; // Position of the site and the contained object RECT m_rcObjectPos; // Flag indicating if client site should be set early or late unsigned m_bSetClientSiteFirst:1; // Flag indicating whether control is visible or not unsigned m_bVisibleAtRuntime:1; // Flag indicating if control is in-place active unsigned m_bInPlaceActive:1; // Flag indicating if control is UI active unsigned m_bUIActive:1; // Flag indicating if control is in-place locked and cannot be deactivated unsigned m_bInPlaceLocked:1; // Flag indicating if the site allows windowless controls unsigned m_bSupportWindowlessActivation:1; // Flag indicating if control is windowless (after being created) unsigned m_bWindowless:1; // Flag indicating if only safely scriptable controls are allowed unsigned m_bSafeForScriptingObjectsOnly:1; // Return the default security policy object static CControlSiteSecurityPolicy *GetDefaultControlSecurityPolicy(); friend class CAxHost; protected: // Pointers to object interfaces // Raw pointer to the object CComPtr<IUnknown> m_spObject; // Pointer to objects IViewObject interface CComQIPtr<IViewObject, &IID_IViewObject> m_spIViewObject; // Pointer to object's IOleObject interface CComQIPtr<IOleObject, &IID_IOleObject> m_spIOleObject; // Pointer to object's IOleInPlaceObject interface CComQIPtr<IOleInPlaceObject, &IID_IOleInPlaceObject> m_spIOleInPlaceObject; // Pointer to object's IOleInPlaceObjectWindowless interface CComQIPtr<IOleInPlaceObjectWindowless, &IID_IOleInPlaceObjectWindowless> m_spIOleInPlaceObjectWindowless; // CLSID of the control CComQIPtr<IOleControl> m_spIOleControl; CLSID m_CLSID; // Parameter list PropertyList m_ParameterList; // Pointer to the security policy CControlSiteSecurityPolicy *m_pSecurityPolicy; // Document and Service provider IUnknown *m_spInner; void (*m_spInnerDeallocater)(IUnknown *m_spInner); // Binding variables // Flag indicating whether binding is in progress unsigned m_bBindingInProgress; // Result from the binding operation HRESULT m_hrBindResult; // Double buffer drawing variables used for windowless controls // Area of buffer RECT m_rcBuffer; // Bitmap to buffer HBITMAP m_hBMBuffer; // Bitmap to buffer HBITMAP m_hBMBufferOld; // Device context HDC m_hDCBuffer; // Clipping area of site HRGN m_hRgnBuffer; // Flags indicating how the buffer was painted DWORD m_dwBufferFlags; // The last control size passed by GetExtent SIZEL m_currentSize; // Ambient properties // Locale ID LCID m_nAmbientLocale; // Foreground colour COLORREF m_clrAmbientForeColor; // Background colour COLORREF m_clrAmbientBackColor; // Flag indicating if control should hatch itself bool m_bAmbientShowHatching:1; // Flag indicating if control should have grab handles bool m_bAmbientShowGrabHandles:1; // Flag indicating if control is in edit/user mode bool m_bAmbientUserMode:1; // Flag indicating if control has a 3d border or not bool m_bAmbientAppearance:1; // Flag indicating if the size passed in is different from the control. bool m_needUpdateContainerSize:1; protected: // Notifies the attached control of a change to an ambient property virtual void FireAmbientPropertyChange(DISPID id); public: // Construction and destruction // Constructor CControlSite(); // Destructor virtual ~CControlSite(); BEGIN_COM_MAP(CControlSite) COM_INTERFACE_ENTRY(IOleWindow) COM_INTERFACE_ENTRY(IOleClientSite) COM_INTERFACE_ENTRY(IOleInPlaceSite) COM_INTERFACE_ENTRY(IOleInPlaceSiteWindowless) COM_INTERFACE_ENTRY_IID(IID_IOleInPlaceSite, IOleInPlaceSiteWindowless) COM_INTERFACE_ENTRY_IID(IID_IOleInPlaceSiteEx, IOleInPlaceSiteWindowless) COM_INTERFACE_ENTRY(IOleControlSite) COM_INTERFACE_ENTRY(IDispatch) COM_INTERFACE_ENTRY_IID(IID_IAdviseSink, IAdviseSinkEx) COM_INTERFACE_ENTRY_IID(IID_IAdviseSink2, IAdviseSinkEx) COM_INTERFACE_ENTRY_IID(IID_IAdviseSinkEx, IAdviseSinkEx) COM_INTERFACE_ENTRY(IOleCommandTarget) COM_INTERFACE_ENTRY(IBindStatusCallback) COM_INTERFACE_ENTRY(IWindowForBindingUI) COM_INTERFACE_ENTRY_AGGREGATE_BLIND(m_spInner) END_COM_MAP() BEGIN_OLECOMMAND_TABLE() END_OLECOMMAND_TABLE() // Returns the window used when processing ole commands HWND GetCommandTargetWindow() { return NULL; // TODO } // Object creation and management functions // Creates and initialises an object virtual HRESULT Create(REFCLSID clsid, PropertyList &pl = PropertyList(), LPCWSTR szCodebase = NULL, IBindCtx *pBindContext = NULL); // Attaches the object to the site virtual HRESULT Attach(HWND hwndParent, const RECT &rcPos, IUnknown *pInitStream = NULL); // Detaches the object from the site virtual HRESULT Detach(); // Returns the IUnknown pointer for the object virtual HRESULT GetControlUnknown(IUnknown **ppObject); // Sets the bounding rectangle for the object virtual HRESULT SetPosition(const RECT &rcPos); // Draws the object using the provided DC virtual HRESULT Draw(HDC hdc); // Performs the specified action on the object virtual HRESULT DoVerb(LONG nVerb, LPMSG lpMsg = NULL); // Sets an advise sink up for changes to the object virtual HRESULT Advise(IUnknown *pIUnkSink, const IID &iid, DWORD *pdwCookie); // Removes an advise sink virtual HRESULT Unadvise(const IID &iid, DWORD dwCookie); // Get the control size, in pixels. virtual HRESULT GetControlSize(LPSIZEL size); // Set the control size, in pixels. virtual HRESULT SetControlSize(const LPSIZEL size, LPSIZEL out); void SetInnerWindow(IUnknown *unk, void (*Deleter)(IUnknown *unk)) { m_spInner = unk; m_spInnerDeallocater = Deleter; } // Set the security policy object. Ownership of this object remains with the caller and the security // policy object is meant to exist for as long as it is set here. virtual void SetSecurityPolicy(CControlSiteSecurityPolicy *pSecurityPolicy) { m_pSecurityPolicy = pSecurityPolicy; } virtual CControlSiteSecurityPolicy *GetSecurityPolicy() const { return m_pSecurityPolicy; } // Methods to set ambient properties virtual void SetAmbientUserMode(BOOL bUser); // Inline helper methods // Returns the object's CLSID virtual const CLSID &GetObjectCLSID() const { return m_CLSID; } // Tests if the object is valid or not virtual BOOL IsObjectValid() const { return (m_spObject) ? TRUE : FALSE; } // Returns the parent window to this one virtual HWND GetParentWindow() const { return m_hWndParent; } // Returns the inplace active state of the object virtual BOOL IsInPlaceActive() const { return m_bInPlaceActive; } // Returns the m_bVisibleAtRuntime virtual BOOL IsVisibleAtRuntime() const { return m_bVisibleAtRuntime; } // Return and reset m_needUpdateContainerSize virtual BOOL CheckAndResetNeedUpdateContainerSize() { BOOL ret = m_needUpdateContainerSize; m_needUpdateContainerSize = false; return ret; } // IDispatch virtual HRESULT STDMETHODCALLTYPE GetTypeInfoCount(/* [out] */ UINT __RPC_FAR *pctinfo); virtual HRESULT STDMETHODCALLTYPE GetTypeInfo(/* [in] */ UINT iTInfo, /* [in] */ LCID lcid, /* [out] */ ITypeInfo __RPC_FAR *__RPC_FAR *ppTInfo); virtual HRESULT STDMETHODCALLTYPE GetIDsOfNames(/* [in] */ REFIID riid, /* [size_is][in] */ LPOLESTR __RPC_FAR *rgszNames, /* [in] */ UINT cNames, /* [in] */ LCID lcid, /* [size_is][out] */ DISPID __RPC_FAR *rgDispId); virtual /* [local] */ HRESULT STDMETHODCALLTYPE Invoke(/* [in] */ DISPID dispIdMember, /* [in] */ REFIID riid, /* [in] */ LCID lcid, /* [in] */ WORD wFlags, /* [out][in] */ DISPPARAMS __RPC_FAR *pDispParams, /* [out] */ VARIANT __RPC_FAR *pVarResult, /* [out] */ EXCEPINFO __RPC_FAR *pExcepInfo, /* [out] */ UINT __RPC_FAR *puArgErr); // IAdviseSink implementation virtual /* [local] */ void STDMETHODCALLTYPE OnDataChange(/* [unique][in] */ FORMATETC __RPC_FAR *pFormatetc, /* [unique][in] */ STGMEDIUM __RPC_FAR *pStgmed); virtual /* [local] */ void STDMETHODCALLTYPE OnViewChange(/* [in] */ DWORD dwAspect, /* [in] */ LONG lindex); virtual /* [local] */ void STDMETHODCALLTYPE OnRename(/* [in] */ IMoniker __RPC_FAR *pmk); virtual /* [local] */ void STDMETHODCALLTYPE OnSave(void); virtual /* [local] */ void STDMETHODCALLTYPE OnClose(void); // IAdviseSink2 virtual /* [local] */ void STDMETHODCALLTYPE OnLinkSrcChange(/* [unique][in] */ IMoniker __RPC_FAR *pmk); // IAdviseSinkEx implementation virtual /* [local] */ void STDMETHODCALLTYPE OnViewStatusChange(/* [in] */ DWORD dwViewStatus); // IOleWindow implementation virtual /* [input_sync] */ HRESULT STDMETHODCALLTYPE GetWindow(/* [out] */ HWND __RPC_FAR *phwnd); virtual HRESULT STDMETHODCALLTYPE ContextSensitiveHelp(/* [in] */ BOOL fEnterMode); // IOleClientSite implementation virtual HRESULT STDMETHODCALLTYPE SaveObject(void); virtual HRESULT STDMETHODCALLTYPE GetMoniker(/* [in] */ DWORD dwAssign, /* [in] */ DWORD dwWhichMoniker, /* [out] */ IMoniker __RPC_FAR *__RPC_FAR *ppmk); virtual HRESULT STDMETHODCALLTYPE GetContainer(/* [out] */ IOleContainer __RPC_FAR *__RPC_FAR *ppContainer); virtual HRESULT STDMETHODCALLTYPE ShowObject(void); virtual HRESULT STDMETHODCALLTYPE OnShowWindow(/* [in] */ BOOL fShow); virtual HRESULT STDMETHODCALLTYPE RequestNewObjectLayout(void); // IOleInPlaceSite implementation virtual HRESULT STDMETHODCALLTYPE CanInPlaceActivate(void); virtual HRESULT STDMETHODCALLTYPE OnInPlaceActivate(void); virtual HRESULT STDMETHODCALLTYPE OnUIActivate(void); virtual HRESULT STDMETHODCALLTYPE GetWindowContext(/* [out] */ IOleInPlaceFrame __RPC_FAR *__RPC_FAR *ppFrame, /* [out] */ IOleInPlaceUIWindow __RPC_FAR *__RPC_FAR *ppDoc, /* [out] */ LPRECT lprcPosRect, /* [out] */ LPRECT lprcClipRect, /* [out][in] */ LPOLEINPLACEFRAMEINFO lpFrameInfo); virtual HRESULT STDMETHODCALLTYPE Scroll(/* [in] */ SIZE scrollExtant); virtual HRESULT STDMETHODCALLTYPE OnUIDeactivate(/* [in] */ BOOL fUndoable); virtual HRESULT STDMETHODCALLTYPE OnInPlaceDeactivate(void); virtual HRESULT STDMETHODCALLTYPE DiscardUndoState(void); virtual HRESULT STDMETHODCALLTYPE DeactivateAndUndo(void); virtual HRESULT STDMETHODCALLTYPE OnPosRectChange(/* [in] */ LPCRECT lprcPosRect); // IOleInPlaceSiteEx implementation virtual HRESULT STDMETHODCALLTYPE OnInPlaceActivateEx(/* [out] */ BOOL __RPC_FAR *pfNoRedraw, /* [in] */ DWORD dwFlags); virtual HRESULT STDMETHODCALLTYPE OnInPlaceDeactivateEx(/* [in] */ BOOL fNoRedraw); virtual HRESULT STDMETHODCALLTYPE RequestUIActivate(void); // IOleInPlaceSiteWindowless implementation virtual HRESULT STDMETHODCALLTYPE CanWindowlessActivate(void); virtual HRESULT STDMETHODCALLTYPE GetCapture(void); virtual HRESULT STDMETHODCALLTYPE SetCapture(/* [in] */ BOOL fCapture); virtual HRESULT STDMETHODCALLTYPE GetFocus(void); virtual HRESULT STDMETHODCALLTYPE SetFocus(/* [in] */ BOOL fFocus); virtual HRESULT STDMETHODCALLTYPE GetDC(/* [in] */ LPCRECT pRect, /* [in] */ DWORD grfFlags, /* [out] */ HDC __RPC_FAR *phDC); virtual HRESULT STDMETHODCALLTYPE ReleaseDC(/* [in] */ HDC hDC); virtual HRESULT STDMETHODCALLTYPE InvalidateRect(/* [in] */ LPCRECT pRect, /* [in] */ BOOL fErase); virtual HRESULT STDMETHODCALLTYPE InvalidateRgn(/* [in] */ HRGN hRGN, /* [in] */ BOOL fErase); virtual HRESULT STDMETHODCALLTYPE ScrollRect(/* [in] */ INT dx, /* [in] */ INT dy, /* [in] */ LPCRECT pRectScroll, /* [in] */ LPCRECT pRectClip); virtual HRESULT STDMETHODCALLTYPE AdjustRect(/* [out][in] */ LPRECT prc); virtual HRESULT STDMETHODCALLTYPE OnDefWindowMessage(/* [in] */ UINT msg, /* [in] */ WPARAM wParam, /* [in] */ LPARAM lParam, /* [out] */ LRESULT __RPC_FAR *plResult); // IOleControlSite implementation virtual HRESULT STDMETHODCALLTYPE OnControlInfoChanged(void); virtual HRESULT STDMETHODCALLTYPE LockInPlaceActive(/* [in] */ BOOL fLock); virtual HRESULT STDMETHODCALLTYPE GetExtendedControl(/* [out] */ IDispatch __RPC_FAR *__RPC_FAR *ppDisp); virtual HRESULT STDMETHODCALLTYPE TransformCoords(/* [out][in] */ POINTL __RPC_FAR *pPtlHimetric, /* [out][in] */ POINTF __RPC_FAR *pPtfContainer, /* [in] */ DWORD dwFlags); virtual HRESULT STDMETHODCALLTYPE TranslateAccelerator(/* [in] */ MSG __RPC_FAR *pMsg, /* [in] */ DWORD grfModifiers); virtual HRESULT STDMETHODCALLTYPE OnFocus(/* [in] */ BOOL fGotFocus); virtual HRESULT STDMETHODCALLTYPE ShowPropertyFrame( void); // IBindStatusCallback virtual HRESULT STDMETHODCALLTYPE OnStartBinding(/* [in] */ DWORD dwReserved, /* [in] */ IBinding __RPC_FAR *pib); virtual HRESULT STDMETHODCALLTYPE GetPriority(/* [out] */ LONG __RPC_FAR *pnPriority); virtual HRESULT STDMETHODCALLTYPE OnLowResource(/* [in] */ DWORD reserved); virtual HRESULT STDMETHODCALLTYPE OnProgress(/* [in] */ ULONG ulProgress, /* [in] */ ULONG ulProgressMax, /* [in] */ ULONG ulStatusCode, /* [in] */ LPCWSTR szStatusText); virtual HRESULT STDMETHODCALLTYPE OnStopBinding(/* [in] */ HRESULT hresult, /* [unique][in] */ LPCWSTR szError); virtual /* [local] */ HRESULT STDMETHODCALLTYPE GetBindInfo( /* [out] */ DWORD __RPC_FAR *grfBINDF, /* [unique][out][in] */ BINDINFO __RPC_FAR *pbindinfo); virtual /* [local] */ HRESULT STDMETHODCALLTYPE OnDataAvailable(/* [in] */ DWORD grfBSCF, /* [in] */ DWORD dwSize, /* [in] */ FORMATETC __RPC_FAR *pformatetc, /* [in] */ STGMEDIUM __RPC_FAR *pstgmed); virtual HRESULT STDMETHODCALLTYPE OnObjectAvailable(/* [in] */ REFIID riid, /* [iid_is][in] */ IUnknown __RPC_FAR *punk); // IWindowForBindingUI virtual HRESULT STDMETHODCALLTYPE GetWindow(/* [in] */ REFGUID rguidReason, /* [out] */ HWND *phwnd); }; #endif
C++
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ /* ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0/LGPL 2.1 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is mozilla.org code. * * The Initial Developer of the Original Code is * Netscape Communications Corporation. * Portions created by the Initial Developer are Copyright (C) 1998 * the Initial Developer. All Rights Reserved. * * Contributor(s): * Adam Lock <adamlock@eircom.net> * * Alternatively, the contents of this file may be used under the terms of * either the GNU General Public License Version 2 or later (the "GPL"), or * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), * in which case the provisions of the GPL or the LGPL are applicable instead * of those above. If you wish to allow use of your version of this file only * under the terms of either the GPL or the LGPL, and not to allow others to * use your version of this file under the terms of the MPL, indicate your * decision by deleting the provisions above and replace them with the notice * and other provisions required by the GPL or the LGPL. If you do not delete * the provisions above, a recipient may use your version of this file under * the terms of any one of the MPL, the GPL or the LGPL. * * ***** END LICENSE BLOCK ***** */ #include "StdAfx.h" #include "ItemContainer.h" CItemContainer::CItemContainer() { } CItemContainer::~CItemContainer() { } /////////////////////////////////////////////////////////////////////////////// // IParseDisplayName implementation HRESULT STDMETHODCALLTYPE CItemContainer::ParseDisplayName(/* [unique][in] */ IBindCtx __RPC_FAR *pbc, /* [in] */ LPOLESTR pszDisplayName, /* [out] */ ULONG __RPC_FAR *pchEaten, /* [out] */ IMoniker __RPC_FAR *__RPC_FAR *ppmkOut) { // TODO return E_NOTIMPL; } /////////////////////////////////////////////////////////////////////////////// // IOleContainer implementation HRESULT STDMETHODCALLTYPE CItemContainer::EnumObjects(/* [in] */ DWORD grfFlags, /* [out] */ IEnumUnknown __RPC_FAR *__RPC_FAR *ppenum) { HRESULT hr = E_NOTIMPL; /* if (ppenum == NULL) { return E_POINTER; } *ppenum = NULL; typedef CComObject<CComEnumOnSTL<IEnumUnknown, &IID_IEnumUnknown, IUnknown*, _CopyInterface<IUnknown>, CNamedObjectList > > enumunk; enumunk* p = NULL; p = new enumunk; if(p == NULL) { return E_OUTOFMEMORY; } hr = p->Init(); if (SUCCEEDED(hr)) { hr = p->QueryInterface(IID_IEnumUnknown, (void**) ppenum); } if (FAILED(hRes)) { delete p; } */ return hr; } HRESULT STDMETHODCALLTYPE CItemContainer::LockContainer(/* [in] */ BOOL fLock) { // TODO return S_OK; } /////////////////////////////////////////////////////////////////////////////// // IOleItemContainer implementation HRESULT STDMETHODCALLTYPE CItemContainer::GetObject(/* [in] */ LPOLESTR pszItem, /* [in] */ DWORD dwSpeedNeeded, /* [unique][in] */ IBindCtx __RPC_FAR *pbc, /* [in] */ REFIID riid, /* [iid_is][out] */ void __RPC_FAR *__RPC_FAR *ppvObject) { if (pszItem == NULL) { return E_INVALIDARG; } if (ppvObject == NULL) { return E_INVALIDARG; } *ppvObject = NULL; return MK_E_NOOBJECT; } HRESULT STDMETHODCALLTYPE CItemContainer::GetObjectStorage(/* [in] */ LPOLESTR pszItem, /* [unique][in] */ IBindCtx __RPC_FAR *pbc, /* [in] */ REFIID riid, /* [iid_is][out] */ void __RPC_FAR *__RPC_FAR *ppvStorage) { // TODO return MK_E_NOOBJECT; } HRESULT STDMETHODCALLTYPE CItemContainer::IsRunning(/* [in] */ LPOLESTR pszItem) { // TODO return MK_E_NOOBJECT; }
C++
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ /* ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0/LGPL 2.1 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is mozilla.org code. * * The Initial Developer of the Original Code is * Netscape Communications Corporation. * Portions created by the Initial Developer are Copyright (C) 1998 * the Initial Developer. All Rights Reserved. * * Contributor(s): * Adam Lock <adamlock@netscape.com> * * Alternatively, the contents of this file may be used under the terms of * either the GNU General Public License Version 2 or later (the "GPL"), or * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), * in which case the provisions of the GPL or the LGPL are applicable instead * of those above. If you wish to allow use of your version of this file only * under the terms of either the GPL or the LGPL, and not to allow others to * use your version of this file under the terms of the MPL, indicate your * decision by deleting the provisions above and replace them with the notice * and other provisions required by the GPL or the LGPL. If you do not delete * the provisions above, a recipient may use your version of this file under * the terms of any one of the MPL, the GPL or the LGPL. * * ***** END LICENSE BLOCK ***** */ #ifndef CONTROLEVENTSINK_H #define CONTROLEVENTSINK_H #include <map> // This class listens for events from the specified control class CControlEventSink : public CComObjectRootEx<CComSingleThreadModel>, public IDispatch { public: CControlEventSink(); // Current event connection point CComPtr<IConnectionPoint> m_spEventCP; CComPtr<ITypeInfo> m_spEventSinkTypeInfo; DWORD m_dwEventCookie; IID m_EventIID; typedef std::map<DISPID, wchar_t *> EventMap; EventMap events; NPP instance; protected: virtual ~CControlEventSink(); bool m_bSubscribed; static HRESULT WINAPI SinkQI(void* pv, REFIID riid, LPVOID* ppv, DWORD dw) { CControlEventSink *pThis = (CControlEventSink *) pv; if (!IsEqualIID(pThis->m_EventIID, GUID_NULL) && IsEqualIID(pThis->m_EventIID, riid)) { return pThis->QueryInterface(__uuidof(IDispatch), ppv); } return E_NOINTERFACE; } public: BEGIN_COM_MAP(CControlEventSink) COM_INTERFACE_ENTRY(IDispatch) COM_INTERFACE_ENTRY_FUNC_BLIND(0, SinkQI) END_COM_MAP() virtual HRESULT SubscribeToEvents(IUnknown *pControl); virtual void UnsubscribeFromEvents(); virtual BOOL GetEventSinkIID(IUnknown *pControl, IID &iid, ITypeInfo **typeInfo); virtual HRESULT InternalInvoke(DISPID dispIdMember, REFIID riid, LCID lcid, WORD wFlags, DISPPARAMS *pDispParams, VARIANT *pVarResult, EXCEPINFO *pExcepInfo, UINT *puArgErr); // IDispatch virtual HRESULT STDMETHODCALLTYPE GetTypeInfoCount(/* [out] */ UINT __RPC_FAR *pctinfo); virtual HRESULT STDMETHODCALLTYPE GetTypeInfo(/* [in] */ UINT iTInfo, /* [in] */ LCID lcid, /* [out] */ ITypeInfo __RPC_FAR *__RPC_FAR *ppTInfo); virtual HRESULT STDMETHODCALLTYPE GetIDsOfNames(/* [in] */ REFIID riid, /* [size_is][in] */ LPOLESTR __RPC_FAR *rgszNames, /* [in] */ UINT cNames, /* [in] */ LCID lcid, /* [size_is][out] */ DISPID __RPC_FAR *rgDispId); virtual /* [local] */ HRESULT STDMETHODCALLTYPE Invoke(/* [in] */ DISPID dispIdMember, /* [in] */ REFIID riid, /* [in] */ LCID lcid, /* [in] */ WORD wFlags, /* [out][in] */ DISPPARAMS __RPC_FAR *pDispParams, /* [out] */ VARIANT __RPC_FAR *pVarResult, /* [out] */ EXCEPINFO __RPC_FAR *pExcepInfo, /* [out] */ UINT __RPC_FAR *puArgErr); }; typedef CComObject<CControlEventSink> CControlEventSinkInstance; #endif
C++
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ /* ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0/LGPL 2.1 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is mozilla.org code. * * The Initial Developer of the Original Code is * Netscape Communications Corporation. * Portions created by the Initial Developer are Copyright (C) 1998 * the Initial Developer. All Rights Reserved. * * Contributor(s): * Adam Lock <adamlock@netscape.com> * * Alternatively, the contents of this file may be used under the terms of * either the GNU General Public License Version 2 or later (the "GPL"), or * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), * in which case the provisions of the GPL or the LGPL are applicable instead * of those above. If you wish to allow use of your version of this file only * under the terms of either the GPL or the LGPL, and not to allow others to * use your version of this file under the terms of the MPL, indicate your * decision by deleting the provisions above and replace them with the notice * and other provisions required by the GPL or the LGPL. If you do not delete * the provisions above, a recipient may use your version of this file under * the terms of any one of the MPL, the GPL or the LGPL. * * ***** END LICENSE BLOCK ***** */ #include "stdafx.h" #include "ControlSiteIPFrame.h" CControlSiteIPFrame::CControlSiteIPFrame() { m_hwndFrame = NULL; } CControlSiteIPFrame::~CControlSiteIPFrame() { } /////////////////////////////////////////////////////////////////////////////// // IOleWindow implementation HRESULT STDMETHODCALLTYPE CControlSiteIPFrame::GetWindow(/* [out] */ HWND __RPC_FAR *phwnd) { if (phwnd == NULL) { return E_INVALIDARG; } *phwnd = m_hwndFrame; return S_OK; } HRESULT STDMETHODCALLTYPE CControlSiteIPFrame::ContextSensitiveHelp(/* [in] */ BOOL fEnterMode) { return S_OK; } /////////////////////////////////////////////////////////////////////////////// // IOleInPlaceUIWindow implementation HRESULT STDMETHODCALLTYPE CControlSiteIPFrame::GetBorder(/* [out] */ LPRECT lprectBorder) { return INPLACE_E_NOTOOLSPACE; } HRESULT STDMETHODCALLTYPE CControlSiteIPFrame::RequestBorderSpace(/* [unique][in] */ LPCBORDERWIDTHS pborderwidths) { return INPLACE_E_NOTOOLSPACE; } HRESULT STDMETHODCALLTYPE CControlSiteIPFrame::SetBorderSpace(/* [unique][in] */ LPCBORDERWIDTHS pborderwidths) { return S_OK; } HRESULT STDMETHODCALLTYPE CControlSiteIPFrame::SetActiveObject(/* [unique][in] */ IOleInPlaceActiveObject __RPC_FAR *pActiveObject, /* [unique][string][in] */ LPCOLESTR pszObjName) { return S_OK; } /////////////////////////////////////////////////////////////////////////////// // IOleInPlaceFrame implementation HRESULT STDMETHODCALLTYPE CControlSiteIPFrame::InsertMenus(/* [in] */ HMENU hmenuShared, /* [out][in] */ LPOLEMENUGROUPWIDTHS lpMenuWidths) { return S_OK; } HRESULT STDMETHODCALLTYPE CControlSiteIPFrame::SetMenu(/* [in] */ HMENU hmenuShared, /* [in] */ HOLEMENU holemenu, /* [in] */ HWND hwndActiveObject) { return S_OK; } HRESULT STDMETHODCALLTYPE CControlSiteIPFrame::RemoveMenus(/* [in] */ HMENU hmenuShared) { return S_OK; } HRESULT STDMETHODCALLTYPE CControlSiteIPFrame::SetStatusText(/* [in] */ LPCOLESTR pszStatusText) { return S_OK; } HRESULT STDMETHODCALLTYPE CControlSiteIPFrame::EnableModeless(/* [in] */ BOOL fEnable) { return S_OK; } HRESULT STDMETHODCALLTYPE CControlSiteIPFrame::TranslateAccelerator(/* [in] */ LPMSG lpmsg, /* [in] */ WORD wID) { return E_NOTIMPL; }
C++
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ /* ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0/LGPL 2.1 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is mozilla.org code. * * The Initial Developer of the Original Code is * Netscape Communications Corporation. * Portions created by the Initial Developer are Copyright (C) 1998 * the Initial Developer. All Rights Reserved. * * Contributor(s): * Adam Lock <adamlock@eircom.net> * Ruediger Jungbeck <ruediger.jungbeck@rsj.de> * * Alternatively, the contents of this file may be used under the terms of * either the GNU General Public License Version 2 or later (the "GPL"), or * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), * in which case the provisions of the GPL or the LGPL are applicable instead * of those above. If you wish to allow use of your version of this file only * under the terms of either the GPL or the LGPL, and not to allow others to * use your version of this file under the terms of the MPL, indicate your * decision by deleting the provisions above and replace them with the notice * and other provisions required by the GPL or the LGPL. If you do not delete * the provisions above, a recipient may use your version of this file under * the terms of any one of the MPL, the GPL or the LGPL. * * ***** END LICENSE BLOCK ***** */ // stdafx.h : include file for standard system include files, // or project specific include files that are used frequently, // but are changed infrequently #if !defined(AFX_STDAFX_H__1339B542_3453_11D2_93B9_000000000000__INCLUDED_) #define AFX_STDAFX_H__1339B542_3453_11D2_93B9_000000000000__INCLUDED_ #if _MSC_VER >= 1000 #pragma once #endif // _MSC_VER >= 1000 // under MSVC shut off copious warnings about debug symbol too long #ifdef _MSC_VER #pragma warning( disable: 4786 ) #endif //#include "jstypes.h" //#include "prtypes.h" // Mozilla headers //#include "jscompat.h" //#include "prthread.h" //#include "prprf.h" //#include "nsID.h" //#include "nsIComponentManager.h" //#include "nsIServiceManager.h" //#include "nsStringAPI.h" //#include "nsCOMPtr.h" //#include "nsComponentManagerUtils.h" //#include "nsServiceManagerUtils.h" //#include "nsIDocument.h" //#include "nsIDocumentObserver.h" //#include "nsVoidArray.h" //#include "nsIDOMNode.h" //#include "nsIDOMNodeList.h" //#include "nsIDOMDocument.h" //#include "nsIDOMDocumentType.h" //#include "nsIDOMElement.h" //#undef _WIN32_WINNT //#define _WIN32_WINNT 0x0400 #define _ATL_APARTMENT_THREADED //#define _ATL_STATIC_REGISTRY // #define _ATL_DEBUG_INTERFACES // ATL headers // The ATL headers that come with the platform SDK have bad for scoping #if _MSC_VER >= 1400 #pragma conform(forScope, push, atlhack, off) #endif #include <atlbase.h> //You may derive a class from CComModule and use it if you want to override //something, but do not change the name of _Module extern CComModule _Module; #include <atlcom.h> #include <atlctl.h> #if _MSC_VER >= 1400 #pragma conform(forScope, pop, atlhack) #endif #include <mshtml.h> #include <mshtmhst.h> #include <docobj.h> //#include <winsock2.h> #include <comdef.h> #include <vector> #include <list> #include <string> // New winsock2.h doesn't define this anymore typedef long int32; #define NS_SCRIPTABLE #include "nscore.h" #include "npapi.h" //#include "npupp.h" #include "npfunctions.h" #include "nsID.h" #include <npruntime.h> #include "../variants.h" #include "PropertyList.h" #include "PropertyBag.h" #include "ItemContainer.h" #include "ControlSite.h" #include "ControlSiteIPFrame.h" #include "ControlEventSink.h" extern NPNetscapeFuncs NPNFuncs; // Turn off warnings about debug symbols for templates being too long #pragma warning(disable : 4786) #define TRACE_METHOD(fn) \ { \ ATLTRACE(_T("0x%04x %s()\n"), (int) GetCurrentThreadId(), _T(#fn)); \ } #define TRACE_METHOD_ARGS(fn, pattern, args) \ { \ ATLTRACE(_T("0x%04x %s(") _T(pattern) _T(")\n"), (int) GetCurrentThreadId(), _T(#fn), args); \ } //{{AFX_INSERT_LOCATION}} // Microsoft Developer Studio will insert additional declarations immediately before the previous line. #define NS_ASSERTION(x, y) #endif // !defined(AFX_STDAFX_H__1339B542_3453_11D2_93B9_000000000000__INCLUDED)
C++
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ /* ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0/LGPL 2.1 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is mozilla.org code. * * The Initial Developer of the Original Code is * Netscape Communications Corporation. * Portions created by the Initial Developer are Copyright (C) 1998 * the Initial Developer. All Rights Reserved. * * Contributor(s): * Adam Lock <adamlock@netscape.com> * * Alternatively, the contents of this file may be used under the terms of * either the GNU General Public License Version 2 or later (the "GPL"), or * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), * in which case the provisions of the GPL or the LGPL are applicable instead * of those above. If you wish to allow use of your version of this file only * under the terms of either the GPL or the LGPL, and not to allow others to * use your version of this file under the terms of the MPL, indicate your * decision by deleting the provisions above and replace them with the notice * and other provisions required by the GPL or the LGPL. If you do not delete * the provisions above, a recipient may use your version of this file under * the terms of any one of the MPL, the GPL or the LGPL. * * ***** END LICENSE BLOCK ***** */ #include "StdAfx.h" #include "../npactivex.h" #include "ControlEventSink.h" CControlEventSink::CControlEventSink() : m_dwEventCookie(0), m_bSubscribed(false), m_EventIID(GUID_NULL), events() { } CControlEventSink::~CControlEventSink() { UnsubscribeFromEvents(); } BOOL CControlEventSink::GetEventSinkIID(IUnknown *pControl, IID &iid, ITypeInfo **typeInfo) { iid = GUID_NULL; if (!pControl) { return FALSE; } // IProvideClassInfo2 way is easiest // CComQIPtr<IProvideClassInfo2> classInfo2 = pControl; // if (classInfo2) // { // classInfo2->GetGUID(GUIDKIND_DEFAULT_SOURCE_DISP_IID, &iid); // if (!::IsEqualIID(iid, GUID_NULL)) // { // return TRUE; // } // } // Yuck, the hard way CComQIPtr<IProvideClassInfo> classInfo = pControl; if (!classInfo) { np_log(instance, 0, "no classInfo"); return FALSE; } // Search the class type information for the default source interface // which is the outgoing event sink. CComPtr<ITypeInfo> classTypeInfo; classInfo->GetClassInfo(&classTypeInfo); if (!classTypeInfo) { np_log(instance, 0, "noclassTypeinfo"); return FALSE; } TYPEATTR *classAttr = NULL; if (FAILED(classTypeInfo->GetTypeAttr(&classAttr))) { np_log(instance, 0, "noclassTypeinfo->GetTypeAttr"); return FALSE; } INT implFlags = 0; for (UINT i = 0; i < classAttr->cImplTypes; i++) { // Search for the interface with the [default, source] attr if (SUCCEEDED(classTypeInfo->GetImplTypeFlags(i, &implFlags)) && implFlags == (IMPLTYPEFLAG_FDEFAULT | IMPLTYPEFLAG_FSOURCE)) { CComPtr<ITypeInfo> eventSinkTypeInfo; HREFTYPE hRefType; if (SUCCEEDED(classTypeInfo->GetRefTypeOfImplType(i, &hRefType)) && SUCCEEDED(classTypeInfo->GetRefTypeInfo(hRefType, &eventSinkTypeInfo))) { TYPEATTR *eventSinkAttr = NULL; if (SUCCEEDED(eventSinkTypeInfo->GetTypeAttr(&eventSinkAttr))) { iid = eventSinkAttr->guid; if (typeInfo) { *typeInfo = eventSinkTypeInfo.p; (*typeInfo)->AddRef(); } eventSinkTypeInfo->ReleaseTypeAttr(eventSinkAttr); } } break; } } classTypeInfo->ReleaseTypeAttr(classAttr); return (!::IsEqualIID(iid, GUID_NULL)); } void CControlEventSink::UnsubscribeFromEvents() { if (m_bSubscribed) { DWORD tmpCookie = m_dwEventCookie; m_dwEventCookie = 0; m_bSubscribed = false; // Unsubscribe and reset - This seems to complete release and destroy us... m_spEventCP->Unadvise(tmpCookie); // Unadvise handles the Release m_spEventCP.Release(); } else { m_spEventCP.Release(); } } HRESULT CControlEventSink::SubscribeToEvents(IUnknown *pControl) { if (!pControl) { np_log(instance, 0, "not valid control"); return E_INVALIDARG; } // Throw away any existing connections UnsubscribeFromEvents(); // Grab the outgoing event sink IID which will be used to subscribe // to events via the connection point container. IID iidEventSink; CComPtr<ITypeInfo> typeInfo; if (!GetEventSinkIID(pControl, iidEventSink, &typeInfo)) { np_log(instance, 0, "Can't get event sink iid"); return E_FAIL; } // Get the connection point CComQIPtr<IConnectionPointContainer> ccp = pControl; CComPtr<IConnectionPoint> cp; if (!ccp) { np_log(instance, 0, "not valid ccp"); return E_FAIL; } // Custom IID m_EventIID = iidEventSink; DWORD dwCookie = 0;/* CComPtr<IEnumConnectionPoints> e; ccp->EnumConnectionPoints(&e); e->Next(1, &cp, &dwCookie);*/ if (FAILED(ccp->FindConnectionPoint(m_EventIID, &cp))) { np_log(instance, 0, "failed to find connection point"); return E_FAIL; } if (FAILED(cp->Advise(this, &dwCookie))) { np_log(instance, 0, "failed to advise"); return E_FAIL; } m_bSubscribed = true; m_spEventCP = cp; m_dwEventCookie = dwCookie; m_spEventSinkTypeInfo = typeInfo; return S_OK; } HRESULT CControlEventSink::InternalInvoke(DISPID dispIdMember, REFIID riid, LCID lcid, WORD wFlags, DISPPARAMS *pDispParams, VARIANT *pVarResult, EXCEPINFO *pExcepInfo, UINT *puArgErr) { USES_CONVERSION; if (DISPATCH_METHOD != wFlags) { // any other reason to call us?! return S_FALSE; } EventMap::iterator cur = events.find(dispIdMember); if (events.end() != cur) { // invoke this event handler NPVariant result; NPVariant *args = NULL; if (pDispParams->cArgs > 0) { args = (NPVariant *)calloc(pDispParams->cArgs, sizeof(NPVariant)); if (!args) { return S_FALSE; } for (unsigned int i = 0; i < pDispParams->cArgs; ++i) { // convert the arguments in reverse order Variant2NPVar(&pDispParams->rgvarg[i], &args[pDispParams->cArgs - i - 1], instance); } } NPObject *globalObj = NULL; NPNFuncs.getvalue(instance, NPNVWindowNPObject, &globalObj); NPIdentifier handler = NPNFuncs.getstringidentifier(W2A((*cur).second)); bool success = NPNFuncs.invoke(instance, globalObj, handler, args, pDispParams->cArgs, &result); NPNFuncs.releaseobject(globalObj); for (unsigned int i = 0; i < pDispParams->cArgs; ++i) { // convert the arguments if (args[i].type == NPVariantType_String) { // was allocated earlier by Variant2NPVar NPNFuncs.memfree((void *)args[i].value.stringValue.UTF8Characters); } } if (!success) { return S_FALSE; } if (pVarResult) { // set the result NPVar2Variant(&result, pVarResult, instance); } NPNFuncs.releasevariantvalue(&result); } return S_OK; } /////////////////////////////////////////////////////////////////////////////// // IDispatch implementation HRESULT STDMETHODCALLTYPE CControlEventSink::GetTypeInfoCount(/* [out] */ UINT __RPC_FAR *pctinfo) { return E_NOTIMPL; } HRESULT STDMETHODCALLTYPE CControlEventSink::GetTypeInfo(/* [in] */ UINT iTInfo, /* [in] */ LCID lcid, /* [out] */ ITypeInfo __RPC_FAR *__RPC_FAR *ppTInfo) { return E_NOTIMPL; } HRESULT STDMETHODCALLTYPE CControlEventSink::GetIDsOfNames(/* [in] */ REFIID riid, /* [size_is][in] */ LPOLESTR __RPC_FAR *rgszNames, /* [in] */ UINT cNames, /* [in] */ LCID lcid, /* [size_is][out] */ DISPID __RPC_FAR *rgDispId) { return E_NOTIMPL; } HRESULT STDMETHODCALLTYPE CControlEventSink::Invoke(/* [in] */ DISPID dispIdMember, /* [in] */ REFIID riid, /* [in] */ LCID lcid, /* [in] */ WORD wFlags, /* [out][in] */ DISPPARAMS __RPC_FAR *pDispParams, /* [out] */ VARIANT __RPC_FAR *pVarResult, /* [out] */ EXCEPINFO __RPC_FAR *pExcepInfo, /* [out] */ UINT __RPC_FAR *puArgErr) { return InternalInvoke(dispIdMember, riid, lcid, wFlags, pDispParams, pVarResult, pExcepInfo, puArgErr); }
C++