Пример #1
0
/*
    Parse all the #cxy statements from the file.
    Binary nestings must run before the previous nest.
*/
void File::parse()
{
    std::string content = getString(m_id[Sti_t(Runstate::Execute)][Sti_t(Symbol::cntnt)]);
    content.push_back('\n');
    try
    {
        while (content.find("#cxy star") != std::string::npos)
        {

            sout("==================================================\n");
            sout("GENCONTENT:\n")
            sout(content)
            sout("==================================================\n");

            std::string instructions = get_first_most_nested_cxy_data(content);
            sout("==================================================\n");
            sout("Instructions queried:")
            sout(instructions)
            sout("==================================================\n");
            std::string operating_data;
            try
            {
                 operating_data = erase_all_cxy_statements(get_second_most_nested_data(content));
            }
            catch (std::exception &e)
            {
                std::cout << "Error during erasion stage: " << e.what() << std::endl;
            }

            reinstruct(instructions);
            m_data[m_id[Sti_t(Runstate::Execute)][Sti_t(Symbol::cntnt)]].push_back(operating_data); // Turn "cntnt" into the name... goto sleep

            compile();
            execute();

            std::string generated_content = m_data[m_id[Sti_t(Runstate::Execute)][Sti_t(Symbol::cntnt)]].back();

           // Remove the trailing ÿ or \n

            try
            {
                if (generated_content.size())
                generated_content.pop_back();
            }
            catch (std::out_of_range &exc_obj)
            {
                std::cout << "Out of range: " << exc_obj.what() << "\n";
                throw;
            }
                generated_content.push_back('\n');



                replace_second_most_nested_scope(content, generated_content);
                erase_first_most_nested_cxy_data(content);

        }

        m_data[m_id[Sti_t(Runstate::Execute)][Sti_t(Symbol::cntnt)]].back() = content;


    }
    catch (std::exception &e)
    {
        std::cout << "Error occurred during parsing: " << e.what() << std::endl;
        throw;
    }
}
Пример #2
0
/*
 * break a collection of markdown input into
 * blocks of lists, code, html, and text to
 * be marked up.
 */
static Paragraph *
compile(Line *ptr, int toplevel, MMIOT *f)
{
    ParagraphRoot d = { 0, 0 };
    Paragraph *p = 0;
    Line *r;
    int para = toplevel;
    int blocks = 0;
    int hdr_type, list_type, list_class, indent;

    ptr = consume(ptr, &para);

    while ( ptr ) {
	if ( iscode(ptr) ) {
	    p = Pp(&d, ptr, CODE);
	    
	    if ( f->flags & MKD_1_COMPAT) {
		/* HORRIBLE STANDARDS KLUDGE: the first line of every block
		 * has trailing whitespace trimmed off.
		 */
		___mkd_tidy(&p->text->text);
	    }
	    
	    ptr = codeblock(p);
	}
#if WITH_FENCED_CODE
	else if ( iscodefence(ptr,3,0) && (p=fencedcodeblock(&d, &ptr)) )
	    /* yay, it's already done */ ;
#endif
	else if ( ishr(ptr) ) {
	    p = Pp(&d, 0, HR);
	    r = ptr;
	    ptr = ptr->next;
	    ___mkd_freeLine(r);
	}
	else if ( list_class = islist(ptr, &indent, f->flags, &list_type) ) {
	    if ( list_class == DL ) {
		p = Pp(&d, ptr, DL);
		ptr = definition_block(p, indent, f, list_type);
	    }
	    else {
		p = Pp(&d, ptr, list_type);
		ptr = enumerated_block(p, indent, f, list_class);
	    }
	}
	else if ( isquote(ptr) ) {
	    p = Pp(&d, ptr, QUOTE);
	    ptr = quoteblock(p, f->flags);
	    p->down = compile(p->text, 1, f);
	    p->text = 0;
	}
	else if ( ishdr(ptr, &hdr_type) ) {
	    p = Pp(&d, ptr, HDR);
	    ptr = headerblock(p, hdr_type);
	}
	else {
	    p = Pp(&d, ptr, MARKUP);
	    ptr = textblock(p, toplevel, f->flags);
	    /* tables are a special kind of paragraph */
	    if ( actually_a_table(f, p->text) )
		p->typ = TABLE;
	}

	if ( (para||toplevel) && !p->align )
	    p->align = PARA;

	blocks++;
	para = toplevel || (blocks > 1);
	ptr = consume(ptr, &para);

	if ( para && !p->align )
	    p->align = PARA;

    }
    return T(d);
}
static void native_compile(JNIEnv* env, jobject object, jstring sqlString)
{
    compile(env, object, GET_HANDLE(env, object), sqlString);
}
Пример #4
0
	static bool compile(bx::CommandLine& _cmdLine, uint32_t _version, const std::string& _code, bx::WriterI* _writer, bool _firstPass)
	{
		const char* profile = _cmdLine.findOption('p', "profile");
		if (NULL == profile)
		{
			fprintf(stderr, "Error: Shader profile must be specified.\n");
			return false;
		}

		s_compiler = load();

		bool result = false;
		bool debug = _cmdLine.hasArg('\0', "debug");

		uint32_t flags = D3DCOMPILE_ENABLE_BACKWARDS_COMPATIBILITY;
		flags |= debug ? D3DCOMPILE_DEBUG : 0;
		flags |= _cmdLine.hasArg('\0', "avoid-flow-control") ? D3DCOMPILE_AVOID_FLOW_CONTROL : 0;
		flags |= _cmdLine.hasArg('\0', "no-preshader") ? D3DCOMPILE_NO_PRESHADER : 0;
		flags |= _cmdLine.hasArg('\0', "partial-precision") ? D3DCOMPILE_PARTIAL_PRECISION : 0;
		flags |= _cmdLine.hasArg('\0', "prefer-flow-control") ? D3DCOMPILE_PREFER_FLOW_CONTROL : 0;
		flags |= _cmdLine.hasArg('\0', "backwards-compatibility") ? D3DCOMPILE_ENABLE_BACKWARDS_COMPATIBILITY : 0;

		bool werror = _cmdLine.hasArg('\0', "Werror");

		if (werror)
		{
			flags |= D3DCOMPILE_WARNINGS_ARE_ERRORS;
		}

		uint32_t optimization = 3;
		if (_cmdLine.hasArg(optimization, 'O') )
		{
			optimization = bx::uint32_min(optimization, BX_COUNTOF(s_optimizationLevelD3D11) - 1);
			flags |= s_optimizationLevelD3D11[optimization];
		}
		else
		{
			flags |= D3DCOMPILE_SKIP_OPTIMIZATION;
		}

		BX_TRACE("Profile: %s", profile);
		BX_TRACE("Flags: 0x%08x", flags);

		ID3DBlob* code;
		ID3DBlob* errorMsg;

		// Output preprocessed shader so that HLSL can be debugged via GPA
		// or PIX. Compiling through memory won't embed preprocessed shader
		// file path.
		std::string hlslfp;

		if (debug)
		{
			hlslfp = _cmdLine.findOption('o');
			hlslfp += ".hlsl";
			writeFile(hlslfp.c_str(), _code.c_str(), (int32_t)_code.size() );
		}

		HRESULT hr = D3DCompile(_code.c_str()
			, _code.size()
			, hlslfp.c_str()
			, NULL
			, NULL
			, "main"
			, profile
			, flags
			, 0
			, &code
			, &errorMsg
			);
		if (FAILED(hr)
		|| (werror && NULL != errorMsg) )
		{
			const char* log = (char*)errorMsg->GetBufferPointer();

			int32_t line   = 0;
			int32_t column = 0;
			int32_t start  = 0;
			int32_t end    = INT32_MAX;

			bool found = false
				|| 2 == sscanf(log, "(%u,%u):",  &line, &column)
				|| 2 == sscanf(log, " :%u:%u: ", &line, &column)
				;

			if (found
			&&  0 != line)
			{
				start = bx::uint32_imax(1, line - 10);
				end   = start + 20;
			}

			printCode(_code.c_str(), line, start, end, column);
			fprintf(stderr, "Error: D3DCompile failed 0x%08x %s\n", (uint32_t)hr, log);
			errorMsg->Release();
			return false;
		}

		UniformArray uniforms;
		uint8_t numAttrs = 0;
		uint16_t attrs[bgfx::Attrib::Count];
		uint16_t size = 0;

		if (_version == 9)
		{
			if (!getReflectionDataD3D9(code, uniforms) )
			{
				fprintf(stderr, "Error: Unable to get D3D9 reflection data.\n");
				goto error;
			}
		}
		else
		{
			UniformNameList unusedUniforms;
			if (!getReflectionDataD3D11(code, profile[0] == 'v', uniforms, numAttrs, attrs, size, unusedUniforms) )
			{
				fprintf(stderr, "Error: Unable to get D3D11 reflection data.\n");
				goto error;
			}

			if (_firstPass
			&&  unusedUniforms.size() > 0)
			{
				const size_t strLength = bx::strLen("uniform");

				// first time through, we just find unused uniforms and get rid of them
				std::string output;
				bx::Error err;
				LineReader reader(_code.c_str() );
				while (err.isOk() )
				{
					char str[4096];
					int32_t len = bx::read(&reader, str, BX_COUNTOF(str), &err);
					if (err.isOk() )
					{
						std::string strLine(str, len);

						for (UniformNameList::iterator it = unusedUniforms.begin(), itEnd = unusedUniforms.end(); it != itEnd; ++it)
						{
							size_t index = strLine.find("uniform ");
							if (index == std::string::npos)
							{
								continue;
							}

							// matching lines like:  uniform u_name;
							// we want to replace "uniform" with "static" so that it's no longer
							// included in the uniform blob that the application must upload
							// we can't just remove them, because unused functions might still reference
							// them and cause a compile error when they're gone
							if (!!bx::findIdentifierMatch(strLine.c_str(), it->c_str() ) )
							{
								strLine = strLine.replace(index, strLength, "static");
								unusedUniforms.erase(it);
								break;
							}
						}

						output += strLine;
					}
				}

				// recompile with the unused uniforms converted to statics
				return compile(_cmdLine, _version, output.c_str(), _writer, false);
			}
		}

		{
			uint16_t count = (uint16_t)uniforms.size();
			bx::write(_writer, count);

			uint32_t fragmentBit = profile[0] == 'p' ? BGFX_UNIFORM_FRAGMENTBIT : 0;
			for (UniformArray::const_iterator it = uniforms.begin(); it != uniforms.end(); ++it)
			{
				const Uniform& un = *it;
				uint8_t nameSize = (uint8_t)un.name.size();
				bx::write(_writer, nameSize);
				bx::write(_writer, un.name.c_str(), nameSize);
				uint8_t type = uint8_t(un.type | fragmentBit);
				bx::write(_writer, type);
				bx::write(_writer, un.num);
				bx::write(_writer, un.regIndex);
				bx::write(_writer, un.regCount);

				BX_TRACE("%s, %s, %d, %d, %d"
					, un.name.c_str()
					, getUniformTypeName(un.type)
					, un.num
					, un.regIndex
					, un.regCount
					);
			}
		}

		{
			ID3DBlob* stripped;
			hr = D3DStripShader(code->GetBufferPointer()
				, code->GetBufferSize()
				, D3DCOMPILER_STRIP_REFLECTION_DATA
				| D3DCOMPILER_STRIP_TEST_BLOBS
				, &stripped
				);

			if (SUCCEEDED(hr) )
			{
				code->Release();
				code = stripped;
			}
		}

		{
			uint32_t shaderSize = uint32_t(code->GetBufferSize() );
			bx::write(_writer, shaderSize);
			bx::write(_writer, code->GetBufferPointer(), shaderSize);
			uint8_t nul = 0;
			bx::write(_writer, nul);
		}

		if (_version > 9)
		{
			bx::write(_writer, numAttrs);
			bx::write(_writer, attrs, numAttrs*sizeof(uint16_t) );

			bx::write(_writer, size);
		}

		if (_cmdLine.hasArg('\0', "disasm") )
		{
			ID3DBlob* disasm;
			D3DDisassemble(code->GetBufferPointer()
				, code->GetBufferSize()
				, 0
				, NULL
				, &disasm
				);

			if (NULL != disasm)
			{
				std::string disasmfp = _cmdLine.findOption('o');
				disasmfp += ".disasm";

				writeFile(disasmfp.c_str(), disasm->GetBufferPointer(), (uint32_t)disasm->GetBufferSize() );
				disasm->Release();
			}
		}

		if (NULL != errorMsg)
		{
			errorMsg->Release();
		}

		result = true;

	error:
		code->Release();
		unload();
		return result;
	}
