JNIEXPORT jbooleanArray JNICALL Java_at_wisch_joystick_FFJoystick_getFFCapabilitiesNative (JNIEnv *env, jclass, jint hapticDeviceIndex) {
	int supported;
	bool capabilitiesArray[16];
	SDL_HapticEffect effect;
 
	// EFFECTS
	effect.type = SDL_HAPTIC_CONSTANT;
	supported = SDL_HapticEffectSupported(ffjoysticks[hapticDeviceIndex], &effect);
	if (supported == SDL_TRUE) {
		capabilitiesArray[0] = true;
	} else if (supported == SDL_FALSE) {
		capabilitiesArray[0] = false;
	} else {
		throwException(env, SDL_GetError());
		capabilitiesArray[0] = false;
	}
	
	effect.type = SDL_HAPTIC_SINE;
	supported = SDL_HapticEffectSupported(ffjoysticks[hapticDeviceIndex], &effect);
	if (supported == SDL_TRUE) {
		capabilitiesArray[1] = true;
	} else if (supported == SDL_FALSE) {
		capabilitiesArray[1] = false;
	} else {
		throwException(env, SDL_GetError());
		capabilitiesArray[1] = false;
	}

	effect.type = SDL_HAPTIC_SQUARE;
	supported = SDL_HapticEffectSupported(ffjoysticks[hapticDeviceIndex], &effect);
	if (supported == SDL_TRUE) {
		capabilitiesArray[2] = true;
	} else if (supported == SDL_FALSE) {
		capabilitiesArray[2] = false;
	} else {
		throwException(env, SDL_GetError());
		capabilitiesArray[2] = false;
	}

	effect.type = SDL_HAPTIC_TRIANGLE;
	supported = SDL_HapticEffectSupported(ffjoysticks[hapticDeviceIndex], &effect);
	if (supported == SDL_TRUE) {
		capabilitiesArray[3] = true;
	} else if (supported == SDL_FALSE) {
		capabilitiesArray[3] = false;
	} else {
		throwException(env, SDL_GetError());
		capabilitiesArray[3] = false;
	}

	effect.type = SDL_HAPTIC_SAWTOOTHUP;
	supported = SDL_HapticEffectSupported(ffjoysticks[hapticDeviceIndex], &effect);
	if (supported == SDL_TRUE) {
		capabilitiesArray[4] = true;
	} else if (supported == SDL_FALSE) {
		capabilitiesArray[4] = false;
	} else {
		throwException(env, SDL_GetError());
		capabilitiesArray[4] = false;
	}

	effect.type = SDL_HAPTIC_SAWTOOTHDOWN;
	supported = SDL_HapticEffectSupported(ffjoysticks[hapticDeviceIndex], &effect);
	if (supported == SDL_TRUE) {
		capabilitiesArray[5] = true;
	} else if (supported == SDL_FALSE) {
		capabilitiesArray[5] = false;
	} else {
		throwException(env, SDL_GetError());
		capabilitiesArray[5] = false;
	}

	effect.type = SDL_HAPTIC_RAMP;
	supported = SDL_HapticEffectSupported(ffjoysticks[hapticDeviceIndex], &effect);
	if (supported == SDL_TRUE) {
		capabilitiesArray[6] = true;
	} else if (supported == SDL_FALSE) {
		capabilitiesArray[6] = false;
	} else {
		throwException(env, SDL_GetError());
		capabilitiesArray[6] = false;
	}

	effect.type = SDL_HAPTIC_SPRING;
	supported = SDL_HapticEffectSupported(ffjoysticks[hapticDeviceIndex], &effect);
	if (supported == SDL_TRUE) {
		capabilitiesArray[7] = true;
	} else if (supported == SDL_FALSE) {
		capabilitiesArray[7] = false;
	} else {
		throwException(env, SDL_GetError());
		capabilitiesArray[7] = false;
	}

	effect.type = SDL_HAPTIC_DAMPER;
	supported = SDL_HapticEffectSupported(ffjoysticks[hapticDeviceIndex], &effect);
	if (supported == SDL_TRUE) {
		capabilitiesArray[8] = true;
	} else if (supported == SDL_FALSE) {
		capabilitiesArray[8] = false;
	} else {
		throwException(env, SDL_GetError());
		capabilitiesArray[8] = false;
	}

	effect.type = SDL_HAPTIC_INERTIA;
	supported = SDL_HapticEffectSupported(ffjoysticks[hapticDeviceIndex], &effect);
	if (supported == SDL_TRUE) {
		capabilitiesArray[9] = true;
	} else if (supported == SDL_FALSE) {
		capabilitiesArray[9] = false;
	} else {
		throwException(env, SDL_GetError());
		capabilitiesArray[9] = false;
	}

	effect.type = SDL_HAPTIC_FRICTION;
	supported = SDL_HapticEffectSupported(ffjoysticks[hapticDeviceIndex], &effect);
	if (supported == SDL_TRUE) {
		capabilitiesArray[10] = true;
	} else if (supported == SDL_FALSE) {
		capabilitiesArray[10] = false;
	} else {
		throwException(env, SDL_GetError());
		capabilitiesArray[10] = false;
	}

	effect.type = SDL_HAPTIC_CUSTOM;
	supported = SDL_HapticEffectSupported(ffjoysticks[hapticDeviceIndex], &effect);
	if (supported == SDL_TRUE) {
		capabilitiesArray[11] = true;
	} else if (supported == SDL_FALSE) {
		capabilitiesArray[11] = false;
	} else {
		throwException(env, SDL_GetError());
		capabilitiesArray[11] = false;
	}

	// OTHER
	// THIS IS ACTUALLY LOGICALLY WRONG (effect.type should be neither of the
	//		following 4) - because of information hiding (we cannot access the field
	//		unsigned int supported (Supported effects) in SDL_Haptic from here)
	//		we have to do it this way....

	effect.type = SDL_HAPTIC_GAIN;
	supported = SDL_HapticEffectSupported(ffjoysticks[hapticDeviceIndex], &effect);
	if (supported == SDL_TRUE) {
		capabilitiesArray[12] = true;
	} else if (supported == SDL_FALSE) {
		capabilitiesArray[12] = false;
	} else {
		throwException(env, SDL_GetError());
		capabilitiesArray[12] = false;
	}

	effect.type = SDL_HAPTIC_AUTOCENTER;
	supported = SDL_HapticEffectSupported(ffjoysticks[hapticDeviceIndex], &effect);
	if (supported == SDL_TRUE) {
		capabilitiesArray[13] = true;
	} else if (supported == SDL_FALSE) {
		capabilitiesArray[13] = false;
	} else {
		throwException(env, SDL_GetError());
		capabilitiesArray[13] = false;
	}

	effect.type = SDL_HAPTIC_STATUS;
	supported = SDL_HapticEffectSupported(ffjoysticks[hapticDeviceIndex], &effect);
	if (supported == SDL_TRUE) {
		capabilitiesArray[14] = true;
	} else if (supported == SDL_FALSE) {
		capabilitiesArray[14] = false;
	} else {
		throwException(env, SDL_GetError());
		capabilitiesArray[14] = false;
	}

	effect.type = SDL_HAPTIC_PAUSE;
	supported = SDL_HapticEffectSupported(ffjoysticks[hapticDeviceIndex], &effect);
	if (supported == SDL_TRUE) {
		capabilitiesArray[15] = true;
	} else if (supported == SDL_FALSE) {
		capabilitiesArray[15] = false;
	} else {
		throwException(env, SDL_GetError());
		capabilitiesArray[15] = false;
	}
	jbooleanArray jCapabilitiesArray = (jbooleanArray)env->NewBooleanArray(16);
	env->SetBooleanArrayRegion(jCapabilitiesArray, 0, 16, (jboolean *)capabilitiesArray);
	return (jCapabilitiesArray);

}
void SqliteDatabaseBackend::checkIfLogCouldBeCheckpointed(int resultCode)
{
    if (resultCode != SQLITE_OK)
        throwException("SqliteDatabaseBackend::checkpointFullWalLog: WAL log could not be checkpointed!");
}
JNIEXPORT jintArray JNICALL Java_at_wisch_joystick_EventPollThread_pollForEvent (JNIEnv *env, jobject){
	
	int returnArray[7] = { -8, -8, 0, 0, 0, 0};
	/* index 0: eventStored
	 * index 1: joystickIndex
	 * index 2: eventType
	 * index 3: componentIndex
	 * index 4: value1
	 * index 5: value2
	 */
	
	SDL_Event event;

	/*
	 * According to the SDL documentation it should not be necessary, but i did not get
	 * any events without calling JoystickUpdate manually here.
	 */
	SDL_JoystickUpdate();

	returnArray[0] = SDL_PeepEvents(&event, 1, SDL_GETEVENT, SDL_JOYEVENTMASK);
	
	if (returnArray[0]){
		if (!event.type) {
			throwException(env, SDL_GetError());
			returnArray[0] = -14;
		} else {
			switch (event.type) {
				case (SDL_JOYBUTTONDOWN): //see SDL_JOYBUTTONUP below
				case (SDL_JOYBUTTONUP) : {
					returnArray[1] = event.jbutton.which;
					returnArray[2] = 1;
					returnArray[3] = event.jbutton.button;
					returnArray[4] = event.jbutton.state;
					returnArray[5] = 0;
					break; }
				case SDL_JOYHATMOTION: {
					returnArray[1] = event.jhat.which;
					returnArray[2] = 5;
					returnArray[3] = event.jhat.hat;
					returnArray[4] = translateHatState(event.jhat.value);
					returnArray[5] = 0;
					break; }
				case SDL_JOYAXISMOTION: {
					returnArray[1] = event.jaxis.which;
					returnArray[2] = 2;
					returnArray[3] = event.jaxis.axis;
					if (INVERTAXISORDER) returnArray[3] = SDL_JoystickNumAxes(joysticks[returnArray[1]])-returnArray[3]-1;
					returnArray[4] = event.jaxis.value;
					returnArray[5] = 0;
					break; }
				case SDL_JOYBALLMOTION: {
					returnArray[1] = event.jball.which;
					returnArray[2] = 6;
					returnArray[3] = event.jball.ball;
					returnArray[4] = event.jball.xrel;
					returnArray[5] = event.jball.yrel;
					break; }
			}
		}
	}
	jintArray returnJArray = (jintArray)env->NewIntArray(6);
	env->SetIntArrayRegion(returnJArray, 0, 6, (jint *)returnArray);
	return (returnJArray);
}
Exemplo n.º 4
0
 //---------------------------------------------------------------------
 inline void onPngError(FILE* file, const std::string& filename, const std::string& error) {
     fclose (file);
     Log::error(TAG, "error processing file \"%s\" : %s", filename.c_str(), error.c_str());
     throwException(TAG, ExceptionType::IO, "error processing file texture file");
 }
