void failed(const char *s1, const char *s2) { prp(); prs(s1); if (s2) { prs(colon); prs(s2); ; } newline(); exitsh(ERROR); }
/* * fake diagnostics to continue to look like original * test(1) diagnostics */ static void bfailed(const unsigned char *s1, const unsigned char *s2, const unsigned char *s3) { prp(); prs(s1); if (s2) { prs(colon); prs(s2); prs(s3); } newline(); exitsh(ERROR); }
void GridApplicInterface:: derived_map(const Variables& vars, const ActiveSet& set, Response& response, int fn_eval_id) { // // Launch the grid solver (asynchronously) // ParamResponsePair prp(vars, interfaceId, response, fn_eval_id); derived_map_asynch(prp); // // Call wait_local_evaluations() until our id is in the set // PRPQueue prp_queue; prp_queue.push_back(prp); if (!completionSet.empty()) { Cerr << "derived_map - should start with an empty completion set\n"; abort_handler(-1); } wait_local_evaluations(prp_queue); // rebuilds completionSet response = prp_queue.front().prp_response(); completionSet.clear(); #if 0 // // Read the params file and handle exceptions // try { if (evalCommRank == 0) read_results_files(response, fn_eval_id); } catch(String& err_msg) { // a String exception involves detection of an incomplete file/data // set. In the synchronous case, there is no potential for an incomplete // file resulting from a race condition -> echo the error and abort. Cerr << err_msg << std::endl; abort_handler(-1); } catch(int fail_code) { // The approach here is to have catch(int) rethrow the exception to an // outer catch (either the catch within manage_failure or a catch that // calls manage_failure). throw; } #endif }
static void synbad(void) { prp(); prs(synmsg); if ((flags & ttyflg) == 0) { prs(atline); prn(standin->flin); } prs(colon); prc(LQ); if (wdval) prsym(wdval); else prs(wdarg->argval); prc(RQ); prs(unexpected); newline(); exitsh(SYNBAD); }
/*! Applies the given \a command to the given \a backend. */ QScriptDebuggerResponse QScriptDebuggerCommandExecutor::execute( QScriptDebuggerBackend *backend, const QScriptDebuggerCommand &command) { QScriptDebuggerResponse response; switch (command.type()) { case QScriptDebuggerCommand::None: break; case QScriptDebuggerCommand::Interrupt: backend->interruptEvaluation(); break; case QScriptDebuggerCommand::Continue: if (backend->engine()->isEvaluating()) { backend->continueEvalution(); response.setAsync(true); } break; case QScriptDebuggerCommand::StepInto: { QVariant attr = command.attribute(QScriptDebuggerCommand::StepCount); int count = attr.isValid() ? attr.toInt() : 1; backend->stepInto(count); response.setAsync(true); } break; case QScriptDebuggerCommand::StepOver: { QVariant attr = command.attribute(QScriptDebuggerCommand::StepCount); int count = attr.isValid() ? attr.toInt() : 1; backend->stepOver(count); response.setAsync(true); } break; case QScriptDebuggerCommand::StepOut: backend->stepOut(); response.setAsync(true); break; case QScriptDebuggerCommand::RunToLocation: backend->runToLocation(command.fileName(), command.lineNumber()); response.setAsync(true); break; case QScriptDebuggerCommand::RunToLocationByID: backend->runToLocation(command.scriptId(), command.lineNumber()); response.setAsync(true); break; case QScriptDebuggerCommand::ForceReturn: { int contextIndex = command.contextIndex(); QScriptDebuggerValue value = command.scriptValue(); QScriptEngine *engine = backend->engine(); QScriptValue realValue = value.toScriptValue(engine); backend->returnToCaller(contextIndex, realValue); response.setAsync(true); } break; case QScriptDebuggerCommand::Resume: backend->resume(); response.setAsync(true); break; case QScriptDebuggerCommand::SetBreakpoint: { QScriptBreakpointData data = command.breakpointData(); if (!data.isValid()) data = QScriptBreakpointData(command.fileName(), command.lineNumber()); int id = backend->setBreakpoint(data); response.setResult(id); } break; case QScriptDebuggerCommand::DeleteBreakpoint: { int id = command.breakpointId(); if (!backend->deleteBreakpoint(id)) response.setError(QScriptDebuggerResponse::InvalidBreakpointID); } break; case QScriptDebuggerCommand::DeleteAllBreakpoints: backend->deleteAllBreakpoints(); break; case QScriptDebuggerCommand::GetBreakpoints: { QScriptBreakpointMap bps = backend->breakpoints(); if (!bps.isEmpty()) response.setResult(bps); } break; case QScriptDebuggerCommand::GetBreakpointData: { int id = command.breakpointId(); QScriptBreakpointData data = backend->breakpointData(id); if (data.isValid()) response.setResult(data); else response.setError(QScriptDebuggerResponse::InvalidBreakpointID); } break; case QScriptDebuggerCommand::SetBreakpointData: { int id = command.breakpointId(); QScriptBreakpointData data = command.breakpointData(); if (!backend->setBreakpointData(id, data)) response.setError(QScriptDebuggerResponse::InvalidBreakpointID); } break; case QScriptDebuggerCommand::GetScripts: { QScriptScriptMap scripts = backend->scripts(); if (!scripts.isEmpty()) response.setResult(scripts); } break; case QScriptDebuggerCommand::GetScriptData: { qint64 id = command.scriptId(); QScriptScriptData data = backend->scriptData(id); if (data.isValid()) response.setResult(data); else response.setError(QScriptDebuggerResponse::InvalidScriptID); } break; case QScriptDebuggerCommand::ScriptsCheckpoint: backend->scriptsCheckpoint(); response.setResult(QVariant::fromValue(backend->scriptsDelta())); break; case QScriptDebuggerCommand::GetScriptsDelta: response.setResult(QVariant::fromValue(backend->scriptsDelta())); break; case QScriptDebuggerCommand::ResolveScript: response.setResult(backend->resolveScript(command.fileName())); break; case QScriptDebuggerCommand::GetBacktrace: response.setResult(backend->backtrace()); break; case QScriptDebuggerCommand::GetContextCount: response.setResult(backend->contextCount()); break; case QScriptDebuggerCommand::GetContextState: { QScriptContext *ctx = backend->context(command.contextIndex()); if (ctx) response.setResult(static_cast<int>(ctx->state())); else response.setError(QScriptDebuggerResponse::InvalidContextIndex); } break; case QScriptDebuggerCommand::GetContextID: { int idx = command.contextIndex(); if ((idx >= 0) && (idx < backend->contextCount())) response.setResult(backend->contextIds()[idx]); else response.setError(QScriptDebuggerResponse::InvalidContextIndex); } break; case QScriptDebuggerCommand::GetContextInfo: { QScriptContext *ctx = backend->context(command.contextIndex()); if (ctx) response.setResult(QScriptContextInfo(ctx)); else response.setError(QScriptDebuggerResponse::InvalidContextIndex); } break; case QScriptDebuggerCommand::GetThisObject: { QScriptContext *ctx = backend->context(command.contextIndex()); if (ctx) response.setResult(ctx->thisObject()); else response.setError(QScriptDebuggerResponse::InvalidContextIndex); } break; case QScriptDebuggerCommand::GetActivationObject: { QScriptContext *ctx = backend->context(command.contextIndex()); if (ctx) response.setResult(ctx->activationObject()); else response.setError(QScriptDebuggerResponse::InvalidContextIndex); } break; case QScriptDebuggerCommand::GetScopeChain: { QScriptContext *ctx = backend->context(command.contextIndex()); if (ctx) { QScriptDebuggerValueList dest; QScriptValueList src = ctx->scopeChain(); for (int i = 0; i < src.size(); ++i) dest.append(src.at(i)); response.setResult(dest); } else { response.setError(QScriptDebuggerResponse::InvalidContextIndex); } } break; case QScriptDebuggerCommand::ContextsCheckpoint: { response.setResult(QVariant::fromValue(backend->contextsCheckpoint())); } break; case QScriptDebuggerCommand::GetPropertyExpressionValue: { QScriptContext *ctx = backend->context(command.contextIndex()); int lineNumber = command.lineNumber(); QVariant attr = command.attribute(QScriptDebuggerCommand::UserAttribute); QStringList path = attr.toStringList(); if (!ctx || path.isEmpty()) break; QScriptContextInfo ctxInfo(ctx); if (ctx->callee().isValid() && ((lineNumber < ctxInfo.functionStartLineNumber()) || (lineNumber > ctxInfo.functionEndLineNumber()))) { break; } QScriptValueList objects; int pathIndex = 0; if (path.at(0) == QLatin1String("this")) { objects.append(ctx->thisObject()); ++pathIndex; } else { objects << ctx->scopeChain(); } for (int i = 0; i < objects.size(); ++i) { QScriptValue val = objects.at(i); for (int j = pathIndex; val.isValid() && (j < path.size()); ++j) { val = val.property(path.at(j)); } if (val.isValid()) { bool hadException = (ctx->state() == QScriptContext::ExceptionState); QString str = val.toString(); if (!hadException && backend->engine()->hasUncaughtException()) backend->engine()->clearExceptions(); response.setResult(str); break; } } } break; case QScriptDebuggerCommand::GetCompletions: { QScriptContext *ctx = backend->context(command.contextIndex()); QVariant attr = command.attribute(QScriptDebuggerCommand::UserAttribute); QStringList path = attr.toStringList(); if (!ctx || path.isEmpty()) break; QScriptValueList objects; QString prefix = path.last(); QSet<QString> matches; if (path.size() > 1) { const QString &topLevelIdent = path.at(0); QScriptValue obj; if (topLevelIdent == QLatin1String("this")) { obj = ctx->thisObject(); } else { QScriptValueList scopeChain; scopeChain = ctx->scopeChain(); for (int i = 0; i < scopeChain.size(); ++i) { QScriptValue oo = scopeChain.at(i).property(topLevelIdent); if (oo.isObject()) { obj = oo; break; } } } for (int i = 1; obj.isObject() && (i < path.size()-1); ++i) obj = obj.property(path.at(i)); if (obj.isValid()) objects.append(obj); } else { objects << ctx->scopeChain(); QStringList keywords; keywords.append(QString::fromLatin1("this")); keywords.append(QString::fromLatin1("true")); keywords.append(QString::fromLatin1("false")); keywords.append(QString::fromLatin1("null")); for (int i = 0; i < keywords.size(); ++i) { const QString &kwd = keywords.at(i); if (isPrefixOf(prefix, kwd)) matches.insert(kwd); } } for (int i = 0; i < objects.size(); ++i) { QScriptValue obj = objects.at(i); while (obj.isObject()) { QScriptValueIterator it(obj); while (it.hasNext()) { it.next(); QString propertyName = it.name(); if (isPrefixOf(prefix, propertyName)) matches.insert(propertyName); } obj = obj.prototype(); } } QStringList matchesList = matches.toList(); qStableSort(matchesList); response.setResult(matchesList); } break; case QScriptDebuggerCommand::NewScriptObjectSnapshot: { int id = backend->newScriptObjectSnapshot(); response.setResult(id); } break; case QScriptDebuggerCommand::ScriptObjectSnapshotCapture: { int id = command.snapshotId(); QScriptObjectSnapshot *snap = backend->scriptObjectSnapshot(id); Q_ASSERT(snap != 0); QScriptDebuggerValue object = command.scriptValue(); Q_ASSERT(object.type() == QScriptDebuggerValue::ObjectValue); QScriptEngine *engine = backend->engine(); QScriptValue realObject = object.toScriptValue(engine); Q_ASSERT(realObject.isObject()); QScriptObjectSnapshot::Delta delta = snap->capture(realObject); QScriptDebuggerObjectSnapshotDelta result; result.removedProperties = delta.removedProperties; bool didIgnoreExceptions = backend->ignoreExceptions(); backend->setIgnoreExceptions(true); for (int i = 0; i < delta.changedProperties.size(); ++i) { const QScriptValueProperty &src = delta.changedProperties.at(i); bool hadException = engine->hasUncaughtException(); QString str = src.value().toString(); if (!hadException && engine->hasUncaughtException()) engine->clearExceptions(); QScriptDebuggerValueProperty dest(src.name(), src.value(), str, src.flags()); result.changedProperties.append(dest); } for (int j = 0; j < delta.addedProperties.size(); ++j) { const QScriptValueProperty &src = delta.addedProperties.at(j); bool hadException = engine->hasUncaughtException(); QString str = src.value().toString(); if (!hadException && engine->hasUncaughtException()) engine->clearExceptions(); QScriptDebuggerValueProperty dest(src.name(), src.value(), str, src.flags()); result.addedProperties.append(dest); } backend->setIgnoreExceptions(didIgnoreExceptions); response.setResult(QVariant::fromValue(result)); } break; case QScriptDebuggerCommand::DeleteScriptObjectSnapshot: { int id = command.snapshotId(); backend->deleteScriptObjectSnapshot(id); } break; case QScriptDebuggerCommand::NewScriptValueIterator: { QScriptDebuggerValue object = command.scriptValue(); Q_ASSERT(object.type() == QScriptDebuggerValue::ObjectValue); QScriptEngine *engine = backend->engine(); QScriptValue realObject = object.toScriptValue(engine); Q_ASSERT(realObject.isObject()); int id = backend->newScriptValueIterator(realObject); response.setResult(id); } break; case QScriptDebuggerCommand::GetPropertiesByIterator: { int id = command.iteratorId(); int count = 1000; QScriptValueIterator *it = backend->scriptValueIterator(id); Q_ASSERT(it != 0); QScriptDebuggerValuePropertyList props; for (int i = 0; (i < count) && it->hasNext(); ++i) { it->next(); QString name = it->name(); QScriptValue value = it->value(); QString valueAsString = value.toString(); QScriptValue::PropertyFlags flags = it->flags(); QScriptDebuggerValueProperty prp(name, value, valueAsString, flags); props.append(prp); } response.setResult(props); } break; case QScriptDebuggerCommand::DeleteScriptValueIterator: { int id = command.iteratorId(); backend->deleteScriptValueIterator(id); } break; case QScriptDebuggerCommand::Evaluate: { int contextIndex = command.contextIndex(); QString program = command.program(); QString fileName = command.fileName(); int lineNumber = command.lineNumber(); backend->evaluate(contextIndex, program, fileName, lineNumber); response.setAsync(true); } break; case QScriptDebuggerCommand::ScriptValueToString: { QScriptDebuggerValue value = command.scriptValue(); QScriptEngine *engine = backend->engine(); QScriptValue realValue = value.toScriptValue(engine); response.setResult(realValue.toString()); } break; case QScriptDebuggerCommand::SetScriptValueProperty: { QScriptDebuggerValue object = command.scriptValue(); QScriptEngine *engine = backend->engine(); QScriptValue realObject = object.toScriptValue(engine); QScriptDebuggerValue value = command.subordinateScriptValue(); QScriptValue realValue = value.toScriptValue(engine); QString name = command.name(); realObject.setProperty(name, realValue); } break; case QScriptDebuggerCommand::ClearExceptions: backend->engine()->clearExceptions(); break; case QScriptDebuggerCommand::UserCommand: case QScriptDebuggerCommand::MaxUserCommand: break; } return response; }
int main(int argc, char* argv[]) { totalStartTime = getCPUTime(); printf("%lf\n",totalStartTime); int i; FILE* fp = fopen(argv[1],"a+b"); if (fp==NULL) { printf("fopen error: cannot open file\n"); exit(1); } int* prptable; unsigned char mac[MAXBLOCKSIZE]; unsigned long fileLen1,fileLen2; // get the file size fseek(fp,0,SEEK_END); fileLen1 = ftell(fp); // generate keys master_keygen(argv[2]); printf("key for file permutation: "); displayCharArray(k_file_perm,16); printf("key for ecc permutation: "); displayCharArray(k_ecc_perm,16); printf("key for ecc encryption: "); displayCharArray(k_ecc_enc,16); printf("key for challenge generation: "); displayCharArray(k_chal,16); printf("key for random index generation: "); displayCharArray(k_ind,16); printf("key for response encryption: "); displayCharArray(k_enc,16); printf("key for MAC computation: "); displayCharArray(k_mac,16); // blockize the file int blocks = blockize(fp); t = blocks; fclose(fp); fp = fopen(argv[1],"a+b"); // computing MAC printf("\nComputing file's MAC...\n"); printf("\nmac size %lu\n",sizeof(mac)); macStartTime = getCPUTime(); hmac(argv[1],mac,k_mac); macTime = getCPUTime() - macStartTime; printf("\nMAC = "); displayCharArray(mac,16); // perform a file level PRP printf("\nSRF PRP for the entire file...\n"); prpStartTime = getCPUTime(); prptable = prp(blocks, k_file_perm); prpTime += getCPUTime() - prpStartTime; eccStartTime = getCPUTime(); initialize_ecc(); inc_encoding(fp,prptable); eccTime = getCPUTime() - eccStartTime - readTime; printf("\nFile blocks after outer layer encoding: %lu\n",t); // precompute q challenge and responsess printf("\nPrecomputation for %d challenges and responses\n",q); chalStartTime = getCPUTime(); Chal c[q]; int j,p; // use k_chal to generate kjc keygen_init(); seeding(k_chal); unsigned char * kjc[q]; for(j=0;j<q;j++) { kjc[j] = malloc(16*sizeof(unsigned char *)); keygen(kjc[j], 16); } // use kjc to generate random indices for(j=0;j<q;j++) { keygen_init(); seeding(kjc[j]); for(p=0;p<v;p++) { unsigned long randomIndex; char rand[8]; keygen(rand, 8); randomIndex = *(unsigned long *)rand; c[j].s[p] = randomIndex % t; } } // use k_ind to generate random index u keygen_init(); seeding(k_ind); for(j=0;j<q;j++) { unsigned int randomIndex; char rand[4]; keygen(rand, 4); randomIndex = *(unsigned int *)rand; c[j].u = randomIndex % w; } printf("Precomputation for challenges finishes\n"); // precompute challenge responses precompute_response(fp,c,k_enc); printf("Precomputation for responses finishes\n"); chalTime+=getCPUTime()-chalStartTime - write2Time; // append MAC at the end of the files printf("\nAppend MAC to the end of the file...\n"); write2StartTime = getCPUTime(); clock_gettime(CLOCK_MONOTONIC, &start); fwrite(mac,16,1,fp); clock_gettime(CLOCK_MONOTONIC, &finish); double addTime = finish.tv_sec - start.tv_sec; addTime += (finish.tv_nsec - start.tv_nsec)/1000000000.0; write2Time += getCPUTime() - write2StartTime+addTime; fseek(fp,0,SEEK_END); fileLen2 = ftell(fp); fclose(fp); printf("\nPOR encoding done\n"); // display time performance totalTime = getCPUTime() - totalStartTime; printf("#RESULT#\n"); printf("%lu\n",fileLen1); printf("%lu\n",fileLen2); printf("%lf\n",totalTime); printf("%lf\n",readTime); printf("%lf\n",prpTime); printf("%lf\n",eccTime); printf("%lf\n",macTime); printf("%lf\n",chalTime); printf("%lf\n",write1Time+write2Time); printf("%lf\n",encTime); }
// outer layer ECC using incremental encoding int inc_encoding (FILE* fp,int* prptable) { printf("\nIncremental encoding starts...\n"); int i,j,enc_blocks,d=n-k; // get file length fseek(fp,0,SEEK_END); fileLen = ftell(fp); // divide by message length k, get number of encoding blocks if(fileLen % k==0) enc_blocks = fileLen/k; else enc_blocks = fileLen/k+1; printf("There are %d encoding blocks\n",enc_blocks); unsigned char message[k]; unsigned char codeword[n]; unsigned char ** code; // used to store parity part long filecounter = 0; int blockcounter = 0; int round = 0; // code is enc_blocks * d code = (unsigned char **) malloc(enc_blocks*sizeof(unsigned char *)); for (i = 0; i < enc_blocks; i++) { code[i] = (unsigned char *) malloc(d*sizeof(unsigned char)); int ii; for (ii=0;ii<d;ii++) code[i][ii]=0; } rewind(fp); while (!feof(fp)) { unsigned char * buf; if ((buf = malloc(sizeof(unsigned char)*readLen))==NULL) { printf("malloc error: inc_encoding\n"); exit(1); } // incremental encoding, read reaLen each time readStartTime = getCPUTime(); clock_gettime(CLOCK_MONOTONIC, &start); printf("max read in %d bytes\n",readLen); size_t br = fread(buf, 1, readLen, fp); printf("Read in %lu bytes\n",br); fflush(stdout); clock_gettime(CLOCK_MONOTONIC, &finish); double addTime = finish.tv_sec - start.tv_sec; addTime += (finish.tv_nsec - start.tv_nsec)/1000000000.0; readTime += getCPUTime() - readStartTime+addTime; // keep a counter to know where the file pointer up to filecounter = filecounter + br; if (br!=0) { printf("round %d\n",round); printf("filecounter = %lu\n",filecounter); for(i=0;i<enc_blocks;i++) { for(j=0;j<k;j++) { // for each byte in each message, compute index int index = i*k+j; // get block and byte index int block_index = index/BLOCK_SIZE; int byte_index = index%BLOCK_SIZE; // if reach the end, padding 0s if (index>=fileLen) { int a; for(a=j;a<k;a++) message[a]=0; break; } // compute the PRPed index in the file unsigned long file_index = prptable[block_index]*BLOCK_SIZE+byte_index; // check if this byte is read in the memory or not, copy if yes, put 0 otherwise if(file_index<filecounter && file_index>=(filecounter-br)) { unsigned long newind = file_index-filecounter+br; message[j] = buf[newind]; } else message[j] = 0; } //printf("msg for block %d: ",i); //displayCharArray(message,k); // do a partial encoding on the message encode_data(message,k,codeword); // concatenate with previous code to get a whole /*printf("code for block %d: ",i); displayCharArray(codeword,n); printf("parity (before) for block %d: ",i); displayCharArray(code[i],n-k);*/ for(j=0;j<d;j++) code[i][j] = code[i][j] ^ codeword[k+j]; //printf("parity for block %d: ",i); //displayCharArray(code[i],n-k); //printf("\n"); } round = round + 1; } free(buf); } /*// ------------- for debugging unsigned char a[fileLen],r[fileLen]; unsigned char newc[n],newm[k]; rewind(fp); fread(a, 1, fileLen, fp); printf("original:\n"); for (i=0;i<fileLen;i++) { printf("%02x",a[i]); } printf("\n"); for (i=0;i<fileLen/32;i++) { for (j=0;j<32;j++) { r[i*32+j] = a[prptable[i]*32+j]; } } printf("prped:\n"); for (i=0;i<fileLen;i++) { printf("%02x",r[i]); } printf("\n"); for (i=0;i<enc_blocks;i++) { printf("parity part %d: ",i); displayCharArray(code[i],d); unsigned char newcode[n]; int iii; int ii; for(ii=0;ii<k;ii++) { if (i*k+ii>=fileLen) break; newcode[ii] = r[i*k+ii]; newm[ii] = r[i*k+ii]; } if (i==enc_blocks-1) { for(ii=0;ii<k-fileLen%k;ii++){ newm[fileLen%k+ii]=0; newcode[fileLen%k+ii] = 0; } } encode_data(newm,k,newc); printf("actual code %d: ",i); displayCharArray(newc,n); for(iii=0;iii<d;iii++) { newcode[k+iii] = code[i][iii]; } newcode[0] = 99; printf("whole code %d: ",i); displayCharArray(newcode,n); decode_data(newcode, n); int erasure[1]; int syn = check_syndrome (); printf("syndrome: %d\n",syn); if (syn != 0) { correct_errors_erasures(newcode,n,0,erasure); } printf("decode %d: ",i); displayCharArray(newcode,n); } //--------------- for debugging */ free(prptable); prptable = NULL; // perform another PRP for parity part prptable = malloc(sizeof(int)*(enc_blocks)); printf("\nSRF PRP for the outer layer ECC...\n"); prpStartTime = getCPUTime(); prptable = prp(enc_blocks, k_ecc_perm); prpTime += getCPUTime() - prpStartTime; // encrypt parity part and append to the file with PRPed order enc_init(k_ecc_enc); for (i=0;i<enc_blocks;i++) { unsigned char ct[d]; clock_gettime(CLOCK_MONOTONIC, &start); encStartTime = getCPUTime(); encrypt(ct,code[prptable[i]],sizeof(ct)); clock_gettime(CLOCK_MONOTONIC, &finish); double addTime = finish.tv_sec - start.tv_sec; addTime += (finish.tv_nsec - start.tv_nsec)/1000000000.0; encTime += getCPUTime()-encStartTime+addTime; //printf("encrypted for %d: ",i); //displayCharArray(ct,sizeof(ct)); //unsigned char pt[d]; //decrypt(ct,pt,sizeof(ct)); //printf("decrypted for %d: ",i); //displayCharArray(pt,sizeof(ct)); clock_gettime(CLOCK_MONOTONIC, &start); write1StartTime = getCPUTime(); fwrite(ct,d,1,fp); clock_gettime(CLOCK_MONOTONIC, &finish); addTime = finish.tv_sec - start.tv_sec; addTime += (finish.tv_nsec - start.tv_nsec)/1000000000.0; write1Time += getCPUTime()-write1StartTime; } // update t for later challenge computation t = t+enc_blocks; printf("\nIncremental encoding finishes...\n"); free(prptable); for (i = 0; i < enc_blocks; i++){ free(code[i]); } free(code); return 0; }
int main() { try { // Camera settings Camera camera; glm::vec3 vrp(0.0f, 0.0f, 10.0f); glm::vec3 vpn(0.0f, 0.0f, 1.0f); glm::vec3 vup(0.0f, 1.0f, 0.0f); glm::vec3 prp(0.0f, 0.0f, 100.0f); float F = 10.0f; float B = -80.0f; glm::vec2 lower_left(-20.0f, -20.0f); glm::vec2 upper_right(20.0f, 20.0f); camera = Camera(vrp, vpn, vup, prp, lower_left, upper_right, F, B); // Examples int curves = 4; // Amount of examples BezierRow G[curves]; G[0] = BezierRow(glm::vec3(-15.0f, -15.0f, 0.0f), glm::vec3(-10.0f, 25.0f, 0.0f), glm::vec3(10.0f, 25.0f, 0.0f), glm::vec3(15.0f, -15.0f, 0.0f)); G[1] = BezierRow(glm::vec3(-20.0f, 0.0f, 0.0f), glm::vec3(-1.0f, 55.0f, 0.0f), glm::vec3(1.0f, -55.0f, 0.0f), glm::vec3(20.0f, 0.0f, 0.0f)); G[2] = BezierRow(glm::vec3(-1.0f, -5.0f, 0.0f), glm::vec3(-60.0f, 5.0f, 0.0f), glm::vec3(60.0f, 5.0f, 0.0f), glm::vec3(1.0f, -5.0f, 0.0f)); G[3] = BezierRow(glm::vec3(-10.0f, -5.0f, 0.0f), glm::vec3(60.0f, 5.0f, 0.0f), glm::vec3(-60.0f, 5.0f, 0.0f), glm::vec3(10.0f, -5.0f, 0.0f)); int currentfigure = 3; // Set figure between 4 different examples // Decide whether to use sampling or subdivision int decider = 1; int Npoint = 0; std::vector<glm::vec3> points; // Sampling if(decider == 0){ float t = 0.0f; float step = 12.0f; sampling(G[currentfigure], t, step, points); Npoint = step*2; } // Subdivision else if(decider == 1){ DLB /= 8.0f; DRB /= 8.0f; int n = 3; // Amount of curves (smoothness) int npow = pow(2, n+1); // Amount of points subdivide(G[currentfigure], n, points); Npoint = npow; } else{ printf("No method chosen\n"); return 1; } glm::mat4x4 CTM = camera.CurrentTransformationMatrix(); std::cout << "CTM = " << std::endl << CTM << std::endl; // Initialize the graphics InitializeGLFW(); GLFWwindow* Window = CreateWindow(WindowWidth, WindowHeight, WindowTitle.c_str()); InitializeGLEW(); InitializeOpenGL(); glfwSwapBuffers(Window); // Read and Compile the vertex program vertextransform.vert GLuint vertexprogID = CreateGpuProgram("vertextransform.vert", GL_VERTEX_SHADER); // Read and Compile the fragment program linefragment.frag GLuint linefragmentprogID = CreateGpuProgram("linefragment.frag", GL_FRAGMENT_SHADER); // Create a lineshader program and Link it with the vertex and linefragment programs GLuint lineshaderID = CreateShaderProgram(vertexprogID, linefragmentprogID); // Now comes the OpenGL core part // This is where the curve is initialized // User data is in the global variable curveVertices, and the number of entries // is in Ncurvevertices // Make a VertexArrayObject - it is used by the VertexArrayBuffer, and it must be declared! GLuint CurveVertexArrayID; glGenVertexArrays(1, &CurveVertexArrayID); glBindVertexArray(CurveVertexArrayID); // Make a curvevertexbufferObject - it uses the previous VertexArrayBuffer! GLuint curvevertexbuffer; glGenBuffers(1, &curvevertexbuffer); glBindBuffer(GL_ARRAY_BUFFER, curvevertexbuffer); // Give our vertices to OpenGL. glBufferData(GL_ARRAY_BUFFER, Npoint * 3 * sizeof(float), &points[0], GL_STATIC_DRAW); // Validate the shader program ValidateShader(lineshaderID, "Validating the lineshader"); // Get locations of Uniforms GLuint curvevertextransform = glGetUniformLocation(lineshaderID, "CTM"); GLuint curvefragmentcolor = glGetUniformLocation(lineshaderID, "Color"); // Initialize Attributes GLuint curvevertexattribute = glGetAttribLocation(lineshaderID, "VertexPosition"); glVertexAttribPointer(curvevertexattribute, 3, GL_FLOAT, GL_FALSE, 0, 0); // The main loop while (!glfwWindowShouldClose(Window)) { glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glUseProgram(lineshaderID); glm::mat4x4 CTM = camera.CurrentTransformationMatrix(); glUniformMatrix4fv(curvevertextransform, 1, GL_FALSE, &CTM[0][0]); glUniform3f(curvefragmentcolor, 0.2f, 0.2f, 0.2f); glEnableVertexAttribArray(curvevertexattribute); glBindVertexArray(CurveVertexArrayID); // This is very important! There are two "binds"! glDrawArrays(GL_LINES, 0, Npoint); glDisableVertexAttribArray(curvevertexattribute); glUseProgram(0); glfwSwapBuffers(Window); std::stringstream errormessage; errormessage << "End of loop: " << "assignment5.cpp" << ": " << __LINE__ << ": "; ErrorCheck(errormessage.str()); glfwPollEvents(); } } catch (std::exception const& exception) { std::cerr << "Exception: " << exception.what() << std::endl; } glfwTerminate(); return 0; }
int outer_decoding(FILE* orifp, FILE* parifp, FILE *output, FILE* tempfp, decoded_blocks *db) { int i,j,stripes,fileLen,index; int* prp_table; int* reverse_prp_table; char message[k]; char codeword[n]; //unsigned char decodedfile[stripes][k]; int erasure[1]; //FILE* tempfp = fopen("tempfile", "w+b"); if (tempfp == NULL){ printf("couldn't open temperory file for writing.\n"); return -1; } //find the number of stripes in the file fseek(parifp,0,SEEK_END); fileLen = ftell(parifp); printf("display fileLen of parity %d\n",fileLen); //if(fileLen % n==0) stripes = fileLen/d; //else //stripes = fileLen/n+1; printf("number of stripes for outer decoding %d\n",stripes); fflush(stdout); unsigned char ** parity;//[stripes][d]; parity = (unsigned char **) malloc(stripes*sizeof(unsigned char *)); for (i = 0; i < stripes; i++) { parity[i] = (unsigned char *) malloc(d*sizeof(unsigned char)); } //call prp prp_table =malloc(sizeof(int)*stripes); reverse_prp_table = malloc(sizeof(int)*stripes); //perform reverse prp prp_table = prp(stripes, k_ecc_perm); reverseprp(stripes,prp_table,reverse_prp_table); /*for(i=0;i<stripes;i++){ printf("prp %d: %d\n",i,prp_table[i]); printf("rev prp %d: %d\n",i,reverse_prp_table[i]); }*/ //free(prp_table); printf("check1\n"); enc_init(k_ecc_enc); //decrypt parity part rewind(parifp); rewind(orifp); ///number of parity blocks = stripes/2 //read parity parts directly //int parity_start = fileLen-(stripes/2)*d; //fseek(temp_fp,parity_start,SEEK_SET); unsigned char paritybytes[stripes][d]; for (i=0;i<stripes;i++) { unsigned char ct[d]; //unsigned char pt[d]; fread(ct,sizeof(ct),1,parifp); decrypt(ct,paritybytes[prp_table[i]],sizeof(ct)); //printf("prp rev for %d: ",i); //displayCharArray(paritybytes[i],sizeof(ct)); //for(j=0;j<d;j++){ // parity[i][j]=ct[j]; //} } for (i=0;i<stripes;i++) { printf("prp rev for %d: ",i); displayCharArray(paritybytes[i],sizeof(paritybytes[i])); } free(reverse_prp_table); reverse_prp_table = malloc(sizeof(int)*m); prp_table =malloc(sizeof(int)*m); prp_table = prp(m, k_file_perm); reverseprp(m,prp_table,reverse_prp_table); //get the message and the parity, create codeword and decode it //rewind(temp_fp); FILE * prp = fopen("prp","w+b"); for(i=0;i<m;i++) { unsigned char prpbuf[BLOCK_SIZE]; fseek(orifp,prp_table[i]*32,SEEK_SET); size_t br = fread(prpbuf,1,BLOCK_SIZE,orifp); fwrite(prpbuf,1,BLOCK_SIZE,prp); } fclose(prp); prp = fopen("prp","r+b"); for(i=0;i<stripes;i++) { index=0; unsigned char code[n]; size_t br = fread(code,1,k,prp); int pad = k-br; int ii; for (ii=0;ii<pad;ii++) code[br+ii] = 0; for(j=0;j<d;j++) { code[k+j] = paritybytes[i][j]; } printf("whole code %d: ",i); displayCharArray(code,n); decode_data(code, n); int syn = check_syndrome (); printf("syndrome: %d\n",syn); if (syn != 0) { correct_errors_erasures(code,n,0,erasure); } printf("decoded code %d: ",i); displayCharArray(code,n); //calculate block index of the parity part fwrite(code,1,br,tempfp); } fclose(tempfp); for (i = 0; i < stripes; i++){ free(parity[i]); } free(parity); if ((tempfp = fopen("tempfile", "r+b")) == NULL){ printf("couldn't open temperory file for writing.\n"); return -1; } // write data to the file by applying second level of permutation //free(prp_table); //free(reverse_prp_table); //printf("display m = %lu\n",m); rewind(tempfp); rewind(output); unsigned char buf[BLOCK_SIZE]; for(i=0;i<m;i++) { readStartTime = getCPUTime(); fseek(tempfp,reverse_prp_table[i]*32,SEEK_SET); fread(buf, BLOCK_SIZE, 1, tempfp); readEndTime = getCPUTime(); readTime += readEndTime-readStartTime; writeStartTime = getCPUTime(); fwrite(buf,BLOCK_SIZE,1,output); writeEndTime = getCPUTime(); writeTime += writeEndTime-writeStartTime; } printf("check4\n"); fclose(tempfp); fclose(output); fclose(orifp); fclose(parifp); printf("check5\n"); //delete(temp_fp); return 0; }
jsval CStdDeserializer::ReadScriptVal(const char* UNUSED(name), JS::HandleObject appendParent) { JSContext* cx = m_ScriptInterface.GetContext(); JSAutoRequest rq(cx); uint8_t type; NumberU8_Unbounded("type", type); switch (type) { case SCRIPT_TYPE_VOID: return JS::UndefinedValue(); case SCRIPT_TYPE_NULL: return JS::NullValue(); case SCRIPT_TYPE_ARRAY: case SCRIPT_TYPE_OBJECT: case SCRIPT_TYPE_OBJECT_PROTOTYPE: { JS::RootedObject obj(cx); if (appendParent) { obj.set(appendParent); } else if (type == SCRIPT_TYPE_ARRAY) { u32 length; NumberU32_Unbounded("array length", length); obj.set(JS_NewArrayObject(cx, length)); } else if (type == SCRIPT_TYPE_OBJECT) { obj.set(JS_NewPlainObject(cx)); } else // SCRIPT_TYPE_OBJECT_PROTOTYPE { std::wstring prototypeName; String("proto name", prototypeName, 0, 256); // Get constructor object JS::RootedObject proto(cx); GetSerializablePrototype(prototypeName, &proto); if (!proto) throw PSERROR_Deserialize_ScriptError("Failed to find serializable prototype for object"); JS::RootedObject parent(cx, JS_GetParent(proto)); if (!proto || !parent) throw PSERROR_Deserialize_ScriptError(); // TODO: Remove support for parent since this is dropped upstream SpiderMonkey obj.set(JS_NewObjectWithGivenProto(cx, nullptr, proto, parent)); if (!obj) throw PSERROR_Deserialize_ScriptError("JS_NewObject failed"); // Does it have custom Deserialize function? // if so, we let it handle the deserialized data, rather than adding properties directly bool hasCustomDeserialize, hasCustomSerialize; if (!JS_HasProperty(cx, obj, "Serialize", &hasCustomSerialize) || !JS_HasProperty(cx, obj, "Deserialize", &hasCustomDeserialize)) throw PSERROR_Serialize_ScriptError("JS_HasProperty failed"); if (hasCustomDeserialize) { AddScriptBackref(obj); JS::RootedValue serialize(cx); if (!JS_GetProperty(cx, obj, "Serialize", &serialize)) throw PSERROR_Serialize_ScriptError("JS_GetProperty failed"); bool hasNullSerialize = hasCustomSerialize && serialize.isNull(); // If Serialize is null, we'll still call Deserialize but with undefined argument JS::RootedValue data(cx); if (!hasNullSerialize) ScriptVal("data", &data); JS::RootedValue objVal(cx, JS::ObjectValue(*obj)); m_ScriptInterface.CallFunctionVoid(objVal, "Deserialize", data); return JS::ObjectValue(*obj); } } if (!obj) throw PSERROR_Deserialize_ScriptError("Deserializer failed to create new object"); AddScriptBackref(obj); uint32_t numProps; NumberU32_Unbounded("num props", numProps); bool isLatin1; for (uint32_t i = 0; i < numProps; ++i) { Bool("isLatin1", isLatin1); if (isLatin1) { std::vector<JS::Latin1Char> propname; ReadStringLatin1("prop name", propname); JS::RootedValue propval(cx, ReadScriptVal("prop value", JS::NullPtr())); utf16string prp(propname.begin(), propname.end());; // TODO: Should ask upstream about getting a variant of JS_SetProperty with a length param. if (!JS_SetUCProperty(cx, obj, (const char16_t*)prp.data(), prp.length(), propval)) throw PSERROR_Deserialize_ScriptError(); } else { utf16string propname; ReadStringUTF16("prop name", propname); JS::RootedValue propval(cx, ReadScriptVal("prop value", JS::NullPtr())); if (!JS_SetUCProperty(cx, obj, (const char16_t*)propname.data(), propname.length(), propval)) throw PSERROR_Deserialize_ScriptError(); } } return JS::ObjectValue(*obj); } case SCRIPT_TYPE_STRING: { JS::RootedString str(cx); ScriptString("string", &str); return JS::StringValue(str); } case SCRIPT_TYPE_INT: { int32_t value; NumberI32("value", value, JSVAL_INT_MIN, JSVAL_INT_MAX); return JS::NumberValue(value); } case SCRIPT_TYPE_DOUBLE: { double value; NumberDouble_Unbounded("value", value); JS::RootedValue rval(cx, JS::NumberValue(value)); if (rval.isNull()) throw PSERROR_Deserialize_ScriptError("JS_NewNumberValue failed"); return rval; } case SCRIPT_TYPE_BOOLEAN: { uint8_t value; NumberU8("value", value, 0, 1); return JS::BooleanValue(value ? true : false); } case SCRIPT_TYPE_BACKREF: { u32 tag; NumberU32_Unbounded("tag", tag); JS::RootedObject obj(cx); GetScriptBackref(tag, &obj); if (!obj) throw PSERROR_Deserialize_ScriptError("Invalid backref tag"); return JS::ObjectValue(*obj); } case SCRIPT_TYPE_OBJECT_NUMBER: { double value; NumberDouble_Unbounded("value", value); JS::RootedValue val(cx, JS::NumberValue(value)); JS::RootedObject ctorobj(cx); if (!JS_GetClassObject(cx, JSProto_Number, &ctorobj)) throw PSERROR_Deserialize_ScriptError("JS_GetClassObject failed"); JS::RootedObject obj(cx, JS_New(cx, ctorobj, JS::HandleValueArray(val))); if (!obj) throw PSERROR_Deserialize_ScriptError("JS_New failed"); AddScriptBackref(obj); return JS::ObjectValue(*obj); } case SCRIPT_TYPE_OBJECT_STRING: { JS::RootedString str(cx); ScriptString("value", &str); if (!str) throw PSERROR_Deserialize_ScriptError(); JS::RootedValue val(cx, JS::StringValue(str)); JS::RootedObject ctorobj(cx); if (!JS_GetClassObject(cx, JSProto_String, &ctorobj)) throw PSERROR_Deserialize_ScriptError("JS_GetClassObject failed"); JS::RootedObject obj(cx, JS_New(cx, ctorobj, JS::HandleValueArray(val))); if (!obj) throw PSERROR_Deserialize_ScriptError("JS_New failed"); AddScriptBackref(obj); return JS::ObjectValue(*obj); } case SCRIPT_TYPE_OBJECT_BOOLEAN: { bool value; Bool("value", value); JS::RootedValue val(cx, JS::BooleanValue(value)); JS::RootedObject ctorobj(cx); if (!JS_GetClassObject(cx, JSProto_Boolean, &ctorobj)) throw PSERROR_Deserialize_ScriptError("JS_GetClassObject failed"); JS::RootedObject obj(cx, JS_New(cx, ctorobj, JS::HandleValueArray(val))); if (!obj) throw PSERROR_Deserialize_ScriptError("JS_New failed"); AddScriptBackref(obj); return JS::ObjectValue(*obj); } case SCRIPT_TYPE_TYPED_ARRAY: { u8 arrayType; u32 byteOffset, length; NumberU8_Unbounded("array type", arrayType); NumberU32_Unbounded("byte offset", byteOffset); NumberU32_Unbounded("length", length); // To match the serializer order, we reserve the typed array's backref tag here JS::RootedObject arrayObj(cx); AddScriptBackref(arrayObj); // Get buffer object JS::RootedValue bufferVal(cx, ReadScriptVal("buffer", JS::NullPtr())); if (!bufferVal.isObject()) throw PSERROR_Deserialize_ScriptError(); JS::RootedObject bufferObj(cx, &bufferVal.toObject()); if (!JS_IsArrayBufferObject(bufferObj)) throw PSERROR_Deserialize_ScriptError("js_IsArrayBuffer failed"); switch(arrayType) { case SCRIPT_TYPED_ARRAY_INT8: arrayObj = JS_NewInt8ArrayWithBuffer(cx, bufferObj, byteOffset, length); break; case SCRIPT_TYPED_ARRAY_UINT8: arrayObj = JS_NewUint8ArrayWithBuffer(cx, bufferObj, byteOffset, length); break; case SCRIPT_TYPED_ARRAY_INT16: arrayObj = JS_NewInt16ArrayWithBuffer(cx, bufferObj, byteOffset, length); break; case SCRIPT_TYPED_ARRAY_UINT16: arrayObj = JS_NewUint16ArrayWithBuffer(cx, bufferObj, byteOffset, length); break; case SCRIPT_TYPED_ARRAY_INT32: arrayObj = JS_NewInt32ArrayWithBuffer(cx, bufferObj, byteOffset, length); break; case SCRIPT_TYPED_ARRAY_UINT32: arrayObj = JS_NewUint32ArrayWithBuffer(cx, bufferObj, byteOffset, length); break; case SCRIPT_TYPED_ARRAY_FLOAT32: arrayObj = JS_NewFloat32ArrayWithBuffer(cx, bufferObj, byteOffset, length); break; case SCRIPT_TYPED_ARRAY_FLOAT64: arrayObj = JS_NewFloat64ArrayWithBuffer(cx, bufferObj, byteOffset, length); break; case SCRIPT_TYPED_ARRAY_UINT8_CLAMPED: arrayObj = JS_NewUint8ClampedArrayWithBuffer(cx, bufferObj, byteOffset, length); break; default: throw PSERROR_Deserialize_ScriptError("Failed to deserialize unrecognized typed array view"); } if (!arrayObj) throw PSERROR_Deserialize_ScriptError("js_CreateTypedArrayWithBuffer failed"); return JS::ObjectValue(*arrayObj); } case SCRIPT_TYPE_ARRAY_BUFFER: { u32 length; NumberU32_Unbounded("buffer length", length); #if BYTE_ORDER != LITTLE_ENDIAN #error TODO: need to convert JS ArrayBuffer data from little-endian #endif void* contents = malloc(length); ENSURE(contents); RawBytes("buffer data", (u8*)contents, length); JS::RootedObject bufferObj(cx, JS_NewArrayBufferWithContents(cx, length, contents)); AddScriptBackref(bufferObj); return JS::ObjectValue(*bufferObj); } case SCRIPT_TYPE_OBJECT_MAP: { JS::RootedObject obj(cx, JS::NewMapObject(cx)); AddScriptBackref(obj); u32 mapSize; NumberU32_Unbounded("map size", mapSize); for (u32 i=0; i<mapSize; ++i) { JS::RootedValue key(cx, ReadScriptVal("map key", JS::NullPtr())); JS::RootedValue value(cx, ReadScriptVal("map value", JS::NullPtr())); JS::MapSet(cx, obj, key, value); } return JS::ObjectValue(*obj); } case SCRIPT_TYPE_OBJECT_SET: { JS::RootedValue setVal(cx); m_ScriptInterface.Eval("(new Set())", &setVal); JS::RootedObject setObj(cx, &setVal.toObject()); AddScriptBackref(setObj); u32 setSize; NumberU32_Unbounded("set size", setSize); for (u32 i=0; i<setSize; ++i) { JS::RootedValue value(cx, ReadScriptVal("set value", JS::NullPtr())); m_ScriptInterface.CallFunctionVoid(setVal, "add", value); } return setVal; } default: throw PSERROR_Deserialize_OutOfBounds(); } }