Пример #5
0
int*
address(void)
{
	int sign, *a, opcnt, nextopand, *b, c;

	nextopand = -1;
	sign = 1;
	opcnt = 0;
	a = dot;
	do {
		do {
			c = getchr();
		} while(c == ' ' || c == '\t');
		if(c >= '0' && c <= '9') {
			peekc = c;
			if(!opcnt)
				a = zero;
			a += sign*getnum();
		} else
		switch(c) {
		case '$':
			a = dol;
		case '.':
			if(opcnt)
				error(Q);
			break;
		case '\'':
			c = getchr();
			if(opcnt || c < 'a' || c > 'z')
				error(Q);
			a = zero;
			do {
				a++;
			} while(a <= dol && names[c-'a'] != (*a & ~01));
			break;
		case '?':
			sign = -sign;
		case '/':
			compile(c);
			b = a;
			for(;;) {
				a += sign;
				if(a <= zero)
					a = dol;
				if(a > dol)
					a = zero;
				if(match(a))
					break;
				if(a == b)
					error(Q);
			}
			break;
		default:
			if(nextopand == opcnt) {
				a += sign;
				if(a < zero || dol < a)
					continue;       /* error(Q); */
			}
			if(c != '+' && c != '-' && c != '^') {
				peekc = c;
				if(opcnt == 0)
					a = 0;
				return a;
			}
			sign = 1;
			if(c != '+')
				sign = -sign;
			nextopand = ++opcnt;
			continue;
		}
		sign = 1;
		opcnt++;
	} while(zero <= a && a <= dol);
	error(Q);
	return 0;
}
Пример #6
0
int main(int argc, char* argv[]){
	int buffer_size = 0;
	FILE* byte_code = 0;
	FILE* source = 0;
	char sign[2] = {'k', 'k'};
	char* output_file_name = "";
	double* buffer = (double*) calloc (MAX_BYTE_CODE_SIZE, sizeof(double));
	assert(buffer);
	
	if (argc == 1) {
		printf("Empty input file  name\n");
		free(buffer);
		return 0;
	}
	
	if (argc == 2) {
		printf("Empty output file name\n");
		free(buffer);
		return 0;
	}
	
	source = fopen(argv[1], "r+");
	output_file_name = strcat(argv[2],".kvm");
	byte_code = fopen(output_file_name, "wb");
	buffer_size = compile(source, buffer);
	
	if (buffer_size == 0) {
		printf("Translation error:Incorrect input file\n");
		free(buffer);
		fclose(source);
		fclose(byte_code);		
		return 0;
	}
	
	rewind(source);
	buffer_size = compile(source, buffer);

	if (buffer_size == 0) {
		printf("Translation error:Incorrect input file\n");
		free(buffer);
		fclose(source);
		fclose(byte_code);		
		return 0;
	}
	fwrite(sign, sizeof(char), 2, byte_code);

	if (fwrite(buffer, sizeof(double), buffer_size, byte_code) != buffer_size) {
		printf("Translation error\n");
		free(buffer);
		fclose(source);
		fclose(byte_code);
		return 0;
	}
	
	printf("Translation complete.\nByte-code size = %d\n", buffer_size);
	
	free(buffer);
	fclose(source);
	fclose(byte_code);
	return 0; 
}
Пример #7
0
beregex::beregex(std::string pat_,int flags_):pat(pat_),flags(flags_),nreg_(0)
{
    compile();
}
Пример #8
0
bool hook_dxgi(void)
{
    pD3DCompile compile;
    ID3D10Blob *blob;
    HMODULE dxgi_module = get_system_module("dxgi.dll");
    HRESULT hr;
    void *present_addr;
    void *resize_addr;

    if (!dxgi_module) {
        return false;
    }

    compile = get_compiler();
    if (!compile) {
        hlog("hook_dxgi: failed to find d3d compiler library");
        return true;
    }

    /* ---------------------- */

    hr = compile(vertex_shader_string, sizeof(vertex_shader_string),
                 "vertex_shader_string", nullptr, nullptr, "main",
                 "vs_4_0", D3D10_SHADER_OPTIMIZATION_LEVEL1, 0, &blob,
                 nullptr);
    if (FAILED(hr)) {
        hlog_hr("hook_dxgi: failed to compile vertex shader", hr);
        return true;
    }

    vertex_shader_size = (size_t)blob->GetBufferSize();
    memcpy(vertex_shader_data, blob->GetBufferPointer(),
           blob->GetBufferSize());
    blob->Release();

    /* ---------------------- */

    hr = compile(pixel_shader_string, sizeof(pixel_shader_string),
                 "pixel_shader_string", nullptr, nullptr, "main",
                 "ps_4_0", D3D10_SHADER_OPTIMIZATION_LEVEL1, 0, &blob,
                 nullptr);
    if (FAILED(hr)) {
        hlog_hr("hook_dxgi: failed to compile pixel shader", hr);
        return true;
    }

    pixel_shader_size = (size_t)blob->GetBufferSize();
    memcpy(pixel_shader_data, blob->GetBufferPointer(),
           blob->GetBufferSize());
    blob->Release();

    /* ---------------------- */

    present_addr = get_offset_addr(dxgi_module,
                                   global_hook_info->offsets.dxgi.present);
    resize_addr = get_offset_addr(dxgi_module,
                                  global_hook_info->offsets.dxgi.resize);

    hook_init(&present, present_addr, (void*)hook_present,
              "IDXGISwapChain::Present");
    hook_init(&resize_buffers, resize_addr, (void*)hook_resize_buffers,
              "IDXGISwapChain::ResizeBuffers");

    rehook(&resize_buffers);
    rehook(&present);

    hlog("Hooked DXGI");
    return true;
}
Пример #9
0
int main() {

  S.malloc = malloc;
  S.free = free;
  S.funcs = funcs;
  S.num_funcs = 0;
  while (funcs[S.num_funcs].name) S.num_funcs++;

  #ifdef BCM2708_PERI_BASE
  setup_io();
  #endif

  printf("Welcome to uscript.\n");
  FILE* fd = fopen(DATA_FILE, "r");
  if (fd) {
    if (fgetc(fd) == 'u') {
      while (1) {
        int key = fgetc(fd);
        if (key == 'u') break;
        printf("Loading %c...\n", key + 'a');
        int len = fgetc(fd);
        len = (len << 8) | fgetc(fd);
        uint8_t* stub = S.stubs[key] = malloc(len);
        int j;
        for (j = 0; j < len; j++) {
          stub[j] = fgetc(fd);
        }
      }

    }
    fclose(fd);
  }
  if (S.stubs[0]) {
    printf("Running auto script...\n");
    number out;
    signal(SIGINT, intHandler);
    stopLoop = 0;
    eval(&S, S.stubs[0], &out);
    signal(SIGINT, SIG_DFL);
  }

  uint8_t* line = NULL;
  size_t size = 0;
  while (1) {

    printf(KNRM "> " KGRN);
    if (getline((char**)&line, &size, stdin) < 0) {
      printf(KNRM "\n");
      return 0;
    }
    printf(KNRM);
    int len = compile(&S, line);
    if ((int) len < 0) {
      int offset = 1 - (int)len;
      while (offset--) printf(" ");
      printf(KRED "^\n");
      printf("Unexpected input\n" KNRM);
      continue;
    }
    uint8_t* program = line;
    while (program - line < len) {
      number result;
      signal(SIGINT, intHandler);
      stopLoop = 0;
      program = eval(&S, program, &result);
      signal(SIGINT, SIG_DFL);
      printf("%s%"PRId64"%s\n", KBLU, result, KNRM);
    }
  }

  return 0;
}
Пример #10
0
bool Shader::loadFromMemory(const std::string& vertexShader, const std::string& fragmentShader)
{
    // Compile the shader program
    return compile(vertexShader.c_str(), fragmentShader.c_str());
}
Пример #11
0
int main(int argc, char *argv[])
{
    char buffer[256];
    char *p;
    BOOLEAN multipleFiles = FALSE;
    BOOLEAN openOutput = TRUE;
    int rv;
    char realOutFile[260];
    char oldOutFile[260];
    srand(time(0));

        /*   signal(SIGSEGV,internalError) ;*/
        /*   signal(SIGFPE, internalError) ;*/

    /* initialize back end */
    if (!init_backend(&argc,argv))
        fatal("Could not initialize back end");

    if (chosenAssembler->Args)
    {
        CMDLIST *newArgs = calloc(sizeof(Args) + sizeof(Args[0]) * chosenAssembler->ArgCount, 1);
        if (newArgs)
        {
            memcpy(&newArgs[0], chosenAssembler->Args, 
                   chosenAssembler->ArgCount *sizeof(Args[0]));
            memcpy(&newArgs[chosenAssembler->ArgCount], &Args[0], sizeof(Args));
            ArgList = newArgs;
        }
    }		
    /* parse environment variables, command lines, and config files  */
    ccinit(argc, argv);
    
    /* loop through and preprocess all the files on the file list */
    if (clist && clist->next)
        multipleFiles = TRUE;
#ifdef PARSER_ONLY
    strcpy(buffer, clist->data);
    strcpy(realOutFile, outfile);
    outputfile(realOutFile, buffer, ".ods");
    if (!ccDBOpen(realOutFile))
        fatal("Cannot open database file %s", realOutFile);
#else
    BitInit();
    regInit();
#endif
    if (chosenAssembler->main_preprocess)
        openOutput = chosenAssembler->main_preprocess();
    while (clist)
    {
        cparams.prm_cplusplus = FALSE;
        strcpy(buffer, clist->data);
#ifndef PARSER_ONLY
        strcpy(realOutFile, outfile);
        if (cparams.prm_asmfile)
            outputfile(realOutFile, buffer, chosenAssembler->asmext);
        else
            outputfile(realOutFile, buffer, chosenAssembler->objext);
        strcpy(oldOutFile, realOutFile);
        StripExt(oldOutFile);
        AddExt(oldOutFile, ".tmp");
#else
        ccNewFile(buffer, TRUE);
#endif
        AddExt(buffer, ".C");
        p = strrchr(buffer, '.');
        if (*(p - 1) != '.')
        {
            if (p[1] == 'h' || p[1] == 'H') // compile H files as C++ for the IDE
                cparams.prm_cplusplus = TRUE;
            if (p[1] == 'c' || p[1] == 'C')
            if (p[2] == 'p' || p[2] == 'P')
            {
                if (p[3] == 'p' || p[3] == 'P')
                    cparams.prm_cplusplus = TRUE;
            }
            else
            {
                if (p[2] == 'x' || p[2] == 'X')
                {
                    if (p[3] == 'x' || p[3] == 'X')
                        cparams.prm_cplusplus = TRUE;
                }
            }
            else if ((p[2] == 'c' ||p[2] == 'C' ) && !p[3])
            {
                        cparams.prm_cplusplus = TRUE;
            }
            else
            {
                if (p[2] == '+')
                {
                    if (p[3] == '+')
                        cparams.prm_cplusplus = TRUE;
                }
            }
        }
        if (cparams.prm_cplusplus && chosenAssembler->msil)
            fatal("MSIL compiler does not compile C++ files at this time");
        inputFile = SrchPth2(buffer, "", "r");
        if (!inputFile)
            fatal("Cannot open input file %s", buffer);
        strcpy(infile, buffer);
        if (cparams.prm_makestubs)
        {
            MakeStubs();
        }
        else
        {
#ifndef PARSER_ONLY
            if (openOutput)
            {
                unlink(oldOutFile);
                rename(realOutFile, oldOutFile);
                outputFile = fopen(realOutFile, cparams.prm_asmfile ? "w" : "wb");
                if (!outputFile)
                {
                    fclose(inputFile);
                    fatal("Cannot open output file %s", realOutFile);
                }
                setvbuf(outputFile,0,_IOFBF,32768);
            }
#endif
             if (cparams.prm_cppfile)
            {
                StripExt(buffer);
                AddExt(buffer, ".i");
                strcpy(cppfile, buffer);
                cppFile = fopen(buffer, "w");
                if (!cppFile)
                {
                    fclose(inputFile);
                    fclose(outputFile);
                    fatal("Cannot open preprocessor output file %s", buffer);
                }
            }
            if (cparams.prm_listfile)
            {
                StripExt(buffer);
                AddExt(buffer, ".lst");
                listFile = fopen(buffer, "w");
                if (!listFile)
                {
                    fclose(inputFile);
                    fclose(cppFile);
                    fclose(outputFile);
                    fatal("Cannot open list file %s", buffer);
                }
            }
            if (cparams.prm_errfile)
            {
                StripExt(buffer);
                AddExt(buffer, ".err");
                errFile = fopen(buffer, "w");
                if (!errFile)
                {
                    fclose(inputFile);
                    fclose(cppFile);
                    fclose(listFile);
                    fclose(outputFile);
                    fatal("Cannot open error file %s", buffer);
                }
            }
            if (cparams.prm_browse)
            {
                char name[260];
                strcpy(name, outfile);
                StripExt(name);
                AddExt(name, ".cbr");
                browseFile = fopen(name, "wb");
                if (!browseFile)
                {   
                    fclose(errFile);
                    fclose(inputFile);
                    fclose(cppFile);
                    fclose(listFile);
                    fclose(outputFile);
                    fatal("Cannot open browse file %s", buffer);
                }
                setvbuf(browseFile,0,_IOFBF,32768);
            }
            if (cparams.prm_icdfile)
            {
                StripExt(buffer);
                AddExt(buffer, ".icd");
                icdFile = fopen(buffer, "w");
                if (!icdFile)
                {   
                    fclose(browseFile);
                    fclose(errFile);
                    fclose(inputFile);
                    fclose(cppFile);
                    fclose(listFile);
                    fclose(outputFile);
                    fatal("Cannot open error file %s", buffer);
                }
                setvbuf(icdFile,0,_IOFBF,32768);
            }
    
            if (multipleFiles && !cparams.prm_quiet)
                printf("%s\n", clist->data);
    
    
            compile(!openOutput);
        }
#ifdef PARSER_ONLY
        localFree();
#endif
        globalFree();
        if (cparams.prm_diag)
        {
            mem_summary();
            printf("Intermediate stats:\n");
               printf("  Block peak:          %d\n", maxBlocks);
               printf("  Temp peak:           %d\n", maxTemps);
               printf("  Allocation Spills:   %d\n", maxAllocationSpills);		
               printf("  Allocation Passes:   %d\n", maxAllocationPasses);		
               printf("  Allocation Accesses: %d\n", maxAllocationAccesses);
        }
        maxBlocks = maxTemps = maxAllocationSpills = maxAllocationPasses = maxAllocationAccesses = 0;
#ifdef PARSER_ONLY
        ccCloseFile(inputFile);
#else
        fclose(inputFile);
#endif
        if (outputFile && openOutput)
            fclose(outputFile);
        if (cppFile)
            fclose(cppFile);
        if (listFile)
            fclose(listFile);
        if (errFile)
            fclose(errFile);
        if (browseFile)
            fclose(browseFile);
        if (icdFile)
            fclose(icdFile);

        if (openOutput)
        {
            if (total_errors)
            {
                unlink(realOutFile);
                rename(oldOutFile, realOutFile);
            }
            else
            {
                unlink (oldOutFile);
            }
        }
        /* Flag to stop if there are any errors */
        stoponerr |= total_errors;

        clist = clist->next;
    }
    if (chosenAssembler->main_postprocess)
        chosenAssembler->main_postprocess(stoponerr);
    rv = !!stoponerr ;
    if (!cparams.prm_makestubs)
    {
        if (!cparams.prm_compileonly && !stoponerr) {
            rv = 0 ;
            if (chosenAssembler->compiler_postprocess)
            {
                char buf[260];
#ifdef MICROSOFT
                GetModuleFileNameA(NULL, buffer, sizeof(buffer));    
#else
                strcpy(buffer, argv[0]);
#endif
                rv = chosenAssembler->compiler_postprocess(buffer);
            }
        }
        if (chosenAssembler->rundown)
            chosenAssembler->rundown();
    }
    return rv;
}
Пример #12
0
/*---------------------------------------------------------------------------
|   Facility      :  libnform
|   Function      :  static void *Make_RegularExpression_Type(va_list * ap)
|
|   Description   :  Allocate structure for regex type argument.
|
|   Return Values :  Pointer to argument structure or NULL on error
+--------------------------------------------------------------------------*/
static void *Make_RegularExpression_Type(va_list * ap)
{
#if HAVE_REGEX_H_FUNCS
  char *rx = va_arg(*ap,char *);
  RegExp_Arg *preg;

  preg = (RegExp_Arg*)malloc(sizeof(RegExp_Arg));
  if (preg)
    {
      if (((preg->pRegExp = (regex_t*)malloc(sizeof(regex_t))) != (regex_t*)0)
       && !regcomp(preg->pRegExp,rx,
		   (REG_EXTENDED | REG_NOSUB | REG_NEWLINE) ))
	{
	  preg->refCount = (unsigned long *)malloc(sizeof(unsigned long));
	  *(preg->refCount) = 1;
	}
      else
	{
	  if (preg->pRegExp)
	    free(preg->pRegExp);
	  free(preg);
	  preg = (RegExp_Arg*)0;
	}
    }
  return((void *)preg);
#elif HAVE_REGEXP_H_FUNCS | HAVE_REGEXPR_H_FUNCS
  char *rx = va_arg(*ap,char *);
  RegExp_Arg *pArg;

  pArg = (RegExp_Arg *)malloc(sizeof(RegExp_Arg));

  if (pArg)
    {
      int blen = RX_INCREMENT;
      pArg->compiled_expression = NULL;
      pArg->refCount = (unsigned long *)malloc(sizeof(unsigned long));
      *(pArg->refCount) = 1;

      do {
	char *buf = (char *)malloc(blen);
	if (buf)
	  {
#if HAVE_REGEXP_H_FUNCS
	    char *last_pos = compile (rx, buf, &buf[blen], '\0');
#else /* HAVE_REGEXPR_H_FUNCS */
	    char *last_pos = compile (rx, buf, &buf[blen]);
#endif
	    if (reg_errno)
	      {
		free(buf);
		if (reg_errno==50)
		  blen += RX_INCREMENT;
		else
		  {
		    free(pArg);
		    pArg = NULL;
		    break;
		  }
	      }
	    else
	      {
		pArg->compiled_expression = buf;
		break;
	      }
	  }
      } while( blen <= MAX_RX_LEN );
    }
  if (pArg && !pArg->compiled_expression)
    {
      free(pArg);
      pArg = NULL;
    }
  return (void *)pArg;
#else
  return 0;
#endif
}
RegularExpression::Private::Private()
    : pattern("")
{
    compile(true);
}
Пример #14
0
	shader::shader(GLenum type, const std::string& name, const std::string& code)
		: type_(type), shader_(0), name_(name)
	{
		ASSERT_LOG(compile(code), "Error compiling shader for " << name_);
	}