Exemplo n.º 5
0
JSObject* constructFunctionSkippingEvalEnabledCheck(
    ExecState* exec, JSGlobalObject* globalObject, const ArgList& args,
    const Identifier& functionName, const String& sourceURL,
    const TextPosition& position, int overrideLineNumber, FunctionConstructionMode functionConstructionMode, JSValue newTarget)
{
    VM& vm = exec->vm();
    auto scope = DECLARE_THROW_SCOPE(vm);

    const char* prefix = nullptr;
    Structure* structure = nullptr;
    switch (functionConstructionMode) {
    case FunctionConstructionMode::Function:
        structure = globalObject->functionStructure();
        prefix = "{function ";
        break;
    case FunctionConstructionMode::Generator:
        structure = globalObject->generatorFunctionStructure();
        prefix = "{function *";
        break;
    case FunctionConstructionMode::Async:
        structure = globalObject->asyncFunctionStructure();
        prefix = "{async function ";
        break;
    }

    // How we stringify functions is sometimes important for web compatibility.
    // See https://bugs.webkit.org/show_bug.cgi?id=24350.
    String program;
    if (args.isEmpty())
        program = makeString(prefix, functionName.string(), "() {\n\n}}");
    else if (args.size() == 1)
        program = makeString(prefix, functionName.string(), "() {\n", args.at(0).toString(exec)->value(exec), "\n}}");
    else {
        StringBuilder builder;
        builder.append(prefix);
        builder.append(functionName.string());
        builder.append('(');
        auto viewWithString = args.at(0).toString(exec)->viewWithUnderlyingString(*exec);
        RETURN_IF_EXCEPTION(scope, nullptr);
        builder.append(viewWithString.view);
        for (size_t i = 1; i < args.size() - 1; i++) {
            builder.appendLiteral(", ");
            auto viewWithString = args.at(i).toString(exec)->viewWithUnderlyingString(*exec);
            RETURN_IF_EXCEPTION(scope, nullptr);
            builder.append(viewWithString.view);
        }
        builder.appendLiteral(") {\n");
        viewWithString = args.at(args.size() - 1).toString(exec)->viewWithUnderlyingString(*exec);
        RETURN_IF_EXCEPTION(scope, nullptr);
        builder.append(viewWithString.view);
        builder.appendLiteral("\n}}");
        program = builder.toString();
    }

    SourceCode source = makeSource(program, sourceURL, position);
    JSObject* exception = nullptr;
    FunctionExecutable* function = FunctionExecutable::fromGlobalCode(functionName, *exec, source, exception, overrideLineNumber);
    if (!function) {
        ASSERT(exception);
        return throwException(exec, scope, exception);
    }

    Structure* subclassStructure = InternalFunction::createSubclassStructure(exec, newTarget, structure);
    RETURN_IF_EXCEPTION(scope, nullptr);

    switch (functionConstructionMode) {
    case FunctionConstructionMode::Function:
        return JSFunction::create(vm, function, globalObject->globalScope(), subclassStructure);
    case FunctionConstructionMode::Generator:
        return JSGeneratorFunction::create(vm, function, globalObject->globalScope(), subclassStructure);
    case FunctionConstructionMode::Async:
        return JSAsyncFunction::create(vm, function, globalObject->globalScope(), subclassStructure);
    }

    ASSERT_NOT_REACHED();
    return nullptr;
}
Exemplo n.º 6
0
NEVER_INLINE static JSValue dataSegmentFail(ExecState* state, VM& vm, Scope& scope, M memorySize, N segmentSize, N offset, Args... args)
{
    return throwException(state, scope, createJSWebAssemblyLinkError(state, vm, makeString(ASCIILiteral("Invalid data segment initialization: segment of "), String::number(segmentSize), ASCIILiteral(" bytes memory of "), String::number(memorySize), ASCIILiteral(" bytes, at offset "), String::number(offset), args...)));
}
Exemplo n.º 7
0
    //---------------------------------------------------------------------
    Status Image::loadAsPNG(const std::string &filename, bool reverse) {

        std::string fname = filename;
        Utils::addFileExt(fname, "png");

        FILE *file;

        // png stuff
        png_structp png_ptr;
        png_infop info_ptr;
        png_byte magic[8];

        // image parameters
        int bit_depth, color_type;

        /* open texture data read / binary */
        file = fopen(fname.c_str(), "rb");

        if (!file) {
            Log::error(TAG, "file %s doesn't exist", fname.c_str());
            return throwException(TAG, ExceptionType::IO, "cannot open file " + fname);
        }

        /* read magic number to ensure this file is a png */
        if (fread (magic, sizeof (magic), 1, file) <= 0) {
            fclose(file);
            Log::error(TAG, "cannot read \"%s\" magic number", fname.c_str());
            return throwException(TAG, ExceptionType::INVALID_FILE, "cannot read texture file");
        }

        /* check for valid magic number */
        if (!png_check_sig (magic, sizeof (magic))) {
            onPngError(file, fname, "is not a valid PNG file");
            return throwException(TAG, ExceptionType::INVALID_FILE, (fname + " is not a valid PNG file").c_str());
        }

        /* create a png read struct */
        png_ptr = png_create_read_struct (PNG_LIBPNG_VER_STRING,
                                          (png_voidp *) fname.c_str(),
                                          png_error_fn,               // error callback
                                          png_warning_fn);            // warning callback

        if (!png_ptr) {
            onPngError(file, fname, "cannot create data structure");
            return throwException(TAG, ExceptionType::MEMORY, "cannot create data structure");
        }

        /* create a png info struct */
        info_ptr = png_create_info_struct (png_ptr);
        if (!info_ptr) {
            onPngError(file, fname, "cannot read info");
            return throwException(TAG, ExceptionType::INVALID_FILE, "cannot read info");
        }

        // initialize the setjmp for returning properly after a libpng error occurred
        if (setjmp (png_jmpbuf (png_ptr))) {
            png_destroy_read_struct (&png_ptr, &info_ptr, NULL);
            onPngError(file, fname, "unknown error");
            return throwException(TAG, ExceptionType::UNKNOWN, "unknown error");
        }

        // setup libpng for using standard C fread() function
        // with our FILE pointer
        png_init_io(png_ptr, file);

        /* tell libpng that we have already read the magic number */
        png_set_sig_bytes(png_ptr, sizeof (magic));

        /* read png info */
        png_read_info(png_ptr, info_ptr);

        /* normalize & update png info,
         * in order that every PNG image read use the same parameters. */
        normalizePngInfo(png_ptr, info_ptr);

        /* create our texture object. */
        //texture = new Texture();

        /* retrieve updated information in IHDR (png header) */
        png_get_IHDR (png_ptr, info_ptr,
                      (png_uint_32*)(&mWidth),
                      (png_uint_32*)(&mHeight),
                      &bit_depth, &color_type,
                      NULL, NULL, NULL);

        Log::trace(TAG, "loading texture of size (%d, %d)", mWidth, mHeight);

        if(!checkSizePowOf2(mWidth, mHeight)) {

            std::stringstream ss;

            ss << "texture size (" << mWidth << ", " << mHeight << ")" << " must be power of 2";
            Log::error(TAG, "%s", ss.str().c_str());
            assert(!"size must be a power of 2");
            return throwException(TAG, ExceptionType::INVALID_FILE, ss.str());
        }

        /* convert PNG color-type to openGL texture format. */
        /* deduce GL Internal format from PNG format. */
        switch (color_type) {
            case PNG_COLOR_TYPE_GRAY:
                mFormat = GL_LUMINANCE;
                mBytesPerPixel = 1;
                break;

            case PNG_COLOR_TYPE_GRAY_ALPHA:
                mFormat = GL_LUMINANCE_ALPHA;
                mBytesPerPixel = 2;
                break;

            case PNG_COLOR_TYPE_RGB:
                mFormat = GL_RGB;
                mBytesPerPixel = 3;
                break;

            case PNG_COLOR_TYPE_RGB_ALPHA:
                mFormat = GL_RGBA;
                mBytesPerPixel = 4;
                break;

            default:
                Log::error(TAG, "unknown PNG color format : %d ", color_type);
                assert(!"unknown PNG color format");
                break;
        }

        /* we can now allocate memory for storing pixel data */
        mPixels = new GLubyte[mWidth *
                              mHeight *
                              mBytesPerPixel];
        assert(mPixels && "cannot alloc Gl texture");

        /* read png data & fill data array */
        mReadPngData(png_ptr, mPixels, reverse);

        /* finish decompression and release memory */
        png_read_end(png_ptr, NULL);
        png_destroy_read_struct(&png_ptr, &info_ptr, NULL);
        fclose(file);

        return STATUS_OK;
    }
