Dataset Viewer (First 5GB)
Auto-converted to Parquet Duplicate
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++
End of preview. Expand in Data Studio

Cpp-Code-Large

Cpp-Code-Large is a large-scale corpus of C++ source code comprising more than 5 million lines of C++ code. The dataset is designed to support research in large language model (LLM) pretraining, code intelligence, software engineering automation, and static program analysis for the C++ ecosystem.

By providing a high-volume, language-specific corpus, Cpp-Code-Large enables systematic experimentation in C++-focused model training, domain adaptation, and downstream code understanding tasks.

Cpp-Code-Large addresses the need for a dedicated C++-only dataset at substantial scale, enabling focused research across systems programming, performance-critical applications, embedded systems, game engines, and large-scale native software projects.

1. Dataset Composition

Programming Language: C++

Total Size: 5M+ lines of C++ code

File Format: .jsonl

Primary Content: C++ source and header files (.cpp, .cc, .cxx, .hpp, .h)

Content Types

The dataset includes a wide variety of C++ constructs and paradigms, such as:

  • Core Language Features

  • Functions and function overloading

  • Templates (function and class templates)

  • Lambda expressions

  • Namespaces

  • Macros and preprocessor directives

  • Inline functions

  • Header/source separation patterns

Object-Oriented Programming

  • Classes and structs

  • Inheritance (single and multiple)

  • Polymorphism and virtual functions

  • Abstract base classes

  • Encapsulation patterns

  • Operator overloading

Modern C++ (C++11/14/17/20) Features

  • Smart pointers (unique_ptr, shared_ptr, weak_ptr)

  • Move semantics and rvalue references

  • Auto keyword and type inference

  • constexpr and consteval usage

  • Structured bindings

Memory and Resource Management

  • RAII patterns

  • Manual memory management (new / delete)

  • Custom allocators

  • Smart pointer ownership patterns

  • Exception-safe resource handling

Standard Template Library (STL)

  • Containers (vector, map, unordered_map, set, etc.)

  • Iterators and algorithms

  • Functional utilities

  • Threading primitives (std::thread, mutex, condition_variable)

  • Filesystem library

  • Chrono utilities

Concurrency and Parallelism

  • Multithreading patterns

  • Synchronization primitives

  • Lock-free patterns (where applicable)

  • Async programming

  • Thread pools

Systems and Low-Level Programming

  • File I/O

  • Socket programming

  • OS-level interactions

  • Embedded-style programming patterns

  • Performance optimization techniques

Build and Project Structures

  • CMake-based project structures

  • Modular header organization

  • Static and dynamic library patterns

  • Cross-platform compatibility patterns

2. Intended Research Applications

2.1 Pretraining

  • Training C++ code foundation models from scratch

  • Continued pretraining of existing LLMs

  • C++-specialized language modeling

  • Tokenizer training for C++ ecosystems

  • Domain adaptation for systems-level models

2.2 Fine-Tuning and Adaptation

  • Code completion systems

  • Intelligent IDE assistants

  • Automated refactoring tools

  • Conversational programming agents

  • C++-specific copilots

  • Static analyzer enhancement models

  • Performance optimization assistants

2.3 Code Intelligence Tasks

  • Code summarization

  • Code-to-text generation

  • Documentation generation

  • Bug detection

  • Security vulnerability detection

  • Clone detection

  • Code similarity modeling

  • Dead code detection

  • Complexity estimation

  • Static and structural analysis

  • Legacy-to-modern C++ migration modeling (e.g., raw pointers → smart pointers)

2.4 Software Engineering Research

  • Empirical studies of C++ coding patterns

  • Analysis of architectural styles in native applications

  • STL and template usage studies

  • Memory management strategy analysis

  • Concurrency pattern modeling

  • AST-based experimentation

  • Cross-version C++ evolution analysis

  • Security practice analysis in performance-critical systems

3. Ecosystem Coverage

C++-Code-Large spans a broad range of C++ application domains, including:

  • Systems software

  • Embedded systems

  • Scientific and numerical computing

  • Desktop applications

  • Cross-platform libraries

  • Networking applications

  • CLI tools

  • Microservices written in C++

The dataset captures both legacy C++ (pre-C++11 style) and modern C++ (C++11/14/17/20) development patterns, enabling cross-era research and modernization studies.

Thanks to open source community for all the guidance & support!!

Downloads last month
57