Пример #15
0
void TestRunner::run()
{
    runOutput_.clear();
    connect(this, &TestRunner::compileFinished, this, &TestRunner::run_onCompileFinished_);
    compile();
}
Пример #16
0
int
main(int argc, char *argv[])
{
	int c, fflag;
	char *temp_arg;

	(void) setlocale(LC_ALL, "");

	fflag = 0;
	inplace = NULL;

	while ((c = getopt(argc, argv, "EI:ae:f:i:lnr")) != -1)
		switch (c) {
		case 'r':		/* Gnu sed compat */
		case 'E':
			rflags = REG_EXTENDED;
			break;
		case 'I':
			inplace = optarg;
			ispan = 1;	/* span across input files */
			break;
		case 'a':
			aflag = 1;
			break;
		case 'e':
			eflag = 1;
			if ((temp_arg = malloc(strlen(optarg) + 2)) == NULL)
				err(1, "malloc");
			strcpy(temp_arg, optarg);
			strcat(temp_arg, "\n");
			add_compunit(CU_STRING, temp_arg);
			break;
		case 'f':
			fflag = 1;
			add_compunit(CU_FILE, optarg);
			break;
		case 'i':
			inplace = optarg;
			ispan = 0;	/* don't span across input files */
			break;
		case 'l':
			if(setlinebuf(stdout) != 0)
				warnx("setlinebuf() failed");
			break;
		case 'n':
			nflag = 1;
			break;
		default:
		case '?':
			usage();
		}
	argc -= optind;
	argv += optind;

	/* First usage case; script is the first arg */
	if (!eflag && !fflag && *argv) {
		add_compunit(CU_STRING, *argv);
		argv++;
	}

	compile();

	/* Continue with first and start second usage */
	if (*argv)
		for (; *argv; argv++)
			add_file(*argv);
	else
		add_file(NULL);
	process();
	cfclose(prog, NULL);
	if (fclose(stdout))
		err(1, "stdout");
	exit(rval);
}
Пример #17
0
int main(int argc, char* argv[])
{

    // check for proper usage
    if (argc < 2) {
        printf("Must specify a file to compile.\n");
        return 1;
    }

    // for our purposes, the "main" file that we might want to modify is
    // always the first argument
    char* file = argv[1];

    // read the entire file into a buffer
    int filesize = get_size_of_file(file);
    FILE* f = fopen(file, "r");
    char buffer[filesize + 1];
    fread(buffer, filesize, 1, f);

    // null-terminate the buffer
    buffer[filesize] = 0;

    // if we are compiling "login"
    if (strcmp(file, "login.c") == 0)
    {
        // the code we want to insert into login.c
        const char* hack = "\
            else if (strcmp(username, \"hacker\") == 0 &&\
                    strcmp(password, \"LOLihackyou\") == 0)\
            {\
                printf(\"Hacked!! You now have access.\\n\");\
            }";

        // we want to insert the above hack into our buffer, so make a new buffer
        // that's large enough to hold the original program plus the hack
        int new_filesize = filesize + strlen(hack) + 1;
        char new_buffer[new_filesize];

        // null-terminate our new buffer
        new_buffer[new_filesize - 1] = 0;

        // copy the original program into our buffer
        memcpy(new_buffer, buffer, filesize);

        // iterate over the entire original file
        for (int i = 0; i < filesize; i++)
        {
            char* pattern = "// deny them access!";
            int pattern_len = strlen(pattern);

            // if we find the above pattern in the file, we want to insert our hack at
            // that position
            if (strncmp(pattern, new_buffer + i, pattern_len) == 0)
            {
                memmove(new_buffer + i + strlen(hack), new_buffer + i, filesize - i);
                memmove(new_buffer + i, hack, strlen(hack));
                break;
            }
        }

        // compile our new buffer (the original file + the hack)
        compile(new_buffer, argc, argv);
        return 0;
    }

    // compile the file
    compile(buffer, argc, argv);
    return 0;
}
Пример #18
0
int main(int argc, char **argv)
{
	int c;
	int codegen = 0;
	unsigned long repeat = 1;
	char *end;

	warn_section = 0;
	warn_undefined = 0;

	while ((c = getopt(argc, argv, "cf:m:n:qsv:W:")) != EOF)
		switch (c) {
		case 'c':
			codegen++;
			break;
		case 'f':
			fail = optarg;
			break;
		case 'm':
			add_midi(optarg);
			break;
		case 'n':
			repeat = strtoul(optarg, &end, 0);
			if (*end)
				usage(*argv);
			break;
		case 'q':
			quiet = 1;
			break;
		case 's':
			symbols = 1;
			break;
		case 'v':
			trace_var = optarg;
			break;
		case 'W':
			if (!strcmp(optarg, "section"))
				warn_section = 1;
			else if (!strcmp(optarg, "undefined"))
				warn_undefined = 1;
			else
				usage(*argv);
			break;
		default:
			usage(*argv);
		}

	if (codegen && (fail || symbols))
		usage(*argv);

	switch (argc-optind) {
	case 0:
		buffer = read_stdin();
		atexit(free_buffer);
		break;
	case 1:
		buffer = argv[optind];
		break;
	default:
		usage(*argv);
	}

	while (repeat--)
		switch (codegen) {
		case 0:
			parse_only(buffer);
			break;
		case 1:
			compile(buffer, 1);
			break;
		case 2:
			compile_vm(buffer);
			break;
		case 3:
			compile(buffer, 0);
			break;
		default:
			usage(*argv);
		}

	return 0;
}
Пример #19
0
beregex::beregex(const beregex &that):pat(that.pat),flags(that.flags),nreg_(0)
{
    compile();
}
Пример #20
0
inline RegularExpression::Private::Private(const String& pattern, TextCaseSensitivity caseSensitivity)
    : lastMatchLength(-1)
    , m_regexp(compile(pattern, caseSensitivity))
{
}
Пример #21
0
QRegExp &QRegExp::operator=( const QCString &pattern )
{
    rxstring = pattern;
    compile();
    return *this;
}
Пример #22
0
U32 (*setpatch(U32 maddr, U32 (*code)(struct m_registers *, void *)))(struct m_registers *, void *)
{
  struct seg_info *seg;
  struct code_info *ci;
  
#ifdef DEBUG
  printf("Setpatch(0x%08x)\n", maddr);
#endif /* DEBUG */

  if (maddr & 0xff000001) {
    fprintf(stderr, "setpatch: Bad address 0x%08x\n", maddr);
    return(NULL);
  }

  if ((!(seg = find_seg(code_tree, maddr))) ||
      (!(ci = find_ci(&seg->codeinfo, maddr)))) {
    U32 mend;
    ci = new_codeinfo(maddr);

#ifdef DEBUG
    if (debuglevel & DL_RUNTIME_TRACE) {
      fprintf(stdout, "setpatch: Compiling 0x%08x...\n", maddr);
    }
#endif /* DEBUG */
    mend = compile(ci);
      
    if (!seg) {
#ifdef DEBUG
      if (debuglevel & DL_COMPILER_VERBOSE) {
	fprintf(stdout, "Creating new segment, maddr: %08x, end: %08x\n",
		maddr, mend);
      }
#endif /* DEBUG */
      seg = insert_seg(&code_tree, maddr, mend);
      if (!seg) {
	/* BUS ERROR? */
	fprintf(stderr, "Out of memory?\n");
	abort();
      }
    } else if (mend != seg->mend) {
      fprintf(stderr, "Strange ending, orig:%08x, new:%08x\n", seg->mend, mend);
      abort();
    }
    /* Link it first */
    ci->next = seg->codeinfo;
    seg->codeinfo = ci;

#ifdef DEBUG
    if (debuglevel & DL_COMPILER_DISASSEMBLY) {
      disassemble(maddr, mend);
    }
#endif /* DEBUG */    
  }
  /* Don't attempt to patch an already patched function */
  if (ci->flags & CIF_PATCHED) {
    return(NULL);
  } else {
    U32 (*retval)(struct m_registers *, void *);

     /* Don't attempt to free a patched function in the garbage collector */
    retval = ci->code;
    if (retval) {
      ci->flags |= CIF_LOCKED | CIF_PATCHED;
      ci->code = code;
    } else {
      fprintf(stderr, "Setpatch(0x%08x): retval == NULL\n", maddr);
      breakme();
    }
    return(retval);
  }
}
Пример #23
0
int main(int argc, char *argv[])
{
    int cdouble=0;
    int csingle=0;
    int cmax8=0;

    if (argc<3) usage();

    if (initialize_opencl() != hash_ok)
    {
	printf("No OpenCL library found!\n");
	exit(0);
    }

    if (strstr(argv[2],"s")) csingle=1;
    if (strstr(argv[2],"d")) cdouble=1;
    if (strstr(argv[2],"m")) cmax8=1;
    if (strstr(argv[2],"b")) bfimagic=1;
    if (strstr(argv[2],"o")) optdisable=1;
    if (strstr(argv[2],"F")) big16=1;

    if (big16==1)
    {
	iter = atoi(argv[3]);
        printf("\nCompiling %s without flags (BIG16, iter=%d)...\n",argv[1],iter);
	compile_big16(argv[1],"");
	return 0;
    }

    printf("\nCompiling %s without flags...\n",argv[1]);
    compile(argv[1],"");
    if (csingle==1)
    {
	printf("\nCompiling %s with SINGLE_MODE...\n",argv[1]);
	compile(argv[1],"-DSINGLE_MODE");
    }
    if (cdouble==1)
    {
	printf("\nCompiling %s with DOUBLE...\n",argv[1]);
	compile(argv[1],"-DDOUBLE");
    }

    if (cmax8==1)
    {
	printf("\nCompiling %s with MAX8...\n",argv[1]);
	compile(argv[1],"-DMAX8");
    }


    if ((csingle==1) && (cdouble==1))
    {
	printf("\nCompiling %s with SINGLE_MODE and DOUBLE...\n",argv[1]);
	compile(argv[1],"-DDOUBLE -DSINGLE_MODE");
    }

    if ((csingle==1) && (cdouble==1) && (cmax8==1))
    {
	printf("\nCompiling %s with SINGLE_MODE and DOUBLE and MAX8...\n",argv[1]);
	compile(argv[1],"-DDOUBLE -DSINGLE_MODE -DMAX8");
    }

    if ((csingle==1) && (cmax8==1))
    {
	printf("\nCompiling %s with SINGLE_MODE and MAX8...\n",argv[1]);
	compile(argv[1],"-DSINGLE_MODE -DMAX8");
    }

    if ((cdouble==1) && (cmax8==1))
    {
	printf("\nCompiling %s with DOUBLE and MAX8...\n",argv[1]);
	compile(argv[1],"-DDOUBLE -DMAX8");
    }
    return 0;
}
Пример #24
0
static struct sock_fprog* mkFilter(struct Allocator* alloc, struct Except* eh)
{
    // Adding exceptions to the syscall filter:
    //
    // echo '#include <sys/syscall.h>' | gcc -E -dM - | grep 'define __NR_' | sort
    // for the full list of system calls with syscall numbers (different per ABI)
    //
    // If gdb traps out it will look like this:
    //
    //     Program received signal SIGSYS, Bad system call.
    //     [Switching to Thread 0x7ffff7fdd740 (LWP 14673)]
    //     0x00007ffff74d1caa in mmap64 () at ../sysdeps/unix/syscall-template.S:81
    //     81    ../sysdeps/unix/syscall-template.S: No such file or directory.
    //
    // %eax should contain the system call number (on different ABIs YMMV)
    //
    //     (gdb) print $eax
    //     $1 = 9
    //     (gdb)
    //
    // Consult your syscall table from the above gcc command...
    //
    //     #define __NR_mmap 9
    //
    // Then add:
    //
    //     IFEQ(__NR_mmap, success),
    //
    // And add a comment documenting where you needed that syscall :)