void SqliteDatabaseBackend::checkDatabaseBackendIsNotNull()
{
    if (sqliteDatabaseBackend == nullptr)
        throwException("SqliteDatabaseBackend: database backend is not initialized!");
}
void SqliteDatabaseBackend::checkIfMultithreadingIsActivated(int resultCode)
{
    if (resultCode != SQLITE_OK)
        throwException("SqliteDatabaseBackend::activateMultiThreading: multithreading can't be activated!");
}
void SqliteDatabaseBackend::checkPragmaValue(const Utf8String &databaseValue, const Utf8String &expectedValue)
{
    if (databaseValue != expectedValue)
        throwException("SqliteDatabaseBackend::setPragmaValue: pragma value is not set!");
}
void SqliteDatabaseBackend::checkDatabaseHandleIsNotNull()
{
    if (sqliteDatabaseBackend->databaseHandle == nullptr)
        throwException("SqliteDatabaseBackend: database is not open!");
}
void SqliteDatabaseBackend::checkForOpenDatabaseWhichCanBeClosed()
{
    if (databaseHandle == nullptr)
        throwException("SqliteDatabaseBackend::close: database is not open so it can not be closed.");
}
Exemplo n.º 13
0
JSObject* VM::throwException(ExecState* exec, JSObject* error)
{
    return asObject(throwException(exec, JSValue(error)));
}
Exemplo n.º 14
0
/*
 * Find an appropriate pixel format
 */
static int findPixelFormatFromBPP(JNIEnv *env, HDC hdc, jobject pixel_format, int bpp, bool double_buffer)
{
	jclass cls_pixel_format = (*env)->GetObjectClass(env, pixel_format);
	int alpha = (int)(*env)->GetIntField(env, pixel_format, (*env)->GetFieldID(env, cls_pixel_format, "alpha", "I"));
	int depth = (int)(*env)->GetIntField(env, pixel_format, (*env)->GetFieldID(env, cls_pixel_format, "depth", "I"));
	int stencil = (int)(*env)->GetIntField(env, pixel_format, (*env)->GetFieldID(env, cls_pixel_format, "stencil", "I"));
	int num_aux_buffers = (int)(*env)->GetIntField(env, pixel_format, (*env)->GetFieldID(env, cls_pixel_format, "num_aux_buffers", "I"));
	int accum_bpp = (int)(*env)->GetIntField(env, pixel_format, (*env)->GetFieldID(env, cls_pixel_format, "accum_bpp", "I"));
	int accum_alpha = (int)(*env)->GetIntField(env, pixel_format, (*env)->GetFieldID(env, cls_pixel_format, "accum_alpha", "I"));
	jboolean stereo = (*env)->GetBooleanField(env, pixel_format, (*env)->GetFieldID(env, cls_pixel_format, "stereo", "Z"));
	unsigned int flags = PFD_DRAW_TO_WINDOW |   // support window
		PFD_SUPPORT_OPENGL |
		(double_buffer ? PFD_DOUBLEBUFFER : 0) |
		(stereo ? PFD_STEREO : 0);
	PIXELFORMATDESCRIPTOR desc;
	int iPixelFormat;
	PIXELFORMATDESCRIPTOR pfd = {
		sizeof(PIXELFORMATDESCRIPTOR),   // size of this pfd
		1,                     // version number
		flags,         // RGBA type
		PFD_TYPE_RGBA,
		(BYTE)bpp,
		0, 0, 0, 0, 0, 0,      // color bits ignored
		(BYTE)alpha,
		0,                     // shift bit ignored
		accum_bpp + accum_alpha,                     // no accumulation buffer
		0, 0, 0, 0,            // accum bits ignored
		(BYTE)depth,
		(BYTE)stencil,
		num_aux_buffers,
		PFD_MAIN_PLANE,        // main layer
		0,                     // reserved
		0, 0, 0                // layer masks ignored
	};
	// get the best available match of pixel format for the device context
	iPixelFormat = ChoosePixelFormat(hdc, &pfd);
	if (iPixelFormat == 0) {
		throwException(env, "Failed to choose pixel format");
		return -1;
	}

	if (DescribePixelFormat(hdc, iPixelFormat, sizeof(PIXELFORMATDESCRIPTOR), &desc) == 0) {
		throwException(env, "Could not describe pixel format");
		return -1;
	}

	if (desc.cColorBits < bpp) {
		throwException(env, "Insufficient color precision");
		return -1;
	}

	if (desc.cAlphaBits < alpha) {
		throwException(env, "Insufficient alpha precision");
		return -1;
	}

	if (desc.cStencilBits < stencil) {
		throwException(env, "Insufficient stencil precision");
		return -1;
	}

	if (desc.cDepthBits < depth) {
		throwException(env, "Insufficient depth buffer precision");
		return -1;
	}

	if ((desc.dwFlags & PFD_GENERIC_FORMAT) != 0) {
		jboolean allowSoftwareOpenGL = getBooleanProperty(env, "org.lwjgl.opengl.Display.allowSoftwareOpenGL");
		// secondary check for software override
		if(!allowSoftwareOpenGL) {
			throwException(env, "Pixel format not accelerated");
			return -1;
		}
	}

	if ((desc.dwFlags & flags) != flags) {
		throwException(env, "Capabilities not supported");
		return -1;
	}
	return iPixelFormat;
}
Exemplo n.º 15
0
 void XemProcessor::xemInstructionNotHandled ( __XProcHandlerArgs__ )
 {
   throwException ( RuntimeException, "Xem instruction not handled : %s\n", item.getKey().c_str() );
 }