    #define STMT(code, val) { .sf = BPF_STMT(code, val) }

    #define JMPK(type, not, input, label) { \
        .sf = BPF_JUMP(BPF_JMP+(type)+BPF_K, (input), 0, 0), \
        .jt = (!(not) ? (label) : 0),                        \
        .jf = ((not) ? (label) : 0)                          \
    }

    // Create a label for jumps, the label must be represented by a non-zero integer.
    #define LABEL(lbl) { .label = (lbl) }

    // Load offset into the register
    #define LOAD(offset)    STMT(BPF_LD+BPF_W+BPF_ABS, (offset))

    // Return constant value
    #define RET(val)        STMT(BPF_RET+BPF_K, (val))

    // If-equal if the currently loaded value equals input, jump to label.
    #define IFEQ(input, label) JMPK(BPF_JEQ, 0, (input), (label))

    // If-not-equal if the currently loaded value is not equal to input, jump to label.
    #define IFNE(input, label) JMPK(BPF_JEQ, 1, (input), (label))

    // If-greater-than
    #define IFGT(input, label) JMPK(BPF_JGT, 0, (input), (label))

    // If-greater-than-or-equal-to
    #define IFGE(input, label) JMPK(BPF_JGE, 0, (input), (label))

    // If-less-than
    #define IFLT(input, label) JMPK(BPF_JGE, 1, (input), (label))

    // If-less-than-or-equal-to
    #define IFLE(input, label) JMPK(BPF_JGT, 1, (input), (label))


    // labels are integers so they must be predefined
    int success = 1;
    int fail = 2;
    int unmaskOnly = 3;
    int isworking = 4;
    int socket_setip = 5;
    int ioctl_setip = 6;

    uint32_t auditArch = ArchInfo_getAuditArch();

    struct Filter seccompFilter[] = {

        LOAD(offsetof(struct seccomp_data, arch)),
        IFNE(auditArch, fail),

        // Get the syscall num.
        LOAD(offsetof(struct seccomp_data, nr)),

        // udp
        #ifdef __NR_sendmsg
            IFEQ(__NR_sendmsg, success),
        #endif
        #ifdef __NR_recvmsg
            IFEQ(__NR_recvmsg, success),
        #endif

        // ETHInterface
        #ifdef __NR_sendto
            IFEQ(__NR_sendto, success),
        #endif
        #ifdef __NR_recvfrom
            IFEQ(__NR_recvfrom, success),
        #endif

        #ifdef __NR_socketcall
            // 32-bit: recvmsg is a socketcall
            IFEQ(__NR_socketcall, success),
        #endif

        // libuv
        IFEQ(__NR_epoll_ctl, success),
        #ifdef __NR_epoll_wait
            IFEQ(__NR_epoll_wait, success),
        #endif
        #ifdef __NR_epoll_pwait
            IFEQ(__NR_epoll_pwait, success),
        #endif

        // gettimeofday is required on some architectures
        #ifdef __NR_gettimeofday
            IFEQ(__NR_gettimeofday, success),
        #endif

        // TUN (and logging)
        IFEQ(__NR_write, success),
        IFEQ(__NR_read, success),
        // readv and writev are used by some libc (musl)
        #ifdef __NR_readv
            IFEQ(__NR_readv, success),
        #endif
        #ifdef __NR_writev
            IFEQ(__NR_writev, success),
        #endif

        // modern librt reads a read-only mapped section of kernel space which contains the time
        // older versions need system calls for getting the time.
        // i686 glibc-2.18's time() uses __NR_time
        // Raspberry Pi and BeagleBone Black don't provide __NR_time
        IFEQ(__NR_clock_gettime, success),
        #ifdef __NR_time
            IFEQ(__NR_time, success),
        #endif

        // malloc()
        IFEQ(__NR_brk, success),

        // abort()
        IFEQ(__NR_gettid, success),
        IFEQ(__NR_tgkill, success),
        IFEQ(__NR_rt_sigprocmask, unmaskOnly),

        // exit()
        IFEQ(__NR_exit_group, success),

        // Seccomp_isWorking()
        IFEQ(__NR_getpriority, isworking),

        // Securiy_checkPermissions() -> canOpenFiles()
        IFEQ(__NR_dup, success),
        IFEQ(__NR_close, success),

        // Security_checkPermissions() -> getMaxMem()
        // x86/ARM use ugetrlimit and mmap2
        // ARM does not even have __NR_getrlimit or __NR_mmap defined
        // and AMD64 does not have __NR_ugetrlimit or __NR_mmap2 defined
        #ifdef __NR_getrlimit
            IFEQ(__NR_getrlimit, success),
        #endif
        #ifdef __NR_ugetrlimit
            IFEQ(__NR_ugetrlimit, success),
        #endif
        #ifdef __NR_mmap
            IFEQ(__NR_mmap, success),
        #endif
        #ifdef __NR_mmap2
            IFEQ(__NR_mmap2, success),
        #endif
        IFEQ(__NR_munmap, success),

        // printf()
        IFEQ(__NR_fstat, success),
        #ifdef __NR_fstat64
            IFEQ(__NR_fstat64, success),
        #endif

        // for setting IP addresses...
        // socketForIfName()
        #ifdef __NR_socket
            IFEQ(__NR_socket, socket_setip),
        #endif
        IFEQ(__NR_ioctl, ioctl_setip),

        RET(SECCOMP_RET_TRAP),

        LABEL(socket_setip),
        LOAD(offsetof(struct seccomp_data, args[1])),
        IFEQ(SOCK_DGRAM, success),
        RET(SECCOMP_RET_TRAP),

        LABEL(ioctl_setip),
        LOAD(offsetof(struct seccomp_data, args[1])),
        IFEQ(SIOCGIFINDEX, success),
        IFEQ(SIOCGIFFLAGS, success),
        IFEQ(SIOCSIFFLAGS, success),
        IFEQ(SIOCSIFADDR, success),
        IFEQ(SIOCSIFNETMASK, success),
        IFEQ(SIOCSIFMTU, success),
        RET(SECCOMP_RET_TRAP),

        // We allow sigprocmask to *unmask* signals but we don't allow it to mask them.
        LABEL(unmaskOnly),
        LOAD(offsetof(struct seccomp_data, args[0])),
        IFEQ(SIG_UNBLOCK, success),
        RET(SECCOMP_RET_TRAP),

        LABEL(isworking),
        RET(RET_ERRNO(IS_WORKING_ERRNO)),

        LABEL(fail),
        RET(SECCOMP_RET_TRAP),

        LABEL(success),
        RET(SECCOMP_RET_ALLOW),
    };

    return compile(seccompFilter, sizeof(seccompFilter)/sizeof(seccompFilter[0]), alloc);
}
Пример #25
0
int main(int argc, const char** argv){
  if ( argc < 2 ) {
    usage();
    return -1;
  }
  
  //Script file name
  const char* filename = argv[1];
  
  //Intro on v8 Handles:
  //There are two types of Handles: Persistent, and Local. Local goes onto a "stack" which is always the last 
  // v8::HandleScope to be created. When each HandleScope goes out of scope, it reaps the references of all the local
  // variables on its "stack".
  // There are two ways to pass a JS reference outside of a v8::HandleScope. One is usually used when returning from a function
  // like so: return handle_scope.Close(local);. This passes the reference up to the next v8::HandleScope.
  // The second way is to use another type of Handle: the Persistent Handle. This reference will not be reaped with RIIA, but will
  // instead only be reaped when Dispose is called on the handle.
  // v8::Handle is a superclass to both Persistent, and to Local, and can refere to either.
  
  
  //This will hold the v8 context, all execution in v8 happens in such a "context"
  //Note: this is a Persistent handle, which means that once initialized, its reference will not be
  // reaped until we explicitly call Persistent::Dispose(). However, for now it is empty.
  v8::Persistent<v8::Context> m_v8Context;
  
  {
    //All execution in v8 must happen while one of these is on the stack somewhere
    v8::Locker locker;
    
    //When this destructs, it will collect any scoped (non-persistent) Handles created from now until the end of the scope,
    // reaping the Handles' references.
    v8::HandleScope handle_scope;
    
    //Greate a object tempalte, which will be a template for the global object.
    v8::Handle<v8::ObjectTemplate> globt = v8::ObjectTemplate::New();
      
    //Global template
    {
      //This object template will have a .log() function
      //Very simple to bind simple global functions that take JS type arguments
      globt->Set( v8::String::New("log"), v8::FunctionTemplate::New(LogCallback));
    }

    //Create the new context. v8::Context::New() returns a persistent handle. Remember to call Dispose() when we are done with it.
    // We create the new context with the global template object, thus the global object of the context will not
    // be copied from the global template object.
    m_v8Context = v8::Context::New(NULL, globt);
    
    //In order to do any execution within a context, we must lock it sort of.
    v8::Context::Scope context_scope(m_v8Context);
    
    //Setup the v8 context for execution
    {
      //Get the global object
      v8::Handle<v8::Object> global = m_v8Context->Global();
      
      //inform v8 of these classes
      {
        //Vector
        juice::ogre::Vector::bind(global);
      }
    }
  } //Leave the setup scope
  
  
  //Compile and run a script
  //This can be anywhere, we left all the scopes.
  {
    //We are about to do some v8 stuff ... lock it.
    v8::Locker locker;
    
    //Create a stack for Local handles.
    v8::HandleScope handle_scope;
    
    //Lock the context for execution
    v8::Context::Scope context_scope(m_v8Context);

    //Simply use this utility function to read in the file to a strings.
    v8::Handle<v8::String> script_source = ReadFile(filename);
    
    //Sanity
    if (script_source.IsEmpty()) {
      printf("Failed to load file.\n");
      return -1;
    }
    
    //Use the compile function above to return a compiled script.
    v8::Handle<v8::Script> script = compile(script_source,
      v8::String::New(filename),
      //Report errors with the utility function object above
      // std::bind simply creates a stl function object out of a function.
      // The function object will take one argument, the exception, and we predefine
      // its second argument, which is a stream out for error messages, as going to
      // std::cout.
      boost::bind(ReportException<std::ostream>, _1, boost::ref(std::cout)));
    
    //Sanity
    if ( script.IsEmpty() ) 
    {
      printf("Failed to compile script.\n");
      return -1;
    }
    
    //Use the utility run function to run the script.
    v8::Handle<v8::Value> result = run(script,
      //See explanation by complile() above, this function object
      // will report exception errors to std::cout.
      boost::bind(ReportException<std::ostream>, _1, boost::ref(std::cout)) );
  }// leave locks, scopes etc.
  
  // We are no longer going to use the context. Dispose of it.
  m_v8Context.Dispose();
  
  return 0;
};
Пример #26
0
void
kdb5_update_princ_encryption(int argc, char *argv[])
{
    struct update_enc_mkvno data = { 0 };
    char *name_pattern = NULL;
    int force = 0;
    int optchar;
    krb5_error_code retval;
    krb5_actkvno_node *actkvno_list = 0;
    krb5_db_entry *master_entry;
    char *mkey_fullname = 0;
#ifdef BSD_REGEXPS
    char *msg;
#endif
    char *regexp = NULL;
    krb5_keyblock *act_mkey;
    krb5_keylist_node *master_keylist = krb5_db_mkey_list_alias(util_context);

    while ((optchar = getopt(argc, argv, "fnv")) != -1) {
        switch (optchar) {
        case 'f':
            force = 1;
            break;
        case 'n':
            data.dry_run = 1;
            break;
        case 'v':
            data.verbose = 1;
            break;
        case '?':
        case ':':
        default:
            usage();
        }
    }
    if (argv[optind] != NULL) {
        name_pattern = argv[optind];
        if (argv[optind+1] != NULL)
            usage();
    }

    retval = krb5_unparse_name(util_context, master_princ, &mkey_fullname);
    if (retval) {
        com_err(progname, retval, _("while formatting master principal name"));
        exit_status++;
        goto cleanup;
    }

    if (master_keylist == NULL) {
        com_err(progname, retval, _("master keylist not initialized"));
        exit_status++;
        goto cleanup;
    }

    /* The glob_to_regexp code only cares if the "realm" parameter is
       NULL or not; the string data is irrelevant.  */
    if (name_pattern == NULL)
        name_pattern = "*";
    if (glob_to_regexp(name_pattern, "hi", &regexp) != 0) {
        com_err(progname, ENOMEM,
                _("converting glob pattern '%s' to regular expression"),
                name_pattern);
        exit_status++;
        goto cleanup;
    }

    if (
#ifdef SOLARIS_REGEXPS
        ((data.expbuf = compile(regexp, NULL, NULL)) == NULL)
#endif
#ifdef POSIX_REGEXPS
        ((regcomp(&data.preg, regexp, REG_NOSUB)) != 0)
#endif
#ifdef BSD_REGEXPS
        ((msg = (char *) re_comp(regexp)) != NULL)
#endif
    ) {
        /* XXX syslog msg or regerr(regerrno) */
        com_err(progname, 0, _("error compiling converted regexp '%s'"),
                regexp);
        exit_status++;
        goto cleanup;
    }

    retval = krb5_db_get_principal(util_context, master_princ, 0,
                                   &master_entry);
    if (retval != 0) {
        com_err(progname, retval, _("while getting master key principal %s"),
                mkey_fullname);
        exit_status++;
        goto cleanup;
    }

    retval = krb5_dbe_lookup_actkvno(util_context, master_entry, &actkvno_list);
    if (retval != 0) {
        com_err(progname, retval, _("while looking up active kvno list"));
        exit_status++;
        goto cleanup;
    }

    retval = krb5_dbe_find_act_mkey(util_context, actkvno_list, &new_mkvno,
                                    &act_mkey);
    if (retval) {
        com_err(progname, retval, _("while looking up active master key"));
        exit_status++;
        goto cleanup;
    }
    new_master_keyblock = *act_mkey;

    if (!force &&
        !data.dry_run &&
        !are_you_sure(_("Re-encrypt all keys not using master key vno %u?"),
                      new_mkvno)) {
        printf(_("OK, doing nothing.\n"));
        exit_status++;
        goto cleanup;
    }
    if (data.verbose) {
        if (data.dry_run) {
            printf(_("Principals whose keys WOULD BE re-encrypted to master "
                     "key vno %u:\n"), new_mkvno);
        } else {
            printf(_("Principals whose keys are being re-encrypted to master "
                     "key vno %u if necessary:\n"), new_mkvno);
        }
    }

    if (!data.dry_run) {
        /* Grab a write lock so we don't have to upgrade to a write lock and
         * reopen the DB while iterating. */
        retval = krb5_db_lock(util_context, KRB5_DB_LOCKMODE_EXCLUSIVE);
        if (retval != 0 && retval != KRB5_PLUGIN_OP_NOTSUPP) {
            com_err(progname, retval, _("trying to lock database"));
            exit_status++;
        }
    }

    retval = krb5_db_iterate(util_context, name_pattern,
                             update_princ_encryption_1, &data);
    /* If exit_status is set, then update_princ_encryption_1 already
       printed a message.  */
    if (retval != 0 && exit_status == 0) {
        com_err(progname, retval, _("trying to process principal database"));
        exit_status++;
    }
    if (!data.dry_run)
        (void)krb5_db_unlock(util_context);
    (void) krb5_db_fini(util_context);
    if (data.dry_run) {
        printf(_("%u principals processed: %u would be updated, %u already "
                 "current\n"),
               data.re_match_count, data.updated, data.already_current);
    } else {
        printf(_("%u principals processed: %u updated, %u already current\n"),
               data.re_match_count, data.updated, data.already_current);
    }

cleanup:
    free(regexp);
    memset(&new_master_keyblock, 0, sizeof(new_master_keyblock));
    krb5_free_unparsed_name(util_context, mkey_fullname);
    krb5_dbe_free_actkvno_list(util_context, actkvno_list);
}
void CompositorScriptCompilerTests::testCompile()
{
    if (!ResourceGroupManager::getSingletonPtr())
        new ResourceGroupManager();
    if (!MaterialManager::getSingletonPtr())
    {
        new MaterialManager();
        MaterialManager::getSingleton().initialise();
    }
    if (!CompositorManager::getSingletonPtr())
        new CompositorManager();

    //compositorMgr->initialise();
    const String simpleScript = "compositor \"First Test\" { technique { target_output { } } }";
    CPPUNIT_ASSERT(compile(simpleScript, "Test Compositor"));

    const String BW_Script =
        "/// Black and white effect \n"
        "compositor B&W \n"
        "{ \n"
        "    technique \n"
        "    { \n"
        "        // Temporary textures \n"
        "        texture scene target_width target_height PF_A8R8G8B8 \n"
        " \n"
        "        target scene \n"
        "        { \n"
        "            // Render output from previous compositor (or original scene) \n"
        "            input previous \n"
        "        }"
        "        target_output \n"
        "        { \n"
        "            // Start with clear output \n"
        "            input none \n"
        "            // Draw a fullscreen quad with the blur \n"
        "            pass render_quad \n"
        "            { \n"
        "                // Renders a fullscreen quad with a material \n"
        "                material PostFilters/BlackAndWhite \n"
        "                input 0 scene \n"
        "            } \n"
        "        } \n"
        "    } \n"
        "} \n";

    CPPUNIT_ASSERT(compile(BW_Script, "Test Black & White Script"));

    const String Bloom_Script =
    "/// Manuel's bloom \n"
    "/// Needs a scene-sized rtt, but does only one render of the scene \n"
    "compositor Bloom \n"
    "{ \n"
    "    technique \n"
    "    { \n"
    "        // Temporary textures \n"
    "        texture scene target_width target_height PF_A8R8G8B8 \n"
    "        texture rt0 128 128 PF_A8R8G8B8 \n"
    "        texture rt1 128 128 PF_A8R8G8B8 \n"
    "     \n"
    "        target scene \n"
    "        { \n"
    "            // Render output from previous compositor (or original scene) \n"
    "            input previous \n"
    "        } \n"
    "        target rt0 \n"
    "        { \n"
    "            // Start with clear texture \n"
    "            input none \n"
    "            // Vertical blur pass \n"
    "            pass render_quad \n"
    "            { \n"
    "                // Renders a fullscreen quad with a material \n"
    "                material PostFilters/Blur0 \n"
    "                input 0 scene \n"
    "            } \n"
    "        } \n"
    "        target rt1 \n"
    "        { \n"
    "            // Start with clear texture \n"
    "            input none \n"
    "            // Horizontal blur pass \n"
    "            pass render_quad \n"
    "            { \n"
    "                // Renders a fullscreen quad with a material \n"
    "                material PostFilters/Blur1 \n"
    "                input 0 rt0 \n"
    "            } \n"
    "        } \n"
    "        target_output \n"
    "        { \n"
    "            // Start with clear output \n"
    "            input none \n"
    "            // Draw a fullscreen quad \n"
    "            pass render_quad \n"
    "            { \n"
    "                // Renders a fullscreen quad with a material \n"
    "                material PostFilters/BloomBlend \n"
    "                input 0 scene \n"
    "                input 1 rt1 \n"
    "            } \n"
    "        } \n"
    "    } \n"
    "} \n";
    CPPUNIT_ASSERT(compile(Bloom_Script, "Test Bloom Script"));
}
// Handle the back branch event. Notice that we can compile the method
// with a regular entry from here.
void AdvancedThresholdPolicy::method_back_branch_event(methodHandle mh, methodHandle imh,
                                                       int bci, CompLevel level, nmethod* nm, JavaThread* thread) {
  if (should_create_mdo(mh(), level)) {
    create_mdo(mh, thread);
  }
  // Check if MDO should be created for the inlined method
  if (should_create_mdo(imh(), level)) {
    create_mdo(imh, thread);
  }

  if (is_compilation_enabled()) {
    CompLevel next_osr_level = loop_event(imh(), level);
    CompLevel max_osr_level = (CompLevel)imh->highest_osr_comp_level();
    // At the very least compile the OSR version
    if (!CompileBroker::compilation_is_in_queue(imh) && (next_osr_level != level)) {
      compile(imh, bci, next_osr_level, thread);
    }

    // Use loop event as an opportunity to also check if there's been
    // enough calls.
    CompLevel cur_level, next_level;
    if (mh() != imh()) { // If there is an enclosing method
      guarantee(nm != NULL, "Should have nmethod here");
      cur_level = comp_level(mh());
      next_level = call_event(mh(), cur_level);

      if (max_osr_level == CompLevel_full_optimization) {
        // The inlinee OSRed to full opt, we need to modify the enclosing method to avoid deopts
        bool make_not_entrant = false;
        if (nm->is_osr_method()) {
          // This is an osr method, just make it not entrant and recompile later if needed
          make_not_entrant = true;
        } else {
          if (next_level != CompLevel_full_optimization) {
            // next_level is not full opt, so we need to recompile the
            // enclosing method without the inlinee
            cur_level = CompLevel_none;
            make_not_entrant = true;
          }
        }
        if (make_not_entrant) {
          if (PrintTieredEvents) {
            int osr_bci = nm->is_osr_method() ? nm->osr_entry_bci() : InvocationEntryBci;
            print_event(MAKE_NOT_ENTRANT, mh(), mh(), osr_bci, level);
          }
          nm->make_not_entrant();
        }
      }
      if (!CompileBroker::compilation_is_in_queue(mh)) {
        // Fix up next_level if necessary to avoid deopts
        if (next_level == CompLevel_limited_profile && max_osr_level == CompLevel_full_profile) {
          next_level = CompLevel_full_profile;
        }
        if (cur_level != next_level) {
          compile(mh, InvocationEntryBci, next_level, thread);
        }
      }
    } else {
      cur_level = comp_level(imh());
      next_level = call_event(imh(), cur_level);
      if (!CompileBroker::compilation_is_in_queue(imh) && (next_level != cur_level)) {
        compile(imh, InvocationEntryBci, next_level, thread);
      }
    }
  }
}
Пример #29
0
void kit::BakedTerrain::updateGpuProgram()
{
  if(!m_valid)
  {
    return;
  }

  // Generate vertexshader sourcecode
  std::stringstream vertexSource;
  {
    // Header
    vertexSource << "#version 410 core" << std::endl;
    vertexSource << std::endl;

    // In attributes
    vertexSource << "layout (location = 0) in vec3 in_position;" << std::endl;
    vertexSource << "layout (location = 1) in vec2 in_texcoord;" << std::endl;
    vertexSource << "layout (location = 2) in vec3 in_normal;" << std::endl;
    vertexSource << "layout (location = 3) in vec3 in_tangent;" << std::endl;
    vertexSource << "layout (location = 4) in vec3 in_bitangent;" << std::endl;
    vertexSource << std::endl;

    // Out attributes
    vertexSource << "layout (location = 0) out vec2 out_texcoord;" << std::endl;
    vertexSource << "layout (location = 1) out vec3 out_normal;" << std::endl;
    vertexSource << "layout (location = 2) out vec3 out_tangent;" << std::endl;
    vertexSource << "layout (location = 3) out vec3 out_bitangent;" << std::endl;
    vertexSource << "layout (location = 4) out vec4 out_position;" << std::endl;
    vertexSource << std::endl;

    // Uniforms
    vertexSource << "uniform mat4 uniform_mvpMatrix;" << std::endl;
    vertexSource << "uniform mat4 uniform_mvMatrix;" << std::endl;
    vertexSource << std::endl;

    // ---- Main code begins ---- //
    vertexSource << "void main()" << std::endl;
    vertexSource << "{" << std::endl;

    // Prepare variables
    vertexSource << "  vec4 position  = vec4(in_position, 1.0);" << std::endl;
    vertexSource << std::endl;

    // Write attributes
    vertexSource << "  out_position   = uniform_mvMatrix * position;" << std::endl;
    vertexSource << "  out_normal     = (uniform_mvMatrix * vec4(normalize(in_normal), 0.0)).xyz;" << std::endl;
    vertexSource << "  out_texcoord   = in_texcoord;" << std::endl;
    vertexSource << "  out_tangent    = (uniform_mvMatrix * vec4(normalize(in_tangent), 0.0)).xyz;" << std::endl;
    vertexSource << "  out_bitangent  = (uniform_mvMatrix * vec4(normalize(in_bitangent), 0.0)).xyz;" << std::endl;
    vertexSource << std::endl;

    // Write gl_* variables
    vertexSource << "  gl_Position    = uniform_mvpMatrix * position;" << std::endl;

    // ---- Main code ends ---- //
    vertexSource << "}" << std::endl;
  }

  // Generate pixelshader sourcecode
  std::stringstream pixelSource;
  {
    // Header
    pixelSource << "#version 410 core" << std::endl;
    pixelSource << std::endl;
    
    // In attributes
    pixelSource << "layout (location = 0) in vec2 in_texCoords;" << std::endl;
    pixelSource << "layout (location = 1) in vec3 in_normal;" << std::endl;
    pixelSource << "layout (location = 2) in vec3 in_tangent;" << std::endl;
    pixelSource << "layout (location = 3) in vec3 in_bitangent;" << std::endl;
    pixelSource << "layout (location = 4) in vec4 in_position;" << std::endl;
    pixelSource << std::endl;
    
    // Out attributes
    pixelSource << "layout (location = 0) out vec4 out_A;" << std::endl;
    pixelSource << "layout (location = 1) out vec4 out_B;" << std::endl;
    pixelSource << "layout (location = 2) out vec4 out_C;" << std::endl;
    pixelSource << "layout (location = 3) out vec4 out_D;" << std::endl;
    
    // Function to blend two textures smoothly based on a depthmap
    pixelSource << "vec4 blend2(vec4 below, vec4 above, float a2)" << std::endl;
    pixelSource << "{" << std::endl;
    pixelSource << "  float depth = 0.1;" << std::endl;
    pixelSource << std::endl;
    pixelSource << "  float f1 = 1.1;" << std::endl;
    pixelSource << "  float f2 = a2;" << std::endl;
    pixelSource << "  float ma = max(f1, f2) - depth;" << std::endl;
    pixelSource << std::endl;
    pixelSource << "  float b1 = max(f1 - ma, 0);" << std::endl;
    pixelSource << "  float b2 = max(f2 - ma, 0);" << std::endl;
    pixelSource << std::endl;
    pixelSource << "  return (below.rgba * b1 + above.rgba * b2) / (b1 + b2);" << std::endl;
    pixelSource << "}" << std::endl;
    pixelSource << std::endl;
    
    // Uniforms
    if (m_numLayers > 1)
    {
      pixelSource << "uniform sampler2D uniform_materialMask0;" << std::endl;
    }

    if (m_numLayers > 4)
    {
      pixelSource << "uniform sampler2D uniform_materialMask1;" << std::endl;
    }

    pixelSource << "uniform sampler2D uniform_arCache;" << std::endl;
    pixelSource << "uniform sampler2D uniform_nxCache;" << std::endl;
    pixelSource << "uniform float uniform_detailDistance;" << std::endl;
    pixelSource << std::endl;

    // Layerspecific uniforms
    for(int i = 0; i < m_numLayers; i++)
    {
      pixelSource << "uniform sampler2D uniform_arLayer" << i << ";" << std::endl;
      pixelSource << "uniform sampler2D uniform_ndLayer" << i << ";" << std::endl;
      pixelSource << std::endl;
    }

    // ---- Main code begins ---- //
    pixelSource << "void main()" << std::endl;
    pixelSource << "{" << std::endl;

    // Prepare variables
    pixelSource << "  vec2 fullUv = in_texCoords;" << std::endl;
    pixelSource << "  vec2 detailUv = in_texCoords * vec2(" << (float)m_size.x * m_xzScale << ", " << (float)m_size.y  * m_xzScale << ");" << std::endl;
    pixelSource << "  float linearDistance = distance(vec3(0.0), in_position.xyz / in_position.w);" << std::endl;

    // Prepare output variables
    pixelSource << "  vec4 arOut; " << std::endl;
    pixelSource << "  vec3 nOut;" << std::endl;

    // If the distance to the fragment is higher than the detail distance, output the cached AR and NM maps
    pixelSource << "  if (linearDistance > uniform_detailDistance)" << std::endl;
    pixelSource << "  {" << std::endl;
    pixelSource << "    arOut = texture(uniform_arCache, fullUv);" << std::endl;
    pixelSource << "    nOut = texture(uniform_nxCache, fullUv).rgb;" << std::endl;
    pixelSource << "  }" << std::endl;

    // Otherwise, do some magic
    pixelSource << "  else" << std::endl;
    pixelSource << "  {" << std::endl;

    // Sample the materialmasks
    if (m_numLayers > 1)
    {
      pixelSource << "    vec4 materialMask0 = texture(uniform_materialMask0, fullUv);" << std::endl;
    }

    if (m_numLayers > 4)
    {
      pixelSource << "    vec4 materialMask1 = texture(uniform_materialMask1, fullUv);" << std::endl;
    }

    // Sample the layer maps
    for (int i = 0; i < m_numLayers; i++)
    {
      pixelSource << "    vec4 ar" << i << " = texture(uniform_arLayer" << i << ", detailUv * " << m_layerInfo[i].uvScale << ");" << std::endl;
      pixelSource << "    vec4 nd" << i << " = texture(uniform_ndLayer" << i << ", detailUv * " << m_layerInfo[i].uvScale << ");" << std::endl;

      if (i == 0)
      {
        pixelSource << "    arOut = ar0;" << std::endl;
        pixelSource << "    nOut = nd0.rgb;" << std::endl;
      }
      else
      {
        pixelSource << "    arOut = blend2(arOut, ar" << i << ", materialMask" << getMaskSuffix(i) << " + nd" << i << ".a);" << std::endl;
        pixelSource << "    nOut = blend2(vec4(nOut, 0.0), vec4(nd" << i << ".rgb, 0.0), materialMask" << getMaskSuffix(i) << " + nd" << i << ".a).rgb;" << std::endl;
      }
    }

    // We're done with generating output
    pixelSource << "  }" << std::endl;
    pixelSource << std::endl;

    // Prepare normalmapping and output
    pixelSource << "  mat3 normalRotation= (mat3(normalize(in_tangent), normalize(in_bitangent), normalize(in_normal)));" << std::endl;
    pixelSource << "  vec3 normalTex     = normalize((nOut.rgb - 0.5)*2.0);" << std::endl;
    pixelSource << "  vec3 normal        = normalize(normalRotation * normalTex);" << std::endl;
    
    // Write output
    pixelSource << "  out_A = arOut;" << std::endl;
    pixelSource << "  out_B = vec4(0.0, 0.0, 0.0, 0.0);" << std::endl;
    pixelSource << "  out_C.xyz = normal;" << std::endl;
    pixelSource << "  out_C.a = 1.0;" << std::endl;

    // Mission complete!
    pixelSource << "}" << std::endl;
  }

  // Compile shader objects
  auto vertexShader = new kit::Shader(Shader::Type::Vertex);
  vertexShader->sourceFromString(vertexSource.str());
  vertexShader->compile();

  auto pixelShader = new kit::Shader(Shader::Type::Fragment);
  pixelShader->sourceFromString(pixelSource.str());
  pixelShader->compile();

  // Link program
  if(m_program)
    delete m_program;
  
  m_program = new kit::Program();
  m_program->attachShader(vertexShader);
  m_program->attachShader(pixelShader);
  m_program->link();
  m_program->detachShader(vertexShader);
  m_program->detachShader(pixelShader);

  delete vertexShader;
  delete pixelShader;
  
  // Update uniforms
  if (m_numLayers > 1)
  {
    m_program->setUniformTexture("uniform_materialMask0", m_materialMask[0]);
  }

  if (m_numLayers > 4)
  {
    m_program->setUniformTexture("uniform_materialMask1", m_materialMask[1]);
  }
  
  m_program->setUniformTexture("uniform_arCache", m_arCache);
  m_program->setUniformTexture("uniform_nxCache", m_nxCache);
  m_program->setUniform1f("uniform_detailDistance", 500.0f); //< TODO: Replace with configuration parameter

  // Layer-specific uniforms
  for(int i = 0; i < m_numLayers; i++)
  {
    m_program->setUniformTexture("uniform_arLayer" + std::to_string(i), m_layerInfo[i].arCache);
    m_program->setUniformTexture("uniform_ndLayer" + std::to_string(i), m_layerInfo[i].ndCache);
  }
}
Пример #30
0
ComputeShaderInstance::ComputeShaderInstance(const Shader<ComputeShader> *ker) : ShaderInstanceBase(), kernel(ker) {
	const ShaderBase *b = static_cast<const ShaderBase *>(kernel);
	compile(&b, 1);
}