void SqliteDatabaseBackend::checkIfLoogingIsActivated(int resultCode)
{
    if (resultCode != SQLITE_OK)
        throwException("SqliteDatabaseBackend::activateLogging: logging can't be activated!");
}
Exemplo n.º 17
0
 void XemProcessor::xemInstructionException ( __XProcHandlerArgs__ )
 {
   String message = getXProcessor().evalChildrenAsString ( item );
   throwException ( RuntimeException, "%s", message.c_str() );
 }
void SqliteDatabaseBackend::checkMmapSizeIsSet(int resultCode)
{
    if (resultCode != SQLITE_OK)
        throwException("SqliteDatabaseBackend::checkMmapSizeIsSet: mmap size can't be changed!");
}
Exemplo n.º 19
0
JSValue WebAssemblyModuleRecord::evaluate(ExecState* state)
{
    VM& vm = state->vm();
    auto scope = DECLARE_THROW_SCOPE(vm);

    {
        JSWebAssemblyModule* module = m_instance->module();
        const Wasm::ModuleInformation& moduleInformation = module->moduleInformation();
        JSWebAssemblyTable* table = m_instance->table();
        for (const Wasm::Element& element : moduleInformation.elements) {
            // It should be a validation error to have any elements without a table.
            // Also, it could be that a table wasn't imported, or that the table
            // imported wasn't compatible. However, those should error out before
            // getting here.
            ASSERT(!!table);
            if (!element.functionIndices.size())
                continue;

            uint32_t tableIndex = element.offset;
            uint64_t lastWrittenIndex = static_cast<uint64_t>(tableIndex) + static_cast<uint64_t>(element.functionIndices.size()) - 1;
            if (lastWrittenIndex >= table->size())
                return throwException(state, scope, createJSWebAssemblyLinkError(state, vm, ASCIILiteral("Element is trying to set an out of bounds table index")));

            for (uint32_t i = 0; i < element.functionIndices.size(); ++i) {
                // FIXME: This essentially means we're exporting an import.
                // We need a story here. We need to create a WebAssemblyFunction
                // for the import.
                // https://bugs.webkit.org/show_bug.cgi?id=165510
                uint32_t functionIndex = element.functionIndices[i];
                if (functionIndex < module->functionImportCount()) {
                    return JSValue::decode(
                        throwVMRangeError(state, scope, ASCIILiteral("Element is setting the table value with an import. This is not yet implemented. FIXME.")));
                }

                JSWebAssemblyCallee* jsEntrypointCallee = module->jsEntrypointCalleeFromFunctionIndexSpace(functionIndex);
                JSWebAssemblyCallee* wasmEntrypointCallee = module->wasmEntrypointCalleeFromFunctionIndexSpace(functionIndex);
                Wasm::SignatureIndex signatureIndex = module->signatureIndexFromFunctionIndexSpace(functionIndex);
                const Wasm::Signature* signature = Wasm::SignatureInformation::get(&vm, signatureIndex);
                // FIXME: Say we export local function "foo" at funciton index 0.
                // What if we also set it to the table an Element w/ index 0.
                // Does (new Instance(...)).exports.foo === table.get(0)?
                // https://bugs.webkit.org/show_bug.cgi?id=165825
                WebAssemblyFunction* function = WebAssemblyFunction::create(
                    vm, m_instance->globalObject(), signature->argumentCount(), String(), m_instance.get(), jsEntrypointCallee, wasmEntrypointCallee, signatureIndex);

                table->setFunction(vm, tableIndex, function);
                ++tableIndex;
            }
        }
    }

    {
        const Vector<Wasm::Segment::Ptr>& data = m_instance->module()->moduleInformation().data;
        JSWebAssemblyMemory* jsMemory = m_instance->memory();
        if (!data.isEmpty()) {
            uint8_t* memory = reinterpret_cast<uint8_t*>(jsMemory->memory()->memory());
            uint64_t sizeInBytes = jsMemory->memory()->size();
            for (auto& segment : data) {
                if (segment->sizeInBytes) {
                    uint32_t offset;
                    if (segment->offset.isGlobalImport())
                        offset = static_cast<uint32_t>(m_instance->loadI32Global(segment->offset.globalImportIndex()));
                    else
                        offset = segment->offset.constValue();

                    if (UNLIKELY(sizeInBytes < segment->sizeInBytes))
                        return dataSegmentFail(state, vm, scope, sizeInBytes, segment->sizeInBytes, offset, ASCIILiteral(", segment is too big"));
                    if (UNLIKELY(offset > sizeInBytes - segment->sizeInBytes))
                        return dataSegmentFail(state, vm, scope, sizeInBytes, segment->sizeInBytes, offset, ASCIILiteral(", segment writes outside of memory"));
                    RELEASE_ASSERT(memory);
                    memcpy(memory + offset, &segment->byte(0), segment->sizeInBytes);
                }
            }
        }
    }

    if (JSCell* startFunction = m_startFunction.get()) {
        CallData callData;
        CallType callType = JSC::getCallData(startFunction, callData);
        call(state, startFunction, callType, callData, jsUndefined(), state->emptyList());
        RETURN_IF_EXCEPTION(scope, { });
    }

    return jsUndefined();
}
void SqliteDatabaseBackend::checkInitializeSqliteLibraryWasSuccesful(int resultCode)
{
    if (resultCode != SQLITE_OK)
        throwException("SqliteDatabaseBackend::initializeSqliteLibrary: SqliteLibrary cannot initialized!");
}
Exemplo n.º 21
0
    //-------------------------------------------------------------------------------
    Status Image::loadAsPNG(BYTE* data) {
        png_byte header[8];
        png_structp pngPtr = NULL;
        png_infop infoPtr = NULL;
        png_bytep* rowPtrs = NULL;
        png_int_32 rowSize;
        bool transparency;

        ///////////////////////////////////////////////:
        // Check the header signature
        memcpy(header, data, sizeof(header));
        if (png_sig_cmp(header, 0, 8) != 0) goto ERROR;

        pngPtr = png_create_read_struct(PNG_LIBPNG_VER_STRING,
                                        NULL,
                                        png_error_fn,           // error callback
                                        png_warning_fn);        // warning callback
        if (!pngPtr) goto ERROR;

        infoPtr = png_create_info_struct(pngPtr);
        if (!infoPtr) goto ERROR;

        if (setjmp(png_jmpbuf(pngPtr))) goto ERROR;

        ////////////////////////////////////////////////////////////////////////
        // Create the read structure and set the read function from a memory pointer
        ByteBuffer bb;
        bb.offset = 8; //sig
        bb.data = data;
        png_set_read_fn(pngPtr, &bb, memoryReadCallback);

        //tell libpng we already read the signature
        png_set_sig_bytes(pngPtr, 8);

        png_read_info(pngPtr, infoPtr);

        png_int_32 depth, colorType;
        png_uint_32 width, height;
        png_get_IHDR(pngPtr, infoPtr, &width, &height,
                     &depth, &colorType, NULL, NULL, NULL);
        mWidth = width;
        mHeight = height;

        // Creates a full alpha channel if transparency is encoded as
        // an array of palette entries or a single transparent color.
        transparency = false;
        if (png_get_valid(pngPtr, infoPtr, PNG_INFO_tRNS)) {
            png_set_tRNS_to_alpha(pngPtr);
            transparency = true;
        }
        // Expands PNG with less than 8bits per channel to 8bits.
        if (depth < 8) {
            png_set_packing(pngPtr);
        }
            // Shrinks PNG with 16bits per color channel down to 8bits.
        else if (depth == 16){
            png_set_strip_16(pngPtr);
        }
        // Indicates that image needs conversion to RGBA if needed.
        switch (colorType){
            case PNG_COLOR_TYPE_PALETTE:
                png_set_palette_to_rgb(pngPtr);
                if (transparency) {
                    mFormat = GL_RGBA;
                    mBytesPerPixel = 4;
                } else {
                    mFormat = GL_RGB;
                    mBytesPerPixel = 3;
                }
                break;
            case PNG_COLOR_TYPE_RGB:
                if (transparency) {
                    mFormat = GL_RGBA;
                    mBytesPerPixel = 4;
                } else {
                    mFormat = GL_RGB;
                    mBytesPerPixel = 3;
                }
                break;
            case PNG_COLOR_TYPE_RGBA:
                if (transparency) {
                    mFormat = GL_RGBA;
                    mBytesPerPixel = 4;
                } else {
                    mFormat = GL_RGB;
                    mBytesPerPixel = 3;
                }
                break;
            case PNG_COLOR_TYPE_GRAY:
                png_set_expand_gray_1_2_4_to_8(pngPtr);
                mFormat = transparency  ? GL_LUMINANCE_ALPHA : GL_LUMINANCE;
                if (transparency) {
                    mFormat = GL_LUMINANCE_ALPHA;
                    mBytesPerPixel = 2;
                } else {
                    mFormat = GL_LUMINANCE;
                    mBytesPerPixel = 1;
                }
                break;
            case PNG_COLOR_TYPE_GA:
                png_set_expand_gray_1_2_4_to_8(pngPtr);
                if (transparency) {
                    mFormat = GL_LUMINANCE_ALPHA;
                    mBytesPerPixel = 2;
                } else {
                    mFormat = GL_LUMINANCE;
                    mBytesPerPixel = 1;
                }
                break;
            default:
                assert(false);
                break;
        }
        png_read_update_info(pngPtr, infoPtr);

        rowSize = png_get_rowbytes(pngPtr, infoPtr);
        if(rowSize <= 0) goto ERROR;
        mPixels = new BYTE[rowSize * height];
        if(!mPixels) goto ERROR;
        rowPtrs = new png_bytep[height];
        if(!rowPtrs) goto ERROR;

        for(U32 i = 0; i < height; ++i){
            rowPtrs[height - (i + 1)] = mPixels + i * rowSize;
        }
        png_read_image(pngPtr, rowPtrs);

        png_destroy_read_struct(&pngPtr, &infoPtr, NULL);
        delete[] rowPtrs;
        return STATUS_OK;

        ERROR:
        Log::error(TAG, "Error while reading PNG data");
        delete[] rowPtrs; delete[] mPixels;
        if(pngPtr != NULL){
            png_infop* infoPtrP = infoPtr != NULL ? &infoPtr : NULL;
            png_destroy_read_struct(&pngPtr, infoPtrP, NULL);
        }
        return throwException(TAG, ExceptionType::INVALID_FILE, "unknown error while reading PNG data");
    }
void SqliteDatabaseBackend::checkShutdownSqliteLibraryWasSuccesful(int resultCode)
{
    if (resultCode != SQLITE_OK)
        throwException("SqliteDatabaseBackend::shutdownSqliteLibrary: SqliteLibrary cannot be shutdowned!");
}
Exemplo n.º 23
0
  void XPath::evalFunctionKeyBuild ( ElementRef& baseElement, ElementMultiMapRef& map,
      XPath& matchXPath, XPath& useXPath, XPath& scopeXPath, KeyId mapId )
  { 
    bool recursive = true; // Warn !!
    
    Log_EvalKey ( "evalFunctionKeyBuild(baseElement=%s, match=%s, use=%s, scope=%s\n",
                  baseElement.getKey().c_str(), matchXPath.expression, useXPath.expression, scopeXPath.expression);

    if ( ! recursive )
      {
        Warn ( "Building key in a non-recursive mode ! This is against XSL specifications !\n" );
      }
    
    if ( ! baseElement.getChild() )
      {
        Log_EvalKey ( "Base element has no children !\n" );
        return;
      }
    
    ElementRef current = baseElement;
    
    Log_EvalKey ( "Building Key !\n" );
    Log_EvalKey ( "baseElement = '%s'\n", baseElement.getKey().c_str() );
    Log_EvalKey ( "baseElement = '%s'\n", baseElement.generateVersatileXPath().c_str() );

    __ui64 iterated = 0, found = 0;
    bool currentMatches;

    while ( true )
      {
        Log_EvalKey ( "[At element %s (0x%llx:%x/%s), matching '%s' ?\n",
            current.generateVersatileXPath().c_str(), current.getElementId(), current.getKeyId(), current.getKey().c_str(),
            matchXPath.expression );

        currentMatches = false;
        iterated++;

        if ( matchXPath.matches ( current ) )
          {
            Log_EvalKey ( "Matches !\n" );
            currentMatches = true;
            found++;
            
            if ( map )
              {
                map.insert ( current, useXPath );
              }
            else
              {
                NodeSet scopeNodeSet;
                scopeXPath.eval ( scopeNodeSet, current );
                if ( scopeNodeSet.size() == 1 && scopeNodeSet.front().isElement() )
                  {                
                    ElementRef scopeElement = scopeNodeSet.toElement();
                    ElementMultiMapRef currentMap = scopeElement.findAttr ( mapId, AttributeType_SKMap );
                    if ( ! currentMap )
                      {
                        Info ( "New skMap at '%s'\n", scopeElement.generateVersatileXPath().c_str() );
                        currentMap = scopeElement.addSKMap ( mapId, SKMapType_ElementMultiMap );
                      }
                    Log_EvalKey ( "Inserting '%s'\n", current.generateVersatileXPath().c_str() );
                    currentMap.insert ( current, useXPath );
                  }
                else
                  {
                    Info ( "Silently ignoring '%s' : scope did not eval to an Element.\n",
                        current.generateVersatileXPath().c_str() );
                  }
              }
          }
        if ( current.getChild() && ( !currentMatches || recursive ) )
          {
            Log_EvalKey ( "Don't match, but has children.\n" );
            current = current.getChild();
            continue;
          }
        else
          {
            Log_EvalKey ( "Don't match, but no has child.\n" );
          }
        while ( ! current.getYounger() )
          {
            AssertBug ( current != baseElement, "How did I get there ?\n" );

            current = current.getFather();

            if ( ! current )
              {
                throwException ( Exception, "Preliminary end of element !\n" );
              }

            AssertBug ( current, "current had no father !\n" );

            if ( current == baseElement ) 
              {
                Log_EvalKey ( "Indexing finished : iterated over %llu, found %llu.\n", iterated, found );
                return;
              }
          }
        current = current.getYounger ();
      }
  }
Exemplo n.º 24
0
static void outOfBounds() {
    throwException(ap(nameArrayException, ap(nameIndexOutOfBounds, nameNil)));
}